1
0
Fork 1
mirror of https://github.com/SomboChea/ui synced 2024-05-03 18:11:36 +07:00
verdaccio-ui/src/utils/login.ts
Priscila Oliveira 42d3bb8508 feat: login Dialog Component - Replaced class by func. comp + added react-hook-form (#341)
* refactor: convert class to func

* refactor: changed login form logic

* refactor: conver to testing-library tests

* refactor: moved dependency

* refactor: replaced uglifyjs-webpack-plugin by terser-webpack-plugin

* fix: fixed e2e errors

* fix: fixed e2e test

* Delete settings.json

* fix: vscode settings rollback

* refactor: rollback webpack config

* refactor: updated eslint rule

* fix: removed --fix

* refactor: incresed the bundle size
2019-12-06 18:09:01 +01:00

86 lines
1.8 KiB
TypeScript

import isString from 'lodash/isString';
import isNumber from 'lodash/isNumber';
import isEmpty from 'lodash/isEmpty';
import { Base64 } from 'js-base64';
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: "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) {
console.error('login error', e.message);
const error = {
type: 'error',
description: 'Unable to sign in',
};
return { error };
}
}