-
Notifications
You must be signed in to change notification settings - Fork 2
/
User.ts
63 lines (56 loc) · 1.58 KB
/
User.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
import * as mongoose from 'mongoose';
import mongooseEncryption from 'mongoose-encryption';
import config from './config.js';
import yahooAuth from './yahooAuth.js';
export interface ILeague {
key: string;
lastNotifiedTransaction?: string;
name: string;
}
export interface IUser {
accessToken: string;
email: string;
expires: Date;
id: string;
leagues: ILeague[];
refreshToken: string;
renewToken: () => Promise<void>;
}
const userSchema = new mongoose.Schema(
{
email: { type: String, required: true },
accessToken: { type: String, required: true },
refreshToken: { type: String, required: true },
expires: { type: Date, required: true },
leagues: [
{
_id: false,
key: { type: String, required: true },
name: { type: String, required: true },
lastNotifiedTransaction: String,
},
],
},
{ timestamps: true },
);
if (config.MONGO_ENCRYPTION_KEY) {
userSchema.plugin(mongooseEncryption, {
encryptionKey: config.MONGO_ENCRYPTION_KEY,
signingKey: config.MONGO_SIGNING_KEY,
encryptedFields: ['accessToken', 'refreshToken'],
additionalAuthenticatedFields: ['email'],
});
}
userSchema.methods.renewToken = async function renewToken() {
const token = yahooAuth.createToken(
this.accessToken,
this.refreshToken,
'bearer',
{},
);
const newToken = await token.refresh();
this.accessToken = newToken.accessToken;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.expires = (newToken as any).expires;
};
export default mongoose.model<IUser>('User', userSchema);