-
-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathcookie-utils.ts
More file actions
34 lines (26 loc) · 781 Bytes
/
cookie-utils.ts
File metadata and controls
34 lines (26 loc) · 781 Bytes
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
import cookie from 'js-cookie';
import jwtDecode from 'jwt-decode';
export const setAuthCookies = ({ token }: { token: string }) => {
cookie.set('token', token);
};
export const removeAuthCookies = () => {
cookie.remove('token');
};
export const setAuthorizationHeader = (token = getAuthToken()) => {
if (hasValidAuthToken(token)) {
return { Authorization: `Bearer ${token}` };
}
return {};
};
export const getAuthToken = () => {
return cookie.get('token');
};
export const hasValidAuthToken = (token = cookie.get('token')) => {
if (token === undefined) {
return false;
}
const jwt = jwtDecode<{ exp: number }>(token);
const currentTime = new Date().getTime() / 1000;
// Valid if jwt expiry is in the future
return currentTime < jwt.exp;
};