77 lines
1.9 KiB
JavaScript
77 lines
1.9 KiB
JavaScript
import { AES, enc } from 'crypto-js'
|
|
import { LOGIN_KEY, SECRET_KEY, STORE_KEY } from './enum'
|
|
|
|
export class Helpers {
|
|
static setCookie = (cname, cvalue, exdays) => {
|
|
const d = new Date()
|
|
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000)
|
|
let expires = `expires=${d.toUTCString()}`
|
|
document.cookie = `${cname}=${cvalue};${expires};path=/`
|
|
}
|
|
|
|
static getCookie = (cname) => {
|
|
let name = cname + '='
|
|
let ca = document.cookie.split(';')
|
|
for (let i = 0; i < ca.length; i++) {
|
|
let c = ca[i]
|
|
while (c.charAt(0) == ' ') {
|
|
c = c.substring(1)
|
|
}
|
|
if (c.indexOf(name) == 0) {
|
|
return c.substring(name.length, c.length)
|
|
}
|
|
}
|
|
return ''
|
|
}
|
|
|
|
static deleteCookie = (cname) => {
|
|
document.cookie = `${cname}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`
|
|
}
|
|
|
|
static clearStorage = () => {
|
|
localStorage.removeItem(LOGIN_KEY)
|
|
localStorage.removeItem(STORE_KEY)
|
|
}
|
|
|
|
static checkTokenExpired = (exp) => {
|
|
const currentTime = Math.floor(new Date().getTime() / 1000)
|
|
return exp < currentTime
|
|
}
|
|
|
|
static encrypt = (obj) => {
|
|
return AES.encrypt(JSON.stringify(obj), SECRET_KEY).toString()
|
|
}
|
|
|
|
static decrypt = (hash, defaultValue = {}) => {
|
|
return hash
|
|
? JSON.parse(AES.decrypt(hash, SECRET_KEY).toString(enc.Utf8))
|
|
: defaultValue
|
|
}
|
|
|
|
static clearObject = (object) => {
|
|
for (var propName in object) {
|
|
if (
|
|
object[propName] === null ||
|
|
object[propName] === undefined ||
|
|
object[propName] === ''
|
|
) {
|
|
delete object[propName]
|
|
}
|
|
}
|
|
return object
|
|
}
|
|
|
|
static clearArrayWithNullObject = (array) => {
|
|
if (array instanceof Array) {
|
|
array.forEach((element, i) => {
|
|
if (element instanceof Object) {
|
|
const obk = this.clearObject(element)
|
|
if (obk) array.splice(i, 1)
|
|
}
|
|
})
|
|
}
|
|
|
|
return array.length > 0 ? array : null
|
|
}
|
|
}
|