Fixes module 'admin' (handler 'user') when no login is provided.
[platal.git] / classes / xorgsession.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 user_id 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 $res = XDB::query('SELECT a.uid, a.password
83 FROM accounts AS a
84 INNER JOIN aliases AS l ON (l.id = a.uid AND l.type != \'homonyme\')
85 WHERE l.' . $login_type . ' = {?} AND a.state = \'active\'',
86 $login);
87 if (list($uid, $password) = $res->fetchOneRow()) {
88 $expected_response = sha1("$uname:$password:" . S::v('challenge'));
89 /* XXX: Deprecates len(password) > 10 conversion */
90 if ($response != $expected_response) {
91 if (!S::logged()) {
92 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
93 } else {
94 Platal::page()->trigError('Mot de passe invalide');
95 }
96 S::logger($uid)->log('auth_fail', 'bad password');
97 return null;
98 }
99 return $uid;
100 }
101 Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
102 return null;
103 }
104
105
106 /** Check auth.
107 */
108 protected function doAuth($level)
109 {
110 global $globals;
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 User::getSilentWithValues(null, array('user_id' => S::i('auth_by_cookie')));
122 }
123
124
125 /* We want to do auth... we must have infos from a form.
126 */
127 if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
128 return null;
129 }
130
131 /** We come from an authentication form.
132 */
133 if (S::suid()) {
134 $login = $uname = S::suid('uid');
135 $redirect = false;
136 } else {
137 $uname = Env::v('username');
138 if (Env::v('domain') == "alias") {
139 $res = XDB::query('SELECT redirect
140 FROM virtual
141 INNER JOIN virtual_redirect USING(vid)
142 WHERE alias LIKE {?}',
143 $uname . '@' . $globals->mail->alias_dom);
144 $redirect = $res->fetchOneCell();
145 if ($redirect) {
146 $login = substr($redirect, 0, strpos($redirect, '@'));
147 } else {
148 $login = '';
149 }
150 } else {
151 $login = $uname;
152 $redirect = false;
153 }
154 }
155
156 $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && is_numeric($uname)) ? 'id' : 'alias');
157 if (!is_null($uid) && S::suid()) {
158 if (S::suid('uid') == $uid) {
159 $uid = S::i('uid');
160 } else {
161 $uid = null;
162 }
163 }
164 if (!is_null($uid)) {
165 S::set('auth', AUTH_MDP);
166 if (!S::suid()) {
167 if (Post::has('domain')) {
168 if (($domain = Post::v('domain', 'login')) == 'alias') {
169 Cookie::set('domain', 'alias', 300);
170 } else {
171 Cookie::kill('domain');
172 }
173 }
174 }
175 S::kill('challenge');
176 S::logger($uid)->log('auth_ok');
177 }
178 return User::getSilentWithValues(null, array('user_id' => $uid));
179 }
180
181 protected function startSessionAs($user, $level)
182 {
183 if ((!is_null(S::v('user')) && S::v('user')->id() != $user->id())
184 || (S::has('uid') && S::i('uid') != $user->id())) {
185 return false;
186 } else if (S::has('uid')) {
187 return true;
188 }
189 if ($level == AUTH_SUID) {
190 S::set('auth', AUTH_MDP);
191 }
192
193 // Retrieves main user properties.
194 /** TODO: Move needed informations to account tables */
195 /** TODO: Currently suppressed data are matricule, promo */
196 /** TODO: Use the User object to fetch all this */
197 $res = XDB::query("SELECT a.uid, a.hruid, a.display_name, a.full_name,
198 a.sex = 'female' AS femme, a.email_format,
199 a.token, FIND_IN_SET('watch', a.flags) AS watch_account,
200 UNIX_TIMESTAMP(fp.last_seen) AS banana_last, UNIX_TIMESTAMP(w.last) AS watch_last,
201 a.last_version, g.g_account_name IS NOT NULL AS googleapps,
202 UNIX_TIMESTAMP(s.start) AS lastlogin, s.host,
203 a.is_admin, at.perms
204 FROM accounts AS a
205 INNER JOIN account_types AS at ON(a.type = at.type)
206 INNER JOIN watch AS w ON(w.uid = a.uid)
207 LEFT JOIN forum_profiles AS fp ON(fp.uid = a.uid)
208 LEFT JOIN gapps_accounts AS g ON(a.uid = g.l_userid AND g.g_status = 'active')
209 LEFT JOIN logger.last_sessions AS ls ON (ls.uid = a.uid)
210 LEFT JOIN logger.sessions AS s ON(s.id = ls.id)
211 WHERE a.uid = {?} AND a.state = 'active'", $user->id());
212 $sess = $res->fetchOneAssoc();
213 $perms = $sess['perms'];
214 unset($sess['perms']);
215
216 // Loads the data into the real session.
217 $_SESSION = array_merge($_SESSION, $sess);
218
219 // Starts the session's logger, and sets up the permanent cookie.
220 if (S::suid()) {
221 S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
222 } else {
223 S::logger()->saveLastSession();
224 Cookie::set('uid', $user->id(), 300);
225
226 if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
227 $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
228 } else {
229 $this->killAccessCookie();
230 }
231 }
232
233 // Finalizes the session setup.
234 $this->makePerms($perms, S::b('is_admin'));
235 $this->securityChecks();
236 $this->setSkin();
237 $this->updateNbNotifs();
238 check_redirect();
239
240 // We should not have to use this private data anymore
241 S::kill('auth_by_cookie');
242 return true;
243 }
244
245 /** Start a session without authentication data for the given user.
246 * This is used to identify the user after his registration, to be
247 * removed after rewriting registration procedure.
248 * XXX: Temporary
249 */
250 public function startWeakSession($user)
251 {
252 if (!$this->startSessionAs($user, AUTH_MDP)) {
253 $this->destroy();
254 return false;
255 }
256 S::set('auth', AUTH_MDP);
257 return true;
258 }
259
260 private function securityChecks()
261 {
262 $mail_subject = array();
263 if (check_account()) {
264 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
265 }
266 if (check_ip('unsafe')) {
267 $mail_subject[] = 'Une IP surveillee a tente de se connecter';
268 if (check_ip('ban')) {
269 send_warning_mail(implode(' - ', $mail_subject));
270 $this->destroy();
271 Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
272 . 'Merci de contacter au plus vite '
273 . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
274 return false;
275 }
276 }
277 if (count($mail_subject)) {
278 send_warning_mail(implode(' - ', $mail_subject));
279 }
280 }
281
282 public function tokenAuth($login, $token)
283 {
284 $res = XDB::query('SELECT a.uid AS user_id, a.hruid
285 FROM aliases AS l
286 INNER JOIN accounts AS a ON (l.id = a.uid AND a.state = \'active\')
287 WHERE a.token = {?} AND l.alias = {?} AND l.type != \'homonyme\'',
288 $token, $login);
289 if ($res->numRows() == 1) {
290 return new User(null, $res->fetchOneAssoc());
291 }
292 return null;
293 }
294
295 protected function makePerms($perm, $is_admin)
296 {
297 S::set('perms', User::makePerms($perm, $is_admin));
298 }
299
300 public function setSkin()
301 {
302 if (S::logged() && (!S::has('skin') || S::suid())) {
303 $res = XDB::query('SELECT skin_tpl
304 FROM accounts AS a
305 INNER JOIN skins AS s on (a.skin = s.id)
306 WHERE a.uid = {?} AND skin_tpl != \'\'', S::i('uid'));
307 S::set('skin', $res->fetchOneCell());
308 }
309 }
310
311 public function loggedLevel()
312 {
313 return AUTH_COOKIE;
314 }
315
316 public function sureLevel()
317 {
318 return AUTH_MDP;
319 }
320
321
322 public function updateNbNotifs()
323 {
324 require_once 'notifs.inc.php';
325 $user = S::user();
326 $n = Watch::getCount($user);
327 S::set('notifs', $n);
328 }
329
330 public function setAccessCookie($replace = false, $log = true) {
331 if (S::suid() || ($replace && !Cookie::blank('access'))) {
332 return;
333 }
334 Cookie::set('access', sha1(S::user()->password()), 300, true);
335 if ($log) {
336 S::logger()->log('cookie_on');
337 }
338 }
339
340 public function killAccessCookie($log = true) {
341 Cookie::kill('access');
342 if ($log) {
343 S::logger()->log('cookie_off');
344 }
345 }
346
347 public function killLoginFormCookies() {
348 Cookie::kill('uid');
349 Cookie::kill('domain');
350 }
351 }
352
353 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
354 ?>