Moving to GitHub.
[platal.git] / classes / xorgsession.php
index a6ed341..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   *
@@ -77,36 +77,29 @@ class XorgSession extends PlSession
         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)
     {
-        if ($login_type == 'alias') {
-            $res = XDB::query('SELECT  a.uid, a.password
-                                 FROM  accounts AS a
-                           INNER JOIN  aliases  AS l ON (l.uid = a.uid AND l.type != \'homonyme\')
-                                WHERE  l.alias = {?} AND a.state = \'active\'',
-                              $login);
+        if ($user === null) {
+            Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
+            return false;
         } else {
-            $res = XDB::query('SELECT  uid, password
-                                 FROM  accounts
-                                WHERE  ' . $login_type . ' = {?}',
-                              $login);
-        }
-        if (list($uid, $password) = $res->fetchOneRow()) {
-            $expected_response = sha1("$uname:$password:" . S::v('challenge'));
+            $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;
     }
 
 
@@ -138,61 +131,30 @@ class XorgSession extends PlSession
         /** We come from an authentication form.
          */
         if (S::suid()) {
-            $login = $uname = S::suid('uid');
-            $loginType = 'uid';
-            $redirect = false;
+            $login = S::suid('uid');
         } else {
-            $uname = Post::v('username');
-            if (Post::s('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 = '';
-                }
-                $loginType = 'alias';
-            } else if (Post::s('domain') == "ax") {
-                $login = $uname;
-                $redirect = false;
-                $loginType = 'hruid';
-            } else {
-                $login = $uname;
-                $redirect = false;
-                $loginType = 'alias';
-            }
+            $login = Post::v('username');
         }
 
-        $uid = $this->checkPassword($uname, $login, Post::v('response'), $loginType);
-        if (!is_null($uid) && S::suid()) {
-            if (S::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::suid()) {
-                if (Post::has('domain')) {
-                    $domain = Post::v('domain', 'login');
-                    if ($domain == 'alias') {
-                        Cookie::set('domain', 'alias', 300);
-                    } else if ($domain == 'ax') {
-                        Cookie::set('domain', 'ax', 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 User::getSilentWithUID($uid);
+        return $user;
     }
 
     protected function startSessionAs($user, $level)
@@ -204,11 +166,11 @@ class XorgSession extends PlSession
             return true;
         }
         if ($level == AUTH_SUID) {
-            S::set('auth', AUTH_MDP);
+            S::set('auth', AUTH_PASSWD);
         }
 
         // Loads uid and hruid into the session for developement conveniance.
-        $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid));
+        $_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::suid()) {
@@ -221,6 +183,13 @@ class XorgSession extends PlSession
                 $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);
+                }
             }
         }
 
@@ -229,7 +198,10 @@ class XorgSession extends PlSession
         $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');
@@ -258,13 +230,60 @@ 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  a.uid, a.hruid
-                             FROM  aliases  AS l
-                       INNER JOIN  accounts AS a ON (l.uid = a.uid AND a.state = \'active\')
-                            WHERE  a.token = {?} AND l.alias = {?} AND l.type != \'homonyme\'',
-                           $token, $login);
+                             FROM  accounts AS a
+                            WHERE  a.token = {?} AND a.hruid = {?} AND a.state = \'active\'',
+                          $token, $login);
         if ($res->numRows() == 1) {
             return new User(null, $res->fetchOneAssoc());
         }
@@ -294,7 +313,7 @@ class XorgSession extends PlSession
 
     public function sureLevel()
     {
-        return AUTH_MDP;
+        return AUTH_PASSWD;
     }
 
 
@@ -329,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:
 ?>