/** * Creates an instance of this class (only once) and returns it * @return GoogleAuth */ public static function getInstance() { # Create the instance if it hasn't been created yet if (!isset(GoogleAuth::$instance)) { GoogleAuth::$instance = new GoogleAuth(); } # Set auth access token # Access token is session is set when user successfully signs in # using Google and is returned back to the page (the method to catch the code # that is passed back is in index.php) GoogleAuth::$auth = HTTPSession::getInstance()->ACCESS_TOKEN; # If auth code is not empty, it means that user was successfully signed in # using Google sign in, therefore set the received access token for client # and authorise using HTTPSession if (!empty(GoogleAuth::$auth)) { GoogleAuth::$instance->setToken(); # TODO: First we need to check if session is still valid # This implementation needs to be finished in the future version, # since it gets more complex and takes too much time if (GoogleAuth::$instance->checkIfExpired()) { echo "Google session expired"; die; } # Login the user using provided email HTTPSession::getInstance()->LoginGoogle(GoogleAuth::$instance->getUserEmail()); } # Return the new instance or already existing instance return GoogleAuth::$instance; }
public function index($error = null) { # If user is logged in but accidentally arrives to login page # redirect the user to home page if (HTTPSession::getInstance()->IsLoggedIn()) { header('Location: ' . SITE_URL); } # Get link for google auth (this is for the "Sign in using Google" button $link = GoogleAuth::getInstance()->getAuthLink(); # Display login page $this->view('login/index', ['error' => $error, 'link' => $link], false); }
<?php $redirect = function () { if (array_key_exists('state', $_GET)) { header('Location: ' . $_GET['state']); } else { header('Location: /'); } }; $auth = new GoogleAuth(Config::get('GOOGLE_WA_CLIENT_ID'), Config::get('GOOGLE_WA_CLIENT_SECRET'), Config::get('GOOGLE_OAUTH_REDIRECT_URI'), Config::get('GOOGLE_OAUTH_SCOPES')); $info = $auth->getUserInfo($_GET['code']); if (null === $info) { // Access denied $redirect(); } else { // Access granted $email = $info['email']; $nick = $info['name']; $picture = $info['picture']; $user = Users::getByEmail($email); if (null == $user) { $user = Users::add($email); $user->setNick($nick); $user->setPicture(Image::INSERT($picture)); } $user->login(); $redirect(); }
<?php # Initial steps performed before the application is started require_once 'app/init.php'; # Check whether code was passed back # This happens when user tries to login using GoogleAuth and # code is passed back, which is processed in the GoogleAuth class afterwards if (isset($_GET['code'])) { # If it was, pass it to the class GoogleAuth::getInstance()->checkCode($_GET['code']); } ### Start up the App class which takes care of routing ### $app = new App();
if (preg_match('/^[a-zA-Z0-9\\x80-\\xff]{4,20}$/i', $name)) { if (preg_match('/^[0-9]{4,20}$/', $name)) { $errors[] = '名字不能全为数字'; } else { error_reporting(0); session_start(); if ($seccode === intval($_SESSION['code'])) { $db_user = $DBS->fetch_one_array("SELECT * FROM yunbbs_users WHERE name='" . $name . "' LIMIT 1"); if ($db_user) { $pwmd5 = encode_password($pw, $db_user['regtime']); if ($pwmd5 == $db_user['password']) { // G Auth Checking $gsecret = $db_user['gauthsecret']; if ($gsecret != Null) { if ($gcode) { $ga = new GoogleAuth(); $checkResult = $ga->verifyCode($gsecret, $gcode); if ($checkResult) { //设置cookie $db_ucode = md5($db_user['id'] . $db_user['password'] . $db_user['regtime'] . $db_user['lastposttime'] . $db_user['lastreplytime']); $cur_uid = $db_user['id']; setcookie("cur_uid", $cur_uid, time() + 86400 * 365, '/'); setcookie("cur_uname", $name, time() + 86400 * 365, '/'); setcookie("cur_ucode", $db_ucode, time() + 86400 * 365, '/'); $cur_user = $db_user; unset($db_user); header('location: /'); exit('logined'); } else { $errors[] = '安全码已过期或输入不正确!'; }
# Define site URL constant, which is further used in controllers define('SITE_URL', $config->{'site_url'}); # Set time zone date_default_timezone_set($config->{'timezone'}); # Include essential classes require_once 'core/DatetimeConverter.php'; require_once 'core/App.php'; require_once 'core/Controller.php'; require_once 'core/GoogleAuth.php'; require_once 'models/DataBoundObject.php'; require_once 'models/ProjectFactory.php'; require_once 'models/HTTPSession.php'; require_once 'models/Notification.php'; require_once 'models/NotificationAP.php'; require_once 'models/NotificationMeeting.php'; require_once 'models/NotificationNote.php'; # Start a more secure session $objSession = HTTPSession::getInstance(); # Update the inactivity time on every reload of the page $objSession->Impress(); # Start up a GoogleAuth # TODO: This must be commented out for ssms.emilc.cz, because there's wrong redirect_uri GoogleAuth::getInstance(); # Check if user is NOT logged in if (!$objSession->IsLoggedIn()) { # Redirect to login page only if we're not already on login page # otherwise we would get a redirect loop if (isset($_GET['url']) && !(strpos($_GET['url'], 'login') !== false)) { header("Location: " . SITE_URL . "login"); } }
<?php require_once 'init.php'; $db = new DB(); $googleClient = new Google_Client(); $auth = new GoogleAuth($db, $googleClient); if ($auth->checkRedirectCode()) { header('Location: login.php'); } ?> <!DOCTYPE html> <html lang="nl"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Samenvattingen | Login</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous"> <!-- MATERIAL BOOTSTRAP? <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/paper/bootstrap.min.css"> --> <link rel="stylesheet" href="http://localhost/samenvattingen/css/base.css"> <!-- CHANGE TO NON-LOCAL URL --> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]-->
public static function processLogin() { if (isset($_GET['code'])) { require_once '../config.php'; $params = array('client_id' => self::$client_id, 'client_secret' => self::$client_secret, 'redirect_uri' => 'http://' . self::$redirect_host . self::$redirect_path, 'grant_type' => 'authorization_code', 'code' => $_GET['code']); $url = 'https://accounts.google.com/o/oauth2/token'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, urldecode(http_build_query($params))); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($curl); curl_close($curl); $tokenInfo = json_decode($result, true); if (isset($tokenInfo['access_token'])) { $params['access_token'] = $tokenInfo['access_token']; $userInfo = json_decode(file_get_contents('https://www.googleapis.com/oauth2/v1/userinfo' . '?' . urldecode(http_build_query($params))), true); if (isset($userInfo['id'])) { $userInfo = array('nickname' => $userInfo['given_name'] . $userInfo['id'], 'email' => $userInfo['email'], 'first_name' => $userInfo['given_name'], 'last_name' => $userInfo['family_name'], 'password' => 'Google_id' . $userInfo['id']); require_once 'Session.php'; session_start(); Session::set('user', $userInfo); header('Location: /?route=security/social_auth'); } } } } } GoogleAuth::processLogin();
<tbody> <tr> <td width="120" align="right">请输入Google Auth中显示的验证码以便确认</td> <td width="auto" align="left"><input type="text" class="sl" name="gauthcode" value="" /></td> </tr> <tr> <td width="120" align="right"></td> <td width="auto" align="left"><input type="submit" value="确定关闭二次登录" name="submit" class="textbtn" /></td> </tr> </tbody></table> </form> </div>'; } else { $ga = new GoogleAuth(); $secret = $ga->createSecret(); $qrCodeUrl = $ga->createQRCode($options['name'], $secret); echo ' <a name="4"></a> <div class="title"><i class="fa fa-angle-double-right"></i> 设置二次验证 </div> <div class="main-box"> <p class="red">', $tip4, '</p> <form method="post" action="', $_SERVER["REQUEST_URI"], '#4"> <input type="hidden" name="action" value="setgauth" /> <input type="hidden" name="gsecret" value="', $secret, '" /> <table cellpadding="5" cellspacing="8" border="0" width="100%" class="fs12" height="120px"> <tbody> <tr>
<?php require_once 'googleapp/init.php'; $auth = new GoogleAuth(); $auth->logout(); header('Location: index.php');
<?php $state = urlencode(Lib::getCurrentUrl()); $auth = new GoogleAuth(Config::get('GOOGLE_WA_CLIENT_ID'), Config::get('GOOGLE_WA_CLIENT_SECRET'), Config::get('GOOGLE_OAUTH_REDIRECT_URI'), Config::get('GOOGLE_OAUTH_SCOPES'), $state); ?> <a href="<?php echo $auth->getAuthLink(); ?> " component="LoginWithGoogle"> <span class="icon"></span> <span class="text">[[COMPONENT name=Label text='Login with Google' id=login-with-google]]</span> </a>
if (isset($_GET['provider']) && !empty($_GET['provider'])) { $provider = $_GET['provider']; fwrite($output, $provider); $headerBody = file_get_contents("php://input"); if (is_string($headerBody)) { //fwrite($output, "\n\n".$headerBody); $parsedBody = json_decode($headerBody, true); if (isset($parsedBody['code']) && !empty($parsedBody['code'])) { /* Query the DB, check if user's created in provider's specific table If yes: authenticate with that info If no: check if user is currently authenticated (Bearer) If yes: add info to that specific provider's table If no: create a user with info from the API and add it to provider's table */ $googleClient = new Google_Client(); $googleAuth = new GoogleAuth($googleClient); $accessToken = json_decode($googleAuth->getAccessToken($parsedBody['code']), true); $userData = json_decode(file_get_contents("https://www.googleapis.com/userinfo/v2/me?access_token=" . $accessToken['access_token']), true); //fwrite($output, "\nsuccess".print_r($userData, true)); try { $dbh = new PDO($dbn, $database['user'], $database['password']); } catch (PDOException $e) { fwrite($output, "Connection failed: " . $e->getMessage()); header("HTTP/1.1 500 Internal Server Error"); } $checkQuery = $dbh->prepare("SELECT users.* FROM google_users, users WHERE google_users.google_id = :googleid AND users.id = google_users.user_id LIMIT 1;"); $checkQuery->bindParam(":googleid", $userData['id']); $checkQuery->execute(); $checkQueryResults = $checkQuery->fetch(PDO::FETCH_ASSOC); fwrite($output, "\n\n" . print_r($checkQueryResults, true) . "\n" . $userData['id']); if ($checkQueryResults) {
/** * A method to process POST request for editing an existing meeting * @param null $post the $_POST array */ public function editPost($post = null) { if (isset($post)) { # Create an object of existing meeting $meeting = $this->model('Meeting', $post['id']); # Check if we have access to editing $this->checkAuthIsApproved($meeting); $this->checkAuthCancelled($meeting); $this->checkAuthProjectScope($meeting->getProjectId()); # Set googleEventId to the value provided from database (if any) $googleEventId = $meeting->getGoogleEventId(); # Get details from post request $deadline = $post['deadline']; $deadline_time_hours = $post['deadline_time_hours']; $deadline_time_minutes = $post['deadline_time_minutes']; $isApproved = 0; if (isset($post['isApproved'])) { $isApproved = 1; } # If it's the supervisor who edits, it's automatically approved if (HTTPSession::getInstance()->USER_TYPE == User::USER_TYPE_SUPERVISOR) { $isApproved = 1; } $arrivedOnTime = 0; if (isset($post['arrivedOnTime'])) { $arrivedOnTime = 1; } $takenPlace = 0; if (isset($post['takenPlace'])) { $takenPlace = 1; } $isCancelled = 0; if (isset($post['isCancelled'])) { $isCancelled = 1; } # Set correct format of provided date $dateTime = DateTime::createFromFormat('d-m-Y H:i', $deadline . " " . $deadline_time_hours . ":" . $deadline_time_minutes); $date = $dateTime->format('Y-m-d H:i:s'); # Set meeting with provided details $meeting->setDatetime($date); $meeting->setIsApproved($isApproved); $meeting->setTakenPlace($takenPlace); $meeting->setArrivedOnTime($arrivedOnTime); $meeting->setIsCancelled($isCancelled); # Check if meeting is approved by a supervisor and user is logged in as google user # Also check if googleEventId exists for this meeting if ($isApproved && !empty(GoogleAuth::$auth) && !empty($googleEventId)) { # Get google auth format of datetime $datetimeGoogleStart = DatetimeConverter::getGoogleAuthDateTimeFormat($date); $datetimeGoogleEnd = $dateTime; $datetimeGoogleEnd->modify("+1 hour"); $datetimeGoogleEnd = DatetimeConverter::getGoogleAuthDateTimeFormat($datetimeGoogleEnd->format('Y-m-d H:i:s')); # In that case, we can add it to the google calendar and save the id of this event $googleEventId = GoogleAuth::getInstance()->editEventInCalendar($googleEventId, $datetimeGoogleStart, $datetimeGoogleEnd); } if (!empty($googleEventId)) { $meeting->setGoogleEventId($googleEventId); } # Save changes $meeting->Save(); # If meeting has taken place, create a notification if ($takenPlace) { new NotificationMeeting($meeting->getID(), NotificationMeeting::TAKEN_PLACE); } } # Redirect back to meetings header('Location: ' . SITE_URL . 'meetings/' . $post['id']); die; }
<?php require_once 'init.php'; $db = new DB(); $googleClient = new Google_Client(); $auth = new GoogleAuth($db, $googleClient); ?> <!-- HEADER TO INCLUDE IN ALL PAGES --> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <!-- Correct display on mobile screens --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" id="brand" href="index.php">Samenvattingen</a> </div> <!-- Collection of all navbar elements to collapse on mobile --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <!-- Links --> <ul class="nav navbar-nav"> </ul> <!-- Search --> <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="NLT H3">