StephenGrider / AdvancedReduxCode

MIT License
839 stars 574 forks source link

auth server problem #17

Open jamessawyer opened 7 years ago

jamessawyer commented 7 years ago

I found your "auth/server" project, you defined the 'services/passport.js' file, but you didn't export it, and used it nowhere. I was wondering how to use it?

YannisMarios commented 7 years ago

I did the auth project from the udemy tutorial in ES6:

controllers/authentication.js

import User from '../models/user';
import jwt from 'jwt-simple';
import {config} from '../config';

// function to create user tokens
function TokenForUser(user) {
  const timestamp = new Date().getTime();
  // sub =  the subject of the token is this user with id user.id
  // iat = Issued At Time
  return jwt.encode({sub: user.id, iat: timestamp}, config.secret);
}

function SignUp(req, res, next) {
  // Get email and password from request body
  const email = req.body.email;
  const password = req.body.password;

  if(!email || !password) {
    return res.status(422).send({error: 'You must provide an email and a password'})
  }

  // See if a user with the given email exists
  User.findOne({email:email}, (err, existingUser) => {
    if(err) {
      return next(err);
    }
    // If a user with email does exist, return an error
    if(existingUser) {
      return res.status(422).send({error: 'Email is in use'});
    }
    // If a user with email does NOT exist create and save user
    const user = new User({
      email: email,
      password: password
    });

    user.save((err) => {
      if(err) {
        return next(err);
      }
      // Respond to request indicating the user was created
      res.json({token: TokenForUser(user)});
    });
  });
}

// User has already passed from the requireSignIn middleware
// and has been authenticated all we need to do now is
// send back a token
function SignIn(req, res, next) {
 //req.user contains our user
  res.send({token: TokenForUser(req.user)});
}

export { SignUp, SignIn };

services/passport.js

import User from '../models/user';
import {config} from '../config';
import passport from 'passport';
import {Strategy as JwtStrategy, ExtractJwt} from 'passport-jwt';
import LocalStrategy from 'passport-local';

// Setup options for JWT Strategy
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('authorization'),
  secretOrKey: config.secret
};

// Create JWT Strategy
const jwtLogin = new JwtStrategy(jwtOptions, (payload, done) => {
  User.findById(payload.sub, (err, user) => {
    if(err) { return done(err, false); }
    if(user) {
      done(null, user);
    } else {
      done(null, false);
    }
  });

});

// Set Local Strategy options
const localOptions = {usernameField: 'email'};

// Create Local Strategy
const localLogin = new LocalStrategy(localOptions, function(email, password, done) {
  User.findOne({email: email}, function(err, user){
    if(err) { return done(err); } 
    if(!user) { return done(null, false); } // user not found in db

    // User found so compare password
    user.comparePassword(password, function(err, isMatch) {
      if(err) { return done(err); }
      if(!isMatch) { return done(null, false); } // incorrect password
      return done(null, user); // password is correct return the user
    })
  });
});

const jWtStrategy = passport.use(jwtLogin);
const localStrategy = passport.use(localLogin);

// Tell Passport to use these Strategies
export {jWtStrategy, localStrategy};

Then in router.js

import * as Authentication from './controllers/authentication';
import passportService from './services/passport';
import passport from 'passport';

// use the 'jwt' Strategy and do not use a sesison cookie
const requireJWT = passport.authenticate('jwt', {session: false});
const requireSignIn = passport.authenticate('local', {session: false});

export default (app) => {
  app.get('/', requireJWT, function(req, res) {
    res.send({hi:'there'});
  });
  // Before users access /signin route to get a token
  // they have to pass from the requireSignIn middleware
  app.post('/signin', requireSignIn, Authentication.SignIn);

  app.post('/signup', Authentication.SignUp);
}

I hope that helps :-)

enso123456 commented 6 years ago

The comparePassword method in the userSchema returns an incorrect argument. Do you know how to fix the code?