Port X.org session management to the new session format.
[platal.git] / include / xorg / session.inc.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 S::bootstrap('perms_backup', new PlFlagSet());
28 }
29
30 public function startAvailableAuth()
31 {
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);
39 } else if ($cookie == 1 || $cooke == -2) {
40 return false;
41 }
42 }
43 if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
44 $_SESSION['log']->log("view_page", $_SERVER['REQUEST_URI']);
45 }
46 return true;
47 }
48
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 }
57
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)
77 {
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) {
97 echo $response . '<br />';
98 echo $expected_response . '<br />';
99 echo $uname . '<br />' . $password . '<br />';
100 // $logger = S::logger($uid);
101 // $logger->log('auth_fail', 'bad password');
102 return null;
103 }
104 return $uid;
105 }
106 return null;
107 }
108
109
110 /** Check auth.
111 */
112 protected function doAuth($level)
113 {
114 global $globals;
115
116 /* Cookie authentication
117 */
118 if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
119 $this->tryCookie();
120 }
121 if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
122 if (!S::logged()) {
123 S::set('auth', AUTH_COOKIE);
124 }
125 return S::i('auth_by_cookie');
126 }
127
128
129 /* We want to do auth... we must have infos from a form.
130 */
131 if (!Env::has('username') || !Env::has('response') || !S::has('challenge')) {
132 return null;
133 }
134
135 /** We come from an authentication form.
136 */
137 if (S::has('suid')) {
138 $suid = S::v('suid');
139 $login = $uname = $suid['forlife'];
140 $redirect = false;
141 } else {
142 $uname = Env::v('username');
143
144 if (Env::v('domain') == "alias") {
145 $res = XDB::query('SELECT redirect
146 FROM virtual
147 INNER JOIN virtual_redirect USING(vid)
148 WHERE alias LIKE {?}',
149 $uname . '@' . $globals->mail->alias_dom);
150 $redirect = $res->fetchOneCell();
151 if ($redirect) {
152 $login = substr($redirect, 0, strpos($redirect, '@'));
153 } else {
154 $login = '';
155 }
156 } else {
157 $login = $uname;
158 $redirect = false;
159 }
160 }
161
162 $logger = S::logger();
163 $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias');
164 if (!is_null($uid)) {
165 S::set('auth', AUTH_MDP);
166 if (Post::has('domain')) {
167 if (($domain = Post::v('domain', 'login')) == 'alias') {
168 setcookie('ORGdomain', "alias", (time() + 25920000), '/', '', 0);
169 } else {
170 setcookie('ORGdomain', '', (time() - 3600), '/', '', 0);
171 }
172 // pour que la modification soit effective dans le reste de la page
173 $_COOKIE['ORGdomain'] = $domain;
174 }
175 S::kill('challenge');
176 if ($logger) {
177 $logger->log('auth_ok');
178 }
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 $res = XDB::query('SELECT u.user_id AS uid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
195 matricule, password, FIND_IN_SET(\'femme\', u.flags) AS femme,
196 a.alias AS forlife, a2.alias AS bestalias,
197 q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash,
198 FIND_IN_SET(\'watch\', u.flags) AS watch_account, q.last_version
199 FROM auth_user_md5 AS u
200 INNER JOIN auth_user_quick AS q USING(user_id)
201 INNER JOIN aliases AS a ON (u.user_id = a.id AND a.type = \'a_vie\')
202 INNER JOIN aliases AS a2 ON (u.user_id = a2.id AND FIND_IN_SET(\'bestalias\', a2.flags))
203 WHERE u.user_id = {?} AND u.perms IN(\'admin\', \'user\')', $uid);
204 $sess = $res->fetchOneAssoc();
205 $perms = $sess['perms'];
206 unset($sess['perms']);
207 $res = XDB::query('SELECT UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
208 FROM logger.sessions AS s
209 WHERE s.uid = {?} AND s.suid = 0
210 ORDER BY s.start DESC
211 LIMIT 1', $uid);
212 if ($res->numRows()) {
213 $sess = array_merge($sess, $res->fetchOneAssoc());
214 }
215 $suid = S::v('suid');
216
217 if ($suid) {
218 $logger = S::logger();
219 $logger->log("suid_start", S::v('forlife')." by {$suid['uid']}");
220 $sess['suid'] = $suid;
221 } else {
222 $logger = S::logger();
223 //$logger->log("connexion", Env::v('n'));
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);
228 if ($logger) {
229 $logger->log("cookie_on");
230 }
231 } else {
232 setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
233 if ($logger) {
234 $logger->log("cookie_off");
235 }
236 }
237 }
238
239 $_SESSION = array_merge($_SESSION, $sess);
240 $this->makePerms($perms);
241 $this->securityChecks();
242 $this->setSkin();
243 update_NbNotifs();
244 check_redirect();
245 return true;
246 }
247
248 private function securityChecks()
249 {
250 $mail_subject = array();
251 if (check_account()) {
252 $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
253 }
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 }
264 }
265 if (count($mail_subject)) {
266 send_warning_mail(implode(' - ', $mail_subject));
267 }
268 }
269
270 private function makePerms($perm)
271 {
272 $flags = new PlFlagSet();
273 if ($perm == 'disabled' || $perm == 'ext') {
274 return $flags;
275 }
276 $flags->addFlag(PERMS_USER);
277 if ($perm == 'admin') {
278 $flags->addFlag(PERMS_ADMIN);
279 }
280 S::set('perms', $flags);
281 S::set('perms_backup', $flags);
282 }
283
284 public function setSkin()
285 {
286 global $globals;
287 if (S::logged() && (!S::has('skin') || S::has('suid'))) {
288 $uid = S::v('uid');
289 $res = XDB::query("SELECT skin_tpl
290 FROM auth_user_quick AS a
291 INNER JOIN skins AS s ON a.skin = s.id
292 WHERE user_id = {?} AND skin_tpl != ''", $uid);
293 S::set('skin', $res->fetchOneCell());
294 }
295 }
296
297 public function sureLevel()
298 {
299 return AUTH_MDP;
300 }
301 }
302
303 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
304 ?>