Ignore duplicates (Closes:#872)
[platal.git] / classes / xorgsession.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 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{
c0799142
FB
24 public function __construct()
25 {
26 parent::__construct();
27 S::bootstrap('perms_backup', new PlFlagSet());
abde67b1
FB
28 }
29
c0799142 30 public function startAvailableAuth()
5480a216 31 {
c0799142
FB
32 if (!(S::v('perms') instanceof PlFlagSet)) {
33 S::set('perms', S::v('perms_backup'));
34 }
35 if (!S::logged()) {
36 $cookie = $this->tryCookie();
37 if ($cookie == 0) {
38 return $this->start(AUTH_COOKIE);
998c070f 39 } else if ($cookie == 1 || $cookie == -2) {
c0799142
FB
40 return false;
41 }
5480a216 42 }
0be07aa6 43 if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
5480a216 44 $_SESSION['log']->log("view_page", $_SERVER['REQUEST_URI']);
0337d704 45 }
c0799142 46 return true;
0337d704 47 }
48
c0799142
FB
49 /** Check the cookie and set the associated user_id in the auth_by_cookie session variable.
50 */
51 private function tryCookie()
52 {
53 S::kill('auth_by_cookie');
54 if (Cookie::v('ORGaccess') == '' || !Cookie::has('ORGuid')) {
55 return -1;
56 }
cab08090 57
c0799142
FB
58 $res = XDB::query('SELECT user_id, password
59 FROM auth_user_md5
60 WHERE user_id = {?} AND perms IN(\'admin\', \'user\')',
61 Cookie::i('ORGuid'));
62 if ($res->numRows() != 0) {
63 list($uid, $password) = $res->fetchOneRow();
64 require_once 'secure_hash.inc.php';
65 $expected_value = hash_encrypt($password);
66 if ($expected_value == Cookie::v('ORGaccess')) {
67 S::set('auth_by_cookie', $uid);
68 return 0;
69 } else {
70 return 1;
71 }
72 }
73 return -2;
74 }
75
76 private function checkPassword($uname, $login, $response, $login_type)
5480a216 77 {
c0799142
FB
78 $res = XDB::query('SELECT u.user_id, u.password
79 FROM auth_user_md5 AS u
80 INNER JOIN aliases AS a ON (a.id = u.user_id AND type != \'homonyme\')
81 WHERE a.' . $login_type . ' = {?} AND u.perms IN(\'admin\', \'user\')',
82 $login);
83 if (list($uid, $password) = $res->fetchOneRow()) {
84 require_once 'secure_hash.inc.php';
85 $expected_response = hash_encrypt("$uname:$password:" . S::v('challenge'));
86 if ($response != $expected_response) {
87 $new_password = hash_xor(Env::v('xorpass'), $password);
88 $expected_response = hash_encrypt("$uname:$new_password:" . S::v('challenge'));
89 if ($response == $expected_response) {
90 XDB::execute('UPDATE auth_user_md5
91 SET password = {?}
92 WHERE user_id = {?}',
93 $new_password, $uid);
94 }
95 }
96 if ($response != $expected_response) {
732e5855 97 S::logger($uid)->log('auth_fail', 'bad password');
c0799142
FB
98 return null;
99 }
100 return $uid;
101 }
102 return null;
0337d704 103 }
cab08090 104
0337d704 105
c0799142
FB
106 /** Check auth.
107 */
108 protected function doAuth($level)
0337d704 109 {
e74411f7 110 global $globals;
c0799142
FB
111
112 /* Cookie authentication
113 */
114 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
115 $this->tryCookie();
116 }
117 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
118 if (!S::logged()) {
119 S::set('auth', AUTH_COOKIE);
120 }
121 return S::i('auth_by_cookie');
e74411f7 122 }
0337d704 123
c0799142
FB
124
125 /* We want to do auth... we must have infos from a form.
126 */
e64c8b61 127 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
c0799142 128 return null;
63528107 129 }
130
c0799142
FB
131 /** We come from an authentication form.
132 */
e74411f7 133 if (S::has('suid')) {
c0799142 134 $suid = S::v('suid');
e74411f7 135 $login = $uname = $suid['forlife'];
136 $redirect = false;
137 } else {
138 $uname = Env::v('username');
139
140 if (Env::v('domain') == "alias") {
c0799142
FB
141 $res = XDB::query('SELECT redirect
142 FROM virtual
143 INNER JOIN virtual_redirect USING(vid)
144 WHERE alias LIKE {?}',
145 $uname . '@' . $globals->mail->alias_dom);
e74411f7 146 $redirect = $res->fetchOneCell();
147 if ($redirect) {
148 $login = substr($redirect, 0, strpos($redirect, '@'));
149 } else {
c0799142 150 $login = '';
e74411f7 151 }
0337d704 152 } else {
e74411f7 153 $login = $uname;
154 $redirect = false;
0337d704 155 }
63528107 156 }
cab08090 157
c0799142
FB
158 $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias');
159 if (!is_null($uid)) {
160 S::set('auth', AUTH_MDP);
161 if (Post::has('domain')) {
162 if (($domain = Post::v('domain', 'login')) == 'alias') {
163 setcookie('ORGdomain', "alias", (time() + 25920000), '/', '', 0);
164 } else {
165 setcookie('ORGdomain', '', (time() - 3600), '/', '', 0);
e74411f7 166 }
c0799142
FB
167 // pour que la modification soit effective dans le reste de la page
168 $_COOKIE['ORGdomain'] = $domain;
e74411f7 169 }
c0799142 170 S::kill('challenge');
732e5855 171 S::logger($uid)->log('auth_ok');
c0799142
FB
172 }
173 return $uid;
174 }
cab08090 175
c0799142
FB
176 protected function startSessionAs($uid, $level)
177 {
178 if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) {
179 return false;
180 } else if (S::has('uid')) {
181 return true;
182 }
183 if ($level == -1) {
184 S::set('auth', AUTH_COOKIE);
185 }
186 unset($_SESSION['log']);
6672b29b
VZ
187
188 // Retrieves main user properties.
c0799142
FB
189 $res = XDB::query('SELECT u.user_id AS uid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
190 matricule, password, FIND_IN_SET(\'femme\', u.flags) AS femme,
191 a.alias AS forlife, a2.alias AS bestalias,
192 q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash,
1610f13a 193 FIND_IN_SET(\'watch\', u.flags) AS watch_account, q.last_version, g.g_account_name IS NOT NULL AS googleapps
c0799142
FB
194 FROM auth_user_md5 AS u
195 INNER JOIN auth_user_quick AS q USING(user_id)
196 INNER JOIN aliases AS a ON (u.user_id = a.id AND a.type = \'a_vie\')
197 INNER JOIN aliases AS a2 ON (u.user_id = a2.id AND FIND_IN_SET(\'bestalias\', a2.flags))
1610f13a 198 LEFT JOIN gapps_accounts AS g ON (u.user_id = g.l_userid AND g.g_status = \'active\')
c0799142
FB
199 WHERE u.user_id = {?} AND u.perms IN(\'admin\', \'user\')', $uid);
200 $sess = $res->fetchOneAssoc();
201 $perms = $sess['perms'];
202 unset($sess['perms']);
6672b29b
VZ
203
204 // Retrieves account usage information (last login, last host).
c0799142
FB
205 $res = XDB::query('SELECT UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
206 FROM logger.sessions AS s
207 WHERE s.uid = {?} AND s.suid = 0
208 ORDER BY s.start DESC
209 LIMIT 1', $uid);
210 if ($res->numRows()) {
211 $sess = array_merge($sess, $res->fetchOneAssoc());
212 }
c0799142 213
6672b29b
VZ
214 // Loads the data into the real session.
215 $_SESSION = array_merge($_SESSION, $sess);
216
217 // Starts the session's logger, and sets up the permanent cookie.
218 if (S::has('suid')) {
219 $suid = S::v('suid');
e4501b51 220 $logger = S::logger($uid);
6672b29b 221 $logger->log("suid_start", S::v('forlife') . " by " . $suid['uid']);
c0799142 222 } else {
e4501b51 223 $logger = S::logger($uid);
c0799142
FB
224 setcookie('ORGuid', $uid, (time() + 25920000), '/', '', 0);
225 if (Post::v('remember', 'false') == 'true') {
226 $cookie = hash_encrypt($sess['password']);
227 setcookie('ORGaccess', $cookie, (time() + 25920000), '/', '', 0);
63528107 228 if ($logger) {
c0799142 229 $logger->log("cookie_on");
63528107 230 }
c0799142
FB
231 } else {
232 setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
233 if ($logger) {
234 $logger->log("cookie_off");
0337d704 235 }
0337d704 236 }
63528107 237 }
b0b937fd 238
6672b29b 239 // Finalizes the session setup.
c0799142
FB
240 $this->makePerms($perms);
241 $this->securityChecks();
242 $this->setSkin();
ebfdf077 243 $this->updateNbNotifs();
c0799142
FB
244 check_redirect();
245 return true;
0337d704 246 }
247
c0799142 248 private function securityChecks()
0337d704 249 {
c0799142
FB
250 $mail_subject = array();
251 if (check_account()) {
252 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
0337d704 253 }
c0799142
FB
254 if (check_ip('unsafe')) {
255 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
256 if (check_ip('ban')) {
257 send_warning_mail(implode(' - ', $mail_subject));
258 $this->destroy();
259 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
260 . 'Merci de contacter au plus vite '
261 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
262 return false;
263 }
0337d704 264 }
c0799142
FB
265 if (count($mail_subject)) {
266 send_warning_mail(implode(' - ', $mail_subject));
0337d704 267 }
268 }
269
0d44ce42
FB
270 public function tokenAuth($login, $token)
271 {
272 // FIXME: we broke the session here because some RSS feeds (mainly wiki feeds) require
273 // a valid nome and checks the permissions. When the PlUser object will be ready, we'll
274 // be able to return a simple 'PlUser' object here without trying to alterate the
275 // session.
276 $res = XDB::query('SELECT u.user_id AS uid, u.perms, u.nom, u.nom_usage, u.prenom, u.promo, FIND_IN_SET(\'femme\', u.flags) AS sexe
277 FROM aliases AS a
278 INNER JOIN auth_user_md5 AS u ON (a.id = u.user_id AND u.perms IN ("admin", "user"))
279 INNER JOIN auth_user_quick AS q ON (a.id = q.user_id AND q.core_rss_hash = {?})
280 WHERE a.alias = {?} AND a.type != "homonyme"', $token, $login);
281 if ($res->numRows() == 1) {
282 $sess = $res->fetchOneAssoc();
283 if (!S::has('uid')) {
284 $_SESSION = $sess;
285 $this->makePerms($sess['perms']);
286 return S::i('uid');
287 } else if (S::i('uid') == $sess['uid']) {
288 return S::i('uid');
289 } else {
290 Platal::page()->kill('Invalid state. To be fixed when hruid is ready');
291 }
292 }
293 return null;
294 }
295
732e5855 296 public function makePerms($perm)
bf517daf 297 {
113f6de8 298 $flags = new PlFlagSet();
bf517daf 299 if ($perm == 'disabled' || $perm == 'ext') {
ab694eb5
FB
300 S::set('perms', $flags);
301 S::set('perms_backup', $flags);
302 return;
bf517daf 303 }
304 $flags->addFlag(PERMS_USER);
305 if ($perm == 'admin') {
306 $flags->addFlag(PERMS_ADMIN);
307 }
c0799142
FB
308 S::set('perms', $flags);
309 S::set('perms_backup', $flags);
bf517daf 310 }
311
c0799142
FB
312 public function setSkin()
313 {
314 global $globals;
315 if (S::logged() && (!S::has('skin') || S::has('suid'))) {
316 $uid = S::v('uid');
317 $res = XDB::query("SELECT skin_tpl
318 FROM auth_user_quick AS a
319 INNER JOIN skins AS s ON a.skin = s.id
320 WHERE user_id = {?} AND skin_tpl != ''", $uid);
321 S::set('skin', $res->fetchOneCell());
5480a216 322 }
323 }
0337d704 324
c0799142
FB
325 public function sureLevel()
326 {
327 return AUTH_MDP;
0337d704 328 }
ebfdf077
FB
329
330
331 public function updateNbNotifs()
332 {
333 require_once 'notifs.inc.php';
334 $n = select_notifs(false, S::i('uid'), S::v('watch_last'), false);
335 S::set('notifs', $n->numRows());
336 }
0337d704 337}
338
a7de4ef7 339// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 340?>