2019-06-20 19:37:28 +07:00
|
|
|
import isString from 'lodash/isString';
|
|
|
|
import isNumber from 'lodash/isNumber';
|
|
|
|
import isEmpty from 'lodash/isEmpty';
|
|
|
|
import { Base64 } from 'js-base64';
|
|
|
|
import API from './api';
|
|
|
|
import { HEADERS } from '../../lib/constants';
|
|
|
|
|
2019-06-22 16:43:59 +07:00
|
|
|
interface PayloadInterface {
|
|
|
|
exp: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function isTokenExpire(token?: string): boolean {
|
2019-06-20 19:37:28 +07:00
|
|
|
if (!isString(token)) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-06-22 16:43:59 +07:00
|
|
|
const [, payload] = token.split('.');
|
2019-06-20 19:37:28 +07:00
|
|
|
|
|
|
|
if (!payload) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-06-22 16:43:59 +07:00
|
|
|
let exp: number;
|
2019-06-20 19:37:28 +07:00
|
|
|
try {
|
2019-06-22 16:43:59 +07:00
|
|
|
exp = JSON.parse(Base64.decode(payload)).exp;
|
2019-06-20 19:37:28 +07:00
|
|
|
} catch (error) {
|
2019-06-22 16:43:59 +07:00
|
|
|
console.error('Invalid token:', error, token);
|
2019-06-20 19:37:28 +07:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-06-22 16:43:59 +07:00
|
|
|
if (!exp || !isNumber(exp)) {
|
2019-06-20 19:37:28 +07:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
// Report as expire before (real expire time - 30s)
|
2019-06-22 16:43:59 +07:00
|
|
|
const jsTimestamp = exp * 1000 - 30000;
|
2019-06-20 19:37:28 +07:00
|
|
|
const expired = Date.now() >= jsTimestamp;
|
|
|
|
|
|
|
|
return expired;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface LoginBody {
|
|
|
|
username?: string;
|
|
|
|
token?: string;
|
|
|
|
error?: LoginError;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface LoginError {
|
|
|
|
title: string;
|
|
|
|
type: string;
|
|
|
|
description: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function makeLogin(username?: string, password?: string): Promise<LoginBody> {
|
|
|
|
// checks isEmpty
|
|
|
|
if (isEmpty(username) || isEmpty(password)) {
|
|
|
|
const error = {
|
|
|
|
title: 'Unable to login',
|
|
|
|
type: 'error',
|
|
|
|
description: "Username or password can't 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) {
|
|
|
|
const error = {
|
|
|
|
title: 'Unable to login',
|
|
|
|
type: 'error',
|
|
|
|
description: e.error,
|
|
|
|
};
|
|
|
|
return { error };
|
|
|
|
}
|
|
|
|
}
|