PeerTube/server/models/oauth-token.js

63 lines
1.8 KiB
JavaScript
Raw Normal View History

const mongoose = require('mongoose')
2016-07-20 17:23:58 +03:00
const logger = require('../helpers/logger')
// ---------------------------------------------------------------------------
const OAuthTokenSchema = mongoose.Schema({
accessToken: String,
2016-07-20 17:23:58 +03:00
accessTokenExpiresAt: Date,
client: { type: mongoose.Schema.Types.ObjectId, ref: 'OAuthClient' },
refreshToken: String,
2016-07-20 17:23:58 +03:00
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,
getByTokenAndPopulateUser,
getByRefreshTokenAndPopulateUser,
removeByUserId
}
mongoose.model('OAuthToken', OAuthTokenSchema)
// ---------------------------------------------------------------------------
2016-07-20 17:23:58 +03:00
function getByRefreshTokenAndPopulateClient (refreshToken) {
return this.findOne({ refreshToken: refreshToken }).populate('client').exec().then(function (token) {
2016-07-20 17:23:58 +03:00
if (!token) return token
const tokenInfos = {
refreshToken: token.refreshToken,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
client: {
id: token.client._id.toString()
},
2016-11-04 13:34:23 +03:00
user: {
id: token.user
}
2016-07-20 17:23:58 +03:00
}
return tokenInfos
}).catch(function (err) {
logger.info('getRefreshToken error.', { error: err })
})
}
2016-07-20 17:23:58 +03:00
function getByTokenAndPopulateUser (bearerToken) {
return this.findOne({ accessToken: bearerToken }).populate('user').exec()
}
2016-07-20 17:23:58 +03:00
function getByRefreshTokenAndPopulateUser (refreshToken) {
return this.findOne({ refreshToken: refreshToken }).populate('user').exec()
2016-07-20 17:23:58 +03:00
}
function removeByUserId (userId, callback) {
return this.remove({ user: userId }, callback)
}