authHandler.js 857 Bytes
Newer Older
abergavenny's avatar
abergavenny committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import passport from 'passport'
import { ExtractJwt, Strategy } from 'passport-jwt'

import config from '../config/appConfig.js'
import { User } from '../db/index.js'

const options = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: config.jwt.secrect
}

passport.use(new Strategy(options, async (payload, done) => {
  try {
    const result = await User.findOne({ _id: payload.userId })

    if (result) {
      const { _id, linkedTo, role } = result

      return done(null, {
        buildingId: linkedTo.toHexString(),
        role,
        userId: _id.toHexString(),
        valid: true
      })
    }

    return done(null, false)
  } catch (err) {
    done(err, false)
  }
}))

export function setupAuthentication (app) {
  app.use(passport.initialize())
}

export default passport.authenticate('jwt', { session: false })