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