feat(auth): implement user authentication with JWT and NextAuth
- Added user registration and login functionality with JWT authentication. - Created auth controller, service, and module in the backend. - Implemented user model and user products management. - Integrated NextAuth for session management on the frontend. - Added middleware for protecting routes and handling public access. - Updated frontend API routes to include authorization headers. - Enhanced recipe and user product models to support ownership and visibility. - Created registration and login pages in the frontend. - Added necessary types for NextAuth session management.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { ProductsModule } from './products/products.module';
|
||||
@@ -9,6 +10,10 @@ import { PantryModule } from './pantry/pantry.module';
|
||||
import { MealPlanModule } from './meal-plan/meal-plan.module';
|
||||
import { ReceiptImportModule } from './receipt-import/receipt-import.module';
|
||||
import { ReceiptAliasModule } from './receipt-alias/receipt-alias.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
import { UserProductsModule } from './user-products/user-products.module';
|
||||
import { JwtAuthGuard } from './auth/jwt-auth.guard';
|
||||
|
||||
|
||||
@Module({
|
||||
@@ -23,6 +28,15 @@ import { ReceiptAliasModule } from './receipt-alias/receipt-alias.module';
|
||||
MealPlanModule,
|
||||
ReceiptImportModule,
|
||||
ReceiptAliasModule,
|
||||
AuthModule,
|
||||
UsersModule,
|
||||
UserProductsModule,
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: JwtAuthGuard,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { Public } from './decorators/public.decorator';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Public()
|
||||
@Post('register')
|
||||
register(@Body() dto: RegisterDto) {
|
||||
return this.authService.register(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('login')
|
||||
login(@Body() dto: LoginDto) {
|
||||
return this.authService.login(dto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
PassportModule,
|
||||
JwtModule.register({
|
||||
secret: process.env.JWT_SECRET ?? 'changeme',
|
||||
signOptions: { expiresIn: '7d' },
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
Injectable,
|
||||
ConflictException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly usersService: UsersService,
|
||||
private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async register(dto: RegisterDto) {
|
||||
const existing = await this.usersService.findByUsername(dto.username);
|
||||
if (existing) throw new ConflictException('Användarnamnet är redan taget');
|
||||
|
||||
const passwordHash = await bcrypt.hash(dto.password, 12);
|
||||
const user = await this.usersService.create({
|
||||
username: dto.username,
|
||||
email: dto.email,
|
||||
passwordHash,
|
||||
});
|
||||
|
||||
return this.issueToken(user.id, user.username);
|
||||
}
|
||||
|
||||
async login(dto: LoginDto) {
|
||||
const user = await this.usersService.findByUsername(dto.username);
|
||||
if (!user) throw new UnauthorizedException('Felaktigt användarnamn eller lösenord');
|
||||
|
||||
const valid = await bcrypt.compare(dto.password, user.passwordHash);
|
||||
if (!valid) throw new UnauthorizedException('Felaktigt användarnamn eller lösenord');
|
||||
|
||||
return this.issueToken(user.id, user.username);
|
||||
}
|
||||
|
||||
private issueToken(userId: number, username: string) {
|
||||
const payload = { sub: userId, username };
|
||||
return {
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
userId,
|
||||
username,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
return request.user as { userId: number; username: string };
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { IsString } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsString()
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
password: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class RegisterDto {
|
||||
@IsString()
|
||||
username: string;
|
||||
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password: string;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Injectable, ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { IS_PUBLIC_KEY } from './decorators/public.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
constructor(private reflector: Reflector) {
|
||||
super();
|
||||
}
|
||||
|
||||
canActivate(context: ExecutionContext) {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) return true;
|
||||
return super.canActivate(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor() {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: process.env.JWT_SECRET ?? 'changeme',
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: { sub: number; username: string }) {
|
||||
return { userId: payload.sub, username: payload.username };
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { Controller, Get, HttpCode, Res } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { HealthService } from './health.service';
|
||||
import { Public } from '../auth/decorators/public.decorator';
|
||||
|
||||
@Public()
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly healthService: HealthService) {}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsInt,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
@@ -47,6 +48,10 @@ export class CreateRecipeDto {
|
||||
@Min(1)
|
||||
servings?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isPublic?: boolean;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ValidateNested({ each: true })
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, ParseIntPipe, Post, Patch } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, ParseIntPipe, Post, Patch, Request } from '@nestjs/common';
|
||||
import { IsString } from 'class-validator';
|
||||
import { RecipesService } from './recipes.service';
|
||||
import { CreateRecipeDto } from './dto/create-recipe.dto';
|
||||
import { ParseMarkdownDto } from './dto/parse-markdown.dto';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
|
||||
class UpdateImageDto {
|
||||
@IsString()
|
||||
@@ -19,8 +20,8 @@ export class RecipesController {
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.recipesService.findAll();
|
||||
findAll(@CurrentUser() user: { userId: number }) {
|
||||
return this.recipesService.findAll(user.userId);
|
||||
}
|
||||
|
||||
@Get(':id/inventory-preview')
|
||||
@@ -29,27 +30,37 @@ export class RecipesController {
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.recipesService.findOne(id);
|
||||
findOne(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@CurrentUser() user: { userId: number },
|
||||
) {
|
||||
return this.recipesService.findOne(id, user.userId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(@Body() createRecipeDto: CreateRecipeDto) {
|
||||
return this.recipesService.create(createRecipeDto);
|
||||
async create(
|
||||
@Body() createRecipeDto: CreateRecipeDto,
|
||||
@CurrentUser() user: { userId: number },
|
||||
) {
|
||||
return this.recipesService.create(createRecipeDto, user.userId);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
async update(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() createRecipeDto: CreateRecipeDto,
|
||||
@CurrentUser() user: { userId: number },
|
||||
) {
|
||||
return this.recipesService.update(id, createRecipeDto);
|
||||
return this.recipesService.update(id, createRecipeDto, user.userId);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(204)
|
||||
async remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.recipesService.remove(id);
|
||||
async remove(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@CurrentUser() user: { userId: number },
|
||||
) {
|
||||
return this.recipesService.remove(id, user.userId);
|
||||
}
|
||||
|
||||
@Post(':id/image')
|
||||
|
||||
@@ -290,27 +290,45 @@ export class RecipesService {
|
||||
};
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
async findAll(userId: number) {
|
||||
return this.prisma.recipe.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ isPublic: true },
|
||||
{ ownerId: userId },
|
||||
{ shares: { some: { userId } } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
ingredients: {
|
||||
include: {
|
||||
product: { include: { nutrition: true } },
|
||||
},
|
||||
},
|
||||
owner: { select: { id: true, username: true } },
|
||||
shares: { select: { userId: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const recipe = await this.prisma.recipe.findUnique({
|
||||
where: { id },
|
||||
async findOne(id: number, userId: number) {
|
||||
const recipe = await this.prisma.recipe.findFirst({
|
||||
where: {
|
||||
id,
|
||||
OR: [
|
||||
{ isPublic: true },
|
||||
{ ownerId: userId },
|
||||
{ shares: { some: { userId } } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
ingredients: {
|
||||
include: {
|
||||
product: { include: { nutrition: true } },
|
||||
},
|
||||
},
|
||||
owner: { select: { id: true, username: true } },
|
||||
shares: { select: { userId: true } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -321,8 +339,8 @@ export class RecipesService {
|
||||
return recipe;
|
||||
}
|
||||
|
||||
async update(id: number, updateRecipeDto: CreateRecipeDto) {
|
||||
// Verifiera att receptet finns
|
||||
async update(id: number, updateRecipeDto: CreateRecipeDto, userId: number) {
|
||||
// Verifiera att receptet finns och att användaren äger det
|
||||
const existingRecipe = await this.prisma.recipe.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
@@ -331,6 +349,11 @@ export class RecipesService {
|
||||
throw new NotFoundException(`Recipe with id ${id} not found`);
|
||||
}
|
||||
|
||||
// Tillåt uppdatering om användaren är ägare ELLER om receptet är publikt utan ägare
|
||||
if (existingRecipe.ownerId !== null && existingRecipe.ownerId !== userId) {
|
||||
throw new NotFoundException(`Recipe with id ${id} not found`);
|
||||
}
|
||||
|
||||
// Ta bort gamla ingredienser
|
||||
await this.prisma.recipeIngredient.deleteMany({
|
||||
where: { recipeId: id },
|
||||
@@ -344,6 +367,7 @@ export class RecipesService {
|
||||
description: updateRecipeDto.description || null,
|
||||
instructions: updateRecipeDto.instructions || null,
|
||||
servings: updateRecipeDto.servings ?? null,
|
||||
...(updateRecipeDto.isPublic !== undefined && { isPublic: updateRecipeDto.isPublic }),
|
||||
...(updateRecipeDto.imageUrl !== undefined && { imageUrl: updateRecipeDto.imageUrl || null }),
|
||||
ingredients: {
|
||||
create: updateRecipeDto.ingredients.map((ingredient) => ({
|
||||
@@ -366,7 +390,7 @@ export class RecipesService {
|
||||
return recipe;
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
async remove(id: number, userId: number) {
|
||||
const existingRecipe = await this.prisma.recipe.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
@@ -375,6 +399,10 @@ export class RecipesService {
|
||||
throw new NotFoundException(`Recipe with id ${id} not found`);
|
||||
}
|
||||
|
||||
if (existingRecipe.ownerId !== null && existingRecipe.ownerId !== userId) {
|
||||
throw new NotFoundException(`Recipe with id ${id} not found`);
|
||||
}
|
||||
|
||||
await this.prisma.recipeIngredient.deleteMany({ where: { recipeId: id } });
|
||||
await this.prisma.recipe.delete({ where: { id } });
|
||||
}
|
||||
@@ -394,7 +422,7 @@ export class RecipesService {
|
||||
});
|
||||
}
|
||||
|
||||
async create(createRecipeDto: CreateRecipeDto) {
|
||||
async create(createRecipeDto: CreateRecipeDto, userId: number) {
|
||||
// Om imageUrl är en extern URL — ladda ner och optimera
|
||||
let imageUrl: string | null = createRecipeDto.imageUrl || null;
|
||||
if (imageUrl && imageUrl.startsWith('http')) {
|
||||
@@ -413,6 +441,8 @@ export class RecipesService {
|
||||
instructions: createRecipeDto.instructions || null,
|
||||
imageUrl,
|
||||
servings: createRecipeDto.servings ?? null,
|
||||
ownerId: userId,
|
||||
isPublic: false,
|
||||
ingredients: {
|
||||
create: createRecipeDto.ingredients.map((ingredient) => ({
|
||||
productId: ingredient.productId,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IsInt, IsString, IsOptional, IsBoolean } from 'class-validator';
|
||||
|
||||
export class UpsertUserProductDto {
|
||||
@IsInt()
|
||||
productId: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
note?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
preferredBrand?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
preferredStore?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isPrivate?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { UserProductsService } from './user-products.service';
|
||||
import { UpsertUserProductDto } from './dto/upsert-user-product.dto';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
|
||||
@Controller('user-products')
|
||||
export class UserProductsController {
|
||||
constructor(private readonly service: UserProductsService) {}
|
||||
|
||||
@Get()
|
||||
findAll(@CurrentUser() user: { userId: number }) {
|
||||
return this.service.findAll(user.userId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
upsert(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Body() dto: UpsertUserProductDto,
|
||||
) {
|
||||
return this.service.upsert(user.userId, dto);
|
||||
}
|
||||
|
||||
@Delete(':productId')
|
||||
remove(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Param('productId', ParseIntPipe) productId: number,
|
||||
) {
|
||||
return this.service.remove(user.userId, productId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserProductsController } from './user-products.controller';
|
||||
import { UserProductsService } from './user-products.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [UserProductsController],
|
||||
providers: [UserProductsService],
|
||||
})
|
||||
export class UserProductsModule {}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { UpsertUserProductDto } from './dto/upsert-user-product.dto';
|
||||
|
||||
const PRODUCT_INCLUDE = {
|
||||
product: {
|
||||
include: {
|
||||
nutrition: true,
|
||||
tags: { include: { tag: true } },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class UserProductsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
findAll(userId: number) {
|
||||
return this.prisma.userProduct.findMany({
|
||||
where: { userId },
|
||||
include: PRODUCT_INCLUDE,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
findOne(userId: number, productId: number) {
|
||||
return this.prisma.userProduct.findUnique({
|
||||
where: { userId_productId: { userId, productId } },
|
||||
include: PRODUCT_INCLUDE,
|
||||
});
|
||||
}
|
||||
|
||||
upsert(userId: number, dto: UpsertUserProductDto) {
|
||||
const { productId, ...data } = dto;
|
||||
return this.prisma.userProduct.upsert({
|
||||
where: { userId_productId: { userId, productId } },
|
||||
create: { userId, productId, ...data },
|
||||
update: data,
|
||||
include: PRODUCT_INCLUDE,
|
||||
});
|
||||
}
|
||||
|
||||
remove(userId: number, productId: number) {
|
||||
return this.prisma.userProduct.delete({
|
||||
where: { userId_productId: { userId, productId } },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersService } from './users.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
findByUsername(username: string) {
|
||||
return this.prisma.user.findUnique({ where: { username } });
|
||||
}
|
||||
|
||||
findById(id: number) {
|
||||
return this.prisma.user.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
create(data: { username: string; email: string; passwordHash: string }) {
|
||||
return this.prisma.user.create({ data });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user