Manage login error messages directly from session management.
[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 S::logger()->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('access') == '' || !Cookie::has('uid')) {
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('uid'));
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('access')) {
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 $user = User::getSilent($uid);
97 $account = new GoogleAppsAccount($user);
98 if ($account->active() && $account->sync_password) {
99 $account->set_password($new_password);
100 }
101 }
102 }
103 }
104 if ($response != $expected_response) {
105 if (!S::logged()) {
106 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
107 } else {
108 Platal::page()->trigError('Mot de passe invalide');
109 }
110 S::logger($uid)->log('auth_fail', 'bad password');
111 return null;
112 }
113 return $uid;
114 }
115 return null;
116 }
117
118
119 /** Check auth.
120 */
121 protected function doAuth($level)
122 {
123 global $globals;
124
125 /* Cookie authentication
126 */
127 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
128 $this->tryCookie();
129 }
130 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
131 if (!S::logged()) {
132 S::set('auth', AUTH_COOKIE);
133 }
134 return S::i('auth_by_cookie');
135 }
136
137
138 /* We want to do auth... we must have infos from a form.
139 */
140 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
141 return null;
142 }
143
144 /** We come from an authentication form.
145 */
146 if (S::has('suid')) {
147 $suid = S::v('suid');
148 $login = $uname = $suid['uid'];
149 $redirect = false;
150 } else {
151 $uname = Env::v('username');
152 if (Env::v('domain') == "alias") {
153 $res = XDB::query('SELECT redirect
154 FROM virtual
155 INNER JOIN virtual_redirect USING(vid)
156 WHERE alias LIKE {?}',
157 $uname . '@' . $globals->mail->alias_dom);
158 $redirect = $res->fetchOneCell();
159 if ($redirect) {
160 $login = substr($redirect, 0, strpos($redirect, '@'));
161 } else {
162 $login = '';
163 }
164 } else {
165 $login = $uname;
166 $redirect = false;
167 }
168 }
169
170 $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && is_numeric($uname)) ? 'id' : 'alias');
171 if (!is_null($uid) && S::has('suid')) {
172 $suid = S::v('suid');
173 if ($suid['uid'] == $uid) {
174 $uid = S::i('uid');
175 } else {
176 $uid = null;
177 }
178 }
179 if (!is_null($uid)) {
180 S::set('auth', AUTH_MDP);
181 if (!S::has('suid')) {
182 if (Post::has('domain')) {
183 if (($domain = Post::v('domain', 'login')) == 'alias') {
184 Cookie::set('domain', 'alias', 300);
185 } else {
186 Cookie::kill('domain');
187 }
188 }
189 }
190 S::kill('challenge');
191 S::logger($uid)->log('auth_ok');
192 }
193 return $uid;
194 }
195
196 protected function startSessionAs($uid, $level)
197 {
198 if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) {
199 return false;
200 } else if (S::has('uid')) {
201 return true;
202 }
203 if ($level == AUTH_SUID) {
204 S::set('auth', AUTH_MDP);
205 }
206
207 // Retrieves main user properties.
208 $res = XDB::query("SELECT u.user_id AS uid, u.hruid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
209 matricule, password, FIND_IN_SET('femme', u.flags) AS femme,
210 q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash,
211 FIND_IN_SET('watch', u.flags) AS watch_account, q.last_version, g.g_account_name IS NOT NULL AS googleapps,
212 UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
213 FROM auth_user_md5 AS u
214 INNER JOIN auth_user_quick AS q USING(user_id)
215 LEFT JOIN gapps_accounts AS g ON (u.user_id = g.l_userid AND g.g_status = 'active')
216 LEFT JOIN logger.last_sessions AS ls ON (ls.uid = u.user_id)
217 LEFT JOIN logger.sessions AS s ON(s.id = ls.id)
218 WHERE u.user_id = {?} AND u.perms IN('admin', 'user')", $uid);
219 $sess = $res->fetchOneAssoc();
220 $perms = $sess['perms'];
221 unset($sess['perms']);
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 $logger->saveLastSession();
234 Cookie::set('uid', $uid, 300);
235
236 if (S::i('auth_by_cookie') == $uid || Post::v('remember', 'false') == 'true') {
237 $this->setAccessCookie(false, S::i('auth_by_cookie') != $uid);
238 } else {
239 $this->killAccessCookie();
240 }
241 }
242
243 // Finalizes the session setup.
244 S::set('perms', User::makePerms($perms));
245 $this->securityChecks();
246 $this->setSkin();
247 $this->updateNbNotifs();
248 check_redirect();
249
250 // We should not have to use this private data anymore
251 S::kill('auth_by_cookie');
252 return true;
253 }
254
255 private function securityChecks()
256 {
257 $mail_subject = array();
258 if (check_account()) {
259 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
260 }
261 if (check_ip('unsafe')) {
262 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
263 if (check_ip('ban')) {
264 send_warning_mail(implode(' - ', $mail_subject));
265 $this->destroy();
266 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
267 . 'Merci de contacter au plus vite '
268 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
269 return false;
270 }
271 }
272 if (count($mail_subject)) {
273 send_warning_mail(implode(' - ', $mail_subject));
274 }
275 }
276
277 public function tokenAuth($login, $token)
278 {
279 $res = XDB::query('SELECT u.hruid
280 FROM aliases AS a
281 INNER JOIN auth_user_md5 AS u ON (a.id = u.user_id AND u.perms IN ("admin", "user"))
282 INNER JOIN auth_user_quick AS q ON (a.id = q.user_id AND q.core_rss_hash = {?})
283 WHERE a.alias = {?} AND a.type != "homonyme"', $token, $login);
284 if ($res->numRows() == 1) {
285 $data = $res->fetchOneAssoc();
286 return new User($data['hruid'], $data);
287 }
288 return null;
289 }
290
291 public function makePerms($perm)
292 {
293 $flags = new PlFlagSet();
294 if ($perm == 'disabled' || $perm == 'ext') {
295 S::set('perms', $flags);
296 return;
297 }
298 $flags->addFlag(PERMS_USER);
299 if ($perm == 'admin') {
300 $flags->addFlag(PERMS_ADMIN);
301 }
302 S::set('perms', $flags);
303 }
304
305 public function setSkin()
306 {
307 if (S::logged() && (!S::has('skin') || S::has('suid'))) {
308 $uid = S::v('uid');
309 $res = XDB::query("SELECT skin_tpl
310 FROM auth_user_quick AS a
311 INNER JOIN skins AS s ON a.skin = s.id
312 WHERE user_id = {?} AND skin_tpl != ''", $uid);
313 S::set('skin', $res->fetchOneCell());
314 }
315 }
316
317 public function loggedLevel()
318 {
319 return AUTH_COOKIE;
320 }
321
322 public function sureLevel()
323 {
324 return AUTH_MDP;
325 }
326
327
328 public function updateNbNotifs()
329 {
330 require_once 'notifs.inc.php';
331 $n = select_notifs(false, S::i('uid'), S::v('watch_last'), false);
332 S::set('notifs', $n->numRows());
333 }
334
335 public function setAccessCookie($replace = false, $log = true) {
336 if (S::has('suid') || ($replace && !Cookie::blank('access'))) {
337 return;
338 }
339 require_once('secure_hash.inc.php');
340 Cookie::set('access', hash_encrypt(S::v('password')), 300, true);
341 if ($log) {
342 S::logger()->log('cookie_on');
343 }
344 }
345
346 public function killAccessCookie($log = true) {
347 Cookie::kill('access');
348 if ($log) {
349 S::logger()->log('cookie_off');
350 }
351 }
352
353 public function killLoginFormCookies() {
354 Cookie::kill('uid');
355 Cookie::kill('domain');
356 }
357 }
358
359 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
360 ?>