-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathToken.ts
168 lines (137 loc) · 5.09 KB
/
Token.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import bcrypt from 'bcryptjs'
import { createHash } from 'crypto'
import { model, ObjectId, Schema } from 'mongoose'
import MongooseDelete, { SoftDeleteDocument } from 'mongoose-delete'
import { BadReq } from '../utils/error.js'
export const TokenScope = {
All: 'all',
Models: 'models',
} as const
export type TokenScopeKeys = (typeof TokenScope)[keyof typeof TokenScope]
export const TokenActions = {
ModelRead: { id: 'model:read', description: 'Grants access to view model/data card settings.' },
ModelWrite: {
id: 'model:write',
description: 'Grants write access to creation and updating of model/data card settings.',
},
ReleaseRead: { id: 'release:read', description: 'Grants access to view releases.' },
ReleaseWrite: { id: 'release:write', description: 'Grants access to create and update releases.' },
AccessRequestRead: { id: 'access_request:read', description: 'Grant access to list access requests' },
AccessRequestWrite: {
id: 'access_request:write',
description: 'Grants access to create, approve and comment on access requests.',
},
FileRead: { id: 'file:read', description: 'Grant access to download and view files.' },
FileWrite: { id: 'file:write', description: 'Grant access to upload and delete files.' },
ImageRead: { id: 'image:read', description: 'Grants access to pull and list images from a model repository.' },
ImageWrite: { id: 'image:write', description: 'Grants access to push and delete images from a model repository.' },
SchemaWrite: {
id: 'schema:write',
description: 'Grants permissions to upload and modify schemas for administrators.',
},
} as const
export const tokenActionIds = Object.values(TokenActions).map((tokenAction) => tokenAction.id)
export type TokenActionsKeys = (typeof TokenActions)[keyof typeof TokenActions]['id']
export const HashType = {
Bcrypt: 'bcrypt',
SHA256: 'sha-256',
}
export type HashTypeKeys = (typeof HashType)[keyof typeof HashType]
// This interface stores information about the properties on the base object.
// It should be used for plain object representations, e.g. for sending to the
// client.
export interface TokenInterface {
_id: ObjectId
user: string
description: string
scope: TokenScopeKeys
modelIds: Array<string>
actions?: Array<TokenActionsKeys>
accessKey: string
secretKey: string
hashMethod: HashTypeKeys
deleted: boolean
createdAt: Date
updatedAt: Date
compareToken: (candidateToken: string) => Promise<boolean>
}
// The doc type includes all values in the plain interface, as well as all the
// properties and functions that Mongoose provides. If a function takes in an
// object from Mongoose it should use this interface
export type TokenDoc = TokenInterface & SoftDeleteDocument
const TokenSchema = new Schema<TokenDoc>(
{
user: { type: String, required: true },
description: { type: String, required: true },
scope: { type: String, enum: Object.values(TokenScope), required: true },
modelIds: [{ type: String }],
actions: [{ type: String, enum: tokenActionIds }],
accessKey: { type: String, required: true, unique: true, index: true },
secretKey: { type: String, required: true, select: false },
hashMethod: { type: String, enum: Object.values(HashType), required: true, default: HashType.SHA256 },
},
{
timestamps: true,
collection: 'v2_tokens',
},
)
TokenSchema.pre('save', function userPreSave(next) {
if (!this.isModified('secretKey') || !this.secretKey) {
next()
return
}
if (!this.hashMethod) {
this.hashMethod = HashType.SHA256
}
if (this.hashMethod === HashType.Bcrypt) {
bcrypt.hash(this.secretKey, 8, (err: Error | null, result: string | undefined) => {
if (err) {
next(err)
return
}
if (!result) {
throw BadReq('Unable to create token')
}
this.secretKey = result
next()
})
} else if (this.hashMethod === HashType.SHA256) {
const hash = createHash('sha256').update(this.secretKey).digest('hex')
this.secretKey = hash
next()
} else {
throw new Error('Unexpected hash type: ' + this.hashMethod)
}
})
TokenSchema.methods.compareToken = function compareToken(candidateToken: string) {
return new Promise((resolve, reject) => {
if (!this.secretKey) {
resolve(false)
return
}
if (this.hashMethod === HashType.Bcrypt) {
bcrypt.compare(candidateToken, this.secretKey, (err: Error | null, result: boolean | undefined) => {
if (err) {
reject(err)
return
}
if (!result) {
BadReq('Unable to compare token')
}
resolve(result)
})
} else if (this.hashMethod === HashType.SHA256) {
const candidateHash = createHash('sha256').update(candidateToken).digest('hex')
if (candidateHash !== this.secretKey) {
resolve(false)
return
}
resolve(true)
} else {
throw new Error('Unexpected hash type: ' + this.hashMethod)
}
})
}
TokenSchema.plugin(MongooseDelete, { overrideMethods: 'all', deletedAt: true })
const TokenModel = model<TokenDoc>('v2_Token', TokenSchema)
export default TokenModel