bullpen/backend/models/refreshToken.model.js

55 lines
1.3 KiB
JavaScript

const { Model } = require('sequelize');
const config = require("../config/auth.config");
const {v4: uuidv4} = require("uuid");
module.exports = (sequelize, DataTypes) => {
class RefreshToken extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
RefreshToken.belongsTo(models.Auth, {
foreignKey: 'authId',
targetKey: 'id'
});
}
}
RefreshToken.init({
token: {
type: DataTypes.STRING,
allowNull: false,
},
expiryDate: {
type: DataTypes.DATE,
allowNull: false,
},
}, {
sequelize,
modelName: 'RefreshToken',
tableName: 'RefreshTokens'
});
RefreshToken.createToken = async function (auth) {
let expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + config.jwtRefreshExpiration);
let _token = uuidv4();
let refreshToken = await this.create({
token: _token,
authId: auth.id,
expiryDate: expiredAt.getTime(),
});
return refreshToken.token;
};
RefreshToken.verifyExpiration = (token) => {
return token.expiryDate.getTime() < new Date().getTime();
};
return RefreshToken;
};