diff --git a/src/backend/auth.api.ts b/src/backend/auth.api.ts index 7a3e45f..ee87e54 100644 --- a/src/backend/auth.api.ts +++ b/src/backend/auth.api.ts @@ -143,18 +143,20 @@ const getUserByUserId = async (userId: string) => { }; const login = async (email: string, password: string) => { + // Delete current session, if any try { - await account.deleteSessions(); - const response = await account.createEmailPasswordSession(email, password); - - if (!response) { + await account.deleteSession("current"); + } catch (error: any) { + if (error?.type !== "general_unauthorized_scope") { throw new Error("Login failed"); } + } - const accountId: string = response && response.userId; - + try { + const session = await account.createEmailPasswordSession(email, password); + const { userId: accountId, expire } = session; const user = await getUserByAccountId(accountId); - return user; + return { user, expires: new Date(expire) }; } catch (error: any) { console.log(error); throw new Error(error.message); diff --git a/src/components/pages/auth/login/index.tsx b/src/components/pages/auth/login/index.tsx index be87e6c..e9078af 100644 --- a/src/components/pages/auth/login/index.tsx +++ b/src/components/pages/auth/login/index.tsx @@ -64,7 +64,7 @@ export default function LoginComponent() { throw new Error("password format not matched"); } - const resp = await login(data.email, data.password); + const { user: resp, expires } = await login(data.email, data.password); if (resp && resp.email === data.email) { const payload: userCollectionDB = { @@ -78,9 +78,9 @@ export default function LoginComponent() { $updatedAt: resp.$updatedAt, }; - setCookie(null, "accountId", payload?.accountId); - setCookie(null, "isVerified", String(payload?.isVerified)); - setCookie(null, "userId", payload?.$id); + setCookie(null, "accountId", payload?.accountId, { expires }); + setCookie(null, "isVerified", String(payload?.isVerified), { expires }); + setCookie(null, "userId", payload?.$id, { expires }); dispatch(saveUserToStore(payload)); toastify("Login Successful", "success");