I'm trying to implement LDAP active directory. When i try to pass in user credential through the front end, I'm getting an error Cannot read property 'session' of undefined. I think i'm not passing in session to AD. I'm able to Authenticate user when i hard code user credential.
How can I solve this?
path = require('path'),
logger = require('morgan'),
ActiveDirectory = require('activedirectory'),
bodyParser = require('body-parser'),
dotenv = require('dotenv'),
passport = require('passport'),
session = require('express-session');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(session({
resave : true,
secret : 'kool',
saveUninitialized : true,
cookie : {}
}));
const Strategy = {
url: 'n/a',
baseDN: 'n/a',
username: 'n/a',
password: 'n/a'
}
const ad = new ActiveDirectory(Strategy);
let user;
app.post('/login', async (req, res) => {
user.session;
const username = req.body.username;
const password = req.body.password;
const loginSuccess = await ad.authenticate(username, password, (err, auth, res, req) => {
if(err) {
console.log(`Yo invalid credentials: ***** ${JSON.stringify(err)} ]******* `);
return
}
if(auth) {
req.session.loggedin = true;
req.session.username = username;
res.redirect('/index')
console.log(`User ${username} is Authenticated`);
} else {
// res.send('Auth Failed')
console.log(`Auth failed`)
res.redirect('/')
}
res.end();
});
});
app.get('/index', function(request, response) {
if(request.session.loggedin) {
response.send(`Welcome back, ${request.session.username}`)
res.render('index', {title: 'Main Page'})
} else {
response.redirect('/')
}
response.end();
})
Related
I'm trying to make a login mechanism with jwt but as I'm a newbie, I'm not sure if I'm doing right.
I already made my server.js which looks like this :
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const path = require('path');
require('dotenv').config();
var cors = require('cors');
const app = express();
const port = process.env.PORT || 8600;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
});
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
const adRoutes = require('./routes/adRoutes.js');
app.use('/Advertisements', adRoutes);
const comRoutes = require('./routes/comRoutes.js');
app.use('/Companies', comRoutes);
const userRoutes = require('./routes/userRoutes.js');
app.use('/Users', userRoutes);
const appRoutes = require('./routes/appRoutes.js');
app.use('/Applications', appRoutes);
const appAuth = require('./routes/loginRoutes.js');
let refreshTokens = [];
app.use('/auth', appAuth);
app.get('/api', authenticateToken, (req, res) => {
res.json(posts.filter(post => post.username === req.user.name))
});
app.post('/auth/token', (req, res) => {
const refrechToken = req.body.token;
if (refrechToken == null) return res.sendStatus(401);
if (!refreshTokens.includes(refrechToken)) return res.sendStatus(403);
jwt.verify(refrechToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = generateAccessToken({ name: user.name });
res.json({ accessToken: accessToken });
}
)
});
app.post('/auth/login', (req, res) => {
const email = req.body.email;
const password = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
const accessToken = generateAccessToken({ email: email });
const refreshToken = jwt.sign(email, process.env.REFRESH_TOKEN_SECRET);
refreshTokens.push(refreshToken);
res.json({ accessToken: accessToken, refreshToken: refreshToken });
});
app.delete('/auth/logout', (req, res) => {
refreshTokens = refreshTokens.filter(token => token !== req.body.token);
res.sendStatus(204);
});
function generateAccessToken(email) {
return jwt.sign(email, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1800s' });
}
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.listen(port)
And I have a login mechanism that works on Postman but without jwt like this :
const express = require('express');
const router = express.Router();
const path = require('path');
const CryptoJS = require('crypto-js');
const UserController = require('../controllers/userController.js');
var con = require("../config.js");
const { log } = require('console');
router.get('/', function(request, response) {
response.sendFile(path.join(__dirname, '../../front', 'login.html'));
});
router.post('/register', (req, res) => {
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
req.body.password = hashedPassword;
UserController.create(req, res);
});
router.post('/login', function(req, res) {
const email = req.body.email;
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
email_ = "\"" + email + "\"";
password_ = "\"" + hashedPassword + "\"";
if (email == "" || hashedPassword == ""){
res.send('Please enter Email and/or Password !');
}
else{
var sql = "SELECT * FROM User WHERE email = " + email_;
con.query(sql, function (err, result) {
if (err) throw err;
if (result.length == 0){
res.send('Incorrect Email !');
}
else{
if (result[0].password == hashedPassword){
req.session.email = result[0].email;
res.send('Login successful!');
}
else{
res.send("Incorrect Password !");
}
}
});
}
});
router.get('/check', function(req, res) {
if (req.session.email) {
console.log(req.session.email);
res.send('Logged in');
} else {
res.send('Not logged in');
}
});
router.get('/logout', function(req, res) {
req.session.destroy();
res.send('Logout successful!');
});
I want to 1. login with token, 2. auto-filled profile using the token and 3. logout system
So that I could make them and that it works on the website, let me know not exact codes but just a mechanism or functions that I need please.
Here's my config.js if you need :
const mysql = require("mysql");
const con = mysql.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "DB name",
port: "port"
});
con.connect((err) => {
if(err)
{
console.warn("Error in connection: " + err.message);
}
});
module.exports = con;
Working with Registration in a Site. For the register Form,Validation is done using mongoose models and trying to Use Flash to display the error message in the Form.
In my nodejs app it shows an error like:
TypeError: req.flash is not a function
I have installed connection-flash npm it is throwing an error like:
TypeError: req.flash is not a function at
E:\node-course\apnadukan\src\routes\index.js:21:24
app.js
const express = require('express');
const path = require('path');
const hbs = require('hbs');
const flash = require("connect-flash");
const passport = require("passport");
const db = require('./connection/db');
// Express Use
const app = express()
const port = 3000;
// Form Data Get
app.use(express.json());
app.use(express.urlencoded({extended:false}));
// HBS Handlebar use
app.set('view engine', 'hbs');
// Router Use
app.use('/', require(path.join(__dirname, 'routes/index.js')))
// Publics assess link (HBS)
const static_path = path.join(__dirname, '../publics');
app.use(express.static(static_path));
// View Set (HBS)
const views = path.join(__dirname, '../src/views');
const partials_path = path.join(__dirname, '../src/views/partials');
app.set('views', views);
hbs.registerPartials(partials_path);
//
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
index.js
const express = require('express');
const addUser = require('../models/register');
let passport = require("passport");
let LocalStrategy = require("passport-local").Strategy;
// const passport = require('../config/passport');
const {validationRegister, validationRegisterMsg} = require('../config/validator');
// const router = express.Router()
const router = require('express').Router()
router.get('/' , (req , res)=>{
res.render('index', {
title: "Welcome To Apna Dukan"
})
})
router.get('/welcome-to-apnadukan', (req , res)=>{
var errorMsg = req.flash('error')[0];
res.render('register', {
title: "Register | Welcome To Apna Dukan",
errorMsg,
page_name: "Register"
});
});
router.post('/welcome-to-apnadukan',
[
validationRegister(),
validationRegisterMsg,
passport.authenticate("local.register", {
successRedirect: "/login",
failureRedirect: "/welcome-to-apnadukan",
failureFlash: true,
}),
],
async (req , res)=>{
try {
if (req.session.oldUrl) {
let oldUrl = req.session.oldUrl;
req.session.oldUrl = null;
res.redirect(oldUrl);
} else {
res.redirect("/welcome-to-apnadukan");
}
} catch (error) {
req.flash("error", error.message);
res.status(400).send(error);
return res.redirect("/");
}
})
router.get('/login' , (req , res)=>{
res.render('login', {
title: "Login | Welcome To Apna Dukan",
page_name: "Login"
})
})
router.post('/login' , (req , res)=>{
req.send("Update");
})
router.get('/recover-password', (req, res)=>{
res.render('recoverpassword',{
title: "Recover Password | Welcome To Apna Dukan",
page_name: "Recover Password"
})
})
router.post('/recover-password', (req, res)=>{
res.render('recoverpassword',{
title: "Recover Password | Welcome To Apna Dukan",
page_name: "Recover Password"
})
})
router.get('/page' , (req , res)=>{
res.send('Hello World!')
})
module.exports = router
Validator.js
const { check, validationResult } = require("express-validator");
const validationRegister = (()=>{
return [
check('name', 'Name is required').not().isEmpty(),
check('username', 'Username is required').not().isEmpty().matches('/^(?![0-9]*$)[a-zA-Z0-9]+$/').withMessage('Only AlphaNumeric character is allowed').isLength({min:6,max:6}).withMessage('Minimum 6 characters required'),
check('email', 'Email is required').not().isEmpty().isEmail().withMessage('Email must be a valid email address.'),
check('password', 'Password is required').not().isEmpty().matches('/^(?=(.*[a-zA-Z].*){2,})(?=.*\d.*)(?=.*\W.*)[a-zA-Z0-9\S]{6,}$/').withMessage('Strong passwords with min 6 characters, at least two letters (not case sensitive), one number, one special character, space is not allowed'),
];
});
const validationRegisterMsg = (req, res, next)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
let messages = [];
errors.array().forEach((error)=>{
messages.push(error.msg)
});
req.flash('error', messages);
// req.flash({error: messages})
return res.redirect('/register');
}
next();
};
module.exports = {validationRegister,validationRegisterMsg};
passport.js
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("../models/register");
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
"local.register",
new LocalStrategy(
{
nameField: 'name',
usernameField: 'username',
emailField: 'email',
passwordField: 'password',
passReqToCallBack: true
},
async (req, username, email, done) => {
try {
const username = await Customer_users.findOne({ username: username });
if (username) {
return done(null, false, { message: "Username already exists" });
}
const user = await Customer_users.findOne({ email: email });
if (user) {
return done(null, false, { message: "Email already exists" });
}
const newUser = await new User();
newUser.name = name;
newUser.username = username;
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
await newUser.save();
return done(null, newUser);
} catch (error) {
console.log(error);
return done(error);
}
}
)
);
You are configuring flash in your app after configuring the routes.
Moving this line app.use(flash()); before line app.use('/', require(path.join(__dirname, 'routes/index.js'))); will resolve the issue.
I have some issues to initiate passport.
I call the function app.use(passport.initialize()); in the file server.js
In the file auth.controllers.js passport is not detected as initialized
Somebody could explain how to "connect" app.use(passport.initialize()) in the server.js to the file auth.controllers.js ?
here my files :
Server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const helmet = require("helmet");
const morgan = require("morgan");
const networkConfig = require("./config/network.config");
const app = express();
const db = require("./config/models");
db.sequelize.sync();
var corsOptions = {
origin: networkConfig.corsOptions.ORIGIN
};
app.use(helmet());
app.use(cors(corsOptions));
app.use(morgan('combined'));
// parsing sur les requetes en type json
app.use(bodyParser.json());
// parsing des urls encodés
app.use(bodyParser.urlencoded({ extended: true }));
// route de vérification de bon fonctionnement
app.get("/", (req, res) => {
res.json({message: "Bienvenue ici"});
});
require("./routes/user.routes")(app);
require("./routes/oauth2.route")(app);
require("./routes/client.routes")(app);
require("./routes/beer.routes")(app);
const ejs = require('ejs');
const session = require('express-session');
const passport = require('passport');
/*
const beerController = require('./controllers/beer');
const userController = require('./controllers/user');
const authController = require('./controllers/auth');
const oauth2Controller = require('./controllers/oauth2');
const clientController = require('./controllers/client');
*/
// Set view engine to ejs
app.set('view engine', 'ejs');
// Use express session support since OAuth2orize requires it
app.use(session({
secret: 'Super Secret Session Key',
saveUninitialized: true,
resave: true
}));
// Use the passport package in our application
app.use(passport.initialize());
// Start the server
app.listen(3000);
user.routes.js
module.exports = app => {
const users = require("../controllers/user.controllers");
const auths = require("../controllers/auth.controllers")(app);
const router = require("express").Router();
// Create endpoint handlers for /users
router.route('/')
.post(users.create)
.get(auths.isAuthenticated, users.findAll);
app.use('/api/users', router);
};
auth.controllers.js
// Load required packages
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var BearerStrategy = require('passport-http-bearer').Strategy
const db = require("../config/models");
const User = db.user;
const Client = db.client;
const Token = db.token;
const Op = db.Sequelize.Op;
passport.use(new BasicStrategy( (username, password, done) => {
User.findOne({where: { username: username }})
.then(function (data) {
if (!data) {
return done(null, false, { message: 'user does not exist'});
} else {
var verify = data.verifyPassword(password);
if(verify == true) { console.log("verify true"); return done(null, data, {message: 'authentication succeded'})}
}
})
.catch( (err) => {
console.log("Error reason : "+ err);
return done(null, false, { message: 'Something went wrong with you authentication'});
}
)
}
));
passport.use('client-basic', new BasicStrategy(
function(username, password, callback) {
console.log("CLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASIC");
Client.findOne({ id: username }, function (err, client) {
if (err) { return callback(err); }
// No client found with that id or bad password
if (!client || client.secret !== password) { return callback(null, false); }
// Success
return callback(null, client);
});
}
));
exports.isAuthenticated = passport.authenticate('basic', { session : false });
exports.isClientAuthenticated = passport.authenticate('client-basic', { session : false });
How could I resolve this problem ?
Regards,
Thats my code:
server.js:
require('dotenv').config()
var fs = require('fs')
var express = require('express')
var app = express()
var helmet = require('helmet')
var router = require('./router')
var session = require('express-session')
var passport = require('passport')
var cookie = require('cookie-parser')
var redis = require('redis').createClient(process.env.REDIS_PORT)
var redisStore = require('connect-redis')(session)
app.use(helmet())
app.use(cookie())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(passport.initialize())
app.use(passport.session())
app.use(session({
store: new redisStore({client: redis}),
secret: 'rior124jybtyokipoev5432rtoe34wpta',
cookie: {
path: '/',
httpOnly: true,
maxAge: 1000*60*60*24*365,
secure: false
},
resave: false,
saveUninitialized: false
}))
app.use(router)
require('./config/passport');
app.listen(process.env._PORT, () => {
console.log('[Info][Backend] Backend http serve succesfuly started! Port: '+process.env._PORT);
})
router/index.js:
var router = require('express').Router()
var auth = require('../lib/auth_mw')
var fs = require('fs')
router.use(require('./logging'))
router.use(require('./news'))
router.get('/', (req, res) => {
res.contentType('text/plain')
res.end(fs.readFileSync(__dirname+'/../siteinfo.txt'))
})
router.get('/private', auth, (req, res) => {
res.end('private')
})
module.exports = router
config/passport.js:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
var users = require('../models').users
passport.serializeUser(function(user, done) {
console.log('serialize: ', user);
done(null, user.email);
});
passport.deserializeUser(function(email, done) {
console.log('deserialize: ', email);
users.findOne({
attributes: [
'email'
],
where: {
email
}
}).then(user => {
done(null, user.email === email ? user.dataValues : false);
})
});
passport.use('local',
new LocalStrategy({ usernameField: 'email' }, async function(
email,
password,
done
) {
let user = await users.findOne({
attributes: [
'email',
'password'
],
where: {
email,
password
}
})
if (user.dataValues.email) {
return done(null, user.dataValues);
} else {
return done(null, false);
}
})
);
Login always succesfull, but when i'm trying to go to /private, deserialize function doesn't called! I found many resolves on the net, but doesn't help. Please, suggest as many resolves as you know
P.S. I use sequelize as a database driver (idk maybe it's important)
This query will return the correct user, So You don't need to check the output again.
users.findOne({
attributes: [
'email'
],
where: {
email
}
})
Try done(null, user.dataValues); instead of done(null, user.email === email ? user.dataValues : false);
Been having some trouble for the past week getting this link to work. Feel like I'm misunderstanding something from the flow.
What I'm struggling with was implementing the passport with passport-facebook. I want to include the passport.authenticate inside the same route as the account linking. Currently only managed to separate the two processes and having two logins. Looking to merge them.
As can be seen here http://recordit.co/osdMl0MUCL
Is there no way to do the passport.authenticate inside the link route ? Been trying with no success.
Tried to move the passport.authenticate inside app.get('/authorize but don't know how to handle the const redirectURISuccess = ${redirectURI}&authorization_code=${authCode};
res.redirect(redirectURISuccess);
I'm thinking would need to do this inside the app.get(/auth/fb/callback' ... but not sure how.
This is what I have currently
'use strict';
require('dotenv').config();
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const http = require('http');
const port = '3000';
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const fbConfig = require('./oauth');
const cookieParser = require('cookie-parser');
const session = require('express-session');
// used to serialize the user for the session
// Not using these yet
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
const Botly = require('botly');
const botly = new Botly({
accessToken: process.env.ACCESS_TOKEN,
verifyToken: '123123321' // the verification token you provided when defining the webhook in facebook
});
const app = express();
// Listen on the account link event
botly.on('account_link', (sender, message, link) => {
// Continue conversation
console.log('CONFIRMED AUITH', link);
botly.sendText({
id: sender,
text: (link.status === 'unlinked') ? 'sorry to see you go' : 'Welcome'
});
botly.sendButtons({
id: sender,
text: 'Please Login Again :-) This time for real',
buttons: [ botly.createAccountLinkButton(`https://${process.env.LOGIN_DOMAIN}/auth/fb/?senderId=' + sender/`) ]
});
});
botly.on('message', (senderId, message, data) => {
const text = `echo: ${data.text}`;
botly.sendText({
id: senderId,
text: text
});
botly.sendButtons({
id: senderId,
text: 'Please Login :)',
buttons: [ botly.createAccountLinkButton(`https://${process.env.LOGIN_DOMAIN}/authorize/`), botly.createAccountUnLinkButton() ]
});
});
app.use(bodyParser.json());
app.use('/', router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'its_my_secret', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/webhook', botly.router());
app.set('port', port);
/*
* This path is used for account linking. The account linking call-to-action
* (sendAccountLinking) is pointed to this URL.
*
*/
app.get('/authorize', function (req, res) {
// Passport setup
passport.use('facebook', new FacebookStrategy({
clientID: fbConfig.facebook.clientID,
clientSecret: fbConfig.facebook.clientSecret,
callbackURL: fbConfig.facebook.callbackURL,
profileFields: [ 'id', 'displayName', 'email' ]
},
// facebook will send back the tokens and profile
function (request, access_token, refresh_token, profile, done) {
// asynchronous
process.nextTick(function () {
console.log('WATCH THIS: ', profile);
return done(null, profile);
});
}));
console.log('%%%%%%%% AccountLinking Testing');
const accountLinkingToken = req.query.account_linking_token;
const redirectURI = req.query.redirect_uri;
console.log('%%%%%%%% /authorize called with accountLinkingToken %s, redirectURI %s', accountLinkingToken, redirectURI);
// Authorization Code should be generated per user by the developer. This will
// be passed to the Account Linking callback.
const authCode = '1234567890';
// Redirect users to this URI on successful login
const redirectURISuccess = `${redirectURI}&authorization_code=${authCode}`;
res.redirect(redirectURISuccess);
});
app.get('/auth/fb', (req, res, next) => {
req.session.senderId = req.query.senderId;
passport.authenticate('facebook', { scope: [ 'email' ] },
{
state: {
senderId: req.query.senderId // senderId will be used after auth to reply to the user
}
})(req, res, next);
});
// Redirection after login
app.get('/auth/fb/callback',
passport.authenticate('facebook', {
successRedirect: `https://m.me/${process.env.app_name}`, // The webview I want to open if user logs in
failureRedirect: '/somePage' // redirect to Messenger if failure
}));
const server = http.createServer(app);
server.listen(port);
I solved it I think. Probably not the best way to go about it though. I'm passing the account linked redirect URI to the callback route and resolving the passport.authenticate in there redirecting if needed.
'use strict';
require('dotenv').config();
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const LINKED = {};
const http = require('http');
const port = '3000';
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const fbConfig = require('./oauth');
const cookieParser = require('cookie-parser');
const session = require('express-session');
// used to serialize the user for the session
// Not using these yet
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
const Botly = require('botly');
const botly = new Botly({
accessToken: process.env.ACCESS_TOKEN,
verifyToken: '123123321' // the verification token you provided when defining the webhook in facebook
});
const app = express();
// Listen on the account link event
botly.on('account_link', (sender, message, link) => {
// Continue conversation
console.log('CONFIRMED AUITH', link);
botly.sendText({
id: sender,
text: (link.status === 'unlinked') ? 'sorry to see you go' : 'Welcome'
});
});
botly.on('message', (senderId, message, data) => {
const text = `echo: ${data.text}`;
botly.sendText({
id: senderId,
text: text
});
botly.sendButtons({
id: senderId,
text: 'Please Login :)',
buttons: [ botly.createAccountLinkButton(`https://${process.env.LOGIN_DOMAIN}/authorize/?senderId=' + senderId/`), botly.createAccountUnLinkButton() ]
});
});
app.use(bodyParser.json());
app.use('/', router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'its_my_secret', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/webhook', botly.router());
app.set('port', port);
// Passport setup
passport.use('facebook', new FacebookStrategy({
clientID: fbConfig.facebook.clientID,
clientSecret: fbConfig.facebook.clientSecret,
callbackURL: fbConfig.facebook.callbackURL,
profileFields: [ 'id', 'displayName', 'email' ]
},
// facebook will send back the tokens and profile
function (request, access_token, refresh_token, profile, done) {
// asynchronous
process.nextTick(function () {
return done(null, profile);
});
}));
/*
* This path is used for account linking. The account linking call-to-action
* (sendAccountLinking) is pointed to this URL.
*
*/
app.get('/authorize', function (req, res, next) {
req.session.senderId = req.query.senderId;
console.log('%%%%%%%% AccountLinking Testing');
const accountLinkingToken = req.query.account_linking_token;
const redirectURI = req.query.redirect_uri;
console.log('%%%%% /authorize called with accountLinkingToken %s, redirectURI %s', accountLinkingToken, redirectURI);
// Authorization Code should be generated per user by the developer. This will
// be passed to the Account Linking callback.
const authCode = '1234567890';
// Redirect users to this URI on successful login
const redirectURISuccess = `${redirectURI}&authorization_code=${authCode}`;
LINKED.redirect = redirectURISuccess;
console.log('redirect to this ', redirectURISuccess);
passport.authenticate('facebook', { scope: [ 'email' ] },
{
state: {
senderId: req.query.senderId // senderId will be used after auth to reply to the user
}
})(req, res, next);
});
// Redirection after login
app.get('/auth/fb/callback', (req, res, next) => {
passport.authenticate('facebook', (err, user, info) => {
if (err) { return next(err); }
if (!user) {
console.log('bad', info);
return res.redirect(LINKED.redirect);
}
console.log('good');
LINKED.user = user;
})(req, res, next);
res.redirect(LINKED.redirect);
});
const server = http.createServer(app);
server.listen(port);