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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
'use strict'
const logger = require('../helpers/logger')
// ---------------------------------------------------------------------------
module.exports = function (sequelize, DataTypes) {
const OAuthToken = sequelize.define('OAuthToken',
{
accessToken: {
type: DataTypes.STRING,
allowNull: false
},
accessTokenExpiresAt: {
type: DataTypes.DATE,
allowNull: false
},
refreshToken: {
type: DataTypes.STRING,
allowNull: false
},
refreshTokenExpiresAt: {
type: DataTypes.DATE,
allowNull: false
}
},
{
classMethods: {
associate,
getByRefreshTokenAndPopulateClient,
getByTokenAndPopulateUser,
getByRefreshTokenAndPopulateUser,
removeByUserId
}
}
)
return OAuthToken
}
// ---------------------------------------------------------------------------
function associate (models) {
this.belongsTo(models.User, {
foreignKey: {
name: 'userId',
allowNull: false
},
onDelete: 'cascade'
})
}
function getByRefreshTokenAndPopulateClient (refreshToken) {
const query = {
where: {
refreshToken: refreshToken
},
include: [ this.associations.OAuthClient ]
}
return this.findOne(query).then(function (token) {
if (!token) return token
const tokenInfos = {
refreshToken: token.refreshToken,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
client: {
id: token.client.id
},
user: {
id: token.user
}
}
return tokenInfos
}).catch(function (err) {
logger.info('getRefreshToken error.', { error: err })
})
}
function getByTokenAndPopulateUser (bearerToken) {
const query = {
where: {
accessToken: bearerToken
},
include: [ this.sequelize.models.User ]
}
return this.findOne(query).then(function (token) {
if (token) token.user = token.User
return token
})
}
function getByRefreshTokenAndPopulateUser (refreshToken) {
const query = {
where: {
refreshToken: refreshToken
},
include: [ this.sequelize.models.User ]
}
return this.findOne(query).then(function (token) {
token.user = token.User
return token
})
}
function removeByUserId (userId, callback) {
const query = {
where: {
userId: userId
}
}
return this.destroy(query).asCallback(callback)
}
|