diff --git a/src/hooks/auth/useSessionCookie.ts b/src/hooks/auth/useSessionCookie.ts new file mode 100644 index 00000000..0d7ce68d --- /dev/null +++ b/src/hooks/auth/useSessionCookie.ts @@ -0,0 +1,18 @@ +import { useEffect } from 'react'; + +import { autorun } from 'mobx'; + +import { useAuthStore } from '~/store/auth/useAuthStore'; +import { setCookie } from '~/utils/dom/cookie'; + +export const useSessionCookie = () => { + const auth = useAuthStore(); + + useEffect( + () => + autorun(() => { + setCookie('session', auth.token, 30); + }), + [auth] + ); +}; diff --git a/src/utils/dom/cookie.ts b/src/utils/dom/cookie.ts new file mode 100644 index 00000000..4eb29a50 --- /dev/null +++ b/src/utils/dom/cookie.ts @@ -0,0 +1,13 @@ +export const setCookie = (name: string, value: string, days: number) => { + let expires; + + if (days) { + const date = new Date(); + date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); + expires = '; expires=' + date.toISOString(); + } else { + expires = ''; + } + + document.cookie = name + '=' + value + expires + '; path=/'; +}; diff --git a/src/utils/providers/AuthProvider.tsx b/src/utils/providers/AuthProvider.tsx index a2391404..9e325a6b 100644 --- a/src/utils/providers/AuthProvider.tsx +++ b/src/utils/providers/AuthProvider.tsx @@ -6,6 +6,7 @@ import { EMPTY_USER } from '~/constants/auth'; import { useAuth } from '~/hooks/auth/useAuth'; import { useMessageEventReactions } from '~/hooks/auth/useMessageEventReactions'; import { useRestorePasswordRedirect } from '~/hooks/auth/useRestorePasswordRedirect'; +import { useSessionCookie } from '~/hooks/auth/useSessionCookie'; interface AuthProviderContextType extends ReturnType {} @@ -24,6 +25,7 @@ export const AuthProvider: FC = observer(({ children }) => { useMessageEventReactions(); useRestorePasswordRedirect(); + useSessionCookie(); return {children}; });