This repository was archived by the owner on Jan 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathlogin.ts
More file actions
86 lines (73 loc) · 1.88 KB
/
login.ts
File metadata and controls
86 lines (73 loc) · 1.88 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
import i18next from 'i18next';
import { Base64 } from 'js-base64';
import isEmpty from 'lodash/isEmpty';
import isNumber from 'lodash/isNumber';
import isString from 'lodash/isString';
import { HEADERS } from '../../lib/constants';
import API from './api';
interface PayloadInterface {
exp: number;
}
export function isTokenExpire(token: string | null): boolean {
if (!isString(token)) {
return true;
}
const [, payload] = token.split('.');
if (!payload) {
return true;
}
let exp: number;
try {
exp = JSON.parse(Base64.decode(payload)).exp;
} catch (error) {
console.error('Invalid token:', error, token);
return true;
}
if (!exp || !isNumber(exp)) {
return true;
}
// Report as expire before (real expire time - 30s)
const jsTimestamp = exp * 1000 - 30000;
const expired = Date.now() >= jsTimestamp;
return expired;
}
export interface LoginBody {
username?: string;
token?: string;
error?: LoginError;
}
export interface LoginError {
type: string;
description: string;
}
export async function makeLogin(username?: string, password?: string): Promise<LoginBody> {
// checks isEmpty
if (isEmpty(username) || isEmpty(password)) {
const error = {
type: 'error',
description: i18next.t('form-validation.username-or-password-cant-be-empty'),
};
return { error };
}
try {
const response: LoginBody = await API.request('login', 'POST', {
body: JSON.stringify({ username, password }),
headers: {
Accept: HEADERS.JSON,
'Content-Type': HEADERS.JSON,
},
});
const result: LoginBody = {
username: response.username,
token: response.token,
};
return result;
} catch (e) {
console.error('login error', e.message);
const error = {
type: 'error',
description: i18next.t('form-validation.unable-to-sign-in'),
};
return { error };
}
}