예제 #1
0
파일: Google.php 프로젝트: BrightFlair/IOU
 protected function startFlow()
 {
     $client = new Client(["clientId" => self::$ID, "clientSecret" => self::$secret, "redirectUri" => "http://localhost:8080/", "scopes" => ["profile", "email"], "hostedDomain" => "localhost:8080"]);
     if (!empty($_GET["error"])) {
         // User probably denied access.
         die("Got an error: {$_GET['error']}");
     } else {
         if (empty($_GET["code"])) {
             // We need to get an authorisation code.
             $authUrl = $client->getAuthorizationUrl();
             $_SESSION["oauth2state"] = $client->state;
             Headers::redirect($authUrl);
             exit;
         } else {
             if (empty($_GET["state"]) || $_GET["state"] !== $_SESSION["oauth2state"]) {
                 // State is invalid - possible CSRF attack.
                 unset($_SESSION["oauth2state"]);
                 die("Invalid state");
             } else {
                 // Try to get an access token using the authorisation grant.
                 try {
                     $token = $client->getAccessToken("authorization_code", ["code" => $_GET["code"]]);
                     $this->details = $client->getUserDetails($token);
                     unset($_SESSION["oauth2state"]);
                 } catch (\Exception $ex) {
                     unset($_SESSION["oauth2state"]);
                     die("Something went wrong! " . $ex->getMessage());
                 }
             }
         }
     }
 }
예제 #2
0
파일: Google.php 프로젝트: ndrx-io/elude
 /**
  * @param Request $request
  * @return \Illuminate\Http\RedirectResponse|\Laravel\Lumen\Http\Redirector
  */
 public function callback(Request $request)
 {
     $state = $request->get('state');
     $sessionState = Session::get('google.oauth2state');
     $code = $request->get('code');
     if ($request->get('error')) {
         $request->session()->flash('error', 'auth.error');
         return redirect(route('auth.loginForm'));
     }
     if (empty($state) || $state !== $sessionState) {
         Session::forget('google.oauth2state');
         $request->session()->flash('error', 'auth.error');
         return redirect(route('auth.loginForm'));
     }
     $token = $this->provider->getAccessToken('authorization_code', ['code' => $code]);
     try {
         /** @var GoogleUser $ownerDetails */
         $ownerDetails = $this->provider->getResourceOwner($token);
         $email = $ownerDetails->getEmail();
         // if we already have the email in DB we log the user
         if (!$this->repository->exists(['email' => $email])) {
             $lastName = $ownerDetails->getLastName();
             $firstName = $ownerDetails->getFirstName();
             $this->createUser($firstName, $lastName, $email);
         }
         // we try to logged in the user with the email and the google oauth access token
         Input::merge(['client_id' => Config::get('oauth2.web_client.client_id')]);
         Input::merge(['client_secret' => Config::get('oauth2.web_client.client_secret')]);
         Input::merge(['grant_type' => 'google']);
         Input::merge(['username' => $email]);
         Input::merge(['password' => $token->getToken()]);
         try {
             Authorizer::issueAccessToken();
             return redirect('/');
         } catch (\Exception $e) {
             $request->session()->flash('error', 'auth.login_error');
             return redirect(route('auth.loginForm'));
         }
     } catch (ModelNotValid $e) {
         $request->session()->flash('error', 'auth.error');
         Log::warn($e->getMessage());
         return redirect(route('auth.loginForm'));
     } catch (\Exception $e) {
         $request->session()->flash('error', 'auth.error');
         Log::warn($e->getMessage());
         return redirect(route('auth.loginForm'));
     }
 }
예제 #3
0
 /**
  * @param Application $app
  *
  * @return string token
  */
 public function handleAuth(Application $app)
 {
     $code = $app->request()->get('code');
     $state = $app->request()->get('state');
     $key = sprintf('google.oauth2state.%s', session_id());
     $sessionState = $this->redisClient->get($key);
     if (is_null($code)) {
         // If we don't have an authorization code then get one
         $url = $this->oauth2Provider->getAuthorizationUrl();
         $this->redisClient->setex($key, 300, $this->oauth2Provider->state);
         $app->redirect($url);
     } elseif (empty($state) || isset($sessionState) && $state !== $sessionState) {
         // Check given state against previously stored one to mitigate CSRF attack
         $this->redisClient->del($key);
         throw new \RuntimeException('Invalid state');
     }
     // clean session
     $this->redisClient->del($key);
     // Try to get an access token (using the authorization code grant)
     return $this->oauth2Provider->getAccessToken('authorization_code', ['code' => $code])->accessToken;
 }
예제 #4
0
 protected function prepareAccessTokenResult(array $result)
 {
     if (isset($result['id_token'])) {
         // [signature, token, ???]
         $id_token_bits = explode(".", $result['id_token']);
         // we could validate the token here but eh
         if (count($id_token_bits) >= 2) {
             $this->id_token = json_decode(self::safe_base64_decode($id_token_bits[1]), true);
         }
     }
     return parent::prepareAccessTokenResult($result);
 }
예제 #5
0
 /**
  * It will return uid, token and information user to save database
  *
  * @return array
  */
 public function authorize()
 {
     $this->view->disable();
     $provider = new Google(['clientId' => $this->clientId, 'clientSecret' => $this->clientSecret, 'redirectUri' => $this->redirectUriAuthorize]);
     $code = $this->request->getQuery('code');
     $state = $this->request->getQuery('state');
     if (!isset($code)) {
         // If we don't have an authorization code then get one
         $authUrl = $provider->getAuthorizationUrl();
         $this->session->set('oauth2state', $provider->state);
         return $this->response->redirect($authUrl);
         // Check given state against previously stored one to mitigate CSRF attack
     } elseif (empty($state) || $state !== $this->session->get('oauth2state')) {
         $this->session->remove('oauth2state');
         exit('Invalid state');
     } else {
         // Try to get an access token (using the authorization code grant)
         $token = $provider->getAccessToken('authorization_code', ['code' => $code]);
         $uid = $provider->getUserUid($token);
         $userDetails = $provider->getUserDetails($token);
         return array($uid, $token, $userDetails);
     }
 }
예제 #6
0
            $code = 0;
            $error = $data['error'];
            if (is_array($error)) {
                $code = $error['code'];
                $error = $error['message'];
            }
            throw new IdentityProviderException($error, $code, $data);
        }
    }
    protected function createResourceOwner(array $response, AccessToken $token)
    {
        return new GoogleUser($response);
    }
}
//Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
$provider = new Google(array('clientId' => $clientId, 'clientSecret' => $clientSecret, 'redirectUri' => $redirectUri, 'scope' => array('https://mail.google.com/'), 'accessType' => 'offline'));
if (!isset($_GET['code'])) {
    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authUrl);
    exit;
    // Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || $_GET['state'] !== $_SESSION['oauth2state']) {
    unset($_SESSION['oauth2state']);
    exit('Invalid state');
} else {
    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', array('code' => $_GET['code']));
    // Use this to get a new access token if the old one expires
    echo 'Refresh Token: ' . $token->getRefreshToken();
 public function authenticateGoogle(Request $request)
 {
     # Get access token from request
     #$accessToken = new AccessToken(array('access_token' => $request->input('access_token')));
     $accessToken = new AccessToken(array('access_token' => 'ya29.3gFWZcLeCgaKJ-rmDE7znkTtuTA1p-7Fv4PgP4EFSn8gc10pG_jotwIDraqvsq9_jGiO'));
     # Create a new provider which takes values from config file
     $provider = new Google(['clientId' => config('easyauth.google.clientId'), 'clientSecret' => config('easyauth.google.clientSecret'), 'redirectUri' => config('easyauth.google.redirectUri'), 'scopes' => config('easyauth.google.scopes')]);
     try {
         # We got an access token, let's now get the owner details
         $ownerDetails = $provider->getResourceOwner($accessToken);
         $profile = array('provider_key' => $ownerDetails->getId(), 'first_name' => $ownerDetails->getFirstName(), 'last_name' => $ownerDetails->getLastName(), 'email' => $ownerDetails->getEmail(), 'avatar' => $ownerDetails->getAvatar(), 'provider' => 'Google+');
         # Use these details to create a new profile or return a token in case the user exists
         return $this->authenticateOrCreateUser($profile);
     } catch (Exception $e) {
         # Failed to get user details
         exit('Something went wrong: ' . $e->getMessage());
     }
 }