Port X.net session to the new schema.
[platal.git] / include / xorg / session.inc.php
index f1a05f6..b63420a 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2006 Polytechnique.org                              *
+ *  Copyright (C) 2003-2008 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-require_once 'platal/session.inc.php';
-
-// {{{ class XorgSession
-
-class XorgSession
+class XorgSession extends PlSession
 {
-    var $challenge;
+    public function __construct()
+    {
+        parent::__construct();
+        S::bootstrap('perms_backup', new PlFlagSet());
+    }
 
-    // {{{ function XorgSession()
+    public function startAvailableAuth()
+    {
+        if (!(S::v('perms') instanceof PlFlagSet)) {
+            S::set('perms', S::v('perms_backup'));
+        }
+        if (!S::logged()) {
+            $cookie = $this->tryCookie();
+            if ($cookie == 0) {
+                return $this->start(AUTH_COOKIE);
+            } else if ($cookie == 1 || $cooke == -2) {
+                return false;
+            }
+        }
+        if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
+            $_SESSION['log']->log("view_page", $_SERVER['REQUEST_URI']);
+        }
+        return true;
+    }
 
-    function XorgSession()
+    /** Check the cookie and set the associated user_id in the auth_by_cookie session variable.
+     */
+    private function tryCookie()
     {
-        $this->challenge = md5(uniqid(rand(), 1));
+        Platal::page()->trigError("Trying cookie");
+        S::kill('auth_by_cookie');
+        if (Cookie::v('ORGaccess') == '' || !Cookie::has('ORGuid')) {
+            return -1;
+        }
 
-       if (!Session::has('uid')) {
-           try_cookie();
+        $res = XDB::query('SELECT  user_id, password
+                             FROM  auth_user_md5
+                            WHERE  user_id = {?} AND perms IN(\'admin\', \'user\')',
+                         Cookie::i('ORGuid'));
+        if ($res->numRows() != 0) {
+            list($uid, $password) = $res->fetchOneRow();
+            require_once 'secure_hash.inc.php';
+            $expected_value = hash_encrypt($password);
+            if ($expected_value == Cookie::v('ORGaccess')) {
+                S::set('auth_by_cookie', $uid);
+                return 0;
+            } else {
+                return 1;
+            }
         }
-       set_skin();
+        return -2;
     }
 
-    // }}}
-    // {{{ function init
-    
-    function init() {
-        @session_start();
-        if (!Session::has('session')) {
-            $_SESSION['session'] = new XorgSession;
+    private function checkPassword($uname, $login, $response, $login_type)
+    {
+        $res = XDB::query('SELECT  u.user_id, u.password
+                             FROM  auth_user_md5 AS u
+                       INNER JOIN  aliases       AS a ON (a.id = u.user_id AND type != \'homonyme\')
+                             WHERE  a.' . $login_type . ' = {?} AND u.perms IN(\'admin\', \'user\')',
+                          $login);
+        if (list($uid, $password) = $res->fetchOneRow()) {
+            require_once 'secure_hash.inc.php';
+            $expected_response = hash_encrypt("$uname:$password:" . S::v('challenge'));
+            if ($response != $expected_response) {
+                $new_password = hash_xor(Env::v('xorpass'), $password);
+                $expected_response = hash_encrypt("$uname:$new_password:" . S::v('challenge'));
+                if ($response == $expected_response) {
+                      XDB::execute('UPDATE  auth_user_md5
+                                       SET  password = {?}
+                                     WHERE  user_id = {?}',
+                                   $new_password, $uid);
+                }
+            }
+            if ($response != $expected_response) {
+                S::logger($uid)->log('auth_fail', 'bad password');
+                return null;
+            }
+            return $uid;
         }
+        return null;
     }
-    
-    // }}}
-    // {{{ function destroy()
-    
-    function destroy() {
-        @session_destroy();
-        unset($_SESSION);
-        XorgSession::init();
-    }
-    
-    // }}}
-    // {{{ function doAuth()
 
-    /** Try to do an authentication.
-     *
-     * @param page the calling page (by reference)
+
+    /** Check auth.
      */
-    function doAuth(&$page,$new_name=false)
+    protected function doAuth($level)
     {
-       global $globals;
-       if (identified()) { // ok, c'est bon, on n'a rien à faire
-           return true;
-       }
+        global $globals;
 
-        if (Session::has('session')) {
-            $session =& Session::getMixed('session');
+        /* Cookie authentication
+         */
+        if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
+            $this->tryCookie();
         }
-        if (Env::has('username') && Env::has('response') && isset($session->challenge))
-       {
-           // si on vient de recevoir une identification par passwordpromptscreen.tpl
-           // ou passwordpromptscreenlogged.tpl
-            $uname = Env::get('username');
-            
-            if (Env::get('domain') == "alias") {
-            
-                $res = $globals->xdb->query(
-                    "SELECT redirect
-                       FROM virtual
-                 INNER JOIN virtual_redirect USING(vid)
-                      WHERE alias LIKE {?}", $uname."@".$globals->mail->alias_dom);
+        if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
+            if (!S::logged()) {
+                S::set('auth', AUTH_COOKIE);
+            }
+            return S::i('auth_by_cookie');
+        }
+
+
+        /* We want to do auth... we must have infos from a form.
+         */
+        if (!Env::has('username') || !Env::has('response') || !S::has('challenge')) {
+            return null;
+        }
+
+        /** We come from an authentication form.
+         */
+        if (S::has('suid')) {
+            $suid  = S::v('suid');
+            $login = $uname = $suid['forlife'];
+            $redirect = false;
+        } else {
+            $uname = Env::v('username');
+
+            if (Env::v('domain') == "alias") {
+                $res = XDB::query('SELECT  redirect
+                                     FROM  virtual
+                               INNER JOIN  virtual_redirect USING(vid)
+                                    WHERE  alias LIKE {?}',
+                                   $uname . '@' . $globals->mail->alias_dom);
                 $redirect = $res->fetchOneCell();
                 if ($redirect) {
                     $login = substr($redirect, 0, strpos($redirect, '@'));
                 } else {
-                    $login = "";
+                    $login = '';
                 }
             } else {
                 $login = $uname;
+                $redirect = false;
             }
-    
-           $field = (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias';
-           $res   = $globals->xdb->query(
-                        "SELECT  u.user_id, u.password
-                           FROM  auth_user_md5 AS u
-                     INNER JOIN  aliases       AS a ON ( a.id=u.user_id AND type!='homonyme' )
-                          WHERE  a.$field = {?} AND u.perms IN('admin','user')", $login);
-    
-            $logger =& Session::getMixed('log');
-           if (list($uid, $password) = $res->fetchOneRow()) {
-                   require_once('secure_hash.inc.php');
-                       $expected_response=hash_encrypt("$uname:$password:{$session->challenge}");
-                       // le password de la base est peut-être encore encodé en md5
-                       if (Env::get('response') != $expected_response) {
-                         $new_password = hash_xor(Env::get('xorpass'), $password);
-                         $expected_response = hash_encrypt("$uname:$new_password:{$session->challenge}");
-                         if (Env::get('response') == $expected_response) {
-                             $globals->xdb->execute("UPDATE auth_user_md5 SET password = {?} WHERE user_id = {?}", $new_password, $uid);
-                         }
-                       }
-                       if (Env::get('response') == $expected_response) {
-                    if (Env::has('domain')) {
-                        if (($domain = Env::get('domain', 'login')) == 'alias') {
-                            setcookie('ORGdomain', "alias", (time()+25920000), '/', '', 0);
-                        } else {
-                            setcookie('ORGdomain', '', (time()-3600), '/', '', 0);
-                        }
-                        // pour que la modification soit effective dans le reste de la page
-                        $_COOKIE['ORGdomain'] = $domain;
-                    }
-    
-                           unset($session->challenge);
-                           if ($logger) {
-                               $logger->log('auth_ok');
-                    }
-                           start_connexion($uid, true);
-                    if (Env::get('remember', 'false') == 'true') {
-                        $cookie = hash_encrypt(Session::get('password'));
-                        setcookie('ORGaccess',$cookie,(time()+25920000),'/','',0);
-                        if ($logger) {
-                            $logger->log("cookie_on");
-                        }
-                    } else {
-                        setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
-                        
-                        if ($logger) {
-                            $logger->log("cookie_off");
-                        }
-                    }
-                           return true;
-                       } elseif ($logger) {
-                    $logger->log('auth_fail','bad password');
+        }
+
+        $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias');
+        if (!is_null($uid)) {
+            S::set('auth', AUTH_MDP);
+            if (Post::has('domain')) {
+                if (($domain = Post::v('domain', 'login')) == 'alias') {
+                    setcookie('ORGdomain', "alias", (time() + 25920000), '/', '', 0);
+                } else {
+                    setcookie('ORGdomain', '', (time() - 3600), '/', '', 0);
                 }
-            } elseif ($logger) {
-                    $logger->log('auth_fail','bad login');
+                // pour que la modification soit effective dans le reste de la page
+                $_COOKIE['ORGdomain'] = $domain;
             }
-       }
-        $this->doLogin($page,$new_name);
+            S::kill('challenge');
+            S::logger($uid)->log('auth_ok');
+        }
+        return $uid;
     }
 
-    // }}}
-    // {{{ function doAuthCookie()
-
-    /** Try to do a cookie-based authentication.
-     *
-     * @param page the calling page (by reference)
-     */
-    function doAuthCookie(&$page)
+    protected function startSessionAs($uid, $level)
     {
-       if (logged()) {
-           return;
+        if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) {
+            return false;
+        } else if (S::has('uid')) {
+            return true;
         }
-
-       if (Env::has('username') and Env::has('response')) {
-           return $this->doAuth($page);
+        if ($level == -1) {
+            S::set('auth', AUTH_COOKIE);
         }
-
-       if ($r = try_cookie()) {
-           return $this->doAuth($page,($r>0));
+        unset($_SESSION['log']);
+        $res  = XDB::query('SELECT  u.user_id AS uid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
+                                    matricule, password, FIND_IN_SET(\'femme\', u.flags) AS femme,
+                                    a.alias AS forlife, a2.alias AS bestalias,
+                                    q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash,
+                                    FIND_IN_SET(\'watch\', u.flags) AS watch_account, q.last_version
+                              FROM  auth_user_md5   AS u
+                        INNER JOIN  auth_user_quick AS q  USING(user_id)
+                        INNER JOIN  aliases         AS a  ON (u.user_id = a.id AND a.type = \'a_vie\')
+                        INNER JOIN  aliases         AS a2 ON (u.user_id = a2.id AND FIND_IN_SET(\'bestalias\', a2.flags))
+                             WHERE  u.user_id = {?} AND u.perms IN(\'admin\', \'user\')', $uid);
+        $sess = $res->fetchOneAssoc();
+        $perms = $sess['perms'];
+        unset($sess['perms']);
+        $res = XDB::query('SELECT  UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
+                             FROM  logger.sessions AS s
+                            WHERE  s.uid = {?} AND s.suid = 0
+                         ORDER BY  s.start DESC
+                            LIMIT  1', $uid);
+        if ($res->numRows()) {
+            $sess = array_merge($sess, $res->fetchOneAssoc());
         }
-    }
-
-    // }}}
-    // {{{ function doLogin()
+        $suid = S::v('suid');
 
-    /** Display login screen.
-     */
-    function doLogin(&$page, $new_name=false)
-    {
-        if (logged() and !$new_name) {
-            $page->changeTpl('password_prompt_logged.tpl');
-            $page->addJsLink('javascript/do_challenge_response_logged.js');
-            $page->assign("xorg_tpl", "password_prompt_logged.tpl");
-            $page->run();
+        if ($suid) {
+            $logger = S::logger();
+            $logger->log("suid_start", S::v('forlife')." by {$suid['uid']}");
+            $sess['suid'] = $suid;
         } else {
-            $page->changeTpl('password_prompt.tpl');
-            $page->addJsLink('javascript/do_challenge_response.js');
-            $page->assign("xorg_tpl", "password_prompt.tpl");
-            
-            global $globals;
-            if ($globals->mail->alias_dom) {
-                $page->assign("domains", Array(
-                    $globals->mail->domain."/".$globals->mail->domain2,
-                    $globals->mail->alias_dom."/".$globals->mail->alias_dom2));
-                $page->assign("domains_value", Array("login", "alias"));
-                $page->assign("r_domain", Cookie::get('ORGdomain', 'login'));
+            $logger = S::logger();
+            //$logger->log("connexion", Env::v('n'));
+            setcookie('ORGuid', $uid, (time() + 25920000), '/', '', 0);
+            if (Post::v('remember', 'false') == 'true') {
+                $cookie = hash_encrypt($sess['password']);
+                setcookie('ORGaccess', $cookie, (time() + 25920000), '/', '', 0);
+                if ($logger) {
+                    $logger->log("cookie_on");
+                }
+            } else {
+                setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
+                if ($logger) {
+                    $logger->log("cookie_off");
+                }
             }
-           $page->run();
-       }
-       exit;
-    }
-
-    // }}}
-}
-
-// }}}
-// {{{ function try_cookie()
+        }
 
-/** réalise la récupération de $_SESSION pour qqn avec cookie
- * @return  int     0 if all OK, -1 if no cookie, 1 if cookie with bad hash,
- *                  -2 should not happen
- */
-function try_cookie()
-{
-    global $globals;
-    if (Cookie::get('ORGaccess') == '' or !Cookie::has('ORGuid')) {
-       return -1;
+        $_SESSION = array_merge($_SESSION, $sess);
+        $this->makePerms($perms);
+        $this->securityChecks();
+        $this->setSkin();
+        update_NbNotifs();
+        check_redirect();
+        return true;
     }
 
-    $res = @$globals->xdb->query(
-            "SELECT user_id,password FROM auth_user_md5 WHERE user_id = {?} AND perms IN('admin','user')",
-            Cookie::getInt('ORGuid')
-    );
-    if ($res->numRows() != 0) {
-       list($uid, $password) = $res->fetchOneRow();
-       require_once('secure_hash.inc.php');
-       $expected_value       = hash_encrypt($password);
-       if ($expected_value == Cookie::get('ORGaccess')) {
-           start_connexion($uid, false);
-           return 0;
-       } else {
-            return 1;
+    private function securityChecks()
+    {
+        $mail_subject = array();
+        if (check_account()) {
+            $mail_subject[] = 'Connexion d\'un utilisateur surveillé';
+        }
+        if (check_ip('unsafe')) {
+            $mail_subject[] = 'Une IP surveillee a tente de se connecter';
+            if (check_ip('ban')) {
+                send_warning_mail(implode(' - ', $mail_subject));
+                $this->destroy();
+                Platal::page()->kill('Une erreur est survenue lors de la procédure d\'authentification. '
+                                    . 'Merci de contacter au plus vite '
+                                    . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>');
+                return false;
+            }
+        }
+        if (count($mail_subject)) {
+            send_warning_mail(implode(' - ', $mail_subject));
         }
     }
 
-    return -2;
-}
-
-// }}}
-// {{{ function start_connexion()
-
-/** place les variables de session dépendants de auth_user_md5
- * et met à jour les dates de dernière connexion si nécessaire
- * @return void
- * @see controlpermanent.inc.php controlauthentication.inc.php
- */
-function start_connexion ($uid, $identified)
-{
-    global $globals;
-    $res  = $globals->xdb->query("
-       SELECT  u.user_id AS uid, prenom, nom, perms, promo, matricule, password, FIND_IN_SET('femme', u.flags) AS femme,
-                UNIX_TIMESTAMP(s.start) AS lastlogin, s.host, a.alias AS forlife, a2.alias AS bestalias,
-                q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash
-          FROM  auth_user_md5   AS u
-    INNER JOIN  auth_user_quick AS q  USING(user_id)
-    INNER JOIN aliases         AS a  ON (u.user_id = a.id AND a.type='a_vie')
-    INNER JOIN  aliases                AS a2 ON (u.user_id = a2.id AND FIND_IN_SET('bestalias',a2.flags))
-     LEFT JOIN  logger.sessions AS s  ON (s.uid=u.user_id AND s.suid=0)
-         WHERE  u.user_id = {?} AND u.perms IN('admin','user')
-      ORDER BY  s.start DESC
-         LIMIT  1", $uid);
-    $sess = $res->fetchOneAssoc();
-    $suid = Session::getMixed('suid');
-    
-    if ($suid) {
-       $logger = new DiogenesCoreLogger($uid, $suid);
-       $logger->log("suid_start", Session::get('forlife')." by {$suid['uid']}");
-        $sess['suid'] = $suid;
-    } else {
-        $logger = Session::getMixed('log', new DiogenesCoreLogger($uid));
-        $logger->log("connexion", $_SERVER['PHP_SELF']);
-        setcookie('ORGuid', $uid, (time()+25920000), '/', '', 0);
+    public function makePerms($perm)
+    {
+        $flags = new PlFlagSet();
+        if ($perm == 'disabled' || $perm == 'ext') {
+            S::set('perms', $flags);
+            S::set('perms_backup', $flags);
+            return;
+        }
+        $flags->addFlag(PERMS_USER);
+        if ($perm == 'admin') {
+            $flags->addFlag(PERMS_ADMIN);
+        }
+        S::set('perms', $flags);
+        S::set('perms_backup', $flags);
     }
 
-    $_SESSION         = $sess;
-    $_SESSION['log']  = $logger;
-    $_SESSION['auth'] = ($identified ? AUTH_MDP : AUTH_COOKIE);
-    set_skin();
-}
-
-// }}}
-// {{{ function set_skin()
-
-function set_skin()
-{
-    global $globals;
-    if (logged() && $globals->skin->enable) {
-        $uid = Session::getInt('uid');
-       $res = $globals->xdb->query("SELECT  skin,skin_tpl
-                                      FROM  auth_user_quick AS a
-                                INNER JOIN  skins           AS s ON a.skin=s.id
-                                     WHERE  user_id = {?} AND skin_tpl != ''", $uid);
-       if (list($_SESSION['skin_id'], $_SESSION['skin']) = $res->fetchOneRow()) {
-            return;
+    public function setSkin()
+    {
+        global $globals;
+        if (S::logged() && (!S::has('skin') || S::has('suid'))) {
+            $uid = S::v('uid');
+            $res = XDB::query("SELECT  skin_tpl
+                                 FROM  auth_user_quick AS a
+                           INNER JOIN  skins           AS s ON a.skin = s.id
+                                WHERE  user_id = {?} AND skin_tpl != ''", $uid);
+            S::set('skin', $res->fetchOneCell());
         }
     }
-    if ($globals->skin->enable) {
-        $_SESSION['skin'] = $globals->skin->def_tpl;
-        $_SESSION['skin_id'] = $globals->skin->def_id;
-    } else {
-        $_SESSION['skin'] = 'default.tpl';
-        $_SESSION['skin_id'] = -1;
+
+    public function sureLevel()
+    {
+        return AUTH_MDP;
     }
 }
 
-// }}}
-
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
 ?>