auth.controller.js 1.31 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
7

const signin = async (req, res) => {
  try {
Yoon, Daeki's avatar
Yoon, Daeki committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    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
31
32
  } catch (error) {
    return res.status(400).json({
Yoon, Daeki's avatar
Yoon, Daeki committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
      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) => {
  const authorized = req.profile && req.auth && req.profile._id === req.auth._id
  if (!authorized) {
    return res.status(403).json({
      error: 'User is not authorized'
Yoon, Daeki's avatar
Yoon, Daeki committed
55
56
    })
  }
Yoon, Daeki's avatar
Yoon, Daeki committed
57
  next()
Yoon, Daeki's avatar
Yoon, Daeki committed
58
59
60
61
}

export default {
  signin,
Yoon, Daeki's avatar
Yoon, Daeki committed
62
63
64
  signout,
  requireSignin,
  hasAuthorization,
Yoon, Daeki's avatar
Yoon, Daeki committed
65
}