mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 20:13:49 +00:00
Implement login, add useUser hook
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import { NextApiResponse } from 'next';
|
||||
import { NextHandler } from 'next-connect';
|
||||
import findUserById from '@/services/user/findUserById';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import { getLoginSession } from '../session';
|
||||
import { ExtendedNextApiRequest } from '../types';
|
||||
|
||||
@@ -10,7 +12,12 @@ const getCurrentUser = async (
|
||||
next: NextHandler,
|
||||
) => {
|
||||
const session = await getLoginSession(req);
|
||||
const user = { id: session.id, username: session.username };
|
||||
const user = await findUserById(session?.id);
|
||||
|
||||
if (!user) {
|
||||
throw new ServerError('Could not get user.', 401);
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
};
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { NextApiResponse } from 'next';
|
||||
import Iron from '@hapi/iron';
|
||||
import { SessionRequest, UserInfoSchema, UserSessionSchema } from '@/config/auth/types';
|
||||
import {
|
||||
SessionRequest,
|
||||
BasicUserInfoSchema,
|
||||
UserSessionSchema,
|
||||
} from '@/config/auth/types';
|
||||
import { z } from 'zod';
|
||||
import { MAX_AGE, setTokenCookie, getTokenCookie } from './cookie';
|
||||
import ServerError from '../util/ServerError';
|
||||
@@ -9,7 +13,7 @@ const { TOKEN_SECRET } = process.env;
|
||||
|
||||
export async function setLoginSession(
|
||||
res: NextApiResponse,
|
||||
session: z.infer<typeof UserInfoSchema>,
|
||||
session: z.infer<typeof BasicUserInfoSchema>,
|
||||
) {
|
||||
if (!TOKEN_SECRET) {
|
||||
throw new ServerError('Authentication is not configured.', 500);
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import GetUserSchema from '@/services/user/schema/GetUserSchema';
|
||||
import { IncomingMessage } from 'http';
|
||||
import { NextApiRequest } from 'next';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const UserInfoSchema = z.object({
|
||||
export const BasicUserInfoSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
username: z.string(),
|
||||
});
|
||||
|
||||
export const UserSessionSchema = UserInfoSchema.merge(
|
||||
export const UserSessionSchema = BasicUserInfoSchema.merge(
|
||||
z.object({
|
||||
createdAt: z.number(),
|
||||
maxAge: z.number(),
|
||||
@@ -15,7 +16,7 @@ export const UserSessionSchema = UserInfoSchema.merge(
|
||||
);
|
||||
|
||||
export interface ExtendedNextApiRequest extends NextApiRequest {
|
||||
user?: z.infer<typeof UserInfoSchema>;
|
||||
user?: z.infer<typeof GetUserSchema>;
|
||||
}
|
||||
|
||||
export type SessionRequest = IncomingMessage & {
|
||||
|
||||
Reference in New Issue
Block a user