2016-07-01 10:03:53 -04:00
|
|
|
const mongoose = require('mongoose')
|
|
|
|
|
2016-07-20 10:23:58 -04:00
|
|
|
const logger = require('../helpers/logger')
|
|
|
|
|
2016-07-01 10:03:53 -04:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
const OAuthTokenSchema = mongoose.Schema({
|
|
|
|
accessToken: String,
|
2016-07-20 10:23:58 -04:00
|
|
|
accessTokenExpiresAt: Date,
|
2016-07-01 10:03:53 -04:00
|
|
|
client: { type: mongoose.Schema.Types.ObjectId, ref: 'OAuthClient' },
|
|
|
|
refreshToken: String,
|
2016-07-20 10:23:58 -04:00
|
|
|
refreshTokenExpiresAt: Date,
|
2016-07-01 10:03:53 -04:00
|
|
|
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 = {
|
2016-10-02 06:19:02 -04:00
|
|
|
getByRefreshTokenAndPopulateClient,
|
|
|
|
getByTokenAndPopulateUser,
|
|
|
|
getByRefreshToken,
|
|
|
|
removeByUserId
|
2016-07-01 10:03:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
mongoose.model('OAuthToken', OAuthTokenSchema)
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
2016-07-20 10:23:58 -04:00
|
|
|
function getByRefreshTokenAndPopulateClient (refreshToken) {
|
2016-07-27 15:15:07 -04:00
|
|
|
return this.findOne({ refreshToken: refreshToken }).populate('client').exec().then(function (token) {
|
2016-07-20 10:23:58 -04:00
|
|
|
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 })
|
|
|
|
})
|
2016-07-01 10:03:53 -04:00
|
|
|
}
|
|
|
|
|
2016-07-20 10:23:58 -04:00
|
|
|
function getByTokenAndPopulateUser (bearerToken) {
|
2016-07-27 15:15:07 -04:00
|
|
|
return this.findOne({ accessToken: bearerToken }).populate('user').exec()
|
2016-07-01 10:03:53 -04:00
|
|
|
}
|
2016-07-20 10:23:58 -04:00
|
|
|
|
|
|
|
function getByRefreshToken (refreshToken) {
|
2016-07-27 15:15:07 -04:00
|
|
|
return this.findOne({ refreshToken: refreshToken }).exec()
|
2016-07-20 10:23:58 -04:00
|
|
|
}
|
2016-10-01 03:12:02 -04:00
|
|
|
|
|
|
|
function removeByUserId (userId, callback) {
|
|
|
|
return this.remove({ user: userId }, callback)
|
|
|
|
}
|