skip interstitial page when we come from login page and redirect to different domain
[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 // Start HTML document as a DOM object.
15 extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body
16 $document->formatOutput = true; // we want a nice output
17 $style = $head->appendElement('link');
18 $style->setAttribute('rel', 'stylesheet');
19 $style->setAttribute('href', 'authsystem.css');
20 $head->appendJSFile('authsystem.js');
21 $title->appendText('Authorization Request | KaiRo.at');
22 $h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server');
23
24 $errors = $utils->checkForSecureConnection();
25 $utils->sendSecurityHeaders();
26
27 $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
28 $para->setAttribute('id', 'jswarning');
29 $para->setAttribute('class', 'warn');
30
31 if (!count($errors)) {
32   $session = $utils->initSession(); // Read session or create new session and set cookie.
33   if ($session['logged_in'] && (@$_GET['logout'] == 1)) {
34     $result = $db->prepare('UPDATE `auth_sessions` SET `logged_in` = FALSE WHERE `id` = :sessid;');
35     if (!$result->execute(array(':sessid' => $session['id']))) {
36       $utils->log('logout_failure', 'session: '.$session['id']);
37       $errors[] = _('Unexpected error while logging out.');
38     }
39     $session['logged_in'] = 0;
40   }
41   if (intval($session['user'])) {
42     $result = $db->prepare('SELECT `id`,`email`,`verify_hash`,`group_id` FROM `auth_users` WHERE `id` = :userid;');
43     $result->execute(array(':userid' => $session['user']));
44     $user = $result->fetch(PDO::FETCH_ASSOC);
45     if (!$user['id']) {
46       $utils->log('user_read_failure', 'user: '.$session['user']);
47     }
48   }
49   else {
50     $user = array('id' => 0, 'email' => '');
51   }
52   if (is_null($session)) {
53     $errors[] = _('The session system is not working.').' '._('Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
54   }
55   elseif ($session['logged_in']) {
56     // We are logged in, process authorization request.
57     $request = OAuth2\Request::createFromGlobals();
58     $response = new OAuth2\Response();
59
60     // Validate the authorize request.
61     if (!$server->validateAuthorizeRequest($request, $response)) {
62       $response->send();
63       exit();
64     }
65
66     $is_authorized = !array_key_exists('authorized', $_POST) ? null : (@$_POST['authorized'] === 'yes');
67
68     if (is_null($is_authorized) && (@$request->query['scope'] != 'email')) {
69       // Display an authorization form (unless the scope is email, which we handle as a login request below).
70       $para = $body->appendElement('p', sprintf(_('Hi %s!'), $user['email']));
71       $para->setAttribute('class', 'userwelcome');
72
73       $form = $body->appendForm('', 'POST', 'authform');
74       $form->setAttribute('id', 'authform');
75       $domain_name = parse_url($request->query['redirect_uri'], PHP_URL_HOST);
76       if (!strlen($domain_name)) { $domain_name = $request->query['client_id']; }
77       $form->appendElement('p', sprintf(_('Do you authorize %s to access %s?'), $domain_name, $request->query['scope']));
78       $authinput = $form->appendInputHidden('authorized', 'yes');
79       $authinput->setAttribute('id', 'isauthorized');
80       $submit = $form->appendInputSubmit(_('Yes'));
81       $form->appendText(' ');
82       $button = $form->appendButton(_('No'));
83       $button->setAttribute('id', 'cancelauth');
84     }
85     elseif (@$request->query['scope'] == 'email') {
86       // Display an interstitial page for a login  when we have email scope (verified email for logging in).
87       $domain_name = parse_url($request->query['redirect_uri'], PHP_URL_HOST);
88       if (!strlen($domain_name)) { $domain_name = $request->query['client_id']; }
89       // If the referrer is from the auth system and we have a different domain to redirect to,
90       // we can safely assume we just logged in with that email and skip the interstitial page.
91       $refer_domain = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
92       if (is_null($is_authorized) && ($refer_domain == $_SERVER['SERVER_NAME']) && ($refer_domain != $domain_name) &&
93           (dirname($_SERVER['REQUEST_URI']) == dirname(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)))) {
94         $is_authorized = true;
95       }
96       if (is_null($is_authorized)) {
97         $para = $body->appendElement('p', sprintf(_('Sign in to %s using…'), $domain_name));
98         $para->setAttribute('class', 'signinwelcome');
99         $form = $body->appendForm('', 'POST', 'authform');
100         $form->setAttribute('id', 'authform');
101         $form->setAttribute('class', 'loginarea');
102         $ulist = $form->appendElement('ul');
103         $ulist->setAttribute('class', 'flat emaillist');
104         $emails = $utils->getGroupedEmails($user['group_id']);
105         if (!count($emails)) { $emails = array($user['email']); }
106         foreach ($emails as $email) {
107           $litem = $ulist->appendElement('li');
108           $litem->appendInputRadio('user_email', 'uemail_'.md5($email), $email, $email == $user['email']);
109           $litem->appendLabel('uemail_'.md5($email), $email);
110         }
111         $para = $form->appendElement('p');
112         $para->setAttribute('class', 'small otheremaillinks');
113         $link = $para->appendLink('#', _('Add another email address'));
114         $link->setAttribute('id', 'addanotheremail'); // Makes the JS put the right functionality onto the link.
115         $para->appendText(' ');
116         $link = $para->appendLink('#', _('This is not me'));
117         $link->setAttribute('id', 'isnotme'); // Makes the JS put the right functionality onto the link.
118         $authinput = $form->appendInputHidden('authorized', 'yes');
119         $authinput->setAttribute('id', 'isauthorized');
120         $submit = $form->appendInputSubmit(_('Sign in'));
121         $para = $form->appendElement('p');
122         $para->setAttribute('class', 'small');
123         $link = $para->appendLink('#', _('Cancel'));
124         $link->setAttribute('id', 'cancelauth'); // Makes the JS put the right functionality onto the link.
125         $utils->setRedirect($session, $_SERVER['REQUEST_URI']);
126       }
127     }
128     if (!is_null($is_authorized)) {
129       // Switch to different user if we selected a different email within the group.
130       if (strlen(@$_POST['user_email']) && ($_POST['user_email'] != $user['email'])) {
131         $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash`,`group_id` FROM `auth_users` WHERE `group_id` = :groupid AND `email` = :email;');
132         $result->execute(array(':groupid' => $user['group_id'], ':email' => $_POST['user_email']));
133         $newuser = $result->fetch(PDO::FETCH_ASSOC);
134         if ($newuser) {
135           $user = $newuser;
136           $session = $utils->getLoginSession($user['id'], $session);
137         }
138       }
139       // Handle authorize request, forwarding code in GET parameters if the user has authorized your client.
140       $server->handleAuthorizeRequest($request, $response, $is_authorized, $user['id']);
141       /* For testing only
142       if ($is_authorized) {
143         // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
144         $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
145         exit("SUCCESS! Authorization Code: $code");
146       }
147       */
148       $utils->resetRedirect($session);
149       $response->send();
150       exit();
151     }
152   }
153   else {
154     // Display login/register form.
155     $para = $body->appendElement('p', _('You need to log in or register to continue.'));
156     $para->setAttribute('class', 'logininfo');
157     $utils->appendLoginForm($body, $session, $user);
158     $utils->setRedirect($session, str_replace('&logout=1', '', $_SERVER['REQUEST_URI'])); // Make sure to strip a logout to not get into a loop.
159   }
160 }
161
162 if (count($errors)) {
163   $body->appendElement('p', ((count($errors) <= 1)
164                             ?_('The following error was detected')
165                             :_('The following errors were detected')).':');
166   $list = $body->appendElement('ul');
167   $list->setAttribute('class', 'flat warn');
168   foreach ($errors as $msg) {
169     $item = $list->appendElement('li', $msg);
170   }
171   $body->appendButton(_('Back'), 'history.back();');
172 }
173
174 // Send HTML to client.
175 print($document->saveHTML());
176 ?>