felicity-lims/frontend/vite/src/auth.ts

30 lines
849 B
TypeScript
Raw Normal View History

2022-03-06 02:06:07 +08:00
import { ENCRYPT_AUTH_KEY, STORAGE_AUTH_KEY, USER_GROUP_OVERRIDE } from "./conf";
import { IUser } from "./models/auth";
import { decrypter, encrypter } from "./utils"
2022-03-07 04:39:34 +08:00
const authToStorage = async (data: any) => {
const crypted = await encrypter(data, ENCRYPT_AUTH_KEY)
await localStorage.setItem(STORAGE_AUTH_KEY, crypted);
2022-03-06 02:06:07 +08:00
}
2022-03-07 04:39:34 +08:00
const authFromStorage = async (): Promise<{
2022-03-06 02:06:07 +08:00
token?: string,
tokenType?: string,
user?: IUser
2022-03-07 04:39:34 +08:00
}> => {
const data = await decrypter(localStorage.getItem(STORAGE_AUTH_KEY), ENCRYPT_AUTH_KEY);
2022-03-06 02:06:07 +08:00
if(USER_GROUP_OVERRIDE.length > 0) {
2022-03-07 04:39:34 +08:00
await data?.user?.groups?.forEach(group => {
2022-03-06 02:06:07 +08:00
group.name = USER_GROUP_OVERRIDE
})
}
return data
}
const authLogout = () => {
2022-03-07 04:39:34 +08:00
2022-03-06 02:06:07 +08:00
localStorage.removeItem(STORAGE_AUTH_KEY);
}
export { authToStorage, authFromStorage, authLogout }