Here is the code for JWT:
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
app.use(express.json());
const user = [
{
name: "Rohan",
id: 1,
},
{
name: "Sophie",
id: 2,
},
{
name: "Charlie",
id: 3,
},
];
app.get("/", (req, res) => {
res.send("Welcome to Homepage");
});
app.get("/id", verifyToken, (req, res) => {
res.json(user.filter((id) => user.name === req.user.name));
});
function verifyToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, "secretKey", (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.post("/login", (req, res) => {
const username = req.body.username;
const user = { name: username };
jwt.sign(user, "secretKey", (err, token) => {
res.json({ token: token });
});
});
app.listen(4000, () => {
console.log("Server is listening on port: 4000");
});
The req.headers['authorization'] is returning undefined when console.log(The req.headers['authorization'])
This code for JWT always return Status 401 (Unauthorized) when the request is sent in the format Authorization: Bearer "token" ,
Please help !!
Do you use the Postman for test?
add 'authorization' key in headers section on the postman, like picture:
and not need 'authHeader.split(" ")1;' , please change your code like this:
const token = req.headers["authorization"];
// const token = authHeader && authHeader.split(" ")[1];
console.log(token)
Related
I'm trying to create an application which uses JWKS with RSA to sign cookies. I have some issues with the passport strategy I defined, when I try using it, the following error appears:
done(null, jwks.keys[0])
^
TypeError: Cannot read properties of undefined (reading '0')
My code for the passport Strategy I created is the following:
passport.use('jwt-jku', new JwtStrategy({
jwtFromRequest: req => { return (req && req.cookies) ? req.cookies.jwtCookie : null },
secretOrKeyProvider: (req, rawJwtToken, done) => {
const decoded = jwt.decode(rawJwtToken, { complete: true }) // Tiene .header y .payload
if (decoded.header.jku /* && decoded.payload.role === 'admin' */) {
axios({
method: 'get',
url: decoded.header.jku,
responseType: 'json'
}).then(function (jwks) {
console.log(jwks.toString())
done(null, jwks.keys[0])
})
} /* else if(decoded.payload.role !== 'admin') { ESTO NO VA porq no hay 'res'
req.send("You can't access the fortune teller endpoint! Only admin has access to it!")
} */
}
}, (jwtPayload, done) => { return done(null, jwtPayload ?? false) }
))
I use a file called jwks.json that contains:
{"keys":[{"kty":"RSA","kid":"tbrTvJIqhJ7jnYPdQL-LpkPUwqFltyQnWC5QGGUY8JM","use":"sig","alg":"RS256","e":"AQAB","n":"sFTW93A8v-oDFIS7oB2kzZq0RG15Oim9-FyeiTg6QBHcRb4kbTfXf0bQ3dTe-y0mVKUdZUtFyk71DNmI1INpO9y-QU2b-03KIW56As-kR6cmZeDIFwqDjceoUJreLEdEnxkObxuD5d5Qb7Zt8TS1BiRkX5vpiV32VTWpPZs0TglBv-Jdm54r1bvmrwaVUUMMi0DUptKIKLbqysl1j4OIXQSUMjRJF7OFIDfaZqvhPBNXTW7dbvxbfOq46Gpz_EqD2VBlYXOOgfXh8OhhhPkgZnbkq2HSUO1TZoiGFlq6M-Rah64D_8ESsDG2Bvk1Tx7hUCUmiba4AG2am2Gr8qcMmQ","d":"N0NHogHzkCQrtfUJhptzyJpZL-7tZOyrJJkGeLP-EZFnaxY1_WLYb4PGtxddkPPsBPBAn7vxEgAf7diJeSz8QK4klHvZzG9rT4H7zEC-WFSLBLfnjc0WQMuXtTdsNQ1a9M_aBblmY5cCt5hBqaxepZ-nM42-KfagWsE4Gt43DNN0vO7ztotY5TzKGv2R8TIz8BJIYVLVlUwvFheTDNJ97kz6EMR7keTzRcpg6pj-21l0NCLIySkRv4ZEQirW12kek7hgtI0A-mCiU61-GzX0S_MFEGi16Clk0kIQ6Ld2stT26xT01x0-htubgp-KEgW64GXKetOCzXrjZVivSHywPw","p":"vHSS2gMw56CgPyQmrLQNwR4cwL6QC77Zk5IE2QZlRWBDKUwOYioruqoc8t3Nop5xMcFjbNrtEb2RlMDB-lfyfJtcIWo9xh67AMcZ5Zq-FGnJBTjCry8Vf08r9jAfXzvr5dGbFnp4xV2gpuATQ3apBLy9eCkQKOVshdTbqtbKnCM","q":"74fZ4QSOQKqroCqqGnJ-MyyzTL2mSnthDzo7AmwSIZlzkgaqXO4o27uwRJVW2dxEK0XmDKNd94XNflADv1SDhu3mWcDVjkOjnc-zrVgEZjUWG3sABtwUWlSijOkmZG5jD9KPvb1ksvN0K3Xn0wcu8z1XJ9xSm4gw3NXHM2eBEhM","dp":"Zp64BL1uGQNPn3JpGOwm_T0PfSmHuM2hHwmJWEByTvffOpKu1meOTmQpxVpgiqfqjaR4JqOEKn_m0XCxcEgJxC65WXzHzKWZQRAqGuxLi0QbcZt57_kcpKmRD8semjY_-3JLGE9yik60l4o3Eyp_WRQJvG_n280qbin9wCacR68","dq":"skdAqTQE1KiyuLFIjgqtV1Vr1jBJdqJB6V2D0hexnwRhekwvvJ8eFf2qAkHMtLY2nqaVxM5LABG8ksjnIR68Dk8-5Yqa6Bn7y1dt-hTKoW_dlnKD4JcpJtpbadmWU6W9YWdsyOIP8wk0a6yD8RMlpLEBD4_yhARnqdYLP31IGbU","qi":"iIjOxBfcAwzikLRjMFQRfoEcW2RXDzi0xs2c9keut4j1DVgacVlS5J7sDHcJDsJJToHmaasix7-nl7nA5IYn6UiayzU7BqOc0D-orn8HecWWeYQ6hMZ81U80jRHmSN2cp-g4X2NtduxlGw8yoSlAKxQyEpgb5SqXYcDr5hQNgy4"}]}
I don't know what else to do, following I leave the whole code, maybe its easier to understand or something... Thank you!
const express = require('express')
const logger = require('morgan')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const JwtStrategy = require('passport-jwt').Strategy
const fortune = require('fortune-teller')
const axios = require('axios')
const cookieParser = require('cookie-parser')
const jwt = require('jsonwebtoken')
const fs = require('fs')
const path = require('path')
const jose = require('node-jose') // probar jose
const keyStore = jose.JWK.createKeyStore()
keyStore.generate('RSA', 2048, { alg: 'RS256', use: 'sig' })
.then(result => {
fs.writeFileSync(
path.join(__dirname, 'jwks.json'),
JSON.stringify(keyStore.toJSON(true))
)
// console.log(`Exported JWKSet: ${JSON.stringify(keyStore.toJSON(true), undefined, 2)}`)
})
const port = 3000
const app = express()
app.use(logger('dev'))
app.use(cookieParser())
/*
Configure the local strategy for using it in Passport.
The local strategy requires a `verify` function which receives the credentials
(`username` and `password`) submitted by the user. The function must verify
that the username and password are correct and then invoke `done` with a user
object, which will be set at `req.user` in route handlers after authentication.
*/
passport.use('local', new LocalStrategy(
{
usernameField: 'username', // it MUST match the name of the input field for the username in the login HTML formulary
passwordField: 'password', // it MUST match the name of the input field for the password in the login HTML formulary
session: false // we will store a JWT in the cookie with all the required session data. Our server does not need to keep a session, it's going to be stateless
},
function (username, password, done) {
if (username === 'walrus' && password === 'walrus') {
const user = {
username: 'walrus',
description: 'the only user that deserves to contact the fortune teller'
}
return done(null, user) // the first argument for done is the error, if any. In our case there is no error, and so we pass null. The object user will be added by the passport middleware to req.user and thus will be available there for the next middleware and/or the route handler
}
return done(null, false) // in passport returning false as the user object means that the authentication process failed.
}
))
passport.use('jwt-jku', new JwtStrategy({
jwtFromRequest: req => { return (req && req.cookies) ? req.cookies.jwtCookie : null },
secretOrKeyProvider: (req, rawJwtToken, done) => {
const decoded = jwt.decode(rawJwtToken, { complete: true }) // Tiene .header y .payload
if (decoded.header.jku /* && decoded.payload.role === 'admin' */) {
axios({
method: 'get',
url: decoded.header.jku,
responseType: 'json'
}).then(function (jwks) {
console.log(jwks.toString())
done(null, jwks.keys[0])
})
} /* else if(decoded.payload.role !== 'admin') { ESTO NO VA porq no hay 'res'
req.send("You can't access the fortune teller endpoint! Only admin has access to it!")
} */
}
}, (jwtPayload, done) => { return done(null, jwtPayload ?? false) }
))
app.use(express.urlencoded({ extended: true })) // needed to retrieve html form fields (it's a requirement of the local strategy)
app.use(passport.initialize()) // we load the passport auth middleware to our express application. It should be loaded before any route.
app.get('/', passport.authenticate('jwt-jku', { session: false, failureRedirect: '/login' }),
(req, res) => {
res.send(
"<a href='/'>Refresh</a> / <a href='/logout'>Logout</a><br><br>User: " +
req.user.sub + '<br><br>' + fortune.fortune()
)
}
)
app.get('/login',
(req, res) => {
res.sendFile('login.html', { root: __dirname })
}
)
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', session: false }),
async (req, res) => {
const [key] = keyStore.all({ use: 'sig' })
const opt = {
compact: true,
jwk: key,
fields: {
typ: 'jwt',
jku: 'http://localhost:3000/jwks.json' // IP server
}
}
const payload = JSON.stringify({
exp: Math.floor(Date.now() / 1000) + 604800, // 1 week (7×24×60×60=604800s) from now
iat: Math.floor(Date.now() / 1000),
role: 'user'
})
const token = await jose.JWS.createSign(opt, key).update(payload).final()
// console.log(`Token sent. Debug at https://jwt.io/?value=${token}`)
res.cookie('jwtCookie', token, { httpOnly: true, secure: false }) // Store the token into the cookie
res.redirect('/')
// res.send(token)
}
)
/* app.get('/user', (req, res) => {
const user = { // Create the json object user with a name and a description
name: 'walrus',
description: 'it is what it is'
}
res.json(user) // Send the json object 'user'
}) */
app.get('/jwks.json', async (req, res) => {
const ks = fs.readFileSync('./jwks.json')
const keyStore = await jose.JWK.asKeyStore(ks.toString())
res.send(keyStore.toJSON())
})
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Trying to create a login authentication system as an entry into web development but the fetch I have to access my login functionality doesn't work. Morgan shows "POST -- ms --". (Works through Postman). As far as I can see my cors system is set up as expected. The API will respond if the passport.authenticate('local') is removed.
authenticate.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./models/user');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config.js');
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = function(user) {
return jwt.sign(user, config.secretKey,
{expiresIn: 3600});
};
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload, done) => {
console.log("JWT payload: ", jwt_payload);
User.findOne({_id: jwt_payload._id}, (err, user) => {
if (err) {
return done(err, false);
}
else if (user) {
return done(null, user);
}
else {
return done(null, false);
}
});
}));
routes
var express = require('express');
var UserRouter = express.Router();
var passport = require('passport');
var User = require('../models/user')
var authenticate = require('../authenticate');
const cors = require('./cors');
const bodyParser = require('body-parser');
UserRouter.use(bodyParser.json());
UserRouter.route('/login')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.post(cors.cors, passport.authenticate('local'), (req, res) => {
console.log(req.body);
var token = authenticate.getToken({_id: req.user._id});
res.setHeader('Content-Type', 'application/json');
res.json({success: true, token: token, status: 'You are successfully logged in!'});
res.status(200).send()
});
module.exports = UserRouter;
mongoose schema file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema ({
firstname : {
type: String,
default: ""
},
lastname: {
type: String,
default: ''
},
admin: {
type: Boolean,
default: false
}
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', User);
cors file
const express = require('express');
const cors = require('cors');
var whitelist = ['http://localhost:3000', 'http://localhost:3443']
var corsOptionsDelegate = (req, callback) => {
var corsOptions;
console.log("Validating origin");
console.log(req.header('Origin'));
if(whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true };
}
else {
corsOptions = { origin: false };
}
callback(null, corsOptions);
};
exports.cors = cors();
exports.corsWithOptions = cors(corsOptionsDelegate);
Front end API call
export const loginUser = (creds) => (dispatch) => {
console.log("test")
dispatch(requestLogin(creds))
console.log("attempting login")
return fetch('http://localhost:3443/users/login', {
method: 'POST',
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify(creds)
})
.then(response => {
console.log("got response 1");
if(response.ok) {
return response
} else {
console.log("response errored");
var error = new Error('Error ' + response.status + ': ' + response.statusText);
error.response = response;
throw error;
}
},
error => {
console.log("errored")
throw error;
})
.then(response => response.json())
.then(response => {
console.log("got response 2");
if(response.success) {
// Successful login
localStorage.setItem('token', response.token);
localStorage.setItem('creds', JSON.stringify(creds));
// TODO dispatch success
dispatch(receiveLogin(response));
} else {
var error = new Error('Error ' + response.status);
error.response = response;
throw error;
}
})
.catch(error => dispatch(loginError(error.message)))
}
Does anyone know where I'm going wrong with this? I'm not really getting any useful error messages from my front-end so haven't included.
Terminal output upon login attempt
OPTIONS /users/login 204 3.287 ms - 0
POST /users/login - - ms - -
I'm currently trying my hand at "basic authentication" for users. I can't now get a http response back to my query. The path of the request is 'AuthenticationService' --> 'UserService'. But from 'UserService' I can't get to 'UserRoute' and therefore not to 'httpServer'. The correct order should be: AuthenticationService -->UserService --->Userroute-->httpServer If I change in AuthenticationRoute.js router.post('/', authenticate); to router.post('/authenticate', authenticate) I get a http response, but I dont transmit any data....What do I have to do ?
UserService.js
async function authenticate({ username, password }) {
const user= User.find({userName:username} && {password:password})
/* const user = User.find(u => u.userName === so && u.password === password); */
if (user) {
const { password, ...userWithoutPassword } = user;
return userWithoutPassword;
}
}
module.exports = {
authenticate
}
UserRoute.js
var userService = require('./UserService')
router.post('/', authenticate);
function authenticate(req, res, next) {
userService.authenticate(req.body)
.then(user => user ? res.json(user) : res.status(400).json({ message: 'Username or password is incorrect' }))
.catch(err => next(err));
}
module.exports = router;
AuthenticationService.js
async function basicAuth(req, res, next) {
// make authenticate path public
if (req.path === '/') {
return next();
}
if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
return res.status(401).json({ message: 'Missing Authorization Header' });
}
// verify auth credentials
const base64Credentials = req.headers.authorization.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
console.log(username+password);
const user = await userService.authenticate({ username, password });
if (!user) {
return res.status(401).json({ message: 'Invalid Authentication Credentials' });
}
req.user=user
next();
}
module.exports = {
basicAuth
}
AuthenticationRoute.js
var express = require('express');
var router = express.Router();
var authenticationService=require('./AuthenticationService')
router.post('/authenticate', authenticationService.basicAuth);
module.exports=router;
httpServer.js
const userRoutes = require('./endpoints/user/UserRoute')
const authenticationRoutes= require('./endpoints/authentication/AuthenticationRoute')
var axios = require('axios');
app.use(authenticationRoutes);
app.use(userRoutes);
The request I try to send is:
POST http://localhost:8080/authenticate
Authorization: Basic YWRtaW46MTIz
Trying to make requests and send cookies along with it using React and Express. The requests/responses are working fine. But the cookies are not sent. On the client-side:
import axios from 'axios'
let endPoint = 'http://192.168.1.135:80'
axios.defaults.withCredentials = true;
export async function SubmitPost(username, title, body, time){
let res = await axios.post(`${endPoint}/posts/create`, {username: username, title: title, body: body, time: time})
return res.data
}
The server-side route:
router.post('/create', authenticator.authenticate, async (req, res) => {
let post = new Post({
title: req.body.title,
body: req.body.body,
time: req.body.time,
username: req.body.username
})
post.save().then((doc, err) => {
if (err) {
return res.send(Response('failure', 'Error occured while posting', doc))
}
res.send(Response('success', 'Posted Successfully'))
})
})
And the middleware authenticator:
module.exports.authenticate = (req, res, next) => {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) {
console.log('No authentication token found')
return res.sendStatus(401)
}
jtoken.verify(token, process.env.SECRET, (err, user) => {
if (err) {
console.log(err)
return res.sendStatus(403)
}
req.user = user
next()
})
}
It returns a 401 with a Token Not Found. I have enabled CORS on express as well as cookie-parser
app.use(cookieparser())
app.use(cors({origin: 'http://localhost:3000', credentials: true}))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use('/auth', require('./routes/authentication_route'))
app.use('/posts', require('./routes/post_route'))
I'm developing with express a web page that when the client clicks in "Send E-mail" redirect to google asking for permission to send email through the client email and after the client gave the permission redirect back and send the email.
The code so far:
'use strict';
const express = require('express');
const googleAuth = require('google-auth-library');
const request = require('request');
let router = express.Router();
let app = express();
const SCOPES = [
'https://mail.google.com/'
,'https://www.googleapis.com/auth/gmail.modify'
,'https://www.googleapis.com/auth/gmail.compose'
,'https://www.googleapis.com/auth/gmail.send'
];
const clientSecret = '***********';
const clientId = '**************';
const redirectUrl = 'http://localhost:8080/access-granted';
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
function sendEmail(auth, content, to , from, subject) {
let encodedMail = new Buffer(
`Content-Type: text/plain; charset="UTF-8"\n` +
`MIME-Version: 1.0\n` +
`Content-Transfer-Encoding: 7bit\n` +
`to: ${to}\n` +
`from: ${from}\n` +
`subject: ${subject}\n\n` +
content
)
.toString(`base64`)
.replace(/\+/g, '-')
.replace(/\//g, '_');
request({
method: "POST",
uri: `https://www.googleapis.com/gmail/v1/users/me/messages/send`,
headers: {
"Authorization": `Bearer ${auth}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"raw": encodedMail
})
},
function(err, response, body) {
if(err){
console.log(err); // Failure
} else {
console.log(body); // Success!
}
});
}
app.use('/static', express.static('./www'));
app.use(router)
router.get('/access-granted', (req, res) => {
sendEmail(req.query.code, 'teste email', 'teste#gmail.com', 'teste#gmail.com', 'teste');
res.sendfile('/www/html/index.html', {root: __dirname})
})
router.get('/request-access', (req, res) => {
res.redirect(authUrl);
});
router.get('/', (req, res) => {
res.sendFile('/www/html/index.html', { root: __dirname });
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
module.exports = app;
Every time I try to send a simple E-mail I receive the error 401: Invalid Credentials. But I'm passing in Authorization the client code auth that google sends just gave me...
The recommended way to use google APIs is to use Google API nodejs client which also provides Google OAuth flow. You can then use google.gmail('v1').users.messages.send to send the email :
const gmail = google.gmail('v1');
gmail.users.messages.send({
auth: oauth2Client,
userId: 'me',
resource: {
raw: encodedMail
}
}, function(err, req) {
if (err) {
console.log(err);
} else {
console.log(req);
}
});
auth is OAuth2, the OAuth object that can be populated with your token. You can get the token in the express session :
var oauth2Client = getOAuthClient();
oauth2Client.setCredentials(req.session["tokens"]);
which you've already stored in your OAuth callback endpoint :
var oauth2Client = getOAuthClient();
var session = req.session;
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if (!err) {
oauth2Client.setCredentials(tokens);
session["tokens"] = tokens;
res.send(`<html><body><h1>Login successfull</h1><a href=/send-mail>send mail</a></body></html>`);
} else {
res.send(`<html><body><h1>Login failed</h1></body></html>`);
}
});
Here is a complete example inspired from this google API oauth for node.js example :
'use strict';
const express = require('express');
const google = require('googleapis');
const request = require('request');
const OAuth2 = google.auth.OAuth2;
const session = require('express-session');
const http = require('http');
let app = express();
app.use(session({
secret: 'some-secret',
resave: true,
saveUninitialized: true
}));
const gmail = google.gmail('v1');
const SCOPES = [
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'
];
const clientSecret = 'CLIENT_SECRET';
const clientId = 'CLIENT_ID';
const redirectUrl = 'http://localhost:8080/access-granted';
const mailContent = "test";
const mailFrom = "someemail#gmail.com";
const mailTo = "someemail#gmail.com";
const mailSubject = "subject";
function getOAuthClient() {
return new OAuth2(clientId, clientSecret, redirectUrl);
}
function getAuthUrl() {
let oauth2Client = getOAuthClient();
let url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
//use this below to force approval (will generate refresh_token)
//approval_prompt : 'force'
});
return url;
}
function sendEmail(auth, content, to, from, subject, cb) {
let encodedMail = new Buffer(
`Content-Type: text/plain; charset="UTF-8"\n` +
`MIME-Version: 1.0\n` +
`Content-Transfer-Encoding: 7bit\n` +
`to: ${to}\n` +
`from: ${from}\n` +
`subject: ${subject}\n\n` +
content
)
.toString(`base64`)
.replace(/\+/g, '-')
.replace(/\//g, '_');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: encodedMail
}
}, cb);
}
app.use('/send-mail', (req, res) => {
let oauth2Client = getOAuthClient();
oauth2Client.setCredentials(req.session["tokens"]);
sendEmail(oauth2Client, mailContent, mailTo, mailFrom, mailSubject, function(err, response) {
if (err) {
console.log(err);
res.send(`<html><body><h1>Error</h1><a href=/send-mail>send mail</a></body></html>`);
} else {
res.send(`<html><body><h1>Send mail successfull</h1><a href=/send-mail>send mail</a></body></html>`);
}
});
});
app.use('/access-granted', (req, res) => {
let oauth2Client = getOAuthClient();
let session = req.session;
let code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if (!err) {
oauth2Client.setCredentials(tokens);
session["tokens"] = tokens;
res.send(`<html><body><h1>Login successfull</h1><a href=/send-mail>send mail</a></body></html>`);
} else {
res.send(`<html><body><h1>Login failed</h1></body></html>`);
}
});
})
app.use('/', (req, res) => {
let url = getAuthUrl();
res.send(`<html><body><h1>Authentication using google oAuth</h1><a href=${url}>Login</a></body></html>`)
});
let port = process.env.PORT || 8080;
let server = http.createServer(app);
server.listen(port);
server.on('listening', function() {
console.log(`listening to ${port}`);
});