permission system and no access redirect

This commit is contained in:
Julian Krauser 2024-08-26 13:46:54 +02:00
parent 214f0ddf21
commit cb80771f7a
8 changed files with 107 additions and 18 deletions

View file

@ -3,25 +3,33 @@ import { useAuthStore } from "@/stores/auth";
import { useAccountStore } from "@/stores/account";
import { jwtDecode, type JwtPayload } from "jwt-decode";
import { refreshToken } from "../serverCom";
import type { PermissionObject } from "../types/permissionTypes";
type Payload = JwtPayload & { userId: number; username: string; firstname: string; lastname: string; mail: string };
export type Payload = JwtPayload & {
userId: number;
username: string;
firstname: string;
lastname: string;
mail: string;
permissions: PermissionObject;
};
export async function isAuthenticated(to: any, from: any, next: any) {
const auth = useAuthStore();
NProgress.start();
if (auth.authCheck && localStorage.getItem("access_token")) {
if (auth.authCheck && localStorage.getItem("access_token") && localStorage.getItem("refresh_token")) {
NProgress.done();
next();
return;
}
await isAuthenticatedPromise()
.then(async (result: any) => {
.then(async (result: Payload) => {
NProgress.done();
next();
})
.catch((err: Error) => {
.catch((err: string) => {
NProgress.done();
next({ name: "login" });
next({ name: err ?? "login" });
});
}
@ -33,29 +41,38 @@ export async function isAuthenticatedPromise(): Promise<Payload> {
try {
decoded = jwtDecode<Payload>(localStorage.getItem("accessToken") ?? "");
} catch (error) {
reject("failed");
auth.setFailed();
reject("login");
}
auth.setSuccess();
if (typeof decoded == "string" || !decoded) {
reject("failed");
auth.setFailed();
reject("login");
} else {
// check jwt expiry
const exp = decoded.exp ?? 0;
const localTimezoneOffset = new Date().getTimezoneOffset();
const correctedLocalTime = new Date().getTime() + localTimezoneOffset * 60000;
const correctedLocalTime = new Date().getTime();
if (exp < Math.floor(correctedLocalTime / 1000)) {
await refreshToken()
.then(() => {
console.log("fetched new token");
})
.catch(() => {
reject("expired");
.catch((err: string) => {
console.log("expired");
auth.setFailed();
reject(err);
});
}
var { firstname, lastname, mail, username } = decoded;
account.setAccountData(firstname, lastname, mail, username);
var { firstname, lastname, mail, username, permissions } = decoded;
if (Object.keys(permissions).length === 0) {
auth.setFailed();
reject("nopermissions");
}
auth.setSuccess();
account.setAccountData(firstname, lastname, mail, username, permissions);
resolve(decoded);
}
});

View file

@ -42,6 +42,11 @@ const router = createRouter({
component: () => import("../views/admin/View.vue"),
beforeEnter: [isAuthenticated],
},
{
path: "/nopermissions",
name: "nopermissions",
component: () => import("../views/NoPermission.vue"),
},
{
path: "/:pathMatch(.*)*",
name: "404",