@alphasoftx/google-auth v1.1.0
Google Auth
Google Auth is a NodeJS library which helps in authentication with google in backend!
This library simply exports 2 functions, getGoogleAuthUrl and getGoogleUser, which helps in authentication with google using nodejs backend!
Install
NPM
Latest version
npm i @alphasoftx/google-auth@latestSpecific version
npm i @alphasoftx/google-auth@<version>Yarn
Latest version
yarn add @alphasoftx/google-auth@latestSpecific version
yarn add @alphasoftx/google-auth@<version>Note: Remember to replace <version> with your version name, for example, 1.0.0, 1.1.0, 2.0.1 etc.
Docs
Let's have a look that how this library works, and to do so, we will create a small project!
Step 1
Create a folder named as google-auth-example, this is your project folder!
Step 2
Open command line interface in your project folder and initialise a nodejs project by executing the following command:-
npm initOR
yarn initThese commands will ask some questions related to your project, answer them and your project will be initialised!
Now add a field in your package.json file:-
{
"type": "module",
} This field defines your project as a nodejs module, this is an important field as @alphasoftx/google-auth package doesn't supports require('') syntax!
Step 3
Create a file named as index.js, this will be your main project file!
Note: Project file name should be as same as you written in "main" field in package.json while initialisation of your project!
Step 4
Execute the following command to install all of the dependencies of this project which are express, express-session and @alphasoftx/google-auth:-
npm i express express-session @alphasoftx/google-authOR
yarn add express express-session @alphasoftx/google-authExpress is a backend server module which helps in building server!
Express session is a backend module which helps in authentication with express without any frontend role, you can use jsonwebtoken instead of this module!
Note: you can have more dependencies according to your project, this project has three dependencies as this is a small project!
Step 5
Go to Google developers console and create a project with OAuth client id, for more details, you can watch this youtube video!
Step 6
Now we will start writing code in index.js file:-
// Importing required modules
import express from "express";
import session from "express-session";
import { getGoogleAuthUrl, getGoogleUser } from "@alphasoftx/google-auth";// Variables
const app = express();
const port = 5000;
// Middlewares
app.use(express.json());
app.use(
session({
secret: /* your express-session secret */,
resave: false,
saveUninitialized: true,
})
);// Endpoints of the server
app.get('/', (req, res)=>{
if(req.session.user){
res.send(`
Name: ${req.session.user.name}<br>
Email: ${req.session.user.email}<br>
Image: <img src="${req.session.user.picture}" alt="User image" referrerpolicy="no-referrer"/><br>
<a href="http://localhost:${port}/logout">Logout</a>
`);
}else{
res.send(`<a href='${getGoogleAuthUrl({
redirectUrl: `http://localhost:${port}/auth/google`,
clientId: /* your cliend id */
})}'>Google</a>`);
}
});
app.get('/auth/google', async (req, res)=>{
let user = await getGoogleUser({
...req.query,
clientId: /* your client id */,
clientSecret: /* your client secret */,
redirectUrl: `http://localhost:${port}/auth/google`
});
if(user.err === true){
return res.status(404).send("Url not found!");
}
req.session.user = user;
req.session.save();
res.redirect('/');
});
app.get('/logout', (req, res)=>{
req.session.destroy(err=>{
if(err) return console.log(err.message);
res.redirect('/');
});
});// Starting nodejs server
app.listen(port, () => {
console.log(`Your server is running at http://localhost:${port}`);
});Step 7
Now run your server with following command:-
node index.jsSummary
getGoogleAuthUrl function needs an object with redirectUrl and clientId and it returns a url of google authentication, and you can also pass an optional field named scopes to define google oauth scopes!
getGoogleUser function is used on redirect url to get and save user, this function needs an object with clientId, clientSecret, redirectUrl and req.query and returns an object of user or error message!
Note: Remember to add referrerpolicy="no-referrer" attribute to img tag as sometimes you may get an error that client don't have permission to access the image!