Я пытаюсь выполнить простой вход в Facebook, используя Node.js, MySQL и passport-facebook
.
У меня проблема с req.user
. Основная проблема заключается в том, что он показывает содержимое в console.log(req.user)
, но когда я хочу выполнить запрос к базе данных, вставка работает, а выбор - нет.
Моя ошибка говорит, что req.user.id
не определено независимо от того, в какой маршрут ставлю pool.query
.
Вот мой код:
require('dotenv').config();
const app = require("express")();
const https = require('https');
const io = require('socket.io')(https);
const morgan = require('morgan');
const path = require('path');
const passport = require('passport');
var Strategy = require('passport-facebook').Strategy;
const session = require('express-session');
const fs = require('fs');
const cookieParser =require('cookie-parser');
const bodyParser =require('body-parser')
const { dirname } = require('path');
const pool = require('./database/connection');
const { info } = require('console');
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
//initializer
// OAuth 2.0-based strategies require a `verify` function which receives the
// credential (`accessToken`) for accessing the Facebook API on the user's
// behalf, along with the user's profile. The function must invoke `cb`
// with a user object, which will be set at `req.user` in route handlers after
// authentication.
passport.use(new Strategy({
clientID: process.env['CLIENT_ID'],
clientSecret: process.env['CLIENT_SECRET'],
callbackURL: '/return',
profileFields: ['id', 'displayName', 'email', 'link', 'picture', 'birthday']
},
function(accessToken, refreshToken, profile, cb) {
// In this example, the user's Facebook profile is supplied as the user
// record. In a production-quality application, the Facebook profile should
// be associated with a user record in the application's database, which
// allows for account linking and authentication with other identity
// providers.
return cb(null, profile);
}));
//frameworks
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
//cookie: { secure: true } remove this line for HTTP connection
}))
app.use(passport.initialize());
app.use(passport.session());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://localhost:3000');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'Origin,X-Requested-With,content-type,Accept, Authorization');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
//routes
app.use(require(__dirname + '/routes/routers.js'));
app.use(require(__dirname +'/controllers/user/register.js'));
/* Login facebook with permissions */
app.get('/login/facebook',
passport.authenticate('facebook', { scope: ['email', 'user_photos', 'user_birthday'] }));
/* Returning link to my own pages */
app.get('/return',
passport.authenticate('facebook', { failureRedirect: '/' }),
function(req, res, ) {
const ide = req.user.id;
});
/**The if i need profile this should be my own page */
/* app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.redirect('/using-facebook');
});
*/
https.createServer({
key: fs.readFileSync('./server.key'),
cert: fs.readFileSync('./server.cert')
}, app).listen(8000, ()=>{
console.log('listening');
})
//main router
app.get('/', (req, res)=>{
res.sendFile(__dirname + '/index.html')
})
/*This is from another page of routes**/
router.get ('/using-facebook', async (req, res) =>{
/* Simple data to my users */
/* let user ={
id : req.user._json.id,
name : req.user._json.name,
birthday : req.user._json.birthday,
photo : req.user._json.picture.data.url,
email : req.user._json.email
} */
/* Verify if that user exist */
/* Creating the user*/
const result = await pool.query('INSERT INTO `users`(`id`, `username`, `birthday`, `photo`, `email`) VALUES (?,?,?,?,?)', [req.user._json.id, req.user._json.name,
req.user._json.birthday, req.user._json.picture.data.url, req.user._json.email ], function(error){
if(error){
res.send('Error')
}
else{
res.send('Data successfully added')
}
})
console.log(result);
}),
router.get('/test', async (req, res)=>{
res.send(req.user.id)
await pool.query('SELECT * from `users` where id=?',[req.user.id], function(error, result, fields){
if(result.length >0 ){
if(result ==true)
res.send('Sorry, its seeems like somebody has created an account with this fb');
}
else{
res.send('Perfect this id is new');
}
})
})