]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - lib/apiauthaction.php
Misses this file to merge. I like the comments.
[quix0rs-gnu-social.git] / lib / apiauthaction.php
index 499c50248032eee1e677a7a3cb8fe3028d7626ef..2f2e50a4d747b852f1fcbfb18eed1e384cd9b69b 100644 (file)
@@ -39,7 +39,7 @@
 
 /*! @page authentication Authentication
 
-    StatusNet supports HTTP Basic Authentication and OAuth for API calls.
+    GNU social supports HTTP Basic Authentication and OAuth for API calls.
 
     @warning Currently, users who have created accounts without setting a
     password via OpenID, Facebook Connect, etc., cannot use the API until
 
 */
 
-if (!defined('STATUSNET')) {
-    exit(1);
-}
-
-require_once INSTALLDIR . '/lib/apioauth.php';
+if (!defined('GNUSOCIAL')) { exit(1); }
 
 /**
  * Actions extending this class will require auth
@@ -82,34 +78,47 @@ class ApiAuthAction extends ApiAction
      * @return boolean success flag
      *
      */
-    function prepare($args)
+    protected function prepare(array $args=array())
     {
         parent::prepare($args);
 
-        // NOTE: $this->auth_user has to get set in prepare(), not handle(),
-        // because subclasses do stuff with it in their prepares.
+        // NOTE: $this->scoped and $this->auth_user has to get set in
+        // prepare(), not handle(), as subclasses use them in prepares.
 
-        $oauthReq = $this->getOAuthRequest();
+        // Allow regular login session
+        if (common_logged_in()) {
+            $this->scoped = Profile::current();
+            $this->auth_user = $this->scoped->getUser();
+            if (!$this->auth_user->hasRight(Right::API)) {
+                // TRANS: Authorization exception thrown when a user without API access tries to access the API.
+                throw new AuthorizationException(_('Not allowed to use API.'));
+            }
+            // Let's run this in the same way as if we've just authenticated the user (basic/oauth auth)
+            Event::handle('EndSetApiUser', array($this->auth_user));
+            $this->access = self::READ_WRITE;
+        } else {
+            $oauthReq = $this->getOAuthRequest();
 
-        if (!$oauthReq) {
-            if ($this->requiresAuth()) {
-                $this->checkBasicAuthUser(true);
+            if ($oauthReq instanceof OAuthRequest) {
+                $this->checkOAuthRequest($oauthReq);
             } else {
-                // Check to see if a basic auth user is there even
-                // if one's not required
-                $this->checkBasicAuthUser(false);
+                // If not using OAuth, check if there is a basic auth
+                // and require it if the current action requires it.
+                $this->checkBasicAuthUser($this->requiresAuth());
             }
-        } else {
-            $this->checkOAuthRequest($oauthReq);
-        }
 
-        // NOTE: Make sure we're scoped properly based on the auths!
-        if (isset($this->auth_user) && !empty($this->auth_user)) {
-            $this->scoped = $this->auth_user->getProfile();
-        } else {
-            $this->scoped = null;
+            // NOTE: Make sure we're scoped properly based on the auths!
+            if (isset($this->auth_user) && $this->auth_user instanceof User) {
+                $this->scoped = $this->auth_user->getProfile();
+            } else {
+                $this->scoped = null;
+            }
         }
 
+        // legacy user transferral
+        // TODO: remove when sure no extended classes need it
+        $this->user = $this->auth_user;
+
         // Reject API calls with the wrong access level
 
         if ($this->isReadOnly($args) == false) {
@@ -117,8 +126,7 @@ class ApiAuthAction extends ApiAction
                 // TRANS: Client error 401.
                 $msg = _('API resource requires read-write access, ' .
                          'but you only have read access.');
-                $this->clientError($msg, 401, $this->format);
-                exit;
+                $this->clientError($msg, 401);
             }
         }
 
@@ -133,7 +141,7 @@ class ApiAuthAction extends ApiAction
      */
     function getOAuthRequest()
     {
-        ApiOauthAction::cleanRequest();
+        ApiOAuthAction::cleanRequest();
 
         $req  = OAuthRequest::from_request();
 
@@ -160,7 +168,7 @@ class ApiAuthAction extends ApiAction
      */
     function checkOAuthRequest($request)
     {
-        $datastore   = new ApiStatusNetOAuthDataStore();
+        $datastore   = new ApiGNUsocialOAuthDataStore();
         $server      = new OAuthServer($datastore);
         $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
 
@@ -204,21 +212,25 @@ class ApiAuthAction extends ApiAction
                     // Set the auth user
                     if (Event::handle('StartSetApiUser', array(&$user))) {
                         $user = User::getKV('id', $appUser->profile_id);
-                        if (!empty($user)) {
-                            if (!$user->hasRight(Right::API)) {
-                                // TRANS: Authorization exception thrown when a user without API access tries to access the API.
-                                throw new AuthorizationException(_('Not allowed to use API.'));
-                            }
+                    }
+                    if ($user instanceof User) {
+                        if (!$user->hasRight(Right::API)) {
+                            // TRANS: Authorization exception thrown when a user without API access tries to access the API.
+                            throw new AuthorizationException(_('Not allowed to use API.'));
                         }
                         $this->auth_user = $user;
-                        // FIXME: setting the value returned by common_current_user()
-                        // There should probably be a better method for this. common_set_user()
-                        // does lots of session stuff.
-                        global $_cur;
-                        $_cur = $this->auth_user;
-                        Event::handle('EndSetApiUser', array($user)); 
+                        Event::handle('EndSetApiUser', array($this->auth_user));
+                    } else {
+                        // If $user is not a real User, let's force it to null.
+                        $this->auth_user = null;
                     }
 
+                    // FIXME: setting the value returned by common_current_user()
+                    // There should probably be a better method for this. common_set_user()
+                    // does lots of session stuff.
+                    global $_cur;
+                    $_cur = $this->auth_user;
+
                     $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
                         "application '%s' (id: %d) with %s access.";
 
@@ -246,8 +258,7 @@ class ApiAuthAction extends ApiAction
         } catch (OAuthException $e) {
             $this->logAuthFailure($e->getMessage());
             common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
-            $this->clientError($e->getMessage(), 401, $this->format);
-            exit;
+            $this->clientError($e->getMessage(), 401);
         }
     }
 
@@ -256,7 +267,7 @@ class ApiAuthAction extends ApiAction
      *
      * @return boolean true
      */
-    function requiresAuth()
+    public function requiresAuth()
     {
         return true;
     }
@@ -281,41 +292,46 @@ class ApiAuthAction extends ApiAction
             header('WWW-Authenticate: Basic realm="' . $realm . '"');
 
             // show error if the user clicks 'cancel'
-            // TRANS: Client error thrown when authentication fails becaus a user clicked "Cancel".
-            $this->clientError(_('Could not authenticate you.'), 401, $this->format);
-            exit;
+            // TRANS: Client error thrown when authentication fails because a user clicked "Cancel".
+            $this->clientError(_('Could not authenticate you.'), 401);
 
-        } else {
+        } elseif ($required) {
+            // $this->auth_user_nickname - i.e. PHP_AUTH_USER - will have a value since it was not empty
 
             $user = common_check_user($this->auth_user_nickname,
                                       $this->auth_user_password);
 
-            if (Event::handle('StartSetApiUser', array(&$user))) {
-
-                if (!empty($user)) {
-                    if (!$user->hasRight(Right::API)) {
-                        // TRANS: Authorization exception thrown when a user without API access tries to access the API.
-                        throw new AuthorizationException(_('Not allowed to use API.'));
-                    }
-                    $this->auth_user = $user;
+            Event::handle('StartSetApiUser', array(&$user));
+            if ($user instanceof User) {
+                if (!$user->hasRight(Right::API)) {
+                    // TRANS: Authorization exception thrown when a user without API access tries to access the API.
+                    throw new AuthorizationException(_('Not allowed to use API.'));
                 }
+                $this->auth_user = $user;
 
-                Event::handle('EndSetApiUser', array($user));
+                Event::handle('EndSetApiUser', array($this->auth_user));
+            } else {
+                $this->auth_user = null;
             }
 
             // By default, basic auth users have rw access
             $this->access = self::READ_WRITE;
 
-            if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
+            if (!$this->auth_user instanceof User) {
                 $msg = sprintf(
                     "basic auth nickname = %s",
                     $this->auth_user_nickname
                 );
                 $this->logAuthFailure($msg);
+
+                // We must present WWW-Authenticate in accordance to HTTP status code 401
+                header('WWW-Authenticate: Basic realm="' . $realm . '"');
                 // TRANS: Client error thrown when authentication fails.
-                $this->clientError(_('Could not authenticate you.'), 401, $this->format);
-                exit;
+                $this->clientError(_('Could not authenticate you.'), 401);
             }
+        } else {
+            // all get rw access for actions that don't require auth
+            $this->access = self::READ_WRITE;
         }
     }