auth.controller.js 1.5 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
import jwt from 'jsonwebtoken'
Yoon, Daeki's avatar
Yoon, Daeki committed
2
3
4
import expressJwt from 'express-jwt'
import User from '../user/user.model.js'
import config from '../config/config.js'
Yoon, Daeki's avatar
Yoon, Daeki committed
5
6

const signin = async (req, res) => {
Yoon, Daeki's avatar
sign in    
Yoon, Daeki committed
7
  console.log(req.body);
Yoon, Daeki's avatar
Yoon, Daeki committed
8
  try {
Yoon, Daeki's avatar
Yoon, Daeki committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    let user = await User.findOne({ 'email': req.body.email })
    if (!user) {
      return res.status(401).json({
        error: 'User not found'
      })
    }

    if (!user.authenticate(req.body.password)) {
      return res.status(401).json({
        error: "Email and password don't match"
      })
    }

    const token = jwt.sign({ _id: user._id }, config.jwtSecret)

    return res.json({
      token,
      user: {
        _id: user._id,
        name: user.name,
        email: user.email,
      }
    })
Yoon, Daeki's avatar
Yoon, Daeki committed
32
33
  } catch (error) {
    return res.status(400).json({
Yoon, Daeki's avatar
Yoon, Daeki committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
      error: 'Could not sign in'
    })
  }
}

const signout = (req, res) => {
  return res.json({
    message: 'Signed out'
  })
}

const requireSignin = expressJwt({
  secret: config.jwtSecret,
  requestProperty: 'auth',
  algorithms: ['HS256']
})

const hasAuthorization = (req, res, next) => {
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
52
53
54
  // console.log('profile:', req.profile, 'auth:', req.auth);
  // console.log('id is equal?:', req.profile._id === req.auth._id);
  const authorized = req.profile && req.auth && req.profile._id == req.auth._id
Yoon, Daeki's avatar
Yoon, Daeki committed
55
  if (!authorized) {
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
56
    // console.log('authorized?', authorized);
Yoon, Daeki's avatar
Yoon, Daeki committed
57
58
    return res.status(403).json({
      error: 'User is not authorized'
Yoon, Daeki's avatar
Yoon, Daeki committed
59
60
    })
  }
Yoon, Daeki's avatar
Yoon, Daeki committed
61
  next()
Yoon, Daeki's avatar
Yoon, Daeki committed
62
63
64
65
}

export default {
  signin,
Yoon, Daeki's avatar
Yoon, Daeki committed
66
67
68
  signout,
  requireSignin,
  hasAuthorization,
Yoon, Daeki's avatar
Yoon, Daeki committed
69
}