Logs a user using a token. The token should be discarded as soon as it
was used.

Returns false if the token is not valid, else true.


@param string $token
@return UserInterface
964063
public function loginViaToken($token)
    {
        $user = $this->userDao->getUserByToken($token);
        if ($user) {
            $this->loginWithoutPassword($user->getLogin());
            return true;
        } else {
            return false;
        }
    }
1154350
public function activate($token = null)
    {
        $activated = false;
        if ($token === null) {
            $this->redirect('/');
        }

        $this->loadModel('User.Users');
        $user = $this->Users
            ->find()
            ->select(['id', 'name', 'token'])
            ->where(['status' => 0, 'token' => $token])
            ->limit(1)
            ->first();

        if ($user) {
            if ($this->Users->updateAll(['status' => 1], ['id' => $user->id])) {
                NotificationManager::activated($user)->send();
                $activated = true;
                $this->Flash->success(__d('user', 'Account successfully activated.'), ['key' => 'activate']);
            } else {
                $this->Flash->danger(__d('user', 'Account could not be activated, please try again later.'), ['key' => 'activate']);
            }
        } else {
            $this->Flash->warning(__d('user', 'Account not found or is already active.'), ['key' => 'activate']);
        }

        $this->title(__d('user', 'Account Activation'));
        $this->set(compact('activated', 'token'));
    }
1197389
public function getToken($token = null)
    {
        if ($token != null) {

            return $token;
        }

        if ($this->token == null) {

            throw new RequestRequiresAuthenticationException();
        }

        return $this->token;
    }
619674
public function setToken($token)
    {
        $token = trim($token);

        $this->isChanged('token', $token);

        $this->token = $token;

        return $this;
    }
918217
public static function logout($token)
    {
        // configuration
        $config = self::config();

        // no configuration file
        if (!$config) {
            return false;
        }

        $url = self::$clef_base_url."logout";

        $postdata = http_build_query(array(
            'logout_token' => $token,
            'app_id'       => $config['app_id'],
            'app_secret'   => $config['app_secret']
        ));

        $opts = array('http' => array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        ));

        $context  = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);

        if (!$response) {
            $response = json_decode($response, true);

            if (isset($response['success']) && $response['success']) {
                return $response['clef_id'];
            }
        }

        return false;
    }
116269
public function authenticate(TokenInterface $token)
    {
        if (!$token instanceof GuardTokenInterface) {
            throw new \InvalidArgumentException('GuardAuthenticationProvider only supports GuardTokenInterface.');
        }

        if (!$token instanceof PreAuthenticationGuardToken) {
            /*
             * The listener *only* passes PreAuthenticationGuardToken instances.
             * This means that an authenticated token (e.g. PostAuthenticationGuardToken)
             * is being passed here, which happens if that token becomes
             * "not authenticated" (e.g. happens if the user changes between
             * requests). In this case, the user should be logged out, so
             * we will return an AnonymousToken to accomplish that.
             */

            // this should never happen - but technically, the token is
            // authenticated... so it could just be returned
            if ($token->isAuthenticated()) {
                return $token;
            }

            // this AccountStatusException causes the user to be logged out
            throw new AuthenticationExpiredException();
        }

        $guardAuthenticator = $this->findOriginatingAuthenticator($token);

        if (null === $guardAuthenticator) {
            throw new AuthenticationException(sprintf('Token with provider key "%s" did not originate from any of the guard authenticators of provider "%s".', $token->getGuardProviderKey(), $this->providerKey));
        }

        return $this->authenticateViaGuard($guardAuthenticator, $token);
    }
506182
public function authenticate($token = false)
    {
        $id = $this->getPayload($token)->get('sub');
        if (! $this->auth->byId($id)) {
            return false;
        }

        return $this->auth->user();
    }
1360333
public function checkToken($token, $once = true)
    {
        $check = $this->token() === $token;

        if ($once) {
            $this->delete('__token');
        }

        return $check;
    }
778185
public static function login($token)
  {
    $rememberMe = Remember::$rememberMe;
    $rememberMe->setCleanExpiredTokensOnLogin(true);

    $_SESSION['_uas'] = $token;

    $rememberMe->createCookie($token);

    return (object)array('status' => 'success');
  }
881250
public function authenticatedUser($token = null)
    {
        $token = $this->getToken($token);

        $usersAPI = new Users($token);

        return $usersAPI->authenticatedUser();
    }
993613
protected function checkToken($token)
    {
        try {
            $response = $this->http->get($this->checkTokenURL(), [
                'headers' => [
                    'X-Requested-With' => 'XMLHttpRequest',
                    'Authorization' => 'Bearer ' . $token
                ]
            ]);
            $content = json_decode($response->getBody()->getContents());
            if (isset($content->message)) {
                if ($content->message === 'Token is valid') {
                    return true;
                }
            }
        } catch (\Exception $e) {
            return false;
        }
        return false;
    }
1241700
protected function tokenExpired($token)
    {
        if (!$this->isExpirationEnabled()) {
            return false;
        }

        $expirationTime = strtotime($token['created_at']) + $this->expires;

        return $expirationTime < $this->getCurrentTime();
    }
605417
public function login($token)
    {
        $subject           = SecurityUtils::getSecurityManager()->login($this, $token);
        $this->_principal  = $subject->getPrincipal();
        $this->_principals = $subject->getPrincipals();
        $this->principals = $subject->getPrincipals();

        if ($this->_principals === null || empty($this->_principals)) {
            $msg = "Principals returned from SecurityManager->login( token ) returned an empty set.".
                    "This must be populated with one or more elements.";
            throw new \Exception(msg);
        }
        $this->_authenticated = true;

    }
542521
protected function doAuth($provider, TokenInterface $token)
    {
        if (! $provider instanceof ApiKeyUserProviderInterface) {
            return false;
        }

        /** @var UserInterface $user */
        $user = $provider->loadUserByApiKey($token->getCredentials());

        if ($user) {
            $authenticatedToken = new ApiKeyUserToken($user->getRoles());
            $authenticatedToken->setUser($user);

            return $authenticatedToken;
        }

        throw new AuthenticationException("The API Key authentication failed.");
    }
580299
public function autologin($token)
    {
        if ($autologin = $this->autologin->validate($token)) {
            // Active token found, login the user and redirect to the
            // intended path.
            if ($user = $this->authProvider->loginUsingId($autologin->getUserId())) {
                return redirect($autologin->getPath());
            }
        }

        // Token was invalid, redirect back to the home page.
        return redirect('/');
    }
848802
public function findUserByForgetPasswordToken($token)
    {
        try {
            $builder = $this->createQueryBuilder('u');

            return $builder->where($builder->expr()->eq('u.forgetPasswordToken', ':token'))
                ->andWhere($builder->expr()->isNotNull('u.forgetPasswordExpired'))
                ->andWhere('u.forgetPasswordExpired >= :today')
                ->setParameter('token', $token)
                ->setParameter('today', new \DateTime(), Type::DATETIME)
                ->getQuery()
                ->getSingleResult();

        } catch (NoResultException $ex) {
            // This means that nothing was found this thrown by the getSingleResult method
            return null;
        } catch (NonUniqueResultException $ex) {
            // this means that there was more then one result found and we have duplicate tokens in our database.
            // Look up the code for the error message in the logs
            throw new ProgrammerException('Duplicate Forget Password Token was found.', ProgrammerException::FORGET_PASSWORD_TOKEN_DUPLICATE_EXCEPTION_CODE);
        }
    }
416279
public static function fromToken(TokenInterface $token)
    {
        $user = $token->getUser();

        if ($user instanceof UserInterface) {
            return self::fromAccount($user);
        }

        throw new InvalidArgumentException('The user class must implement "Fxp\Component\Security\Model\UserInterface"');
    }