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