PHP authentication on Google Cloud
How to set up an authentication module on Google Cloud with PHP.
Step 1: Create your list of admin users
Step 1: Create your list of admin users
Go to
https://console.cloud.google.com/iam-admin/iam/project?project=<your_project_name>&authuser=0
and add users and assign roles to them. I used my work Gmail account as an admin user, and my personal Gmail as an ordinary user.Step 2. specify resources for login
In your
app.yaml
file, specify which resources you want to be restricted to authenticated users, and which are admin-only.- url: /
script: index.php
login: required
secure: always
# this requires login but is available to all users
- url: /admin
script: admin/index.php
login: admin
secure: always
# this requires login and is only available to admin users
Step 3. Add authentication PHP to your header include
This is the code for my normal user pages:
<?php
use google\appengine\api\users\User;
use google\appengine\api\users\UserService;
$user = UserService::getCurrentUser();
if (isset($user)) {
$authmessage = sprintf('Logged in as %s | <a href="%s">Log out</a>',
$user->getNickname(),
UserService::createLogoutUrl('/'));
} else {
$authmessage = sprintf('<a href="%s">Log in or register</a>',
UserService::createLoginUrl('/'));
}
if (isset($user) && UserService::isCurrentUserAdmin()) {
$admin = TRUE;
} else {
$admin = FALSE;
}
?>
And this is the PHP in my admin header include:
<?php
use google\appengine\api\users\User;
use google\appengine\api\users\UserService;
$user = UserService::getCurrentUser();
if (isset($user)) {
$authmessage = sprintf('Logged in as %s | <a href="%s">Log out</a>',
$user->getNickname(),
UserService::createLogoutUrl('/'));
} else {
$authmessage = sprintf('<a href="%s">Log in or register</a>',
UserService::createLoginUrl('/'));
}
if (isset($user) && UserService::isCurrentUserAdmin()) {
$admin = TRUE;
} else {
echo 'Sorry, you are not authorised to access this page.';
}
?>
Step 4. Add login / logout links to your header include
In your HTML for the normal header, add the following:
<?php
echo $authmessage;
if($admin == TRUE) {
echo ' | <a href="/admin">Admin</a>';
}
?>
and in your HTML for the admin header, add the following:
<?php
echo $authmessage;
if($admin == TRUE) {
echo ' | <a href="/">App</a>';
}
?>
Documentation
- Documentation for authenticating admin users
https://cloud.google.com/appengine/docs/standard/php/users/adminusers - Documentation for authenticating general users
https://cloud.google.com/appengine/docs/standard/php/users/
Comments
Post a Comment