mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-05 18:48:41 +00:00
feat(auth): add JWT user parsing from token
This commit is contained in:
@@ -18,3 +18,12 @@ export interface User {
|
||||
export interface AuthUser extends User {
|
||||
totpEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface JWTUser {
|
||||
uuid: string;
|
||||
username: string;
|
||||
displayname: string;
|
||||
totpEnabled: boolean;
|
||||
roles: number;
|
||||
isBanned: boolean;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { browser } from '$app/environment';
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import { user } from '$lib/stores/user';
|
||||
import type { JWTUser } from '$lib/types/user';
|
||||
|
||||
export const roles = {
|
||||
User: 1,
|
||||
@@ -146,6 +147,22 @@ export function clearServerTokens(cookies: Cookies) {
|
||||
cookies.delete('refreshToken', { path: '/' });
|
||||
}
|
||||
|
||||
export function getUserFromToken(token: string): JWTUser | null {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
return {
|
||||
uuid: payload.uuid,
|
||||
username: payload.username,
|
||||
displayname: payload.displayname,
|
||||
totpEnabled: payload.totp_enabled === 'True',
|
||||
roles: typeof payload.roles === 'string' ? parseInt(payload.roles, 10) : payload.roles,
|
||||
isBanned: payload.is_banned === 'True'
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const hasRole = (userRoles: number, role: number) => (userRoles & role) !== 0;
|
||||
|
||||
export const getUserRoles = (userRoles: number): Role[] =>
|
||||
|
||||
Reference in New Issue
Block a user