Set up google OAuth2 Login with Express
/// STEP 2. make main.ejs
// include get route, get some data callback, get some data
const express = require('express');
const google = require('googleapis').google;
const jwt = require('jsonwebtoken');
// Google's OAuth2 client
const OAuth2 = google.auth.OAuth2;
// Including our config file
const CONFIG = require('./config');
// Creating our express application
const app = express();
// Allowing ourselves to use cookies
const cookieParser = require('cookie-parser');
app.use(cookieParser());
// Setting up Views
app.set('view engine', 'ejs');
app.set('views', __dirname);
////////// app.get '/' Route /////////////////////////
// GET route where we’ll put our link to log in with google.
app.get('/', function (req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(CONFIG.oauth2Credentials.client_id, CONFIG.oauth2Credentials.client_secret, CONFIG.oauth2Credentials.redirect_uris[0]);
// Obtain the google login link to which we'll send our users to give us access
const loginLink = oauth2Client.generateAuthUrl({
access_type: 'offline', // Indicates that we need to be able to access data continously without the user constantly giving us consent
scope: CONFIG.oauth2Credentials.scopes // Using the access scopes from our config file
});
return res.render("index", { loginLink: loginLink });
});
/////////////////////////////////////////////////////////////
// Redirect user to /get_some_data page,
app.get('/auth_callback', function (req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(CONFIG.oauth2Credentials.client_id, CONFIG.oauth2Credentials.client_secret, CONFIG.oauth2Credentials.redirect_uris[0]);
if (req.query.error) {
// The user did not give us permission.
return res.redirect('/');
} else {
oauth2Client.getToken(req.query.code, function(err, token) {
if (err)
return res.redirect('/');
// Store the credentials given by google into a jsonwebtoken in a cookie called 'jwt'
res.cookie('jwt', jwt.sign(token, CONFIG.JWTsecret));
return res.redirect('/get_some_data'); // renders index template with login link
});
}
});
/////////////// get_some_data page ////////////////////////////
// In aidan's example, 5 user subscribed channels are displayed.
// Needs to create OAuth2 client then add user’s credentials
// to access anything. Then Gets subscriptions, sends to template.
///////////////////////////////////////////////////////////////
app.get('/get_some_data', function (req, res) {
if (!req.cookies.jwt) {
// We haven't logged in
return res.redirect('/');
}
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(CONFIG.oauth2Credentials.client_id, CONFIG.oauth2Credentials.client_secret, CONFIG.oauth2Credentials.redirect_uris[0]);
// Add this specific user's credentials to our OAuth2 client
oauth2Client.credentials = jwt.verify(req.cookies.jwt, CONFIG.JWTsecret);
// Get the youtube service
const service = google.youtube('v3');
// Get five of the user's subscriptions (the channels they're subscribed to)
service.subscriptions.list({
auth: oauth2Client,
mine: true,
part: 'snippet,contentDetails',
maxResults: 5
}).then(response => {
// Render the data view, passing the subscriptions to it
return res.render('data', { subscriptions: response.data.items });
});
});
// Listen on the port defined in the config file
app.listen(CONFIG.port, function () {
console.log(`Listening on port ${CONFIG.port}`);
});
4.25
8
// STEP 4. ///////////////////////////////////////////////
// Lastly create the data.ejs template in order
// to display the data.
//////////////////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Express Google OAuth2 Tutorial by Aidan Lovelace</title>
</head>
<body>
<ul>
<% subscriptions.forEach(function (subscription) { %>
<li><%= subscription.snippet.title %></li>
<% }) %>
</ul>
</body>
</html>
Thank you!
8
0
4
1
//////// STEP 3. //////////////////////////////////////
////// Create base html(ish) file named index.ejs /////
// with a login link to the page we passed to the file.
/////////////// index.ejs /////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Express Google OAuth2 Tutorial by Aidan Lovelace</title>
</head>
<body>
<a href="<%= loginLink %>">Login</a>
</body>
</html>
Thank you!
1
0
4
3
// STEP 1. Install dependencies and make config.js
// project for understanding google authorization with express
//set up your Node.JS project, and install the following dependencies:
// cookie-parser
// ejs
// express
// google-auth-library
// googleapis
// jsonwebtoken
// In the Credentials section of the Google Developer Console,
// create an OAuth Client ID credential of type Web Application.
// Create a file named config.js with the following contents,
// Fill in the client_id, project_id, and client_secret properties
// with the information for your project.
////////////////////////// config.js
const port = 3002;
const baseURL = `http://localhost:${port}`;
module.exports = {
// The secret for the encryption of the jsonwebtoken
JWTsecret: 'mysecret',
baseURL: baseURL,
port: port,
// The credentials and information for OAuth2
oauth2Credentials: {
client_id: "",
project_id: "", // The name of your project
auth_uri: "https://accounts.google.com/o/oauth2/auth",
token_uri: "https://oauth2.googleapis.com/token",
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
client_secret: "",
redirect_uris: [
`${baseURL}/auth_callback`
],
scopes: [
'https://www.googleapis.com/auth/youtube.readonly'
]
}
};
Thank you!
3
0
Are there any code examples left?
New code examples in category Javascript
-
Javascript 2023-04-21 22:52:36
-
Javascript 2022-03-27 22:25:20 javascript download string as file
-
Javascript 2022-03-27 21:40:22 sort numbers in array javascript
-
Javascript 2022-03-27 21:20:04 compare two arrays and return the difference javascript
-
Javascript 2022-03-27 21:15:02 javascript regex french phone number
-
Javascript 2022-03-27 21:05:03 cypress custom error message
-
Javascript 2022-03-27 21:00:05 create element javascript with id
-
Javascript 2022-03-27 20:40:57 feather icons react
-
Javascript 2022-03-27 20:20:01 how to make graphql request in axios
-
Javascript 2022-03-27 20:15:07 bootstrap validator password and confirm password