Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/trigger-auth/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ generator client {

datasource db {
provider = "postgresql"
url = env("AUTH_DATABASE_URL")
url = env("DATABASE_URL")
}

model User {
Expand Down
3 changes: 3 additions & 0 deletions apps/trigger-auth/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@ import { GraphQLModule } from '@nestjs/graphql';
import { PrismaModule } from './prisma/prisma.module';
import { UsersModule } from './users/users.module';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';

@Module({
imports: [
ConfigModule,
PrismaModule,
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
context: ({ req, res }) => ({ req, res }),
autoSchemaFile: true,
}),
UsersModule,
AuthModule,
],
controllers: [],
providers: [],
Expand Down
27 changes: 27 additions & 0 deletions apps/trigger-auth/src/app/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Module } from '@nestjs/common';
import { AuthResolver } from './auth.resolver';
import { JwtModule } from '@nestjs/jwt';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';

@Module({
imports: [
ConfigModule,
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => {
return {
secret: configService.getOrThrow<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.getOrThrow<number>('JWT_EXPIRATION'),
},
};
},
inject: [ConfigService],
}),
UsersModule,
],
providers: [AuthResolver, AuthService],
})
export class AuthModule {}
18 changes: 18 additions & 0 deletions apps/trigger-auth/src/app/auth/auth.resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Args, Context, Mutation, Resolver } from '@nestjs/graphql';
import { User } from '../users/models/user.model';
import { LoginInput } from './dtos/login.input';
import { AuthService } from './auth.service';
import { GqlContext } from '@trigger/nestjs';

@Resolver()
export class AuthResolver {
constructor(private readonly authService: AuthService) {}

@Mutation(() => User)
async login(
@Args('loginInput') loginInput: LoginInput,
@Context() context: GqlContext
) {
return this.authService.login(loginInput, context.res);
}
}
52 changes: 52 additions & 0 deletions apps/trigger-auth/src/app/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Response } from 'express';
import { LoginInput } from './dtos/login.input';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { compare } from 'bcryptjs';
import { ConfigService } from '@nestjs/config';
import { TokenPayload } from './dtos/token-payload.interface';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly configService: ConfigService,
private readonly jwtService: JwtService
) {}

async login(loginInput: LoginInput, response: Response) {
const user = await this.verifyUser(loginInput.email, loginInput.password);
const expires = new Date();
expires.setMilliseconds(
expires.getTime() +
parseInt(this.configService.getOrThrow('JWT_EXPIRATION'), 10)
);
const tokenPayload: TokenPayload = {
userId: user.id,
};
const accessToken = this.jwtService.sign(tokenPayload);

response.cookie('Authentication', accessToken, {
httpOnly: true, // Prevents client-side JS from accessing the cookie & prevents XSS
secure: this.configService.getOrThrow('NODE_ENV') === 'production', // Forces cookie to be sent only over HTTPS & prevents Man-in-the-Middle
expires: expires,
});

return user;
}

private async verifyUser(email: string, password: string) {
try {
const user = await this.usersService.getUser({ email });

const authenticated = await compare(password, user.password);
if (!authenticated)
throw new UnauthorizedException('Invalid credentials');

return user;
} catch (error) {
throw new UnauthorizedException('Invalid credentials');
}
}
}
13 changes: 13 additions & 0 deletions apps/trigger-auth/src/app/auth/dtos/login.input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Field, InputType } from '@nestjs/graphql';
import { IsNotEmpty } from 'class-validator';

@InputType()
export class LoginInput {
@Field()
@IsNotEmpty()
email: string;

@Field()
@IsNotEmpty()
password: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface TokenPayload {
userId: number;
}
1 change: 1 addition & 0 deletions apps/trigger-auth/src/app/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ import { UsersResolver } from './users.resolver';
@Module({
imports: [PrismaModule],
providers: [UsersService, UsersResolver],
exports: [UsersService],
})
export class UsersModule {}
6 changes: 6 additions & 0 deletions apps/trigger-auth/src/app/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,10 @@ export class UsersService {
// Logic to retrieve users
return this.prismaService.user.findMany();
}

async getUser(query: Prisma.UserWhereUniqueInput) {
return this.prismaService.user.findUniqueOrThrow({
where: query,
});
}
}
2 changes: 1 addition & 1 deletion apps/trigger-auth/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async function bootstrap() {
})
);

const port = app.get(ConfigService).getOrThrow('AUTH_PORT');
const port = app.get(ConfigService).getOrThrow('PORT');

await app.listen(port);

Expand Down
6 changes: 6 additions & 0 deletions libs/nestjs/src/lib/graphql/gql-context.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Request, Response } from 'express';

export interface GqlContext {
req: Request;
res: Response;
}
1 change: 1 addition & 0 deletions libs/nestjs/src/lib/graphql/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './abstract.model';
export * from './gql-context.interface';
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^10.0.2",
"@nestjs/graphql": "^13.1.0",
"@nestjs/jwt": "^11.0.0",
"@nestjs/platform-express": "^10.0.2",
"@prisma/client": "6.8.2",
"axios": "^1.6.0",
"bcryptjs": "^3.0.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"express": "^5.1.0",
"graphql": "^16.11.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.0"
Expand All @@ -42,6 +44,7 @@
"@swc/core": "~1.5.7",
"@swc/helpers": "~0.5.11",
"@types/bcryptjs": "^3.0.0",
"@types/express": "^5.0.2",
"@types/jest": "^29.5.12",
"@types/node": "~18.16.9",
"eslint": "^9.8.0",
Expand Down
Loading