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