X-Git-Url: http://these/git/?a=blobdiff_plain;f=src%2Fshared%2Fservices%2FUserService.ts;h=0724f400f3128e267ee869d54c9f3b78cc4145db;hb=7eddc52c1302a1f0d7189576ace44957d6b42d2a;hp=18d0804a96a1a849a7803dff6a92c9b5e7da8fe6;hpb=79bdb7e8e890031cca0f53ba7e9de4878e97a955;p=lemmy-ui.git diff --git a/src/shared/services/UserService.ts b/src/shared/services/UserService.ts index 18d0804..0724f40 100644 --- a/src/shared/services/UserService.ts +++ b/src/shared/services/UserService.ts @@ -1,11 +1,10 @@ -// import Cookies from 'js-cookie'; -import IsomorphicCookie from "isomorphic-cookie"; +import { isAuthPath } from "@utils/app"; +import { clearAuthCookie, isBrowser, setAuthCookie } from "@utils/browser"; +import * as cookie from "cookie"; import jwt_decode from "jwt-decode"; import { LoginResponse, MyUserInfo } from "lemmy-js-client"; -import { isHttps } from "../env"; -import { i18n } from "../i18next"; -import { isAuthPath, toast } from "../utils"; -import isBrowser from "../utils/browser/is-browser"; +import { toast } from "../toast"; +import { I18NextService } from "./I18NextService"; interface Claims { sub: number; @@ -30,9 +29,10 @@ export class UserService { public login(res: LoginResponse) { const expires = new Date(); expires.setDate(expires.getDate() + 365); - if (res.jwt) { - toast(i18n.t("logged_in")); - IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps() }); + + if (isBrowser() && res.jwt) { + toast(I18NextService.i18n.t("logged_in")); + setAuthCookie(res.jwt); this.#setJwtInfo(); } } @@ -40,8 +40,11 @@ export class UserService { public logout() { this.jwtInfo = undefined; this.myUserInfo = undefined; - IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason - document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.hostname; + + if (isBrowser()) { + clearAuthCookie(); + } + if (isAuthPath(location.pathname)) { location.replace("/"); } else { @@ -51,24 +54,29 @@ export class UserService { public auth(throwErr = false): string | undefined { const jwt = this.jwtInfo?.jwt; + if (jwt) { return jwt; } else { const msg = "No JWT cookie found"; + if (throwErr && isBrowser()) { console.error(msg); - toast(i18n.t("not_logged_in"), "danger"); + toast(I18NextService.i18n.t("not_logged_in"), "danger"); } + return undefined; // throw msg; } } #setJwtInfo() { - const jwt: string | undefined = IsomorphicCookie.load("jwt"); + if (isBrowser()) { + const { jwt } = cookie.parse(document.cookie); - if (jwt) { - this.jwtInfo = { jwt, claims: jwt_decode(jwt) }; + if (jwt) { + this.jwtInfo = { jwt, claims: jwt_decode(jwt) }; + } } }