Moving to GitHub.
[platal.git] / classes / xorgsession.php
index 59bf294..2a9e73d 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2010 Polytechnique.org                              *
+ *  Copyright (C) 2003-2014 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
 
 class XorgSession extends PlSession
 {
+    const INVALID_USER = -2;
+    const NO_COOKIE = -1;
+    const COOKIE_SUCCESS = 0;
+    const INVALID_COOKIE = 1;
+
     public function __construct()
     {
         parent::__construct();
@@ -29,10 +34,15 @@ class XorgSession extends PlSession
     public function startAvailableAuth()
     {
         if (!S::logged()) {
-            $cookie = $this->tryCookie();
-            if ($cookie == 0) {
-                return $this->start(AUTH_COOKIE);
-            } else if ($cookie == 1 || $cookie == -2) {
+            switch ($this->tryCookie()) {
+              case self::COOKIE_SUCCESS:
+                if (!$this->start(AUTH_COOKIE)) {
+                    return false;
+                }
+                break;
+
+              case self::INVALID_USER:
+              case self::INVALID_COOKIE:
                 return false;
             }
         }
@@ -42,78 +52,54 @@ class XorgSession extends PlSession
         return true;
     }
 
-    /** Check the cookie and set the associated user_id in the auth_by_cookie session variable.
+    /** Check the cookie and set the associated uid in the auth_by_cookie session variable.
      */
     private function tryCookie()
     {
         S::kill('auth_by_cookie');
         if (Cookie::v('access') == '' || !Cookie::has('uid')) {
-            return -1;
+            return self::NO_COOKIE;
         }
 
-        $res = XDB::query('SELECT  user_id, password
-                             FROM  auth_user_md5
-                            WHERE  user_id = {?} AND perms IN(\'admin\', \'user\')',
+        $res = XDB::query('SELECT  uid, password
+                             FROM  accounts
+                            WHERE  uid = {?} AND state = \'active\'',
                          Cookie::i('uid'));
         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('access')) {
+            if (sha1($password) == Cookie::v('access')) {
                 S::set('auth_by_cookie', $uid);
-                return 0;
+                return self::COOKIE_SUCCESS;
             } else {
-                return 1;
+                return self::INVALID_COOKIE;
             }
         }
-        return -2;
+        return self::INVALID_USER;
     }
 
-    private function checkPassword($uname, $login, $response, $login_type)
+    const TEXT_INVALID_LOGIN = "Mot de passe ou nom d'utilisateur invalide";
+    const TEXT_INVALID_PASS = "Mot de passe invalide";
+
+    private function checkPassword($login, User $user, $response)
     {
-        $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 && Env::has('xorpass')
-                && !preg_match('/^0*$/', Env::v('xorpass'))) {
-                $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);
-
-                    // Update the GoogleApps password as well, if required.
-                    global $globals;
-                    if ($globals->mailstorage->googleapps_domain) {
-                        require_once 'googleapps.inc.php';
-                        $user = User::getSilent($uid);
-                        $account = new GoogleAppsAccount($user);
-                        if ($account->active() && $account->sync_password) {
-                            $account->set_password($new_password);
-                        }
-                    }
-                }
-            }
+        if ($user === null) {
+            Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
+            return false;
+        } else {
+            $password = $user->password();
+            $expected_response = sha1("$login:$password:" . S::v('challenge'));
+            /* Deprecates len(password) > 10 conversion. */
             if ($response != $expected_response) {
                 if (!S::logged()) {
-                    Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
+                    Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
                 } else {
-                    Platal::page()->trigError('Mot de passe invalide');
+                    Platal::page()->trigError(self::TEXT_INVALID_PASS);
                 }
                 S::logger($uid)->log('auth_fail', 'bad password');
-                return null;
+                return false;
             }
-            return $uid;
+            return true;
         }
-        Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
-        return null;
     }
 
 
@@ -132,7 +118,7 @@ class XorgSession extends PlSession
             if (!S::logged()) {
                 S::set('auth', AUTH_COOKIE);
             }
-            return S::i('auth_by_cookie');
+            return User::getSilentWithUID(S::i('auth_by_cookie'));
         }
 
 
@@ -144,113 +130,78 @@ class XorgSession extends PlSession
 
         /** We come from an authentication form.
          */
-        if (S::has('suid')) {
-            $suid  = S::v('suid');
-            $login = $uname = $suid['uid'];
-            $redirect = false;
+        if (S::suid()) {
+            $login = S::suid('uid');
         } 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 = '';
-                }
-            } else {
-                $login = $uname;
-                $redirect = false;
-            }
+            $login = Post::v('username');
         }
 
-        $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && is_numeric($uname)) ? 'id' : 'alias');
-        if (!is_null($uid) && S::has('suid')) {
-            $suid = S::v('suid');
-            if ($suid['uid'] == $uid) {
-                $uid = S::i('uid');
+        $user = User::getSilent($login);
+
+        if (is_null($user)) {
+            Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
+            $success = false;
+        } else {
+            if (S::suid()) {
+                $success = (S::suid('uid') == $user->id());
             } else {
-                $uid = null;
+                $success = $this->checkPassword($login, $user, Post::v('response'));
             }
         }
-        if (!is_null($uid)) {
-            S::set('auth', AUTH_MDP);
-            if (!S::has('suid')) {
-                if (Post::has('domain')) {
-                    if (($domain = Post::v('domain', 'login')) == 'alias') {
-                        Cookie::set('domain', 'alias', 300);
-                    } else {
-                        Cookie::kill('domain');
-                    }
-                }
-            }
+
+        if ($success) {
+            S::set('auth', AUTH_PASSWD);
             S::kill('challenge');
-            S::logger($uid)->log('auth_ok');
+            S::logger($user->id())->log('auth_ok');
         }
-        return $uid;
+        return $user;
     }
 
-    protected function startSessionAs($uid, $level)
+    protected function startSessionAs($user, $level)
     {
-        if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) {
+        if ((!is_null(S::user()) && S::user()->id() != $user->id())
+            || (S::has('uid') && S::i('uid') != $user->id())) {
             return false;
         } else if (S::has('uid')) {
             return true;
         }
         if ($level == AUTH_SUID) {
-            S::set('auth', AUTH_MDP);
-        }
-
-        // Retrieves main user properties.
-        $res  = XDB::query("SELECT  u.user_id AS uid, u.hruid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
-                                    matricule, password, FIND_IN_SET('femme', u.flags) AS femme,
-                                    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, g.g_account_name IS NOT NULL AS googleapps,
-                                    UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
-                              FROM  auth_user_md5   AS u
-                        INNER JOIN  auth_user_quick AS q  USING(user_id)
-                         LEFT JOIN  gapps_accounts  AS g  ON (u.user_id = g.l_userid AND g.g_status = 'active')
-                         LEFT JOIN  #logger#.last_sessions AS ls ON (ls.uid = u.user_id)
-                         LEFT JOIN  #logger#.sessions AS s  ON(s.id = ls.id)
-                             WHERE  u.user_id = {?} AND u.perms IN('admin', 'user')", $uid);
-        if ($res->numRows() != 1) {
-            return false;
+            S::set('auth', AUTH_PASSWD);
         }
 
-        $sess = $res->fetchOneAssoc();
-        $perms = $sess['perms'];
-        unset($sess['perms']);
-
-        // Loads the data into the real session.
-        $_SESSION = array_merge($_SESSION, $sess);
+        // Loads uid and hruid into the session for developement conveniance.
+        $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid, 'token' => $user->token, 'user' => $user));
 
         // Starts the session's logger, and sets up the permanent cookie.
-        if (S::has('suid')) {
-            $suid = S::v('suid');
-            $logger = S::logger($uid);
-            $logger->log("suid_start", S::v('hruid') . " by " . $suid['hruid']);
+        if (S::suid()) {
+            S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
         } else {
-            $logger = S::logger($uid);
-            $logger->saveLastSession();
-            Cookie::set('uid', $uid, 300);
+            S::logger()->saveLastSession();
+            Cookie::set('uid', $user->id(), 300);
 
-            if (S::i('auth_by_cookie') == $uid || Post::v('remember', 'false') == 'true') {
-                $this->setAccessCookie(false, S::i('auth_by_cookie') != $uid);
+            if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
+                $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
             } else {
                 $this->killAccessCookie();
+
+                // If login for an external website and not activating cookie,
+                // mark that we want to disconnect once external auth checks
+                // have been performed.
+                if (Post::b('external_auth')) {
+                    S::set('external_auth_exit', true);
+                }
             }
         }
 
         // Finalizes the session setup.
-        S::set('perms', User::makePerms($perms));
+        $this->makePerms($user->perms, $user->is_admin);
         $this->securityChecks();
         $this->setSkin();
         $this->updateNbNotifs();
-        check_redirect();
+        // Only check email redirection for 'internal' users.
+        if ($user->checkPerms(PERMS_USER)) {
+            check_redirect();
+        }
 
         // We should not have to use this private data anymore
         S::kill('auth_by_cookie');
@@ -279,42 +230,78 @@ class XorgSession extends PlSession
         }
     }
 
+    /**
+     * The authentication schema is based on three query parameters:
+     *   ?user=<hruid>&timestamp=<timestamp>&sig=<sig>
+     * where:
+     *   - hruid is the hruid of the querying user
+     *   - timestamp is the current UNIX timestamp, which has to be within a
+     *     given distance of the server-side UNIX timestamp
+     *   - sig is the HMAC of "<method>#<resource>#<payload>#<timestamp>" using
+     *     a known secret of the user as the key.
+     *
+     * At the moment, the shared secret of the user is the sha1 hash of its
+     * password. This is temporary, though, until better support for tokens is
+     * implemented in plat/al.
+     * TODO(vzanotti): Switch to dedicated secrets for authentication.
+     */
+    public function apiAuth($method, $resource, $payload)
+    {
+        // Verify that the timestamp is within acceptable bounds.
+        $timestamp = Env::i('timestamp', 0);
+        if (abs($timestamp - time()) > Platal::globals()->api->timestamp_tolerance) {
+            return null;
+        }
+
+        // Retrieve the user corresponding to the forlife. Note that at the
+        // moment, other aliases are also accepted.
+        $user = User::getSilent(Env::s('user', ''));
+        if (is_null($user) || !$user->isActive()) {
+            return null;
+        }
+
+        // Determine the list of tokens associated with the user. At the moment,
+        // this is just the sha1 of the password.
+        $tokens = array($user->password());
+
+        // For each token, try to validate the signature.
+        $message = implode('#', array($method, $resource, $payload, $timestamp));
+        $signature = Env::s('sig');
+        foreach ($tokens as $token) {
+            $expected_signature = hash_hmac(
+                Platal::globals()->api->hmac_algo, $message, $token);
+            if ($signature == $expected_signature) {
+                return $user;
+            }
+        }
+
+        return null;
+    }
+
     public function tokenAuth($login, $token)
     {
-        $res = XDB::query('SELECT  u.hruid
-                             FROM  aliases         AS a
-                       INNER JOIN  auth_user_md5   AS u ON (a.id = u.user_id AND u.perms IN ("admin", "user"))
-                       INNER JOIN  auth_user_quick AS q ON (a.id = q.user_id AND q.core_rss_hash = {?})
-                            WHERE  a.alias = {?} AND a.type != "homonyme"', $token, $login);
+        $res = XDB::query('SELECT  a.uid, a.hruid
+                             FROM  accounts AS a
+                            WHERE  a.token = {?} AND a.hruid = {?} AND a.state = \'active\'',
+                          $token, $login);
         if ($res->numRows() == 1) {
-            $data = $res->fetchOneAssoc();
-            return new User($data['hruid'], $data);
+            return new User(null, $res->fetchOneAssoc());
         }
         return null;
     }
 
     protected function makePerms($perm, $is_admin)
     {
-        $flags = new PlFlagSet();
-        if ($perm == 'disabled' || $perm == 'ext') {
-            S::set('perms', $flags);
-            return;
-        }
-        $flags->addFlag(PERMS_USER);
-        if ($perm == 'admin') {
-            $flags->addFlag(PERMS_ADMIN);
-        }
-        S::set('perms', $flags);
+        S::set('perms', User::makePerms($perm, $is_admin));
     }
 
     public function setSkin()
     {
-        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);
+        if (S::logged() && (!S::has('skin') || S::suid())) {
+            $res = XDB::query('SELECT  skin_tpl
+                                 FROM  accounts AS a
+                           INNER JOIN  skins    AS s on (a.skin = s.id)
+                                WHERE  a.uid = {?} AND skin_tpl != \'\'', S::i('uid'));
             S::set('skin', $res->fetchOneCell());
         }
     }
@@ -326,23 +313,23 @@ class XorgSession extends PlSession
 
     public function sureLevel()
     {
-        return AUTH_MDP;
+        return AUTH_PASSWD;
     }
 
 
     public function updateNbNotifs()
     {
         require_once 'notifs.inc.php';
-        $n = select_notifs(false, S::i('uid'), S::v('watch_last'), false);
-        S::set('notifs', $n->numRows());
+        $user = S::user();
+        $n = Watch::getCount($user);
+        S::set('notifs', $n);
     }
 
     public function setAccessCookie($replace = false, $log = true) {
-        if (S::has('suid') || ($replace && !Cookie::blank('access'))) {
+        if (S::suid() || ($replace && !Cookie::blank('access'))) {
             return;
         }
-        require_once('secure_hash.inc.php');
-        Cookie::set('access', hash_encrypt(S::v('password')), 300, true);
+        Cookie::set('access', sha1(S::user()->password()), 300, true);
         if ($log) {
             S::logger()->log('cookie_on');
         }
@@ -361,5 +348,5 @@ class XorgSession extends PlSession
     }
 }
 
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
 ?>