normalize identifiers when comparing them
[indieauth-openid.git] / www / index.php
1 <?php
2 /**
3  * IndieAuth to OpenID proxy.
4  * Proxies IndieAuth authorization requests to one's OpenID server
5  *
6  * PHP version 5
7  *
8  * @package indieauth-openid
9  * @author  Christian Weiske <cweiske@cweiske.de>
10  * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
11  * @link    http://indiewebcamp.com/login-brainstorming
12  * @link    http://indiewebcamp.com/authorization-endpoint
13  * @link    http://indiewebcamp.com/auth-brainstorming
14  * @link    https://indieauth.com/developers
15  */
16
17 require_once 'Net/URL2.php';
18 require_once 'OpenID.php';
19 require_once 'OpenID/RelyingParty.php';
20 require_once 'OpenID/Message.php';
21 require_once 'OpenID/Exception.php';
22
23 function loadDb()
24 {
25     $db = new PDO('sqlite:' . __DIR__ . '/../data/tokens.sq3');
26     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
27     $db->exec("CREATE TABLE IF NOT EXISTS authtokens(
28 code TEXT,
29 me TEXT,
30 redirect_uri TEXT,
31 client_id TEXT,
32 state TEXT,
33 created DATE
34 )");
35     //clean old tokens
36     $stmt = $db->prepare('DELETE FROM authtokens WHERE created < :created');
37     $stmt->execute(array(':created' => date('c', time() - 60)));
38
39     return $db;
40 }
41
42 function create_token($me, $redirect_uri, $client_id, $state)
43 {
44     $code = base64_encode(openssl_random_pseudo_bytes(32));
45     $db = loadDb();
46     $db->prepare(
47         'INSERT INTO authtokens (code, me, redirect_uri, client_id, state, created)'
48         . ' VALUES(:code, :me, :redirect_uri, :client_id, :state, :created)'
49     )->execute(
50         array(
51             ':code' => $code,
52             ':me' => $me,
53             ':redirect_uri' => $redirect_uri,
54             ':client_id' => $client_id,
55             ':state' => (string) $state,
56             ':created' => date('c')
57         )
58     );
59     return $code;
60 }
61
62 function validate_token($code, $redirect_uri, $client_id, $state)
63 {
64     $db = loadDb();
65     $stmt = $db->prepare(
66         'SELECT me FROM authtokens WHERE'
67         . ' code = :code'
68         . ' AND redirect_uri = :redirect_uri'
69         . ' AND client_id = :client_id'
70         . ' AND state = :state'
71         . ' AND created >= :created'
72     );
73     $stmt->execute(
74         array(
75             ':code'         => $code,
76             ':redirect_uri' => $redirect_uri,
77             ':client_id'    => $client_id,
78             ':state'        => (string) $state,
79             ':created'      => date('c', time() - 60)
80         )
81     );
82     $row = $stmt->fetch(PDO::FETCH_ASSOC);
83
84     $stmt = $db->prepare('DELETE FROM authtokens WHERE code = :code');
85     $stmt->execute(array(':code' => $code));
86
87     if ($row === false) {
88         return false;
89     }
90     return $row['me'];
91 }
92
93 function error($msg)
94 {
95     header('HTTP/1.0 400 Bad Request');
96     header('Content-type: text/plain; charset=utf-8');
97     echo $msg . "\n";
98     exit(1);
99 }
100
101 function verifyUrlParameter($givenParams, $paramName)
102 {
103     if (!isset($givenParams[$paramName])) {
104         error('"' . $paramName . '" parameter missing');
105     }
106     $url = parse_url($givenParams[$paramName]);
107     if (!isset($url['scheme'])) {
108         error('Invalid URL in "' . $paramName . '" parameter: scheme missing');
109     }
110     if (!isset($url['host'])) {
111         error('Invalid URL in "' . $paramName . '" parameter: host missing');
112     }
113
114     return $givenParams[$paramName];
115 }
116
117 function getBaseUrl()
118 {
119     if (!isset($_SERVER['REQUEST_SCHEME'])) {
120         $_SERVER['REQUEST_SCHEME'] = 'http';
121     }
122     $file = preg_replace('/[?#].*$/', '', $_SERVER['REQUEST_URI']);
123     return $_SERVER['REQUEST_SCHEME'] . '://'
124         . $_SERVER['HTTP_HOST']
125         . $file;
126 }
127
128 header('IndieAuth: authorization_endpoint');
129 session_start();
130 $returnTo = getBaseUrl();
131 $realm    = getBaseUrl();
132
133 if (isset($_GET['openid_mode']) && $_GET['openid_mode'] != '') {
134     //verify openid response
135     if (!count($_POST)) {
136         list(, $queryString) = explode('?', $_SERVER['REQUEST_URI']);
137     } else {
138         $queryString = file_get_contents('php://input');
139     }
140
141     $message = new \OpenID_Message($queryString, \OpenID_Message::FORMAT_HTTP);
142     $id      = $message->get('openid.claimed_id');
143     if (OpenID::normalizeIdentifier($id) != OpenID::normalizeIdentifier($_SESSION['me'])) {
144         error(
145             sprintf(
146                 'Given identity URL "%s" and claimed OpenID "%s" do not match',
147                 $_SESSION['me'], $id
148             )
149         );
150     }
151     try {
152         $o = new \OpenID_RelyingParty($returnTo, $realm, $_SESSION['me']);
153         $result = $o->verify(new \Net_URL2($returnTo . '?' . $queryString), $message);
154
155         if ($result->success()) {
156             $token = create_token(
157                 $_SESSION['me'], $_SESSION['redirect_uri'],
158                 $_SESSION['client_id'], $_SESSION['state']
159             );
160             //redirect to indieauth
161             $url = new Net_URL2($_SESSION['redirect_uri']);
162             $url->setQueryVariable('code', $token);
163             $url->setQueryVariable('me', $_SESSION['me']);
164             $url->setQueryVariable('state', $_SESSION['state']);
165             header('Location: ' . $url->getURL());
166             exit();
167         } else {
168             error('Error verifying OpenID login: ' . $result->getAssertionMethod());
169         }
170     } catch (OpenID_Exception $e) {
171         error('Error verifying OpenID login: ' . $e->getMessage());
172     }
173 }
174
175 if ($_SERVER['REQUEST_METHOD'] == 'GET') {
176     $me           = verifyUrlParameter($_GET, 'me');
177     $redirect_uri = verifyUrlParameter($_GET, 'redirect_uri');
178     $client_id    = verifyUrlParameter($_GET, 'client_id');
179     $state        = null;
180     if (isset($_GET['state'])) {
181         $state = $_GET['state'];
182     }
183     $response_type = 'id';
184     if (isset($_GET['response_type'])) {
185         $response_type = $_GET['response_type'];
186     }
187     if ($response_type != 'id') {
188         error('unsupported response_type: ' . $response_type);
189     }
190
191     $_SESSION['me']           = $me;
192     $_SESSION['redirect_uri'] = $redirect_uri;
193     $_SESSION['client_id']    = $client_id;
194     $_SESSION['state']        = $state;
195
196     try {
197         $o = new \OpenID_RelyingParty($returnTo, $realm, $me);
198         $authRequest = $o->prepare();
199         $url = $authRequest->getAuthorizeURL();
200         header("Location: $url");
201         exit(0);
202     } catch (OpenID_Exception $e) {
203         error('OpenID error: ' . $e->getMessage());
204     }
205 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
206     $redirect_uri = verifyUrlParameter($_POST, 'redirect_uri');
207     $client_id    = verifyUrlParameter($_POST, 'client_id');
208     $state        = null;
209     if (isset($_POST['state'])) {
210         $state = $_POST['state'];
211     }
212     if (!isset($_POST['code'])) {
213         error('"code" parameter missing');
214     }
215     $token = $_POST['code'];
216
217     $me = validate_token($token, $redirect_uri, $client_id, $state);
218     if ($me === false) {
219         header('HTTP/1.0 400 Bad Request');
220         echo "Validating token failed\n";
221         exit(1);
222     }
223     header('Content-type: application/x-www-form-urlencoded');
224     echo 'me=' . urlencode($me);
225 }
226 ?>