PeerTube/server/models/oauth-token.js

121 lines
2.4 KiB
JavaScript
Raw Normal View History

2016-12-28 15:49:23 +01:00
'use strict'
2016-07-20 16:23:58 +02:00
const logger = require('../helpers/logger')
// ---------------------------------------------------------------------------
2016-12-11 21:50:51 +01:00
module.exports = function (sequelize, DataTypes) {
const OAuthToken = sequelize.define('OAuthToken',
{
accessToken: {
2016-12-28 15:49:23 +01:00
type: DataTypes.STRING,
allowNull: false
2016-12-11 21:50:51 +01:00
},
accessTokenExpiresAt: {
2016-12-28 15:49:23 +01:00
type: DataTypes.DATE,
allowNull: false
2016-12-11 21:50:51 +01:00
},
refreshToken: {
2016-12-28 15:49:23 +01:00
type: DataTypes.STRING,
allowNull: false
2016-12-11 21:50:51 +01:00
},
refreshTokenExpiresAt: {
2016-12-28 15:49:23 +01:00
type: DataTypes.DATE,
allowNull: false
2016-12-11 21:50:51 +01:00
}
},
{
classMethods: {
associate,
getByRefreshTokenAndPopulateClient,
getByTokenAndPopulateUser,
getByRefreshTokenAndPopulateUser,
removeByUserId
}
}
)
return OAuthToken
}
// ---------------------------------------------------------------------------
2016-12-11 21:50:51 +01:00
function associate (models) {
this.belongsTo(models.User, {
foreignKey: {
name: 'userId',
allowNull: false
},
onDelete: 'cascade'
})
}
2016-07-20 16:23:58 +02:00
function getByRefreshTokenAndPopulateClient (refreshToken) {
2016-12-11 21:50:51 +01:00
const query = {
where: {
refreshToken: refreshToken
},
include: [ this.associations.OAuthClient ]
}
return this.findOne(query).then(function (token) {
2016-07-20 16:23:58 +02:00
if (!token) return token
const tokenInfos = {
refreshToken: token.refreshToken,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
client: {
2016-12-11 21:50:51 +01:00
id: token.client.id
2016-07-20 16:23:58 +02:00
},
2016-11-04 11:34:23 +01:00
user: {
id: token.user
}
2016-07-20 16:23:58 +02:00
}
return tokenInfos
}).catch(function (err) {
logger.info('getRefreshToken error.', { error: err })
})
}
2016-07-20 16:23:58 +02:00
function getByTokenAndPopulateUser (bearerToken) {
2016-12-11 21:50:51 +01:00
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
})
}
2016-07-20 16:23:58 +02:00
function getByRefreshTokenAndPopulateUser (refreshToken) {
2016-12-11 21:50:51 +01:00
const query = {
where: {
refreshToken: refreshToken
},
include: [ this.sequelize.models.User ]
}
return this.findOne(query).then(function (token) {
token.user = token.User
return token
})
2016-07-20 16:23:58 +02:00
}
function removeByUserId (userId, callback) {
2016-12-11 21:50:51 +01:00
const query = {
where: {
userId: userId
}
}
return this.destroy(query).asCallback(callback)
}