-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiKey.js
More file actions
100 lines (95 loc) · 2.32 KB
/
Copy pathApiKey.js
File metadata and controls
100 lines (95 loc) · 2.32 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* ApiKey model for storing API keys for external integrations
*/
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 ApiKey = sequelize.define('ApiKey', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
userId: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
},
name: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
key: {
type: DataTypes.TEXT,
allowNull: false,
defaultValue: () => crypto.randomBytes(32).toString('hex'),
get() {
const value = this.getDataValue('key');
return value ? decrypt(value) : null;
},
set(value) {
this.setDataValue('key', value ? encrypt(value) : null);
}
},
permissions: {
type: DataTypes.JSON,
allowNull: false,
defaultValue: [],
comment: 'Array of permission strings'
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
expiresAt: {
type: DataTypes.DATE,
allowNull: true
},
lastUsedAt: {
type: DataTypes.DATE,
allowNull: true
},
ipRestrictions: {
type: DataTypes.JSON,
allowNull: true,
comment: 'Array of allowed IP addresses or CIDR ranges'
},
useCount: {
type: DataTypes.INTEGER,
defaultValue: 0
}
});
module.exports = ApiKey;