Guest User

Untitled

a guest
Dec 14th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. res.cookie('jwt', token, { httpOnly: true, secure: false });
  2.  
  3. const app = express()
  4.  
  5. app.use(bodyParser.urlencoded({extended: true}));
  6. app.use(bodyParser.json());
  7.  
  8. app.use(cookieParser());
  9.  
  10. app.use(function(req, res, next) {
  11. res.header("Access-Control-Allow-Origin", "*");
  12. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  13. next();
  14. });
  15.  
  16. app.post('/login', (req, res) => {
  17. passport.authenticate('local', { session: false }, (error, user) => {
  18. if (error || !user) {
  19. res.status(400).json({ error });
  20. }
  21.  
  22. // Construct JWT payload
  23. const payload = {
  24. email: user.email,
  25. expires: Date.now() + parseInt(process.env.JWT_EXPIRATION_MS),
  26. };
  27.  
  28. // Assign payload to req.user
  29. req.login(payload, {session: false}, (error) => {
  30. if (error) {
  31. res.status(400).send({ error });
  32. }
  33. // Generate a signed JWT
  34. const token = jwt.sign(JSON.stringify(payload), process.env.JWT_SECRET);
  35.  
  36. // Assign JWT to cookie
  37. res.cookie('jwt', token, { httpOnly: true, secure: false });
  38. res.status(200).send({ email: user.email });
  39. });
  40. })(req, res);
  41. });
  42.  
  43. handleLogin = async () => {
  44. const { name, email, password } = this.state
  45.  
  46. try{
  47. const res = await axios.post('http://localhost:8080/login', {
  48. email: email,
  49. password: password,
  50. })
  51.  
  52. if(res.status == 200){
  53. console.log("Logged in")
  54. console.log(res)
  55. }
  56.  
  57. } catch (err) {
  58. console.log(err)
  59. }
  60. }
Add Comment
Please, Sign In to add comment