aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/oauth-token.js
blob: d53fdcf31fd336a970a722582d7c1577dc11a98b (plain) (blame)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const mongoose = require('mongoose')

const logger = require('../helpers/logger')

// ---------------------------------------------------------------------------

const OAuthTokenSchema = mongoose.Schema({
  accessToken: String,
  accessTokenExpiresAt: Date,
  client: { type: mongoose.Schema.Types.ObjectId, ref: 'OAuthClient' },
  refreshToken: String,
  refreshTokenExpiresAt: Date,
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})

OAuthTokenSchema.path('accessToken').required(true)
OAuthTokenSchema.path('client').required(true)
OAuthTokenSchema.path('user').required(true)

OAuthTokenSchema.statics = {
  getByRefreshTokenAndPopulateClient: getByRefreshTokenAndPopulateClient,
  getByTokenAndPopulateUser: getByTokenAndPopulateUser,
  getByRefreshToken: getByRefreshToken,
  removeByUserId: removeByUserId
}

mongoose.model('OAuthToken', OAuthTokenSchema)

// ---------------------------------------------------------------------------

function getByRefreshTokenAndPopulateClient (refreshToken) {
  return this.findOne({ refreshToken: refreshToken }).populate('client').exec().then(function (token) {
    if (!token) return token

    const tokenInfos = {
      refreshToken: token.refreshToken,
      refreshTokenExpiresAt: token.refreshTokenExpiresAt,
      client: {
        id: token.client._id.toString()
      },
      user: token.user
    }

    return tokenInfos
  }).catch(function (err) {
    logger.info('getRefreshToken error.', { error: err })
  })
}

function getByTokenAndPopulateUser (bearerToken) {
  return this.findOne({ accessToken: bearerToken }).populate('user').exec()
}

function getByRefreshToken (refreshToken) {
  return this.findOne({ refreshToken: refreshToken }).exec()
}

function removeByUserId (userId, callback) {
  return this.remove({ user: userId }, callback)
}