-// 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";
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();
}
}
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 {
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;
}
#setJwtInfo() {
if (isBrowser()) {
const { jwt } = cookie.parse(document.cookie);
+
if (jwt) {
this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
}
import canShare from "./can-share";
+import clearAuthCookie from "./clear-auth-cookie";
import dataBsTheme from "./data-bs-theme";
import isBrowser from "./is-browser";
import isDark from "./is-dark";
import loadCss from "./load-css";
import restoreScrollPosition from "./restore-scroll-position";
import saveScrollPosition from "./save-scroll-position";
+import setAuthCookie from "./set-auth-cookie";
import share from "./share";
export {
canShare,
+ clearAuthCookie,
dataBsTheme,
isBrowser,
isDark,
loadCss,
restoreScrollPosition,
saveScrollPosition,
+ setAuthCookie,
share,
};
--- /dev/null
+import { isHttps } from "@utils/env";
+import * as cookie from "cookie";
+import { authCookieName } from "../../config";
+
+export default function setAuthCookie(jwt: string) {
+ document.cookie = cookie.serialize(authCookieName, jwt, {
+ maxAge: 365 * 24 * 60 * 60 * 1000,
+ secure: isHttps(),
+ sameSite: true,
+ path: "/",
+ });
+}