Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[submit] Parts 1-2 and some of Parts 3-4 of the coding challenge #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ This project aims to create a backend solution for a web application. It consist
## Endpoints

- **Login**: `/api/auth/login`
- **Customers**: `/api/auth/customers`
- **Products**: `/api/auth/products`
- **Customers**: `/api/customers`
- **Products**: `/api/products`

## Impress us

Expand Down
297 changes: 281 additions & 16 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/platform-express": "^10.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1"
},
Expand Down
7 changes: 6 additions & 1 deletion src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { Controller } from '@nestjs/common';
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}

@Get()
getHello() {
return { data: 'hello world' };
}
}
3 changes: 2 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { CustomersModule } from './customers/customers.module';

@Module({
imports: [AuthModule, UsersModule],
imports: [AuthModule, UsersModule, CustomersModule],
controllers: [AppController],
providers: [AppService],
})
Expand Down
8 changes: 5 additions & 3 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';

@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}

@HttpCode(HttpStatus.OK)
@Post('login')
signIn() {
return this.authService.signIn();
async signIn(@Body() { username, password }: LoginDto) {
const { token } = await this.authService.signIn(username, password);
return { token };
}
}
40 changes: 40 additions & 0 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}

try {
const payload = await this.jwtService.verifyAsync(token, {
// TODO: get this from env
secret: 'supersecret',
});

// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}

private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
16 changes: 14 additions & 2 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UsersModule } from 'src/users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { AuthGuard } from './auth.guard';

@Module({
providers: [AuthService],
providers: [AuthService, AuthGuard],
controllers: [AuthController],
exports: [AuthService],
exports: [AuthService, AuthGuard],
imports: [
UsersModule,
JwtModule.register({
global: true,
// TODO: move this to env variables
secret: 'supersecret',
signOptions: { expiresIn: '120s' },
}),
],
})
export class AuthModule {}
8 changes: 7 additions & 1 deletion src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';

describe('AuthService', () => {
let service: AuthService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
providers: [
AuthService,
{ provide: UsersService, useValue: {} },
{ provide: JwtService, useValue: {} },
],
}).compile();

service = module.get<AuthService>(AuthService);
Expand Down
30 changes: 27 additions & 3 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,32 @@
import { Injectable } from '@nestjs/common';
import { HttpException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';

@Injectable()
export class AuthService {
async signIn() {
return;
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}

async signIn(username, password) {
const user = await this.usersService.findOne(username);
if (!user) {
throw new HttpException('User not found', 404);
}

if (password !== user.password) {
throw new HttpException('Wrong password', 401);
}

// valid credentials at this point

// create JWT token with user info
const token = this.jwtService.sign({
userId: user.userId,
username: user.username,
});

return { token };
}
}
10 changes: 10 additions & 0 deletions src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { IsNotEmpty } from 'class-validator';

export class LoginDto {
@IsNotEmpty()
username: string;

// TODO: add more constraints here
@IsNotEmpty()
password: string;
}
21 changes: 21 additions & 0 deletions src/customers/customers.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {
Controller,
Get,
HttpCode,
HttpStatus,
UseGuards,
} from '@nestjs/common';
import { CustomersService } from './customers.service';
import { AuthGuard } from 'src/auth/auth.guard';

@Controller('customers')
@UseGuards(AuthGuard)
export class CustomersController {
constructor(private customersService: CustomersService) {}

@Get()
async getAll() {
const customers = await this.customersService.getAll();
return customers;
}
}
11 changes: 11 additions & 0 deletions src/customers/customers.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { CustomersController } from './customers.controller';
import { CustomersService } from './customers.service';
import { AuthModule } from 'src/auth/auth.module';

@Module({
controllers: [CustomersController],
providers: [CustomersService],
imports: [AuthModule],
})
export class CustomersModule {}
42 changes: 42 additions & 0 deletions src/customers/customers.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '../users/users.service';

// Mock some dependencies before importing CustomersService
jest.mock('../Mocks/customers', () => ({
customers: [
{ customer_id: '1', name: 'Test 1', email: '[email protected]' },
{ customer_id: '2', name: 'Test 2', email: '[email protected]' },
],
}));
import { CustomersService } from './customers.service';

describe('CustomersService', () => {
let service: CustomersService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CustomersService, { provide: UsersService, useValue: {} }],
}).compile();

service = module.get<CustomersService>(CustomersService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});

describe('getAll', () => {
it('should return an array', async () => {
const result = await service.getAll();
expect(result).toBeInstanceOf(Array);
});

it('should return mocked customers', async () => {
const result = await service.getAll();
expect(result).toStrictEqual([
{ customer_id: '1', name: 'Test 1', email: '[email protected]' },
{ customer_id: '2', name: 'Test 2', email: '[email protected]' },
]);
});
});
});
10 changes: 10 additions & 0 deletions src/customers/customers.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Injectable } from '@nestjs/common';
import { customers } from '../Mocks/customers';

@Injectable()
export class CustomersService {
// TODO: add Customer type
async getAll() {
return customers;
}
}
3 changes: 3 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
1 change: 1 addition & 0 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type User = {

@Injectable()
export class UsersService {
// TODO: hash the passwords
private readonly users = [
{
userId: 1,
Expand Down