Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import express from 'express'
- import Sequelize from 'sequelize'
- const app = express()
- const port = 3000
- import passport from 'passport'
- import LocalStrategy from 'passport-local'
- import session from 'express-session'
- import bcrypt from 'bcrypt'
- const saltrounds = 10
- import bodyParser from 'body-parser'
- import flash from 'connect-flash'
- app.use(session({
- secret: 'keyboard cat',
- resave: false,
- saveUninitialized: true
- }))
- app.use(passport.initialize())
- app.use(passport.session())
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({
- extended: true
- }));
- app.use(flash())
- //
- //Removed database connection and other model for brevity
- //
- const User = sequelize.define('user', {
- name: {
- type: Sequelize.STRING
- },
- username: {
- type: Sequelize.STRING
- },
- hash: {
- type: Sequelize.STRING
- },
- id: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV4,
- primaryKey: true
- },
- googleid: {
- type: Sequelize.STRING
- }
- })
- User.hashpassword = function (value) {
- bcrypt.genSalt(saltrounds, (err, salt) => {
- bcrypt.hash(value, salt, (err, hash) => {
- return hash;
- })
- })
- }
- User.authenticate = function (value, hash) {
- if(bcrypt.compare(value, hash)){
- console.log(hash)
- return true;
- }
- else
- return false;
- }
- passport.use('local-login', new LocalStrategy((username, password, cb) => {
- User.findOne({where:{username:username}}).then((err, result)=> {
- if (err) return cb(err)
- if (result != undefined) {
- if (User.authenticate(password, result.password)) {
- cb(null, user)
- }
- else cb(null, false, { message: 'Incorrect password' })
- }
- else cb(null, false, { message: 'Incorrect username.' })
- })
- }))
- passport.serializeUser((user, done) => {
- done(null, user.id)
- })
- passport.deserializeUser((id, cb) => {
- User.findOne({where:{id:id}}.then((err, result) => {
- if (err) return cb(err)
- else cb(null, result.id)
- }))
- })
- //
- //Removed DB sync for brevity
- //
- function isLoggedIn(req, res, next) {
- console.log(req.isAuthenticated())
- console.log(req.session)
- if (req.isAuthenticated())
- return next();
- res.status(400).json({
- 'message': 'access denied'
- });
- }
- app.post('/login', (req, res, next) => {
- console.log(req.body)
- passport.authenticate('local-login', {failureFlash: true }, ()=> {
- req.session.save(() => {
- res.send(req.isAuthenticated()) //false
- })
- })(req,res,next)
- })
- app.get('/', isLoggedIn, (req, res) => {
- //
- //home logic
- //
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement