-
Notifications
You must be signed in to change notification settings - Fork 0
/
credentialsService.ts
61 lines (57 loc) · 2.25 KB
/
credentialsService.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
import { sign, verify } from 'jsonwebtoken';
import { AuthistOptions, Credentials, User } from './authist';
import { ERROR_CODE, NotAuthenticated } from './error';
import { handleError } from './providerUtils';
export const createCredentials = (user: User, options: AuthistOptions): Credentials => {
const getPayload = (tokenType: string) => ({
user: {
uid: user.uid,
},
type: tokenType,
});
return {
accessToken: sign(getPayload('accessToken'), getSecret(options), {
expiresIn: (options.token?.lifetimeMinutes || 60) * 60,
}),
refreshToken: sign(getPayload('refreshToken'), getSecret(options), {
expiresIn: (options.token?.refreshLifetimeMinutes || 60 * 24 * 60) * 60,
}),
expiresIn: (options.token?.lifetimeMinutes || 60) * 60,
refreshExpiresIn: (options.token?.refreshLifetimeMinutes || 60 * 24 * 60) * 60,
};
};
export const verifyToken = async (token: string, options: AuthistOptions) => {
try {
if (!options.getUserById) {
throw new Error('Function `getUserById` is not implemented!');
}
const secret = getSecret(options, true);
const decodedToken = verify(token, secret) as { user: { uid: string } };
const { uid } = decodedToken.user;
const user = await options.getUserById(uid);
if (!user) {
throw new NotAuthenticated(ERROR_CODE.UserNotFound);
}
return user;
} catch (error) {
return handleError(error, {}, options);
}
};
export const getSecret = (options: AuthistOptions, verify = false) => {
if (verify && options.token?.jwtPublicKey) {
return options.token.jwtPublicKey;
}
if (options.token?.jwtPrivateKey) {
return options.token.jwtPrivateKey;
}
if (options.token?.jwtSecret) {
return options.token.jwtSecret;
}
console.warn('You should set the JWT secret or private / public keys to prevent security breaches.');
return 'secret';
};
export const refreshToken = (options: AuthistOptions) => async (refreshToken: string) => {
const user = await verifyToken(refreshToken, options);
const credentials = await createCredentials(user, options);
return { credentials, user };
};