useUser.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import toast from "react-hot-toast";
  2. import { altogic } from "src/api/altogic";
  3. import { AltogicAuth, User } from "src/typings/altogic";
  4. import { create } from "zustand";
  5. import useModal from "./useModal";
  6. interface UserActions {
  7. login: (response: AltogicAuth) => void;
  8. logout: () => void;
  9. setUser: (key: keyof typeof initialStates, value: any) => void;
  10. checkSession: () => void;
  11. isPremium: () => boolean;
  12. tokenAuth: () => Promise<void>;
  13. }
  14. const initialStates = {
  15. isAuthenticated: false,
  16. user: null as User | null,
  17. };
  18. export type UserStates = typeof initialStates;
  19. const useUser = create<UserStates & UserActions>()((set, get) => ({
  20. ...initialStates,
  21. setUser: (key, value) => set({ [key]: value }),
  22. isPremium: () => {
  23. const user = get().user;
  24. if (user) return user.type > 0;
  25. return false;
  26. },
  27. logout: () => {
  28. altogic.auth.signOut();
  29. toast.success("Logged out.");
  30. useModal.setState({ account: false });
  31. set(initialStates);
  32. },
  33. login: response => {
  34. set({ user: response.user as any, isAuthenticated: true });
  35. },
  36. tokenAuth: async () => {
  37. if (new URLSearchParams(window.location.search).get("access_token")) {
  38. const data = await altogic.auth.getAuthGrant();
  39. if ((data.user as any)?.type > 0) {
  40. location.replace(location.href.replace("://", "://pro."));
  41. } else {
  42. location.pathname = "/editor";
  43. }
  44. }
  45. },
  46. checkSession: async () => {
  47. const currentSession = altogic.auth.getSession();
  48. if (currentSession) {
  49. const dbUser = await altogic.auth.getUserFromDB();
  50. altogic.auth.setSession(currentSession);
  51. set({ user: dbUser.user as any, isAuthenticated: true });
  52. } else {
  53. if (!new URLSearchParams(window.location.search).get("access_token")) return;
  54. const data = await altogic.auth.getAuthGrant();
  55. if (!data.errors?.items.length) {
  56. set({ user: data.user as any, isAuthenticated: true });
  57. }
  58. }
  59. },
  60. }));
  61. export default useUser;