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
464 changes: 459 additions & 5 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/graphql": "^10.1.7",
"@nestjs/jwt": "^10.0.1",
"@nestjs/mercurius": "^10.1.7",
"@nestjs/mongoose": "^9.2.1",
"@nestjs/passport": "^9.0.0",
"@nestjs/platform-fastify": "^9.2.1",
"@nestjs/terminus": "^9.1.4",
"class-validator": "^0.14.0",
Expand All @@ -31,6 +33,9 @@
"mercurius": "^10.5.1",
"mongoose": "^6.8.2",
"nestjs-pino": "^3.1.1",
"passport": "^0.6.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"pino-http": "^8.3.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0"
Expand All @@ -41,6 +46,8 @@
"@nestjs/testing": "^9.0.0",
"@types/jest": "29.2.5",
"@types/node": "18.11.18",
"@types/passport-jwt": "^3.0.8",
"@types/passport-local": "^1.0.35",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
Expand Down
13 changes: 12 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ import { GraphQLModule } from '@nestjs/graphql';
import { MongooseModule } from '@nestjs/mongoose';
import { MessageModule } from './messages/message.module';
import { CommonModule } from './common/common.module';
import { UsersModule } from './users/users.module';
import { AuthenticationModule } from './authentication/authentication.module';
import { APP_GUARD } from '@nestjs/core';
import { JwtAuthGuard } from './authentication/guards/jwt-auth.guard';

@Module({
imports: [
CommonModule,
AuthenticationModule,
HealthModule,
MessageModule,
LoggerModule.forRoot(),
Expand All @@ -20,8 +25,14 @@ import { CommonModule } from './common/common.module';
graphiql: true,
}),
MongooseModule.forRoot('mongodb://localhost:27017/syslog'),
UsersModule,
],
controllers: [],
providers: [],
providers: [
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
})
export class AppModule {}
32 changes: 32 additions & 0 deletions src/authentication/authentication.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Module } from '@nestjs/common';
import { AuthenticationService } from './authentication.service';
import { UsersModule } from '../users/users.module';
import { LocalStrategy } from './strategies/local.strategy';
import { PassportModule } from '@nestjs/passport';
import { LoginController } from './controllers/login.controller';
import { LocalAuthGuard } from './guards/local-auth.guard';
import { JwtModule } from '@nestjs/jwt';
import { jwtConstants } from './constant';
import { JwtStrategy } from './strategies/jwt.strategy';
import { JwtAuthGuard } from './guards/jwt-auth.guard';

@Module({
controllers: [LoginController],
exports: [AuthenticationService],
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '60s' },
}),
],
providers: [
AuthenticationService,
LocalAuthGuard,
JwtAuthGuard,
LocalStrategy,
JwtStrategy,
],
})
export class AuthenticationModule {}
28 changes: 28 additions & 0 deletions src/authentication/authentication.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthenticationService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}

async validateUser(username: string, pass: string): Promise<any> {
const user = await this.usersService.findOne(username);
if (user && user.password === pass) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { password, ...result } = user;
return result;
}
return null;
}

async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
}
3 changes: 3 additions & 0 deletions src/authentication/constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const jwtConstants = {
secret: 'secretKey',
};
20 changes: 20 additions & 0 deletions src/authentication/controllers/login.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Controller, Request, Post, UseGuards, Get } from '@nestjs/common';
import { LocalAuthGuard } from '../guards/local-auth.guard';
import { AuthenticationService } from '../authentication.service';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';

@Controller()
export class LoginController {
constructor(private authService: AuthenticationService) {}
@UseGuards(LocalAuthGuard)
@Post('auth/login')
async login(@Request() req) {
return this.authService.login(req.user);
}

@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
}
11 changes: 11 additions & 0 deletions src/authentication/guards/gql-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Injectable, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
}
22 changes: 22 additions & 0 deletions src/authentication/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { IS_PUBLIC_KEY } from '../public';

@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);
}
}
5 changes: 5 additions & 0 deletions src/authentication/guards/local-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}
4 changes: 4 additions & 0 deletions src/authentication/public.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
19 changes: 19 additions & 0 deletions src/authentication/strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from '../constant';

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

async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
25 changes: 25 additions & 0 deletions src/authentication/strategies/local.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthenticationService } from '../authentication.service';
import { ModuleRef } from '@nestjs/core';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(
private authService: AuthenticationService,
private moduleRef: ModuleRef,
) {
super({
passReqToCallback: true,
});
}

async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
1 change: 1 addition & 0 deletions src/common/scalars/date.scalar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CustomScalar, Scalar } from '@nestjs/graphql';
import { Kind, ValueNode } from 'graphql';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Scalar('Date', (type) => Date)
export class DateScalar implements CustomScalar<number, Date> {
description = 'Date custom scalar type';
Expand Down
2 changes: 2 additions & 0 deletions src/health/health.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
HealthCheckService,
MemoryHealthIndicator,
} from '@nestjs/terminus';
import { Public } from '../authentication/public';

@Controller('health')
export class HealthController {
Expand All @@ -13,6 +14,7 @@ export class HealthController {
) {}

@Get()
@Public()
@HealthCheck()
check() {
return this.health.check([
Expand Down
9 changes: 9 additions & 0 deletions src/messages/decorators/current-user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';

export const CurrentUser = createParamDecorator(
(data: unknown, context: ExecutionContext) => {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req.user;
},
);
22 changes: 12 additions & 10 deletions src/messages/dto/message.args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,37 @@ import { FACILITY, SEVERITY } from '../schemas/message.schemas';

@ArgsType()
export class MessageArgs {
@Field((type) => Int)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Field((_type) => Int)
@Min(0)
skip = 0;

@Field((type) => Int)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Field((_type) => Int)
@Min(1)
@Max(50)
take = 25;

@Field((type) => Int, {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Field((_type) => Int, {
nullable: true,
})
@Min(0)
@Max(23)
facility?: FACILITY;

@Field((type) => Int, {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Field((_type) => Int, {
nullable: true,
})
@Min(0)
@Max(7)
severity?: SEVERITY;

@Field((type) => [String], {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Field((_type) => [String], {
nullable: true,
})
apps?: string[];

@Field((type) => [String], {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Field((_type) => [String], {
nullable: true,
})
hostnames?: string[];
Expand Down
17 changes: 10 additions & 7 deletions src/messages/message.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { NotFoundException } from '@nestjs/common';
import { Args, Context, Query, Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'mercurius';
import { MessageArgs } from './dto/message.args';
import { Message } from './models/message.model';
import { MessageService } from './message.service';

@Resolver((of) => Message)
import { UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from '../authentication/guards/gql-auth.guard';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Resolver((_of) => Message)
export class MessageResolver {
constructor(private readonly service: MessageService) {}

@Query((returns) => [Message])
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Query((_returns) => [Message])
@UseGuards(GqlAuthGuard)
messages(@Args() args: MessageArgs): Promise<Message[]> {
return this.service.findAll(args);
}

@Subscription((returns) => Message)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Subscription((_returns) => Message)
@UseGuards(GqlAuthGuard)
messagesAdded(@Context('pubsub') pubSub: PubSub) {
return pubSub.subscribe('messagesAdded');
}
Expand Down
8 changes: 8 additions & 0 deletions src/users/users.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';

@Module({
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
21 changes: 21 additions & 0 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
export type User = any;
@Injectable()
export class UsersService {
private readonly users = [
{
userId: 1,
username: 'john',
password: 'changeme',
},
{
userId: 2,
username: 'maria',
password: 'guess',
},
];

async findOne(username: string): Promise<User | undefined> {
return this.users.find((user) => user.username === username);
}
}
Loading