I am working on a chat application where socket is used for bi-directional sharing of messages.
The socket currently works fine but I want to be able to authenticate user before they can have access to the socket connection. I have trying to use passport but it would seem there is something I am not doing right as I get the error No session found.
const createError = require("http-errors");
const express = require("express");
const { join } = require("path");
const logger = require("morgan");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const SequelizeStore = require("connect-session-sequelize")(session.Store);
const db = require("./db");
const { User } = require("./db/models");
const passport = require('passport');
// create store for sessions to persist in database
const sessionStore = new SequelizeStore({ db });
const http = require("http");
const db = require("../db");
const onlineUsers = require("../onlineUsers");
const passportSocketIo = require('passport.socketio');
const { json, urlencoded } = express;
const app = express();
app.use(logger("dev"));
app.use(json());
app.use(urlencoded({ extended: false }));
app.use(express.static(join(__dirname, "public")));
app.use(cookieParser());
app.use(session({
genid:(req)=>{
return req.cookies
},
secret: process.env.SESSION_SECRET,
resave: true,
store: sessionStore,
saveUninitialized: true,
}));
app.use(function (req, res, next) {
const token = req.cookies["messenger-token"];
if (token) {
jwt.verify(token, process.env.SESSION_SECRET, (err, decoded) => {
if (err) {
return next();
}
User.findOne({
where: { id: decoded.id },
}).then((user) => {
req.user = user;
return next();
});
});
} else {
return next();
}
});
app.use(passport.initialize());
app.use(passport.session());
const port = normalizePort(process.env.PORT || "3001");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces, and sync database.
*/
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT"],
credentials: true
}
});
io.use(
passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'messenger-token',
secret: process.env.SESSION_SECRET,
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
})
);
function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}
io.on("connection", (socket) => {
// console.log(`USER ${JSON.stringify(socket)}`);
socket.on("go-online", (id) => {
if (!onlineUsers.includes(id)) {
onlineUsers.push(id);
}
// send the user who just went online to everyone else who is already online
socket.broadcast.emit("add-online-user", id);
});
socket.on("new-message", (data) => {
socket.broadcast.emit("new-message", {
message: data.message,
sender: data.sender,
});
});
socket.on("read-message", (data) => {
socket.broadcast.emit("read-message", data);
});
socket.on("read-messages", (data) => {
socket.broadcast.emit("read-messages", data);
});
socket.on("logout", (id) => {
if (onlineUsers.includes(id)) {
userIndex = onlineUsers.indexOf(id);
onlineUsers.splice(userIndex, 1);
socket.broadcast.emit("remove-offline-user", id);
}
});
});
How can I authenticate user with socket. Feel free to suggest other method aside using passport.
I found the same error in Github and it hasn't been resolved yet.
According to the official document (see "Compatibility with Express middleware" section), you can use express middleware in io.use by using wrap.
const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
The section shows how to use "express-session" module with socket.io. I guess this way is better for you because you already use it.
Related
I have scoured the community for answers, but I cant seem to find one.
In my application, I send user info from the client (react) to /user/save route. When I log the session to the console, all the data is there. But when I log req.session out on any other route it doesn't have any data.
Right now I am accessing the API from localHost while the API is hosted with ngrok.
When I had the API integrated within the same codebase as my React app, all worked well, but now it's a bit funky.
Server.js
const express = require('express');
var expressSession = require('express-session');
const cors = require('cors');
const cookieParser = require("cookie-parser");
const path = require('path');
const app = express();
const axios = require('axios');
const mongoose = require('mongoose');
const rateLimit = require("express-rate-limit");
var cron = require('node-cron');
require('dotenv').config()
const corsConfig = {
"origin": "http://localhost:3000",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"credentials": true
};
// Implemented a rate limiter which is a TEMPORARY FIX for the infinite loop by the useEffect
const limiter = rateLimit({
windowMs: .1 * 60 * 1000, // 10 seconds limit
max: 4
});
// Middleware
const hostValidationMiddleware = require('./Middleware/HostValidationMiddleware');
const sessionValidationMiddleware = require('./Middleware/SessionValidationMiddleware');
const {authenticateJWT} = require('./Middleware/JwtMiddleware');
async function connectToDB() {
// Database
await mongoose.connect(process.env.mongo_url, { useNewUrlParser: true, useUnifiedTopology: true }, () => {
console.log('[connectToDB]: Connected to DB');
})
}
connectToDB();
app.use(cookieParser());
const oneDay = 1000 * 60 * 60 * 24;
// Creating the session in order to save user data to req.session
app.use(
expressSession({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
secure: false,
cookie: {
maxAge: oneDay,
sameSite: "none",
}
})
);
app.use(cors(corsConfig));
//app.use('/', limiter);
app.use(express.json());
app.use('/', hostValidationMiddleware, sessionValidationMiddleware, require('./Routes/Store-Invoices'));
app.use('/', require('./Routes/SaveLoggedInUser') , authenticateJWT, require('./Routes/GetUserInvoices'));
app.use('/', require('./Routes/UpdateUserData'));
app.get('/', async (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(8081, () => {
console.log(`Server listening on 8081`);
});
Saved Logged In User
saveLoggedInUser.post('/user/save', async (req, res) => {
const User = req.body;
const token = await GetJwt(User);
req.session.currentUser = User;
if (token && !('authorization' in req.session) && User) {
req.session.authorization = `Bearer ${token}`
req.session.save();
}
console.log('USER', req.session);
const usersFromDB = await fetchUsersFromDB().catch((e) => { console.log(e) });
findCommonUser(usersFromDB,User);
res.sendStatus(200);
})
Get User Invoices
userInvoices.get('/invoice/user', async (req,res) => {
const invoices = await InvoiceModel.find().catch((e) => {console.log(e)});
const user = req.session;
console.log('INVOICE',user);
});
Client Call
async function fetchUserInvoices() {
// Making a call to external api
const url = `https://f604-104-49-198-21.ngrok.io/invoice/user`;
const invoiceResponse = await axios.get(url, {withCredentials: true}).catch((e) => { console.log(e) });
setData(invoiceResponse.data);
return;
}
It looks like you have your SameSite cookie flag set to "none" which according to MDN now requires the "Secure" flag to also be set to true in order to work. However, as you're using localhost, you probably also can't set Secure to true since you're not on HTTPS.
Removing that line in your Server.js code fixed it for me, as did setting sameSite: "strict".
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,
I'm working doing a login function with node.js Express and are having trouble with sending the session data so my app.js routes know the user is allowed to enter the various sites.
My first thought was to send it when i approve of the login information and redirect to the frontpage in my Auth.js but i can't figure out how to send it so that my frontpage route can see it and handle it with my checkAuth function.
The other idea i had was using a couple of "set/get" routes as shown in my users.js. But can't figure out how i would further implement that.
I don't know which way would be optimal for this sort of application.
This is the Auth.js which is responsible for the login:
const router = require('express').Router();
const User = require("../models/User.js");
const bcrypt = require('bcrypt');
const saltRounds = 12;
router.post('/login', (req, res) => {
// get request from body
const { username, password } = req.body;
//console.log(req.body);
// ask if this is a username with a password
if (username && password) {
// goes through db to see if username exists
User.query().select('username').where('username', username).then(foundUsername => {
try {
if (foundUsername[0].username == username) {
console.log(foundUsername[0].username);
User.query().select("password").where('username', foundUsername[0].username).then(foundPassword => {
console.log(foundPassword[0].password);
bcrypt.compare(password, foundPassword[0].password).then(result => {
console.log(result)
if (result == true) {
// this is where i want to set the req.session.user_id = true;
// and send it to my /frontpage
return res.redirect("/frontpage");
} else {
return res.status(400).send({ response: "wrong username or password" });
};
});
});
} else {
return res.status(400).send({ response: "wrong username or password" });
};
} catch (error) {
return res.status(400).send({ response: "wrong username or password" });
};
});
};
});
module.exports = router;
This is my app.js which checks the incoming request for req.session.user_id
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.json());
// You need to copy the config.template.json file and fill out your own secret
const session = require('express-session');
const config = require('./config/config.json');
app.use(session({
secret: config.sessionSecret,
resave: false,
saveUninitialized: true
}));
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 8 // limit each IP to 8 requests per windowMs
});
app.use('/signup', authLimiter);
app.use('/login', authLimiter);
/* Setup Knex with Objection */
const { Model } = require('objection');
const Knex = require('knex');
const knexfile = require('./knexfile.js');
const knex = Knex(knexfile.development);
Model.knex(knex);
app.get("/", (req, res) => {
return res.sendFile(__dirname + "/public/login.html");
});
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
}
app.get("/frontpage", checkAuth, (req, res) => {
console.log(req.body);
return res.sendFile(__dirname + "/public/frontpage.html");
});
const authRoute = require('./routes/auth.js');
const usersRoute = require('./routes/users.js');
app.use(authRoute);
app.use(usersRoute);
const PORT = 3000;
app.listen(PORT, (error) => {
if (error) {
console.log(error);
}
console.log("Server is running on the port", PORT);
})
});
This is my users.js. This is another way i thought of getting and setting my session value:
router.get('/setsessionvalue', (req, res) => {
req.session.user_id = true;
return res.send({ response: "OK" });
});
router.get('/getsessionvalue', (req, res) => {
return res.send({ response: req.session.user_id });
});
I'm building api for my app and trying to use passport jwt.
I can register new users and login(get the token back) but when I use the Postman to check the "protected" route I can use Any Token like this 'any any'
Pasport.js
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../api/models/user/userModel'),// load up the user model
config = require('../config/database'); // get db config file
module.exports = (passport)=> {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.id}, (err, user)=> {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
Server.js
const express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
morgan = require('morgan'),
passport = require('passport'),
bodyParser = require('body-parser'),
jwt = require('jsonwebtoken'),
config = require('./config/database'),
Event = require('./api/models/event/eventModel'),
User = require('./api/models/user/userModel');
mongoose.Promise = global.Promise;
mongoose.connect(config.database);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(passport.initialize());
/* Routers registration */
const routesEvent = require('./api/routes/event/eventRoutes');
routesEvent(app);
const routesUser = require('./api/routes/user/userRoutes');
routesUser(app);
/* END Routers registration */
/* Express middleware
* which used to return more interactive messages */
app.use((req, res, next)=>{
res.status(404).send({url: req.originalUrl + ' not found'});
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
/* END Express middleware */
// Launch the server on port 3000
const server = app.listen(3000, () => {
const { address, port } = server.address();
console.log(`RESTful API server Listening at http://${address}:${port}`);
});
EventRouter.js
const jwt = require('jsonwebtoken'),
passport = require('passport');
require('../../../config/passport')(passport); // as strategy in ./passport.js needs passport object
module.exports = (app)=> {
const event = require('../../controllers/event/eventController');
// Routes
app.route('/events' )
.get( event.list_all_events, passport.authenticate('jwt', { session: false}));
};
EventController
const mongoose = require('mongoose'),
Event = mongoose.model('Events'),
getToken = require('../../../config/getToken');
exports.list_all_events = (req, res)=> {
let token = getToken(req.headers);
if(token){
Event.find({}, (err, event)=> {
if (err)
res.send(err);
res.json(event);
});
} else {
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
};
I'm definitely doing something wrong in controller or in this file
GetToken.js
module.exports = getToken = (headers)=> {
console.log(headers);
if (headers && headers.authorization) {
let parted = headers.authorization.split(' ');
//Here I can see my Token from the Postman
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
Please, any ideas about a mistake that I'm making above?
Below line act as an middle ware. It is validating JWT token, once token is validated it will call JwtStrategy and setting user object in request and then it will call the actual function which is suppose to be executed.
passport.authenticate('jwt', { session: false})
You really do not need getToken function. It will be taken care by above line. If token is not validated then above line automatically returns 401.
Looks strange but when I changed code to this
EventRouter.js
app.route('/events' )
.get( passport.authenticate('jwt', { session: false}), event.list_all_events)
.post(event.create_event);
It's works like expected
The only one difference is the order in get(passport, function)
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);