public function getProfile($token) { $ticket = $this->_googleClient->verifyIdToken($token); if ($ticket) { $data = $ticket->getAttributes(); return $data['payload']['sub']; // user ID } return false; }
/** * Checks with the site to confirm that the given token is indeed valid * and corresponds with the userID we were given. It can do anything else * it needs as well (e.g. facebook provides a debug_token endpoint) * * @param string $token * @param string $userID * @return bool * @throws RestSystemException */ public function validateToken($token, $userID) { $client = new Google_Client(); $client->setClientId(Config::inst()->get('GoogleApi', 'AppID')); $client->setClientSecret(Config::inst()->get('GoogleApi', 'AppSecret')); $client->addScope(Google_Service_PlusDomains::PLUS_ME); $ticket = $client->verifyIdToken($token); if ($ticket) { return $ticket['sub'] === $userID; } return false; }
public function callback() { $redirectUri = 'http' . (isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] ? 's' : '' : '') . '://' . $_SERVER['HTTP_HOST'] . '/GoogleAuthenticatorController/callback'; $client = new Google_Client(); $client->setClientId(GOOGLE_AUTHENTICATOR_CLIENT_ID); $client->setClientSecret(GOOGLE_AUTHENTICATOR_CLIENT_SECRET); $client->setRedirectUri($redirectUri); $client->addScope("email"); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['google_accesstoken'] = $client->getAccessToken(); header('Location: ' . filter_var($redirectUri, FILTER_SANITIZE_URL)); } if (isset($_SESSION['google_accesstoken']) && $_SESSION['google_accesstoken']) { $client->setAccessToken($_SESSION['google_accesstoken']); } $form = new GoogleAuthenticatorLoginForm($this, 'LoginForm'); if ($client->getAccessToken() && !$client->isAccessTokenExpired()) { $_SESSION['google_accesstoken'] = $client->getAccessToken(); $token_data = $client->verifyIdToken()->getAttributes(); $email = $token_data['payload']['email']; $member = Member::get()->filter(array('Email' => $email))->first(); if (isset($_SESSION['BackURL']) && $_SESSION['BackURL'] && Director::is_site_url($_SESSION['BackURL'])) { $backURL = $_SESSION['BackURL']; } if ($member) { $member->logIn(); if ($backURL) { return $this->redirect($backURL); } if (Security::config()->default_login_dest) { return $this->redirect(Director::absoluteBaseURL() . Security::config()->default_login_dest); } return Controller::curr()->redirectBack(); } else { $form->sessionMessage("The Google account {$email} is not authorised to access the system.", 'bad'); } } else { $form->sessionMessage("There is an error authenticating with Google. Please try again.", 'bad'); } $loginLink = Director::absoluteURL('/Security/login'); if ($backURL) { $loginLink .= '?BackURL=' . urlencode($backURL); } $loginLink .= '#GoogleAuthenticatorLoginForm_LoginForm_tab'; return $this->redirect($loginLink); }
public function googleAction() { $googleClient = new \Google_Client(); $googleClient->setClientId($this->googleClientId); $googleClient->setClientSecret($this->googleClientSecret); $googleClient->setDeveloperKey($this->googleDeveloperKey); $googleClient->setRedirectUri($this->googleRedirectUri); $googleClient->setScopes(array('email')); // // $googleOauthV2 = new \Google_Auth_OAuth2($googleClient); if (isset($_REQUEST['token']) || isset($_REQUEST['code']) || isset($_REQUEST['state'])) { $googleClient->authenticate($_REQUEST['code']); $token = $googleClient->getAccessToken(); if ($token) { $tokenData = $googleClient->verifyIdToken()->getAttributes(); print_r($tokenData); die; } } }
public function auth() { $email = $this->getParam('email', ''); $token = $this->getParam('token', ''); $client = new \Google_Client(); $client->setClientId(Setting::get('google-identity', 'client_id')); $client->setClientSecret(Setting::get('google-identity', 'client_secret')); $client->setRedirectUri($this->config->get('site.full_admin_url') . '/google-identity/auth'); $client->setScopes('email'); $data = $client->verifyIdToken($token)->getAttributes(); if (empty($data['payload']['email']) || $data['payload']['email'] != $email) { return $this->redirect('/session/login?logout=1')->error('There was a problem signing you in, please try again.'); } $userStore = Store::get('User'); $user = $userStore->getByEmail($email); if (is_null($user)) { $authDomains = Setting::get('google-identity', 'login_auto_create'); $authDomains = explode(',', $authDomains); $parts = explode('@', $email, 2); if (!in_array($parts[1], $authDomains)) { return $this->redirect('/session/login?logout=1')->error('You do not have permission to sign in.'); } $user = new User(); $user->setActive(1); $user->setIsAdmin(1); $user->setDateAdded(new \DateTime()); $user->setEmail($email); $user->setName($data['payload']['name']); $user = $userStore->save($user); } $_SESSION['user_id'] = $user->getId(); if (isset($_SESSION['previous_url'])) { return $this->redirect($_SESSION['previous_url']); } return $this->redirect('/'); }
************************************************/ if (!empty($_SESSION['id_token_token']) && isset($_SESSION['id_token_token']['id_token'])) { $client->setAccessToken($_SESSION['id_token_token']); } else { $authUrl = $client->createAuthUrl(); } /************************************************ If we're signed in we can go ahead and retrieve the ID token, which is part of the bundle of data that is exchange in the authenticate step - we only need to do a network call if we have to retrieve the Google certificate to verify it, and that can be cached. ************************************************/ if ($client->getAccessToken()) { $token_data = $client->verifyIdToken(); } ?> <div class="box"> <?php if (isset($authUrl)) { ?> <div class="request"> <a class='login' href='<?php echo $authUrl; ?> '>Connect Me!</a> </div> <?php } else {
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); } else { $authUrl = $client->createAuthUrl(); } /************************************************ If we're signed in we can go ahead and retrieve the ID token, which is part of the bundle of data that is exchange in the authenticate step - we only need to do a network call if we have to retrieve the Google certificate to verify it, and that can be cached. ************************************************/ if ($client->getAccessToken()) { $_SESSION['access_token'] = $client->getAccessToken(); $token_data = $client->verifyIdToken()->getAttributes(); } echo pageHeader("User Query - Retrieving An Id Token"); if ($client_id == '<YOUR_CLIENT_ID>' || $client_secret == '<YOUR_CLIENT_SECRET>' || $redirect_uri == '<YOUR_REDIRECT_URI>') { echo missingClientSecretsWarning(); } ?> <div class="box"> <div class="request"> <?php if (isset($authUrl)) { ?> <a class='login' href='<?php echo $authUrl; ?> '>Connect Me!</a>
function getUserProfile() { $client = new \Google_Client(); $client->setAuthConfigFile('../client_secret.json'); $client->setAccessToken($this->request->session()->read("user.profile_token")); $attr = $client->verifyIdToken(); $userId = $attr->getAttributes()['payload']['sub']; $plus_service = new \Google_Service_Plus($client); $this->request->session()->write("user.profile", $plus_service->people->get($userId)); }
if ($request->get('state') != $app['session']->get('state')) { return new Response('Invalid state parameter', 401); } // Normally the state would be a one-time use token, however in our // simple case, we want a user to be able to connect and disconnect // without reloading the page. Thus, for demonstration, we don't // implement this best practice. //$app['session']->set('state', ''); $code = $request->getContent(); // Exchange the OAuth 2.0 authorization code for user credentials. $client->authenticate($code); $token = json_decode($client->getAccessToken()); // You can read the Google user ID in the ID token. // "sub" represents the ID token subscriber which in our case // is the user ID. This sample does not use the user ID. $attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)->getAttributes(); $gplus_id = $attributes["payload"]["sub"]; // Store the token in the session for later use. $app['session']->set('token', json_encode($token)); $response = 'Successfully connected with token: ' . print_r($token, true); } else { $response = 'Already connected'; } return new Response($response, 200); }); // Get list of people user has shared with this app. $app->get('/people', function () use($app, $client, $plus) { $token = $app['session']->get('token'); if (empty($token)) { return new Response('Unauthorized request', 401); }
/** * Validate this user's credentials against Google. * @param array $auth_settings Plugin settings * @return [mixed] Array containing 'email' and 'authenticated_by' * strings for the successfully authenticated * user, or WP_Error() object on failure. */ private function custom_authenticate_google($auth_settings) { // Get one time use token session_start(); $token = array_key_exists('token', $_SESSION) ? json_decode($_SESSION['token']) : null; // No token, so this is not a succesful Google login. if (is_null($token)) { return new WP_Error('no_google_login', 'No Google credentials provided.'); } // Build the Google Client. $client = new Google_Client(); $client->setApplicationName('WordPress'); $client->setClientId($auth_settings['google_clientid']); $client->setClientSecret($auth_settings['google_clientsecret']); $client->setRedirectUri('postmessage'); // Verify this is a successful Google authentication $ticket = $client->verifyIdToken($token->id_token, $auth_settings['google_clientid']); // Invalid ticket, so this in not a successful Google login. if (!$ticket) { return new WP_Error('invalid_google_login', 'Invalid Google credentials provided.'); } // Get email address $attributes = $ticket->getAttributes(); $email = $attributes['payload']['email']; return array('email' => $email, 'authenticated_by' => 'google'); }
/** * Return a UserInterface object based on the credentials. * * The *credentials* are the return value from getCredentials() * * You may throw an AuthenticationException if you wish. If you return * null, then a UsernameNotFoundException is thrown for you. * * @param mixed $credentials * @param UserProviderInterface $userProvider * * @throws AuthenticationException * * @return UserInterface|null */ public function getUser($credentials, UserProviderInterface $userProvider) { $idToken = $credentials['token']; $gc = new \Google_Client(); $gc->setClientId($this->clientId); $gc->setClientSecret($this->clientSecret); $ticket = $gc->verifyIdToken($idToken); if (!$ticket instanceof \Google_LoginTicket) { return null; } $data = $ticket->getAttributes()['payload']; $email = $data['email']; $googleId = $data['sub']; return $this->oAuthUserCreator->getOrCreateUser($email, $googleId); }
public function googleplus() { session_start(); include_once "oauth/google/examples/templates/base.php"; require_once 'oauth/google/src/Google/autoload.php'; require_once 'oauth/google/src/Google/Service/Plus.php'; /************************************************ ATTENTION: Fill in these values! Make sure the redirect URI is to this page, e.g: http://localhost:8080/user-example.php ************************************************/ $client_id = '850390802439-iam46vt2ah1i291fs4bhr3r8lp43miau.apps.googleusercontent.com'; $client_secret = '-Fgv-YgBFMyPjjYDEztf3vWT'; $redirect_uri = 'https://linuxourse.me/oauth/googleplus'; $client = new Google_Client(); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->setScopes(array('profile', 'email')); /************************************************ If we're logging out we just need to clear our local access token in this case ************************************************/ if (isset($_REQUEST['logout'])) { unset($_SESSION['access_token']); } /************************************************ If we have a code back from the OAuth 2.0 flow, we need to exchange that with the authenticate() function. We store the resultant access token bundle in the session, and redirect to ourself. ************************************************/ if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); } /************************************************ If we have an access token, we can make requests, else we generate an authentication URL. ************************************************/ if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); } else { $authUrl = $client->createAuthUrl(); } /************************************************ If we're signed in we can go ahead and retrieve the ID token, which is part of the bundle of data that is exchange in the authenticate step - we only need to do a network call if we have to retrieve the Google certificate to verify it, and that can be cached. ************************************************/ if ($client->getAccessToken()) { $_SESSION['access_token'] = $client->getAccessToken(); $token_data = $client->verifyIdToken()->getAttributes(); } // echo pageHeader("User Query - Retrieving An Id Token"); if ($client_id == '850390802439-iam46vt2ah1i291fs4bhr3r8lp43miau.apps.googleusercontent.com' || $client_secret == '-Fgv-YgBFMyPjjYDEztf3vWT' || $redirect_uri == site_url('oauth/googleplus')) { // echo missingClientSecretsWarning(); } if (isset($authUrl)) { redirect($authUrl); } //is data found if (isset($token_data)) { $payload = $token_data['payload']; $id = $payload['sub']; $email = $payload['email']; $oauthProvider = 'googleplus'; // $nclient = new Google_Client(); // $plus = new Google_PlusService($nclient); // $me = $plus->people->get('me'); //is user registered $userdata = $this->m_user->isRegistered($oauthProvider, $id); if (!empty($userdata)) { //user is registered //set session if ($userdata['verified'] == 0) { //email not verified $data['title'] = 'Verified email first'; $data['error'] = 'check your email to verification or resend verification code <a data-reveal-id="verificationModal" href="#">here</a>'; $this->baseView('p/loginerror', $data); } else { //create session $loginuser['id_user'] = $userdata['id_user']; $loginuser['username'] = $userdata['username']; $loginuser['email'] = $userdata['email']; $loginuser['fullname'] = $userdata['fullname']; $loginuser['id_country'] = $userdata['id_country']; $loginuser['register_date'] = $userdata['register_date']; $loginuser['password'] = $userdata['password']; $loginuser['level'] = $userdata['level']; $loginuser['status'] = $userdata['status']; $loginuser['pp'] = $userdata['pp']; $loginuser['is_login'] = 1; $sessiondata['student_login'] = $loginuser; $sessiondata['command'] = array(); //for course //set session $this->session->set_userdata($sessiondata); $this->session->set_userdata('dir', '/home/user'); if ($this->session->userdata['student_login']['status'] == 'active') { //jika statusnya aktif $this->db->where('id_user', $this->session->userdata['student_login']['id_user']); $data = array('last_login' => date('Y-m-d h:i:s')); $this->db->update('user', $data); //update login terakhir echo "<SCRIPT LANGUAGE='JavaScript'>\n\t\t\t\t\t\twindow.alert('Login Success');\n\t\t\t\t\t\twindow.location.href='" . site_url() . "';\n\t\t\t\t\t</SCRIPT>"; } else { //jika statusnya banned echo 'gagal memasukan session'; } } } else { //user not registered //redirect to register form $explodeEmail = explode('@', $email); $registerdata = array('oauthProvider' => 'googleplus', 'oauthId' => $id, 'email' => $email, 'username' => $explodeEmail[0], 'fullname' => ''); $params['registerdata'] = $registerdata; $this->session->set_userdata($params); redirect(site_url('p/register')); } } }
$client = new Google_Client(); // Get auth config from developer console json file $client->setAuthConfigFile('secrets/client_id.json'); // Set minimal scope for authentication $client->setScopes(array(Google_Service_Oauth2::USERINFO_EMAIL, Google_Service_Oauth2::USERINFO_PROFILE)); // Set redirect URL to self. Hardcoded for simplicity and readability. $client->setRedirectUri('https://php-marketplace-sso.appspot.com'); // Prepare auth URL $auth_url = $client->createAuthUrl(); if (isset($_GET['code'])) { // We have returned from auth URL $client->authenticate($_GET['code']); // Retrieve the access token $access_token = $client->getAccessToken(); // Verify login server-side $login_ticket = $client->verifyIdToken(); if ($login_ticket) { // We successfully authenticated the user, let's display some infos about him $login_attributes = $login_ticket->getAttributes(); ?> <!DOCTYPE html> <html> <head> <title>Hello, world!</title> </head> <body> <?php echo 'Google user ID: ', $login_attributes['payload']['sub'], '<br>'; echo 'Email: ', $login_attributes['payload']['email'], '<br>'; if (isset($login_attributes['payload']['hd'])) { echo 'Google Apps for Work domain: ', $login_attributes['payload']['hd'], '<br>';
if (!$user || !password_verify($password, $user['password'])) { $response->getBody()->write(json_encode("Email and password combination not found")); return $response->withStatus(400); } unset($user['password']); $authToken = uniqid("auth_", true); $dataStore->createAuthToken($user['id'], $authToken, 0); $response->getBody()->write(json_encode(["user" => $user, "auth_token" => $authToken])); }); $app->post("/auth/google/", function (Request $request, Response $response) use($app, $settings) { $data = $request->getParsedBody(); $idToken = get($data['id_token'], null); $client = new Google_Client(); $client->setClientId($settings['GOOGLE_CLIENT_ID']); try { $loginTicket = $client->verifyIdToken($idToken); } catch (Exception $e) { $response->getBody()->write(json_encode("Invalid google id token")); return $response->withStatus(401); } $attributes = $loginTicket->getAttributes()['payload']; $name = $attributes['name']; $email = $attributes['email']; $email = strtolower($email); $dataStore = DataStore::getInstance(); $user = $dataStore->getUser($email); if ($user === null) { $dataStore->createUser($email, null, $name, "google"); } $user = $dataStore->getUser($email); unset($user['password']);
public function google() { $this->load->model('user_model'); $data = array(); require_once APPPATH . 'libraries/google-api-php-client/src/Google/autoload.php'; //$this->load->model('users_model'); /************************************************ ATTENTION: Fill in these values! Make sure the redirect URI is to this page, e.g: http://localhost:8080/user-example.php ************************************************/ $client_id = '1063903629062-1q9qletmv9v0m7nedfjtq2nu1aabv3mk.apps.googleusercontent.com'; $client_secret = '_beoTqZJ9LuVxN5SmUT39y-c'; $redirect_uri = base_url('login/google'); /************************************************ Make an API request on behalf of a user. In this case we need to have a valid OAuth 2.0 token for the user, so we need to send them through a login flow. To do this we need some information from our API console project. ************************************************/ $client = new Google_Client(); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->setScopes('email'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // Handle authorization flow from the server. if (!isset($_GET['code'])) { $auth_url = $client->createAuthUrl(); //header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); redirect(filter_var($auth_url, FILTER_SANITIZE_URL)); } else { $client->authenticate($_GET['code']); $getAccessToken = $client->getAccessToken(); $tokenData = $client->verifyIdToken()->getAttributes(); //$this->session->set_userdata('access_token', $getAccessToken); $email = getEmail($tokenData); if ($email != '') { $getUserProfile = $this->user_model->get_single_data(array('email' => $email)); if ($getUserProfile['uid'] != '') { $status = $getUserProfile['status']; $level = get_level_name($getUserProfile['level']); $idlevel = $getUserProfile['level']; $name = $getUserProfile['name']; $uid = $getUserProfile['uid']; $sessions = array('uid' => $uid, 'email' => $email, 'name' => $name, 'level' => $level, 'idlevel' => $idlevel, 'access_token' => $getAccessToken); // account diblokir/banned if ($status == '0') { $data['message'] = '!! Account anda diblokir. Untuk informasi lebih lanjut, silahkan hubungi Administrator !!'; // account aktif } elseif ($status == '1') { $this->session->sess_expiration = '3600'; $this->session->set_userdata($sessions); redirect(''); } } else { $data['message'] = 'Anda tidak terdaftar sebagai admin aplikasi ini. Silahkan hubungi Administrator untuk mendapatkan akses.'; } } else { $data['message'] = 'Your Email account is not valid.'; } //$_SESSION['access_token'] = $getAccessToken; //$access_token = json_decode($getAccessToken); //$_SESSION['new_access_token'] = $access_token['access_token']; //$redirect_uri = base_url(''); //header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); //redirect(filter_var($redirect_uri, FILTER_SANITIZE_URL)); } $content['CONTENT'] = $this->parser->parse($this->path_view . '/login', $data, true); $this->parser->parse($this->settings['default_layout'], $content); }
function authGoogle($get) { require_once 'lib/vendor/autoload.php'; # require_once 'lib/google-php-client/vendor/autoload.php'; global $google_clientid, $google_secret, $google_config_file_path; /************************************************* * Ensure you've downloaded your oauth credentials ************************************************/ if (!file_exists($google_config_file_path)) { return array("status" => false, "error" => "Bad config file path"); } /************************************************ * NOTICE: * The redirect URI is to the current page, e.g: * http://localhost:8080/idtoken.php ************************************************/ $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; $client = new Google_Client(); $client->setAuthConfig($google_config_file_path); $client->setRedirectUri($redirect_uri); $client->setScopes('email'); /************************************************ * If we're logging out we just need to clear our * local access token in this case ************************************************/ if (isset($_REQUEST['logout'])) { unset($_SESSION['id_token']); } $token = $get["token"]; try { /************************************************ * If we have a code back from the OAuth 2.0 flow, * we need to exchange that with the * Google_Client::fetchAccessTokenWithAuthCode() * function. We store the resultant access token * bundle in the session, and redirect to ourself. ************************************************/ if (!empty($token) && empty($get["tokens"])) { $fancyToken = array("access_token" => $token); $token = $client->fetchAccessTokenWithAuthCode($get["token"]); $client->setAccessToken($token); // store in the session also $_SESSION['id_token'] = $token; $token_data = $client->verifyIdToken(); } else { if (!empty($get["tokens"])) { $tokens = base64_decode($get["tokens"]); $client->setAccessToken($get["tokens"]); $ta = json_decode($tokens, true); $token_data = $client->verifyIdToken($ta["id_token"]); } else { /************************************************ If we have an access token, we can make requests, else we generate an authentication URL. ************************************************/ $authUrl = $client->createAuthUrl(); } } } catch (Exception $e) { $token2 = $get['token']; if (is_string($token2)) { if ($json = json_decode($token2, true)) { $token2 = $json; } else { // assume $token is just the token string $token2 = array('access_token' => $token2); } } return array("status" => false, "error" => $e->getMessage(), "stack" => $e->getTraceAsString(), "token" => $token, "computed_token" => $token2, "tokens" => base64_decode($get["tokens"])); } /************************************************ If we're signed in we can go ahead and retrieve the ID token, which is part of the bundle of data that is exchange in the authenticate step - we only need to do a network call if we have to retrieve the Google certificate to verify it, and that can be cached. ************************************************/ $return = array("status" => true, "auth_url" => $authUrl, "token_data" => $token_data, "identifier" => $token_data["email"], "verifier" => computeUserPassword($token_data["sub"])); return $return; }