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