我认为我创建了一个标准的护照本地策略,就像之前很多人一样。我解析了表单,尝试passport.serializeUser
,这是人们提到的大多数方式。但是,const env = require('dotenv').load(),
config = require( __dirname + '/config.json' )[process.env.NODE_ENV],
config_web = config.web,
config_fb = config.fb,
_WEB_PORT = config_web.port,
_WEB_HOST = config_web.host,
_FB_ID = config_fb.fid,
_FB_SECRET = config_fb.secret;
const express = require('express'),
app = express(),
compression = require('compression'),
ejs = require('ejs'),
cookieParser = require('cookie-parser'),
fs = require('fs'),
bodyParser = require('body-parser'),
csrf = require('csurf'),
csrfProtection = csrf({ cookie: true }),
parseForm = bodyParser.urlencoded({ extended: true }),
methodOverride = require('method-override'),
randomstring = require("randomstring"),
_DB = require('./db');
moment = require('moment-timezone'),
server = require('http').createServer(app),
FB = require('fb'), fb = new FB.Facebook(),//(options)
request = require('request-promise'),
passport = require('passport'),
fb_Strategy = require('passport-facebook').Strategy,
local_Strategy = require('passport-local').Strategy,
morgan = require('morgan'),
expresssession = require('express-session'),
connectensurelogin = require('connect-ensure-login'),
flash = require('connect-flash'),
bcrypt = require('bcrypt'),
timezone = 'Asia/Hong_Kong';
app.use(flash());
app.use(compression());
app.use(cookieParser());
//app.disable('view cache');
app.set('view engine', 'ejs');
app.set('views', __dirname + "/views");
app.use(express.static(__dirname + '/public')); //, { maxAge: oneDay }));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
//app.use(morgan('combined'));
app.use(expresssession({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 3600000 }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, cb) {
console.log("user");
console.log(user);
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
console.log("obj");
console.log(obj.id);
let select = "SELECT * from user where login_id = '" + obj.id + "' and login_type = '" + obj.type+ "'";
_DB.getConnection(function(err, connection) {
if (err){
console.log("err");
}else{
connection.query( select, function(err, result) {
if(result.length>0){
return cb(null, { name: result[0].name, id: result[0].login_id, login_type: result[0].login_type, accessToken: result[0].token});
}
connection.release();
});
}
});
});
passport.use('local',new local_Strategy({
usernameField: 'email',
passwordField: 'password'//,
//passReqToCallback : true
},
function(username, password, done) {
console.log("local_Strategy");
let getPwd = "SELECT login_pw FROM user WHERE login_id = '" + username + "' and login_type = 'direct'";
_DB.getConnection(function(err, connection) {
if (err){
return done(err);
}else{
connection.query( getPwd, function(err, result) {
if( result.length > 0 ){
let checkPwd = bcrypt.compareSync(password, result[0].login_pw);
if(checkPwd){
return done(null, {type: "direct", id: username});
}else{
return done(null, false);
}
}else{
return done(null, false);
}
connection.release();
});
}
});
}
));
passport.use('facebook',new fb_Strategy({
clientID: _FB_ID,
clientSecret: _FB_SECRET,
callbackURL: `http://${_WEB_HOST}:${_WEB_PORT}/login/facebook/return`
},
function(accessToken, refreshToken, profile, cb) {
console.log("fb_Strategy");
let checkExist = "SELECT token FROM user WHERE login_id = '" + profile.id + "' and login_type = '" + profile.provider + "'";
let insertNew = "INSERT INTO user (name, email, login_type, login_id, token) values ('" + profile.displayName + "','" + profile.email +"','" + profile.provider +"','" + profile.id +"', '" + accessToken + "')";
let update = "UPDATE user SET token = '" + accessToken + "' WHERE login_id = '" + profile.id + "' and login_type = '" + profile.provider + "'";
_DB.getConnection(function(err, connection) {
if (err){
}else{
connection.query( checkExist, function(err, result) {
if(result.length>0){
if(result[0].token == accessToken){
connection.query( update, function(err, result2) {
});
}
}else{
connection.query( insertNew, function(err, result3) {
});
}
connection.release();
return cb(null, {type: profile.provider, id: profile.id});
});
}
});
}));
// app.post('/login', function(req, res, next){
// passport.authenticate('local',{
// //successRedirect: '/',
// //failureRedirect: '/logout?status=login failed',
// failureFlash: true
// }, function(err, user, info){
// console.log(user);
// if(err){
// //return next(err);
// }
// if(!user){
// req.flash('login', 'Failed!')
// return res.redirect('/login/direct');
// }
// res.redirect('/');
// }
// )(req, res, next);
// }
// );
app.post('/login',
passport.authenticate('local',{
successRedirect: '/',
failureRedirect: '/login/direct',//'/logout?status=login failed',
failureFlash: true
}), function(err, user, info){
console.log(err);
console.log(user);
console.log(info);
if(err){
//return next(err);
}
if(!user){
req.flash('login', 'Failed!')
//return res.redirect('/login/direct');
}
//res.redirect('/');
});
app.post('/register', parseForm, csrfProtection, function(req, res){
let c_password = req.body.c_password;
let email = req.body.email;
let type = "direct";
//res.send('data is being processed')
let checkExist = "SELECT id FROM user WHERE email = '" + email + "' and login_type = '" + type + "'";
let insertNew = "INSERT INTO user (name, email, login_type, login_id, login_pw) values ('" + email + "','" + email +"','" + type +"', '" + email +"','" + bcrypt.hashSync(c_password, 10) + "')";
//let update = "UPDATE user SET token = '" + accessToken + "' WHERE login_id = '" + profile.id + "' and login_type = '" + type + "'";
_DB.getConnection(function(err, connection) {
if (err){
}else{
connection.query( checkExist, function(err, result) {
if(result.length>0){
// if(result[0].token == accessToken){
// connection.query( update, function(err, result2) {
// });
// }
req.flash('register', 'Exist!')
res.redirect('/register');
}else{
connection.query( insertNew, function(err, result3) {
req.flash('register', 'OK!')
res.redirect('/login/direct');
});
}
connection.release();
//return cb(null, {type: type, id: email});
});
}
});
});
const now = moment.tz(timezone).format(),
date1 = moment.tz("2017-10-30 17:02", timezone).format(),
date2 = moment.tz("2017-10-27 15:59", timezone).format(),
date3 = moment.tz("2017-10-28 15:59", timezone).format();
if( now >= date1 ){
//console.log('larger');
}else{
//console.log('smaller');
}
app.get('/',
function(req, res) {
console.log("Home");
console.log(req.user );
res.render('index', { user: req.user });
});
app.get('/login',
function(req, res){
if(req.user){
res.redirect('/');
}else{
res.render('login');
}
});
app.get('/login/facebook',
passport.authenticate('facebook', {
scope: ['user_tagged_places', 'user_photos']
}
));
app.get('/login/direct', csrfProtection, function(req, res){
res.render('login_email',{
csrfToken: req.csrfToken(),
message: req.flash('login')
});
});
app.get('/register', csrfProtection, function(req, res){
res.render('reg',{
csrfToken: req.csrfToken(),
message: req.flash('register')
});
});
app.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/profile', connectensurelogin.ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.get('*', function(req, res) {
res.status(404);
//res.send('Sorry cant find that!');
res.redirect('/');
//res.end();
})
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
// handle CSRF token errors here
res.status(403)
res.send('Error.')
})
function isValidKey(key) {
var re = /((\.)|(\$)|(#)|(\[)|(\]))/;
return re.test( key );
}
server.listen(_WEB_PORT, function(){
console.log(`Listening on port http://${_WEB_HOST}:${_WEB_PORT}/`);
});
仍未被触发。
现在可以重定向到主页,但是,在控制用户时,它是未定义的。
blackFrame[50:50+im.shape[0],50:50+im.shape[1]] = im[:,:]