better handle missing auth header, set explicit response types to not get warnings...
[authserver.git] / app / authorize.php
1 <?php
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
4  * You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 // Called e.g. as /authorize?response_type=code&client_id=testclient&state=f00bar&scope=email&redirect_uri=http%3A%2F%2Ffake.example.com%2F
7 // This either redirects to the redirect URL with errors or success added as GET parameters,
8 // or sends a HTML page asking for login / permission to scope (email is always granted in this system but not always for OAuth2 generically)
9 // or sends errors as a JSON document (hopefully shouldn't but seen that in testing).
10
11 // Include the common auth system files (including the OAuth2 Server object).
12 require_once(__DIR__.'/authsystem.inc.php');
13
14 $errors = $utils->checkForSecureConnection();
15 $utils->sendSecurityHeaders();
16
17 // Initialize the HTML document with our basic elements.
18 extract($utils->initHTMLDocument(sprintf(_('Authorization Request | %s'), $utils->settings['operator_name']),
19                                  sprintf(_('%s Authentication Server'), $utils->settings['operator_name']))); // sets $document, $html, $head, $title, $body
20
21 if (!count($errors)) {
22   $session = $utils->initSession(); // Read session or create new session and set cookie.
23   if ($session['logged_in'] && (@$_GET['logout'] == 1)) {
24     $result = $db->prepare('UPDATE `auth_sessions` SET `logged_in` = FALSE WHERE `id` = :sessid;');
25     if (!$result->execute(array(':sessid' => $session['id']))) {
26       $utils->log('logout_failure', 'session: '.$session['id']);
27       $errors[] = _('Unexpected error while logging out.');
28     }
29     $session['logged_in'] = 0;
30   }
31   if (intval($session['user'])) {
32     $result = $db->prepare('SELECT `id`,`email`,`verify_hash`,`group_id` FROM `auth_users` WHERE `id` = :userid;');
33     $result->execute(array(':userid' => $session['user']));
34     $user = $result->fetch(PDO::FETCH_ASSOC);
35     if (!$user['id']) {
36       $utils->log('user_read_failure', 'user: '.$session['user']);
37     }
38   }
39   else {
40     $user = array('id' => 0, 'email' => '');
41   }
42   if (is_null($session)) {
43     $errors[] = _('The session system is not working.').' '
44                 .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
45   }
46   elseif ($session['logged_in']) {
47     // We are logged in, process authorization request.
48     $request = OAuth2\Request::createFromGlobals();
49     $response = new OAuth2\Response();
50
51     // Validate the authorize request.
52     if (!$server->validateAuthorizeRequest($request, $response)) {
53       $response->send();
54       exit();
55     }
56
57     $is_authorized = !array_key_exists('authorized', $_POST) ? null : (@$_POST['authorized'] === 'yes');
58
59     if (is_null($is_authorized) && (@$request->query['scope'] != 'email')) {
60       // Display an authorization form (unless the scope is email, which we handle as a login request below).
61       $para = $body->appendElement('p', sprintf(_('Hi %s!'), $user['email']));
62       $para->setAttribute('class', 'userwelcome');
63
64       $form = $body->appendForm('', 'POST', 'authform');
65       $form->setAttribute('id', 'authform');
66       $domain_name = parse_url($request->query['redirect_uri'], PHP_URL_HOST);
67       if (!strlen($domain_name)) { $domain_name = $request->query['client_id']; }
68       $form->appendElement('p', sprintf(_('Do you authorize %s to access %s?'), $domain_name, $request->query['scope']));
69       $authinput = $form->appendInputHidden('authorized', 'yes');
70       $authinput->setAttribute('id', 'isauthorized');
71       $submit = $form->appendInputSubmit(_('Yes'));
72       $form->appendText(' ');
73       $button = $form->appendButton(_('No'));
74       $button->setAttribute('id', 'cancelauth');
75     }
76     elseif (@$request->query['scope'] == 'email') {
77       // Display an interstitial page for a login  when we have email scope (verified email for logging in).
78       $domain_name = parse_url($request->query['redirect_uri'], PHP_URL_HOST);
79       if (!strlen($domain_name)) { $domain_name = $request->query['client_id']; }
80       // If the referrer is from the auth system and we have a different domain to redirect to,
81       // we can safely assume we just logged in with that email and skip the interstitial page.
82       $refer_domain = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
83       if (is_null($is_authorized) && ($refer_domain == $_SERVER['SERVER_NAME']) && ($refer_domain != $domain_name) &&
84           (dirname($_SERVER['REQUEST_URI']) == dirname(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)))) {
85         $is_authorized = true;
86       }
87       if (is_null($is_authorized)) {
88         $para = $body->appendElement('p', sprintf(_('Sign in to %s using…'), $domain_name));
89         $para->setAttribute('class', 'signinwelcome');
90         $form = $body->appendForm('', 'POST', 'authform');
91         $form->setAttribute('id', 'authform');
92         $form->setAttribute('class', 'loginarea');
93         $ulist = $form->appendElement('ul');
94         $ulist->setAttribute('class', 'flat emaillist');
95         $emails = $utils->getGroupedEmails($user['group_id']);
96         if (!count($emails)) { $emails = array($user['email']); }
97         foreach ($emails as $email) {
98           $litem = $ulist->appendElement('li');
99           $litem->appendInputRadio('user_email', 'uemail_'.md5($email), $email, $email == $user['email']);
100           $litem->appendLabel('uemail_'.md5($email), $email);
101         }
102         $para = $form->appendElement('p');
103         $para->setAttribute('class', 'small otheremaillinks');
104         $link = $para->appendLink('#', _('Add another email address'));
105         $link->setAttribute('id', 'addanotheremail'); // Makes the JS put the right functionality onto the link.
106         $para->appendText(' ');
107         $link = $para->appendLink('#', _('This is not me'));
108         $link->setAttribute('id', 'isnotme'); // Makes the JS put the right functionality onto the link.
109         $authinput = $form->appendInputHidden('authorized', 'yes');
110         $authinput->setAttribute('id', 'isauthorized');
111         $submit = $form->appendInputSubmit(_('Sign in'));
112         $para = $form->appendElement('p');
113         $para->setAttribute('class', 'small');
114         $link = $para->appendLink('#', _('Cancel'));
115         $link->setAttribute('id', 'cancelauth'); // Makes the JS put the right functionality onto the link.
116         $utils->setRedirect($session, $_SERVER['REQUEST_URI']);
117       }
118     }
119     if (!is_null($is_authorized)) {
120       // Switch to different user if we selected a different email within the group.
121       if (strlen(@$_POST['user_email']) && ($_POST['user_email'] != $user['email'])) {
122         $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash`,`group_id` FROM `auth_users` WHERE `group_id` = :groupid AND `email` = :email;');
123         $result->execute(array(':groupid' => $user['group_id'], ':email' => $_POST['user_email']));
124         $newuser = $result->fetch(PDO::FETCH_ASSOC);
125         if ($newuser) {
126           $user = $newuser;
127           $session = $utils->getLoginSession($user['id'], $session);
128         }
129       }
130       if ($settings['piwik_enabled']) {
131         // If we do not send out an HTML file, we need to do the Piwik tracking ourselves.
132         require_once($settings['piwik_tracker_path'].'PiwikTracker.php');
133         PiwikTracker::$URL = ((strpos($settings['piwik_url'], '://') === false) ? 'http://localhost' : '' ).$settings['piwik_url'];
134         $piwikTracker = new PiwikTracker($idSite = $settings['piwik_site_id']);
135         $piwikTracker->doTrackPageView('Handle Authorize Request');
136       }
137       // Handle authorize request, forwarding code in GET parameters if the user has authorized your client.
138       $server->handleAuthorizeRequest($request, $response, $is_authorized, $user['id']);
139       /* For testing only
140       if ($is_authorized) {
141         // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
142         $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
143         exit("SUCCESS! Authorization Code: $code");
144       }
145       */
146       $utils->resetRedirect($session);
147       $response->send();
148       exit();
149     }
150   }
151   else {
152     // Display login/register form.
153     $para = $body->appendElement('p', _('You need to log in or register to continue.'));
154     $para->setAttribute('class', 'logininfo');
155     $utils->appendLoginForm($body, $session, $user);
156     $utils->setRedirect($session, str_replace('&logout=1', '', $_SERVER['REQUEST_URI'])); // Make sure to strip a logout to not get into a loop.
157   }
158 }
159
160 if (count($errors)) {
161   $body->appendElement('p', ((count($errors) <= 1)
162                             ?_('The following error was detected')
163                             :_('The following errors were detected')).':');
164   $list = $body->appendElement('ul');
165   $list->setAttribute('class', 'flat warn');
166   foreach ($errors as $msg) {
167     $item = $list->appendElement('li', $msg);
168   }
169   $body->appendButton(_('Back'), 'history.back();');
170 }
171
172 // Send HTML to client.
173 print($document->saveHTML());
174 ?>