Xnet users should login with their curretn email address.
[platal.git] / classes / xorgsession.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
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
22 class XorgSession extends PlSession
23 {
24 const INVALID_USER = -2;
25 const NO_COOKIE = -1;
26 const COOKIE_SUCCESS = 0;
27 const INVALID_COOKIE = 1;
28
29 public function __construct()
30 {
31 parent::__construct();
32 }
33
34 public function startAvailableAuth()
35 {
36 if (!S::logged()) {
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:
46 return false;
47 }
48 }
49 if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
50 S::logger()->log("view_page", $_SERVER['REQUEST_URI']);
51 }
52 return true;
53 }
54
55 /** Check the cookie and set the associated uid in the auth_by_cookie session variable.
56 */
57 private function tryCookie()
58 {
59 S::kill('auth_by_cookie');
60 if (Cookie::v('access') == '' || !Cookie::has('uid')) {
61 return self::NO_COOKIE;
62 }
63
64 $res = XDB::query('SELECT uid, password
65 FROM accounts
66 WHERE uid = {?} AND state = \'active\'',
67 Cookie::i('uid'));
68 if ($res->numRows() != 0) {
69 list($uid, $password) = $res->fetchOneRow();
70 if (sha1($password) == Cookie::v('access')) {
71 S::set('auth_by_cookie', $uid);
72 return self::COOKIE_SUCCESS;
73 } else {
74 return self::INVALID_COOKIE;
75 }
76 }
77 return self::INVALID_USER;
78 }
79
80 private function checkPassword($uname, $login, $response, $login_type)
81 {
82 if ($login_type == 'alias') {
83 $res = XDB::query('SELECT a.uid, a.password
84 FROM accounts AS a
85 INNER JOIN email_source_account AS e ON (e.uid = a.uid)
86 WHERE e.email = {?}',
87 $login);
88 } else {
89 $res = XDB::query('SELECT uid, password
90 FROM accounts
91 WHERE ' . $login_type . ' = {?}',
92 $login);
93 }
94 if (list($uid, $password) = $res->fetchOneRow()) {
95 $expected_response = sha1("$uname:$password:" . S::v('challenge'));
96 /* Deprecates len(password) > 10 conversion. */
97 if ($response != $expected_response) {
98 if (!S::logged()) {
99 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
100 } else {
101 Platal::page()->trigError('Mot de passe invalide');
102 }
103 S::logger($uid)->log('auth_fail', 'bad password');
104 return null;
105 }
106 return $uid;
107 }
108 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
109 return null;
110 }
111
112
113 /** Check auth.
114 */
115 protected function doAuth($level)
116 {
117 global $globals;
118
119 /* Cookie authentication
120 */
121 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
122 $this->tryCookie();
123 }
124 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
125 if (!S::logged()) {
126 S::set('auth', AUTH_COOKIE);
127 }
128 return User::getSilentWithUID(S::i('auth_by_cookie'));
129 }
130
131
132 /* We want to do auth... we must have infos from a form.
133 */
134 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
135 return null;
136 }
137
138 /** We come from an authentication form.
139 */
140 if (S::suid()) {
141 $login = $uname = S::suid('uid');
142 $loginType = 'uid';
143 } else {
144 $uname = Post::v('username');
145 if (Post::s('domain') == "alias") {
146 $login = XDB::fetchOneCell('SELECT uid
147 FROM email_source_account
148 WHERE email = {?} AND type = \'alias_aux\'',
149 $uname);
150 $loginType = 'uid';
151 } else if (Post::s('domain') == 'hruid') {
152 $login = $uname;
153 $loginType = 'hruid';
154 } else if ((Post::s('domain') == 'email')) {
155 $login = XDB::fetchOneCell('SELECT SQL_CALC_FOUND_ROWS uid
156 FROM accounts
157 WHERE email = {?}',
158 $uname);
159 if (!(XDB::fetchOneCell('SELECT FOUND_ROWS()') == 1)) {
160 $login =null;
161 }
162 $loginType = 'uid';
163 } else {
164 $login = $uname;
165 $loginType = is_numeric($uname) ? 'uid' : 'alias';
166 }
167 }
168
169 $uid = $this->checkPassword($uname, $login, Post::v('response'), $loginType);
170 if (!is_null($uid) && S::suid()) {
171 if (S::suid('uid') == $uid) {
172 $uid = S::i('uid');
173 } else {
174 $uid = null;
175 }
176 }
177 if (!is_null($uid)) {
178 S::set('auth', AUTH_MDP);
179 if (!S::suid()) {
180 if (Post::has('domain')) {
181 $domain = Post::v('domain', 'login');
182 if ($domain == 'alias') {
183 Cookie::set('domain', 'alias', 300);
184 } else if ($domain == 'ax') {
185 Cookie::set('domain', 'ax', 300);
186 } else {
187 Cookie::kill('domain');
188 }
189 }
190 }
191 S::kill('challenge');
192 S::logger($uid)->log('auth_ok');
193 }
194 return User::getSilentWithUID($uid);
195 }
196
197 protected function startSessionAs($user, $level)
198 {
199 if ((!is_null(S::user()) && S::user()->id() != $user->id())
200 || (S::has('uid') && S::i('uid') != $user->id())) {
201 return false;
202 } else if (S::has('uid')) {
203 return true;
204 }
205 if ($level == AUTH_SUID) {
206 S::set('auth', AUTH_MDP);
207 }
208
209 // Loads uid and hruid into the session for developement conveniance.
210 $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid, 'token' => $user->token, 'user' => $user));
211
212 // Starts the session's logger, and sets up the permanent cookie.
213 if (S::suid()) {
214 S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
215 } else {
216 S::logger()->saveLastSession();
217 Cookie::set('uid', $user->id(), 300);
218
219 if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
220 $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
221 } else {
222 $this->killAccessCookie();
223 }
224 }
225
226 // Finalizes the session setup.
227 $this->makePerms($user->perms, $user->is_admin);
228 $this->securityChecks();
229 $this->setSkin();
230 $this->updateNbNotifs();
231 check_redirect();
232
233 // We should not have to use this private data anymore
234 S::kill('auth_by_cookie');
235 return true;
236 }
237
238 private function securityChecks()
239 {
240 $mail_subject = array();
241 if (check_account()) {
242 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
243 }
244 if (check_ip('unsafe')) {
245 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
246 if (check_ip('ban')) {
247 send_warning_mail(implode(' - ', $mail_subject));
248 $this->destroy();
249 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
250 . 'Merci de contacter au plus vite '
251 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
252 return false;
253 }
254 }
255 if (count($mail_subject)) {
256 send_warning_mail(implode(' - ', $mail_subject));
257 }
258 }
259
260 /**
261 * The authentication schema is based on three query parameters:
262 * ?user=<hruid>&timestamp=<timestamp>&sig=<sig>
263 * where:
264 * - hruid is the hruid of the querying user
265 * - timestamp is the current UNIX timestamp, which has to be within a
266 * given distance of the server-side UNIX timestamp
267 * - sig is the HMAC of "<method>#<resource>#<payload>#<timestamp>" using
268 * a known secret of the user as the key.
269 *
270 * At the moment, the shared secret of the user is the sha1 hash of its
271 * password. This is temporary, though, until better support for tokens is
272 * implemented in plat/al.
273 * TODO(vzanotti): Switch to dedicated secrets for authentication.
274 */
275 public function apiAuth($method, $resource, $payload)
276 {
277 // Verify that the timestamp is within acceptable bounds.
278 $timestamp = Env::i('timestamp', 0);
279 if (abs($timestamp - time()) > Platal::globals()->api->timestamp_tolerance) {
280 return null;
281 }
282
283 // Retrieve the user corresponding to the forlife. Note that at the
284 // moment, other aliases are also accepted.
285 $user = User::getSilent(Env::s('user', ''));
286 if (is_null($user) || !$user->isActive()) {
287 return null;
288 }
289
290 // Determine the list of tokens associated with the user. At the moment,
291 // this is just the sha1 of the password.
292 $tokens = array($user->password());
293
294 // For each token, try to validate the signature.
295 $message = implode('#', array($method, $resource, $payload, $timestamp));
296 $signature = Env::s('sig');
297 foreach ($tokens as $token) {
298 $expected_signature = hash_hmac(
299 Platal::globals()->api->hmac_algo, $message, $token);
300 if ($signature == $expected_signature) {
301 return $user;
302 }
303 }
304
305 return null;
306 }
307
308 public function tokenAuth($login, $token)
309 {
310 $res = XDB::query('SELECT a.uid, a.hruid
311 FROM accounts AS a
312 WHERE a.token = {?} AND a.hruid = {?} AND a.state = \'active\'',
313 $token, $login);
314 if ($res->numRows() == 1) {
315 return new User(null, $res->fetchOneAssoc());
316 }
317 return null;
318 }
319
320 protected function makePerms($perm, $is_admin)
321 {
322 S::set('perms', User::makePerms($perm, $is_admin));
323 }
324
325 public function setSkin()
326 {
327 if (S::logged() && (!S::has('skin') || S::suid())) {
328 $res = XDB::query('SELECT skin_tpl
329 FROM accounts AS a
330 INNER JOIN skins AS s on (a.skin = s.id)
331 WHERE a.uid = {?} AND skin_tpl != \'\'', S::i('uid'));
332 S::set('skin', $res->fetchOneCell());
333 }
334 }
335
336 public function loggedLevel()
337 {
338 return AUTH_COOKIE;
339 }
340
341 public function sureLevel()
342 {
343 return AUTH_MDP;
344 }
345
346
347 public function updateNbNotifs()
348 {
349 require_once 'notifs.inc.php';
350 $user = S::user();
351 $n = Watch::getCount($user);
352 S::set('notifs', $n);
353 }
354
355 public function setAccessCookie($replace = false, $log = true) {
356 if (S::suid() || ($replace && !Cookie::blank('access'))) {
357 return;
358 }
359 Cookie::set('access', sha1(S::user()->password()), 300, true);
360 if ($log) {
361 S::logger()->log('cookie_on');
362 }
363 }
364
365 public function killAccessCookie($log = true) {
366 Cookie::kill('access');
367 if ($log) {
368 S::logger()->log('cookie_off');
369 }
370 }
371
372 public function killLoginFormCookies() {
373 Cookie::kill('uid');
374 Cookie::kill('domain');
375 }
376 }
377
378 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
379 ?>