Basic account and session system
Provide a basic account system with login and server side session store identified by a cookie. Upon successful login a signed session cookie is set by the server with the session stored on the server identifying which account it is logged in as. The client uses a shared useFetch on the session endpoint to identify if it's logged in and which account it is logged in as, and refreshes this when loggin in or out.
This commit is contained in:
parent
abdcc83eb9
commit
150cb82f5c
11 changed files with 276 additions and 4 deletions
18
server/api/auth/login.post.ts
Normal file
18
server/api/auth/login.post.ts
Normal file
|
@ -0,0 +1,18 @@
|
|||
import { readAccounts } from "~/server/database";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const { name } = await readBody(event);
|
||||
|
||||
if (!name) {
|
||||
return new Response(undefined, { status: 400 })
|
||||
}
|
||||
|
||||
const accounts = await readAccounts();
|
||||
const account = accounts.find(a => a.name === name);
|
||||
|
||||
if (!account) {
|
||||
return new Response(undefined, { status: 403 })
|
||||
}
|
||||
|
||||
await setAccountSession(event, account.id);
|
||||
})
|
3
server/api/auth/session.delete.ts
Normal file
3
server/api/auth/session.delete.ts
Normal file
|
@ -0,0 +1,3 @@
|
|||
export default defineEventHandler(async (event) => {
|
||||
await clearAccountSession(event);
|
||||
})
|
14
server/api/auth/session.get.ts
Normal file
14
server/api/auth/session.get.ts
Normal file
|
@ -0,0 +1,14 @@
|
|||
import { readAccounts } from "~/server/database";
|
||||
import { AccountSession } from "~/shared/types/account";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = await getAccountSession(event);
|
||||
if (!session)
|
||||
return;
|
||||
const accounts = await readAccounts();
|
||||
|
||||
return {
|
||||
id: session.id,
|
||||
account: accounts.find(account => account.id === session.accountId)!,
|
||||
} satisfies AccountSession;
|
||||
})
|
Loading…
Add table
Add a link
Reference in a new issue