Skip to content

Commit

Permalink
Merge branch 'main' into feature/17-add-pagination-support
Browse files Browse the repository at this point in the history
  • Loading branch information
pem00 committed Aug 11, 2024
2 parents f062c33 + b4f5ff3 commit c4c3234
Show file tree
Hide file tree
Showing 49 changed files with 2,065 additions and 955 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"configurations": [
{
"name": "Debug backend",
"cwd": "${workspaceFolder}\\apps\\backend",
"cwd": "${workspaceFolder}/apps/backend",
"runtimeArgs": ["run", "start:debug"],
"runtimeExecutable": "yarn",
"request": "launch",
Expand Down
7 changes: 7 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Contributing

This application is being developed internally in our organization so the issues will be assigned to our members. If you're not a member but really want to help, look for issues with the 'help wanted' label. If we need outside help, we'll open an issue with that tag and describe our problem there.

If you have a bug report or a feature request for the website, please open an issue and describe the feature/bug as thouroghly as possible.

Thank you!
4 changes: 4 additions & 0 deletions apps/backend/.env.example
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/mydb?schema=public"
AUTHSCH_CLIENT_ID="<generate at auth.sch.bme.hu>"
AUTHSCH_CLIENT_SECRET="<generate at auth.sch.bme.hu>"
JWT_SECRET="very secret value"
FRONTEND_URL="http://localhost:3000"
6 changes: 6 additions & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,19 @@
"test:cov": "jest --coverage"
},
"dependencies": {
"@kir-dev/passport-authsch": "^1.0.0",
"@nestjs/cli": "^10.3.2",
"@nestjs/common": "^10.3.8",
"@nestjs/config": "^3.2.2",
"@nestjs/core": "^10.3.8",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "*",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.8",
"@prisma/client": "^5.13.0",
"nestjs-prisma": "^0.23.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rimraf": "^5.0.5",
"rxjs": "^7.8.1"
Expand All @@ -37,6 +42,7 @@
"@types/express": "^4.17.21",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.7",
"@types/passport-strategy": "^0.2.38",
"@types/supertest": "^6.0.2",
"@typescript-eslint/eslint-plugin": "^7.7.1",
"@typescript-eslint/parser": "^7.7.1",
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
-- CreateEnum
CREATE TYPE "DrinkType" AS ENUM ('BEER', 'WINE', 'SPIRIT', 'COCKTAIL');

-- CreateEnum
CREATE TYPE "Gender" AS ENUM ('Male', 'Female');

-- CreateTable
CREATE TABLE "User" (
"authSchId" TEXT NOT NULL,
"email" TEXT NOT NULL,
"email" TEXT,
"firstName" TEXT NOT NULL,
"lastName" TEXT NOT NULL,
"gender" "Gender",
"weight" DOUBLE PRECISION,
"isAdmin" BOOLEAN NOT NULL DEFAULT false,
"profilePictureUrl" TEXT,

CONSTRAINT "User_pkey" PRIMARY KEY ("authSchId")
Expand All @@ -25,15 +31,6 @@ CREATE TABLE "Drink" (
CONSTRAINT "Drink_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "FavouriteDrink" (
"drinkId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"order" INTEGER NOT NULL,

CONSTRAINT "FavouriteDrink_pkey" PRIMARY KEY ("drinkId","userId")
);

-- CreateTable
CREATE TABLE "Event" (
"id" TEXT NOT NULL,
Expand All @@ -56,18 +53,26 @@ CREATE TABLE "DrinkAction" (
"drinkId" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"hasEffect" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "DrinkAction_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "_DrinkToUser" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- AddForeignKey
ALTER TABLE "FavouriteDrink" ADD CONSTRAINT "FavouriteDrink_drinkId_fkey" FOREIGN KEY ("drinkId") REFERENCES "Drink"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- CreateIndex
CREATE UNIQUE INDEX "_DrinkToUser_AB_unique" ON "_DrinkToUser"("A", "B");

-- AddForeignKey
ALTER TABLE "FavouriteDrink" ADD CONSTRAINT "FavouriteDrink_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("authSchId") ON DELETE RESTRICT ON UPDATE CASCADE;
-- CreateIndex
CREATE INDEX "_DrinkToUser_B_index" ON "_DrinkToUser"("B");

-- AddForeignKey
ALTER TABLE "Event" ADD CONSTRAINT "Event_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("authSchId") ON DELETE RESTRICT ON UPDATE CASCADE;
Expand All @@ -80,3 +85,9 @@ ALTER TABLE "DrinkAction" ADD CONSTRAINT "DrinkAction_eventId_fkey" FOREIGN KEY

-- AddForeignKey
ALTER TABLE "DrinkAction" ADD CONSTRAINT "DrinkAction_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("authSchId") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_DrinkToUser" ADD CONSTRAINT "_DrinkToUser_A_fkey" FOREIGN KEY ("A") REFERENCES "Drink"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_DrinkToUser" ADD CONSTRAINT "_DrinkToUser_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("authSchId") ON DELETE CASCADE ON UPDATE CASCADE;
35 changes: 23 additions & 12 deletions apps/backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
provider = "prisma-client-js"
previewFeatures = ["omitApi"]
}

datasource db {
Expand All @@ -20,14 +21,22 @@ enum DrinkType {
COCKTAIL
}

enum Gender {
Male
Female
}

model User {
authSchId String @id
email String @unique
authSchId String @id
email String? @unique
firstName String
lastName String
gender Gender?
weight Float?
isAdmin Boolean @default(false)
profilePictureUrl String?
// ownedEvents Event[]
// drinkActions DrinkAction[]
ownedEvents Event[]
drinkActions DrinkAction[]
favouriteDrinks Drink[]
}

Expand All @@ -46,8 +55,8 @@ model Drink {

model Event {
id String @id @default(uuid())
// ownerId String
// owner User @relation(fields: [ownerId], references: [authSchId])
ownerId String
owner User @relation(fields: [ownerId], references: [authSchId])
name String
location String
startDate DateTime
Expand All @@ -59,13 +68,15 @@ model Event {
}

model DrinkAction {
id String @id @default(uuid())
id String @id @default(uuid())
price Int
milliliter Int
drinkId String
drink Drink @relation(fields: [drinkId], references: [id])
drink Drink @relation(fields: [drinkId], references: [id])
eventId String
event Event @relation(fields: [eventId], references: [id])
// userId String
// user User @relation(fields: [userId], references: [authSchId])
event Event @relation(fields: [eventId], references: [id])
userId String
user User @relation(fields: [userId], references: [authSchId])
hasEffect Boolean @default(true)
createdAt DateTime @default(now())
}
4 changes: 4 additions & 0 deletions apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { PrismaModule } from 'nestjs-prisma';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { DrinkActionsModule } from './drink-action/drink-action.module';
import { DrinksModule } from './drinks/drinks.module';
import { EventsModule } from './events/events.module';
import { UsersModule } from './users/users.module';
Expand All @@ -15,6 +17,8 @@ import { UsersModule } from './users/users.module';
UsersModule,
EventsModule,
DrinksModule,
DrinkActionsModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
Expand Down
33 changes: 33 additions & 0 deletions apps/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { CurrentUser } from '@kir-dev/passport-authsch';
import { Controller, Get, Redirect, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { User } from 'src/users/entities/user.entity';

import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
/**
* Redirects to the authsch login page
*/
@UseGuards(AuthGuard('authsch'))
@Get('login')
login() {
// never called
}

/**
* Endpoint for authsch to call after login
* Redirects to the frontend with the jwt token
*/
@Get('callback')
@UseGuards(AuthGuard('authsch'))
@Redirect()
oauthRedirect(@CurrentUser() user: User) {
const jwt = this.authService.login(user);
return {
url: `${process.env.FRONTEND_URL}?jwt=${jwt}`,
};
}
}
15 changes: 15 additions & 0 deletions apps/backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
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 { AuthSchStrategy } from './authsch.strategy';
import { JwtStrategy } from './jwt.strategy';

@Module({
controllers: [AuthController],
providers: [AuthService, AuthSchStrategy, JwtStrategy],
imports: [PassportModule, JwtModule],
})
export class AuthModule {}
33 changes: 33 additions & 0 deletions apps/backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { AuthSchProfile } from '@kir-dev/passport-authsch';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from 'nestjs-prisma';
import { User } from 'src/users/entities/user.entity';

@Injectable()
export class AuthService {
constructor(
private prisma: PrismaService,
private jwtService: JwtService
) {}

async findOrCreateUser(userProfile: AuthSchProfile): Promise<User> {
const user = await this.prisma.user.findUnique({ where: { authSchId: userProfile.authSchId } });
if (user) return user;
return await this.prisma.user.create({
data: {
authSchId: userProfile.authSchId,
firstName: userProfile.firstName,
lastName: userProfile.lastName,
email: userProfile.email,
},
});
}

login(user: User): string {
return this.jwtService.sign(user, {
secret: process.env.JWT_SECRET,
expiresIn: '7 days',
});
}
}
21 changes: 21 additions & 0 deletions apps/backend/src/auth/authsch.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { AuthSchProfile, AuthSchScope, Strategy } from '@kir-dev/passport-authsch';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { User } from 'src/users/entities/user.entity';

import { AuthService } from './auth.service';

@Injectable()
export class AuthSchStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
clientId: process.env.AUTHSCH_CLIENT_ID,
clientSecret: process.env.AUTHSCH_CLIENT_SECRET,
scopes: [AuthSchScope.BASIC, AuthSchScope.FIRST_NAME, AuthSchScope.LAST_NAME, AuthSchScope.EMAIL],
});
}

async validate(userProfile: AuthSchProfile): Promise<User> {
return await this.authService.findOrCreateUser(userProfile);
}
}
19 changes: 19 additions & 0 deletions apps/backend/src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { User } from 'src/users/entities/user.entity';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
});
}

validate(payload: User): User {
return payload;
}
}
Loading

0 comments on commit c4c3234

Please sign in to comment.