mirror of
https://github.com/Litlyx/litlyx
synced 2025-12-10 07:48:37 +01:00
71 lines
1.9 KiB
TypeScript
71 lines
1.9 KiB
TypeScript
|
|
import { readUserJwt } from "../AuthManager";
|
|
import { UserModel } from "@schema/UserSchema";
|
|
import { ADMIN_EMAILS } from '@data/ADMINS';
|
|
|
|
import type { H3Event, EventHandlerRequest } from 'h3';
|
|
|
|
export type AuthContextLogged = {
|
|
id: string,
|
|
logged: true,
|
|
user: {
|
|
email: string,
|
|
name: string,
|
|
roles: string[],
|
|
picture?: string,
|
|
}
|
|
}
|
|
|
|
export type AuthContext = { logged: false } | AuthContextLogged;
|
|
|
|
|
|
|
|
async function authorizationMiddleware(event: H3Event<EventHandlerRequest>) {
|
|
const authorization = event.headers.get('Authorization');
|
|
|
|
if (!authorization) {
|
|
event.context.auth = { logged: false, }
|
|
} else {
|
|
|
|
const [type, token] = authorization.split(' ');
|
|
const valid = readUserJwt(token);
|
|
|
|
if (!valid) return event.context.auth = { logged: false }
|
|
|
|
const user = await UserModel.findOne({ email: valid.email })
|
|
|
|
if (!user) return event.context.auth = { logged: false };
|
|
|
|
const premium: any = null;//await PremiumModel.findOne({ user_id: user.id });
|
|
|
|
const roles: string[] = [];
|
|
|
|
if (premium && premium.ends_at.getTime() < Date.now()) {
|
|
// await PremiumModel.deleteOne({ user_id: user.id });
|
|
} else if (premium) {
|
|
roles.push('PREMIUM');
|
|
roles.push('PREMIUM_' + premium.type);
|
|
}
|
|
|
|
if (ADMIN_EMAILS.includes(user.email)) {
|
|
roles.push('ADMIN');
|
|
}
|
|
|
|
const authContext: AuthContext = {
|
|
logged: true,
|
|
user: {
|
|
email: user.email,
|
|
name: user.name,
|
|
picture: user.picture || `https://robohash.org/${user.email}?set=set4`,
|
|
roles
|
|
},
|
|
id: user._id.toString()
|
|
}
|
|
event.context.auth = authContext;
|
|
|
|
}
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
await authorizationMiddleware(event);
|
|
}) |