-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToken.js
More file actions
80 lines (75 loc) · 1.88 KB
/
Copy pathToken.js
File metadata and controls
80 lines (75 loc) · 1.88 KB
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
/**
* Token model for storing refresh tokens
*/
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const crypto = require('crypto');
const config = require('../config');
// Encryption functions for sensitive data
const encrypt = (text) => {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(
config.encryption.algorithm,
Buffer.from(config.encryption.key, 'hex'),
iv
);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
};
const decrypt = (text) => {
const parts = text.split(':');
const iv = Buffer.from(parts[0], 'hex');
const encryptedText = Buffer.from(parts[1], 'hex');
const decipher = crypto.createDecipheriv(
config.encryption.algorithm,
Buffer.from(config.encryption.key, 'hex'),
iv
);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
};
const Token = sequelize.define('Token', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
userId: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
},
refreshToken: {
type: DataTypes.TEXT,
allowNull: false,
get() {
const value = this.getDataValue('refreshToken');
return value ? decrypt(value) : null;
},
set(value) {
this.setDataValue('refreshToken', value ? encrypt(value) : null);
}
},
expiresAt: {
type: DataTypes.DATE,
allowNull: false
},
isRevoked: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
userAgent: {
type: DataTypes.STRING,
allowNull: true
},
ipAddress: {
type: DataTypes.STRING,
allowNull: true
}
});
module.exports = Token;