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:
Nils-Johan Gynther
2026-04-17 19:57:08 +02:00
parent 4c0411a7f2
commit ce0cc6fbf0
55 changed files with 1006 additions and 137 deletions
+7
View File
@@ -15,8 +15,13 @@
"dependencies": {
"@nestjs/common": "^10.3.0",
"@nestjs/core": "^10.3.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.0",
"@prisma/client": "6.12.0",
"bcryptjs": "^2.4.3",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"multer": "^1.4.5-lts.2",
@@ -31,9 +36,11 @@
"@nestjs/cli": "^10.3.0",
"@nestjs/schematics": "^10.1.1",
"@nestjs/testing": "^10.3.0",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^4.17.21",
"@types/multer": "^1.4.12",
"@types/node": "^22.15.29",
"@types/passport-jwt": "^4.0.1",
"@types/pdf-parse": "^1.1.5",
"@types/uuid": "^10.0.0",
"prisma": "6.12.0",
@@ -0,0 +1,55 @@
-- CreateTable: User
CREATE TABLE `User` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`username` VARCHAR(191) NOT NULL,
`email` VARCHAR(191) NOT NULL,
`passwordHash` VARCHAR(191) NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updatedAt` DATETIME(3) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `User_username_key` (`username`),
UNIQUE INDEX `User_email_key` (`email`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable: UserProduct
CREATE TABLE `UserProduct` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`userId` INTEGER NOT NULL,
`productId` INTEGER NOT NULL,
`note` TEXT NULL,
`preferredBrand` VARCHAR(191) NULL,
`preferredStore` VARCHAR(191) NULL,
`isPrivate` BOOLEAN NOT NULL DEFAULT false,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updatedAt` DATETIME(3) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UserProduct_userId_productId_key` (`userId`, `productId`),
INDEX `UserProduct_userId_idx` (`userId`),
INDEX `UserProduct_productId_idx` (`productId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable: RecipeShare
CREATE TABLE `RecipeShare` (
`recipeId` INTEGER NOT NULL,
`userId` INTEGER NOT NULL,
PRIMARY KEY (`recipeId`, `userId`),
INDEX `RecipeShare_userId_idx` (`userId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AlterTable: Product add ownerId
ALTER TABLE `Product` ADD COLUMN `ownerId` INTEGER NULL;
-- AlterTable: Recipe add ownerId and isPublic
ALTER TABLE `Recipe` ADD COLUMN `ownerId` INTEGER NULL,
ADD COLUMN `isPublic` BOOLEAN NOT NULL DEFAULT false;
-- Make all existing recipes (without owner) public
UPDATE `Recipe` SET `isPublic` = true WHERE `ownerId` IS NULL;
-- AddForeignKey
ALTER TABLE `UserProduct` ADD CONSTRAINT `UserProduct_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `UserProduct` ADD CONSTRAINT `UserProduct_productId_fkey` FOREIGN KEY (`productId`) REFERENCES `Product`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `RecipeShare` ADD CONSTRAINT `RecipeShare_recipeId_fkey` FOREIGN KEY (`recipeId`) REFERENCES `Recipe`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `RecipeShare` ADD CONSTRAINT `RecipeShare_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `Product` ADD CONSTRAINT `Product_ownerId_fkey` FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE `Recipe` ADD CONSTRAINT `Recipe_ownerId_fkey` FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
+50 -1
View File
@@ -7,6 +7,19 @@ datasource db {
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
username String @unique
email String @unique
passwordHash String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userProducts UserProduct[]
ownedRecipes Recipe[] @relation("RecipeOwner")
sharedRecipes RecipeShare[]
}
model Product {
id Int @id @default(autoincrement())
name String
@@ -26,6 +39,28 @@ model Product {
receiptAliases ReceiptAlias[]
tags ProductTag[]
nutrition Nutrition?
ownerId Int?
owner User? @relation(fields: [ownerId], references: [id], onDelete: SetNull)
userProducts UserProduct[]
}
model UserProduct {
id Int @id @default(autoincrement())
userId Int
productId Int
note String? @db.Text
preferredBrand String?
preferredStore String?
isPrivate Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
@@unique([userId, productId])
@@index([userId])
@@index([productId])
}
model InventoryItem {
@@ -73,11 +108,25 @@ model Recipe {
instructions String? @db.Text
imageUrl String?
servings Int?
isPublic Boolean @default(false)
ownerId Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
ingredients RecipeIngredient[]
owner User? @relation("RecipeOwner", fields: [ownerId], references: [id], onDelete: SetNull)
ingredients RecipeIngredient[]
mealPlanEntries MealPlanEntry[]
shares RecipeShare[]
}
model RecipeShare {
recipeId Int
userId Int
recipe Recipe @relation(fields: [recipeId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([recipeId, userId])
@@index([userId])
}
model RecipeIngredient {
+14
View File
@@ -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 {}
+23
View File
@@ -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);
}
}
+22
View File
@@ -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 {}
+51
View File
@@ -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);
+9
View File
@@ -0,0 +1,9 @@
import { IsString } from 'class-validator';
export class LoginDto {
@IsString()
username: string;
@IsString()
password: string;
}
+13
View File
@@ -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;
}
+20
View File
@@ -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);
}
}
+18
View File
@@ -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 };
}
}
+2
View File
@@ -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 })
+21 -10
View File
@@ -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')
+38 -8
View File
@@ -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 } },
});
}
}
+10
View File
@@ -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 {}
+19
View File
@@ -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 });
}
}