felicity-lims/webapp/auth.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-04-10 09:29:10 +08:00
import { ENCRYPT_AUTH_KEY, STORAGE_AUTH_KEY, USER_GROUP_OVERRIDE } from './conf';
import { IUser } from './models/auth';
import { decrypter, decrypter2, encrypter } from './utils';
2022-03-06 02:06:07 +08:00
2022-03-07 04:39:34 +08:00
const authToStorage = async (data: any) => {
2023-04-10 09:29:10 +08:00
const crypted = await encrypter(data, ENCRYPT_AUTH_KEY);
2022-03-07 04:39:34 +08:00
await localStorage.setItem(STORAGE_AUTH_KEY, crypted);
2023-04-10 09:29:10 +08:00
};
2022-03-06 02:06:07 +08:00
2022-03-07 04:39:34 +08:00
const authFromStorage = async (): Promise<{
2023-04-10 09:29:10 +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);
2023-04-10 09:29:10 +08:00
if (USER_GROUP_OVERRIDE.length > 0) {
2022-03-07 04:39:34 +08:00
await data?.user?.groups?.forEach(group => {
2023-04-10 09:29:10 +08:00
group.name = USER_GROUP_OVERRIDE;
});
2022-03-06 02:06:07 +08:00
}
2023-04-10 09:29:10 +08:00
return data;
};
2022-03-06 02:06:07 +08:00
2022-03-10 08:00:40 +08:00
const authFromStorage2 = (): {
2023-04-10 09:29:10 +08:00
token?: string;
tokenType?: string;
user?: IUser;
2022-03-10 08:00:40 +08:00
} => {
const data = decrypter2(localStorage.getItem(STORAGE_AUTH_KEY), ENCRYPT_AUTH_KEY);
2023-04-10 09:29:10 +08:00
if (USER_GROUP_OVERRIDE.length > 0) {
2022-03-10 08:00:40 +08:00
data?.user?.groups?.forEach(group => {
2023-04-10 09:29:10 +08:00
group.name = USER_GROUP_OVERRIDE;
});
2022-03-10 08:00:40 +08:00
}
2023-04-10 09:29:10 +08:00
return data;
};
2022-03-10 08:00:40 +08:00
2022-03-06 02:06:07 +08:00
const authLogout = () => {
localStorage.removeItem(STORAGE_AUTH_KEY);
2023-04-10 09:29:10 +08:00
};
const getAuthData = () => {
let data: any = {};
2023-04-10 09:29:10 +08:00
if (localStorage.getItem(STORAGE_AUTH_KEY)) {
const auth = JSON.parse(localStorage.getItem(STORAGE_AUTH_KEY)!);
data = { auth };
}
return data;
2023-04-10 09:29:10 +08:00
};
2023-04-10 09:29:10 +08:00
export { authToStorage, authFromStorage, authFromStorage2, authLogout, getAuthData };