Skip to content

Instantly share code, notes, and snippets.

@Dygear
Last active July 18, 2022 12:01
Show Gist options
  • Save Dygear/4f512e52e5be549afc86f0098dc4762a to your computer and use it in GitHub Desktop.
Save Dygear/4f512e52e5be549afc86f0098dc4762a to your computer and use it in GitHub Desktop.
Google OAuth Login Flow
<?php
if (isset($_GET['logout']))
{
session_unset();
header('Location: /');
return;
}
define('client_id', 'CLIENT_ID');
define('redirect_uri', 'THIS_FILES_URL_ON_INTERNET');
define('client_secret', 'CLIENT_SECRET_KEY');
// Step 1 - Obtain permission.
$query = [
'redirect_uri' => redirect_uri,
'response_type' => 'code',
'client_id' => client_id,
'scope' => 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
'access_type' => 'offline'
# 'approval_prompt' => 'force'
];
if (isset($_SESSION['login']) AND $_SESSION['login'] == 'force')
$query['approval_prompt'] = 'force';
$_SESSION = [];
if (!isset($_GET['code']))
{
header('Location: https://accounts.google.com/o/oauth2/auth?' . http_build_query($query));
die();
}
// Step 2 - Get access token.
$token_request_body = http_build_query([
'code' => $_GET['code'],
'redirect_uri' => redirect_uri,
'client_id' => client_id,
'scope' => 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
'client_secret' => client_secret,
'grant_type' => 'authorization_code'
]);
$response = file_get_contents(
'https://accounts.google.com/o/oauth2/token',
false,
stream_context_create([
'http'=> [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $token_request_body,
'timeout' => 15.0,
'ignore_errors' => true,
]
])
);
$json = json_decode($response, TRUE);
// Step 3 - Obtain user details.
$response = file_get_contents(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token={$json['access_token']}",
false,
stream_context_create([
'http'=> [
'method' => 'GET',
'header' => "Authorization: Bearer {$json['access_token']}\r\n",
'timeout' => 15.0,
'ignore_errors' => true,
]
])
);
$json = json_decode($response, TRUE);
// Step 4 - Check for Errors / WLVAC account.
if (isset($json['error']))
{
die($_SESSION['error'] = $json['error']['code'] . ' ' . $json['error']['message']);
}
# Make sure the user email is correct for this department.
if (!Users::isCorrectEmail($json['email']))
{
$_SESSION['error'] = 'Please sign in with your department email address';
$_SESSION['login'] = 'force';
header('Location: /');
return;
}
$now = (new DateTime('now', new \DateTimeZone('UTC')))->format(DateTime::Google);
$_SESSION = Users::login($json['id'], $json['email'], $json['name'], $json['family_name'], $json['given_name'], $json['picture'], $now);
header('Location: /');
CREATE TABLE users (
userId INTEGER PRIMARY KEY,
Id TEXT NOT NULL UNIQUE,
EmailAddress TEXT NOT NULL UNIQUE,
DisplayName TEXT
)
CREATE TABLE profile (
userId INTEGER PRIMARY KEY,
nameFamily TEXT,
nameGiven TEXT,
picture TEXT,
dateJoined DATETIME DEFAULT CURRENT_DATE,
dateOfBirth DATETIME,
numberBadge INTEGER,
accessLevel INTEGER,
bio BLOB,
theme TEXT,
FOREIGN KEY(userId) REFERENCES users(userId)
)
<?php
class Users
{
const SQL_ASSUME = 'SELECT users.*, profile.accessLevel AS accessLevel FROM users NATURAL LEFT JOIN profile WHERE userId = :userId LIMIT 0, 1;';
const SQL_CHECK_BY_ID = 'SELECT users.*, profile.* FROM users NATURAL LEFT JOIN profile WHERE Id = :Id LIMIT 0, 1;';
const SQL_CHECK_BY_EMAIL = 'SELECT users.*, profile.* FROM users NATURAL LEFT JOIN profile WHERE EmailAddress = :EmailAddress LIMIT 0, 1;';
const SQL_REGISTER_USER = 'INSERT INTO users (Id, EmailAddress, DisplayName) VALUES (:Id, :EmailAddress, :DisplayName);';
const SQL_REGISTER_PROFILE = 'INSERT INTO profile (userId, nameFamily, nameGiven, picture, dateJoined) VALUES (:userId, :nameFamily, :nameGiven, :picture, :dateJoined);';
private static $domains = ['@company.com', '@company.net', '@company.org', '@company.io'];
static public function isCorrectEmail($EmailAddress)
{
foreach (self::$domains as $domain) {
if (substr($EmailAddress, -strlen($domain)) === $domain) {
return true;
}
}
return false;
}
static public function assume(int $userId)
{
global $db;
$statement = $db->prepare(self::SQL_ASSUME);
$statement->execute([':userId' => $userId]);
return $statement->fetch();
}
static public function login($Id, $EmailAddress, $DisplayName, $nameFamily, $nameGiven, $Picture, $dateJoined)
{
// Check this database.
$resultSet = self::checkById($Id);
// If user doesn't exist, register them.
if ($resultSet === false) {
self::register($Id, $EmailAddress, $DisplayName, $nameFamily, $nameGiven, $Picture, $dateJoined);
$resultSet = self::checkById($Id);
}
return $resultSet;
}
static private function checkById($Id)
{
global $db;
$statement = $db->prepare(self::SQL_CHECK_BY_ID);
$statement->execute([':Id' => $Id]);
return $statement->fetch();
}
static public function register($Id, $EmailAddress, $DisplayName, $nameFamily, $nameGiven, $Picture, $dateJoined)
{
global $db;
echo 'Register User';
print_r([
':Id' => $Id,
':EmailAddress' => $EmailAddress,
':DisplayName' => $DisplayName
]);
$statement = $db->prepare(self::SQL_REGISTER_USER);
$statement->execute([
':Id' => $Id,
':EmailAddress' => $EmailAddress,
':DisplayName' => $DisplayName
]);
$userId = $db->lastInsertId();
echo 'Register Profile';
print_r([
':userId' => $userId,
':nameFamily' => $nameFamily,
':nameGiven' => $nameGiven,
':picture' => $Picture,
':dateJoined' => (new DateTime($dateJoined, new \DateTimeZone('UTC')))->setTimezone(new \DateTimeZone('America/New_York'))->format(DateTime::WEB)
]);
$statement = $db->prepare(self::SQL_REGISTER_PROFILE);
$statement->execute([
':userId' => $userId,
':nameFamily' => $nameFamily,
':nameGiven' => $nameGiven,
':picture' => $Picture,
':dateJoined' => (new DateTime($dateJoined, new \DateTimeZone('UTC')))->setTimezone(new \DateTimeZone('America/New_York'))->format(DateTime::WEB)
]);
}
}
@Dygear
Copy link
Author

Dygear commented Jul 18, 2022

This uses 7+ years old PHP code. I'm pretty sure I wrote it for PHP 5.6 and so it doesn't use any of the type system that was put into PHP. I've removed the name spaces as it just muddles this a little for a newer programmer to understand.

You will notice that global $db is in a few functions. This is the connection to the PDO object that has the SQLite database attached to it. I usually have a bootstrap.php file below the webroot that all of my php files call into so they have the same env to work from. It also used as the autoloader for my PHP classes. I'll reproduce what that looks like in this comment because it's not exactly the same in order to save you some time.

Database.php

class Database extends \PDO
{
    /**
     * @param string $file - The file path where the SQLite database is.
     */
    public function __construct($file)
    {
        parent::__construct('sqlite:' . $file);
        $this->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
        $this->query('PRAGMA foreign_keys = ON;');
    }
}

Database has a bunch more functions that don't help you in this case, so I'm not going to expose them. Again $file should always be string so that should be type you add for PHP 7.3 and up.

Use that code like this ...

bootstrap.php

  $db = new Database('/mnt/db/sqlite.db');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment