feat: authentication
This commit is contained in:
17
server/api/auth/sign-in.post.ts
Normal file
17
server/api/auth/sign-in.post.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { z } from "zod";
|
||||
import { env } from "#server/env";
|
||||
|
||||
const bodySchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readValidatedBody(event, bodySchema.parse);
|
||||
|
||||
if (body.username !== env.ADMIN_USERNAME || body.password !== env.ADMIN_PASSWORD) {
|
||||
throw createError({ statusCode: 401, message: "Invalid credentials" });
|
||||
}
|
||||
|
||||
await setUserSession(event, { user: { username: body.username } });
|
||||
});
|
||||
3
server/api/auth/sign-out.post.ts
Normal file
3
server/api/auth/sign-out.post.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
await clearUserSession(event);
|
||||
});
|
||||
@@ -3,6 +3,8 @@ import { z } from 'zod'
|
||||
|
||||
const schema = z.object({
|
||||
DATABASE_URL: z.string().min(1),
|
||||
ADMIN_USERNAME: z.string().min(1).default("admin"),
|
||||
ADMIN_PASSWORD: z.string().min(1),
|
||||
})
|
||||
|
||||
export const env = schema.parse(process.env)
|
||||
|
||||
7
server/middleware/auth.ts
Normal file
7
server/middleware/auth.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export default defineEventHandler(async (event) => {
|
||||
const path = getRequestURL(event).pathname;
|
||||
|
||||
if (path.startsWith("/api/") && !path.startsWith("/api/auth/")) {
|
||||
await requireUserSession(event);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user