X-Git-Url: http://these/git/?a=blobdiff_plain;f=src%2Fshared%2Fservices%2FUserService.ts;h=0724f400f3128e267ee869d54c9f3b78cc4145db;hb=7eddc52c1302a1f0d7189576ace44957d6b42d2a;hp=3757e2369604da65cb19c9cbe2a3b3f087059cdf;hpb=28dc62d44c4959482e7fb5c248d3ca64f8f103d8;p=lemmy-ui.git diff --git a/src/shared/services/UserService.ts b/src/shared/services/UserService.ts index 3757e23..0724f40 100644 --- a/src/shared/services/UserService.ts +++ b/src/shared/services/UserService.ts @@ -1,7 +1,5 @@ -// import Cookies from 'js-cookie'; import { isAuthPath } from "@utils/app"; -import { isBrowser } from "@utils/browser"; -import { isHttps } from "@utils/env"; +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"; @@ -31,15 +29,10 @@ export class UserService { public login(res: LoginResponse) { const expires = new Date(); expires.setDate(expires.getDate() + 365); + if (isBrowser() && res.jwt) { toast(I18NextService.i18n.t("logged_in")); - document.cookie = cookie.serialize("jwt", res.jwt, { - expires, - secure: isHttps(), - domain: location.hostname, - sameSite: true, - path: "/", - }); + setAuthCookie(res.jwt); this.#setJwtInfo(); } } @@ -47,14 +40,11 @@ export class UserService { public logout() { this.jwtInfo = undefined; this.myUserInfo = undefined; + if (isBrowser()) { - document.cookie = cookie.serialize("jwt", "", { - maxAge: 0, - path: "/", - domain: location.hostname, - sameSite: true, - }); + clearAuthCookie(); } + if (isAuthPath(location.pathname)) { location.replace("/"); } else { @@ -64,14 +54,17 @@ 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(I18NextService.i18n.t("not_logged_in"), "danger"); } + return undefined; // throw msg; } @@ -80,6 +73,7 @@ export class UserService { #setJwtInfo() { if (isBrowser()) { const { jwt } = cookie.parse(document.cookie); + if (jwt) { this.jwtInfo = { jwt, claims: jwt_decode(jwt) }; }