Introduces email type alias_aux for emails in auxiliary domains.
[platal.git] / classes / xorgsession.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
5e1513f6 3 * Copyright (C) 2003-2011 Polytechnique.org *
0337d704 4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
c0799142 22class XorgSession extends PlSession
0337d704 23{
45dd32db
FB
24 const INVALID_USER = -2;
25 const NO_COOKIE = -1;
26 const COOKIE_SUCCESS = 0;
27 const INVALID_COOKIE = 1;
28
c0799142
FB
29 public function __construct()
30 {
31 parent::__construct();
abde67b1
FB
32 }
33
c0799142 34 public function startAvailableAuth()
5480a216 35 {
c0799142 36 if (!S::logged()) {
45dd32db
FB
37 switch ($this->tryCookie()) {
38 case self::COOKIE_SUCCESS:
39 if (!$this->start(AUTH_COOKIE)) {
40 return false;
41 }
42 break;
43
44 case self::INVALID_USER:
45 case self::INVALID_COOKIE:
c0799142
FB
46 return false;
47 }
5480a216 48 }
0be07aa6 49 if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
9d214e8e 50 S::logger()->log("view_page", $_SERVER['REQUEST_URI']);
0337d704 51 }
c0799142 52 return true;
0337d704 53 }
54
1bf36cd1 55 /** Check the cookie and set the associated uid in the auth_by_cookie session variable.
c0799142
FB
56 */
57 private function tryCookie()
58 {
59 S::kill('auth_by_cookie');
40565fa2 60 if (Cookie::v('access') == '' || !Cookie::has('uid')) {
45dd32db 61 return self::NO_COOKIE;
c0799142 62 }
cab08090 63
c67ba12a
FB
64 $res = XDB::query('SELECT uid, password
65 FROM accounts
66 WHERE uid = {?} AND state = \'active\'',
8cd3dccc 67 Cookie::i('uid'));
c0799142
FB
68 if ($res->numRows() != 0) {
69 list($uid, $password) = $res->fetchOneRow();
45dd32db 70 if (sha1($password) == Cookie::v('access')) {
c0799142 71 S::set('auth_by_cookie', $uid);
45dd32db 72 return self::COOKIE_SUCCESS;
c0799142 73 } else {
45dd32db 74 return self::INVALID_COOKIE;
c0799142
FB
75 }
76 }
45dd32db 77 return self::INVALID_USER;
c0799142
FB
78 }
79
80 private function checkPassword($uname, $login, $response, $login_type)
5480a216 81 {
675f3174
FB
82 if ($login_type == 'alias') {
83 $res = XDB::query('SELECT a.uid, a.password
3d3797ad
SJ
84 FROM accounts AS a
85 INNER JOIN email_source_account AS e ON (e.uid = a.uid)
86 INNER JOIN email_virtual_domains AS d ON (e.domain = d.id)
87 WHERE e.email = {?} AND d.name = {?}',
88 $login, Platal::globals()->mail->domain);
675f3174
FB
89 } else {
90 $res = XDB::query('SELECT uid, password
91 FROM accounts
92 WHERE ' . $login_type . ' = {?}',
93 $login);
94 }
c0799142 95 if (list($uid, $password) = $res->fetchOneRow()) {
c67ba12a 96 $expected_response = sha1("$uname:$password:" . S::v('challenge'));
7a12b2ca 97 /* Deprecates len(password) > 10 conversion. */
c0799142 98 if ($response != $expected_response) {
86777849
FB
99 if (!S::logged()) {
100 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
101 } else {
102 Platal::page()->trigError('Mot de passe invalide');
103 }
732e5855 104 S::logger($uid)->log('auth_fail', 'bad password');
c0799142
FB
105 return null;
106 }
107 return $uid;
108 }
c6bad0e7 109 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
c0799142 110 return null;
0337d704 111 }
cab08090 112
0337d704 113
c0799142
FB
114 /** Check auth.
115 */
116 protected function doAuth($level)
0337d704 117 {
e74411f7 118 global $globals;
c0799142
FB
119
120 /* Cookie authentication
121 */
122 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
123 $this->tryCookie();
124 }
125 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
126 if (!S::logged()) {
127 S::set('auth', AUTH_COOKIE);
128 }
19fdac5d 129 return User::getSilentWithUID(S::i('auth_by_cookie'));
e74411f7 130 }
0337d704 131
c0799142
FB
132
133 /* We want to do auth... we must have infos from a form.
134 */
e64c8b61 135 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
c0799142 136 return null;
63528107 137 }
138
c0799142
FB
139 /** We come from an authentication form.
140 */
0c02607e
FB
141 if (S::suid()) {
142 $login = $uname = S::suid('uid');
675f3174 143 $loginType = 'uid';
e74411f7 144 } else {
675f3174
FB
145 $uname = Post::v('username');
146 if (Post::s('domain') == "alias") {
3d3797ad 147 $login = XDB::fetchOneCell('SELECT uid
08d33afc
SJ
148 FROM email_source_account
149 WHERE email = {?} AND type = \'alias_aux\'',
150 $uname);
3d3797ad 151 $loginType = 'uid';
675f3174
FB
152 } else if (Post::s('domain') == "ax") {
153 $login = $uname;
675f3174 154 $loginType = 'hruid';
0337d704 155 } else {
e74411f7 156 $login = $uname;
20edd399 157 $loginType = is_numeric($uname) ? 'uid' : 'alias';
0337d704 158 }
63528107 159 }
cab08090 160
675f3174 161 $uid = $this->checkPassword($uname, $login, Post::v('response'), $loginType);
0c02607e
FB
162 if (!is_null($uid) && S::suid()) {
163 if (S::suid('uid') == $uid) {
888465dd
FB
164 $uid = S::i('uid');
165 } else {
166 $uid = null;
167 }
168 }
c0799142
FB
169 if (!is_null($uid)) {
170 S::set('auth', AUTH_MDP);
0c02607e 171 if (!S::suid()) {
888465dd 172 if (Post::has('domain')) {
675f3174
FB
173 $domain = Post::v('domain', 'login');
174 if ($domain == 'alias') {
40565fa2 175 Cookie::set('domain', 'alias', 300);
675f3174
FB
176 } else if ($domain == 'ax') {
177 Cookie::set('domain', 'ax', 300);
888465dd 178 } else {
40565fa2 179 Cookie::kill('domain');
888465dd 180 }
e74411f7 181 }
182 }
c0799142 183 S::kill('challenge');
732e5855 184 S::logger($uid)->log('auth_ok');
c0799142 185 }
19fdac5d 186 return User::getSilentWithUID($uid);
c0799142 187 }
cab08090 188
e2cb093d 189 protected function startSessionAs($user, $level)
c0799142 190 {
b281eb7b 191 if ((!is_null(S::user()) && S::user()->id() != $user->id())
e2cb093d 192 || (S::has('uid') && S::i('uid') != $user->id())) {
c0799142
FB
193 return false;
194 } else if (S::has('uid')) {
195 return true;
196 }
888465dd
FB
197 if ($level == AUTH_SUID) {
198 S::set('auth', AUTH_MDP);
c0799142 199 }
70232020 200
2ab3486b 201 // Loads uid and hruid into the session for developement conveniance.
81b0f4ed 202 $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid, 'token' => $user->token, 'user' => $user));
6672b29b
VZ
203
204 // Starts the session's logger, and sets up the permanent cookie.
0c02607e
FB
205 if (S::suid()) {
206 S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
c0799142 207 } else {
e2cb093d
FB
208 S::logger()->saveLastSession();
209 Cookie::set('uid', $user->id(), 300);
a90cde48 210
e2cb093d
FB
211 if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
212 $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
c0799142 213 } else {
604dfd58 214 $this->killAccessCookie();
0337d704 215 }
63528107 216 }
b0b937fd 217
6672b29b 218 // Finalizes the session setup.
2ab3486b 219 $this->makePerms($user->perms, $user->is_admin);
c0799142
FB
220 $this->securityChecks();
221 $this->setSkin();
ebfdf077 222 $this->updateNbNotifs();
c0799142 223 check_redirect();
d0621f88
FB
224
225 // We should not have to use this private data anymore
226 S::kill('auth_by_cookie');
c0799142 227 return true;
0337d704 228 }
229
c0799142 230 private function securityChecks()
0337d704 231 {
c0799142
FB
232 $mail_subject = array();
233 if (check_account()) {
234 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
0337d704 235 }
c0799142
FB
236 if (check_ip('unsafe')) {
237 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
238 if (check_ip('ban')) {
239 send_warning_mail(implode(' - ', $mail_subject));
240 $this->destroy();
241 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
242 . 'Merci de contacter au plus vite '
243 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
244 return false;
245 }
0337d704 246 }
c0799142
FB
247 if (count($mail_subject)) {
248 send_warning_mail(implode(' - ', $mail_subject));
0337d704 249 }
250 }
251
8ebd6f86
VZ
252 /**
253 * The authentication schema is based on three query parameters:
254 * ?user=<hruid>&timestamp=<timestamp>&sig=<sig>
255 * where:
256 * - hruid is the hruid of the querying user
257 * - timestamp is the current UNIX timestamp, which has to be within a
258 * given distance of the server-side UNIX timestamp
259 * - sig is the HMAC of "<method>#<resource>#<payload>#<timestamp>" using
260 * a known secret of the user as the key.
261 *
262 * At the moment, the shared secret of the user is the sha1 hash of its
263 * password. This is temporary, though, until better support for tokens is
264 * implemented in plat/al.
265 * TODO(vzanotti): Switch to dedicated secrets for authentication.
266 */
267 public function apiAuth($method, $resource, $payload)
268 {
269 // Verify that the timestamp is within acceptable bounds.
270 $timestamp = Env::i('timestamp', 0);
271 if (abs($timestamp - time()) > Platal::globals()->api->timestamp_tolerance) {
272 return null;
273 }
274
275 // Retrieve the user corresponding to the forlife. Note that at the
276 // moment, other aliases are also accepted.
277 $user = User::getSilent(Env::s('user', ''));
278 if (is_null($user) || !$user->isActive()) {
279 return null;
280 }
281
282 // Determine the list of tokens associated with the user. At the moment,
283 // this is just the sha1 of the password.
284 $tokens = array($user->password());
285
286 // For each token, try to validate the signature.
287 $message = implode('#', array($method, $resource, $payload, $timestamp));
288 $signature = Env::s('sig');
289 foreach ($tokens as $token) {
290 $expected_signature = hash_hmac(
291 Platal::globals()->api->hmac_algo, $message, $token);
292 if ($signature == $expected_signature) {
293 return $user;
294 }
295 }
296
297 return null;
298 }
299
0d44ce42
FB
300 public function tokenAuth($login, $token)
301 {
1bf36cd1 302 $res = XDB::query('SELECT a.uid, a.hruid
c3e97f0c
FB
303 FROM accounts AS a
304 WHERE a.token = {?} AND a.hruid = {?} AND a.state = \'active\'',
305 $token, $login);
0d44ce42 306 if ($res->numRows() == 1) {
8c12f931 307 return new User(null, $res->fetchOneAssoc());
0d44ce42
FB
308 }
309 return null;
310 }
311
365ba8c3 312 protected function makePerms($perm, $is_admin)
bf517daf 313 {
365ba8c3 314 S::set('perms', User::makePerms($perm, $is_admin));
bf517daf 315 }
316
c0799142
FB
317 public function setSkin()
318 {
0c02607e 319 if (S::logged() && (!S::has('skin') || S::suid())) {
c67ba12a
FB
320 $res = XDB::query('SELECT skin_tpl
321 FROM accounts AS a
322 INNER JOIN skins AS s on (a.skin = s.id)
323 WHERE a.uid = {?} AND skin_tpl != \'\'', S::i('uid'));
c0799142 324 S::set('skin', $res->fetchOneCell());
5480a216 325 }
326 }
0337d704 327
faa06583
FB
328 public function loggedLevel()
329 {
330 return AUTH_COOKIE;
331 }
332
c0799142
FB
333 public function sureLevel()
334 {
335 return AUTH_MDP;
0337d704 336 }
ebfdf077
FB
337
338
339 public function updateNbNotifs()
340 {
009b8ab7
FB
341 require_once 'notifs.inc.php';
342 $user = S::user();
069ddda8 343 $n = Watch::getCount($user);
009b8ab7 344 S::set('notifs', $n);
ebfdf077 345 }
604dfd58
FB
346
347 public function setAccessCookie($replace = false, $log = true) {
0c02607e 348 if (S::suid() || ($replace && !Cookie::blank('access'))) {
604dfd58
FB
349 return;
350 }
45dd32db 351 Cookie::set('access', sha1(S::user()->password()), 300, true);
604dfd58
FB
352 if ($log) {
353 S::logger()->log('cookie_on');
354 }
355 }
356
357 public function killAccessCookie($log = true) {
358 Cookie::kill('access');
359 if ($log) {
360 S::logger()->log('cookie_off');
361 }
362 }
363
364 public function killLoginFormCookies() {
365 Cookie::kill('uid');
366 Cookie::kill('domain');
367 }
0337d704 368}
369
a7de4ef7 370// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 371?>