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
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ version: '3.8'
services:
api:
container_name: ionicapp_api
restart: unless-stopped
depends_on:
- postgres
build:
Expand All @@ -22,6 +23,7 @@ services:

postgres:
container_name: ionicapp_postgres
restart: unless-stopped
build:
dockerfile: docker/postgres/Dockerfile
environment:
Expand All @@ -48,6 +50,7 @@ services:

redis:
container_name: ionicapp_redis
restart: unless-stopped
image: redis:alpine
ports:
- ${REDIS_PORT}:6379
Expand Down
2 changes: 1 addition & 1 deletion src/dto/id-number.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ export class IdNumberDto {
@IsPositive()
@Expose()
@ApiProperty({ example: 1 })
id: number;
id!: number;
}
8 changes: 4 additions & 4 deletions src/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,26 @@ export class User {
unique: true,
generated: 'uuid',
})
id: string;
id!: string;

@Column({
type: 'varchar',
length: 255,
nullable: false,
})
password: string;
password!: string;

@Column({
type: 'varchar',
length: 255,
nullable: false,
})
name: string;
name!: string;

@Column({
type: 'varchar',
length: 255,
nullable: false,
})
email: string;
email!: string;
}
7 changes: 7 additions & 0 deletions src/helpers/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,10 @@ export const encodePassword = async (passwordRaw: string): Promise<string> => {
const salt = await bcrypt.genSalt(Number(b));
return await bcrypt.hash(passwordRaw, salt);
};

export const checkPassword = async (
password: string,
hashedPassword: string,
): Promise<boolean> => {
return bcrypt.compare(password, hashedPassword);
};
3 changes: 2 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ async function bootstrap(): Promise<void> {
const corsOrigins = configService.get<string>('SITE_ORIGIN');
const corsOriginsArray = corsOrigins?.split(',').filter(Boolean) ?? [];

app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe(validationPipeConfig));

app.enableShutdownHooks();
Expand All @@ -33,7 +34,7 @@ async function bootstrap(): Promise<void> {
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('api/docs', app, document, {
SwaggerModule.setup('docs', app, document, {
swaggerOptions: { persistAuthorization: true },
});
}
Expand Down
32 changes: 12 additions & 20 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
AccessForbiddenException,
AccessTokenGenerationException,
} from '../../exceptions/access-exceptions';
import { checkPassword } from '../../helpers/system';

@Injectable()
export class AuthService {
Expand All @@ -27,33 +28,24 @@ export class AuthService {
return this.jwtService.signAsync(payload, options);
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
async validateUser(email: string, _password: string): Promise<User> {
async validateUser(email: string, password: string): Promise<User> {
const user: User | null = await this.usersRepository.findOneBy({
email,
});

if (!user) {
throw new AccessForbiddenException('Invalid login or password');
}

// use mocked (simplified) auth - allow all users regardles of password
// TODO: remove this after real auth implementation

// const passwordIsValid = await this.hashService.compareHashed(
// password,
// user.password,
// );
// if (!passwordIsValid) {
// throw new AccessForbiddenException('Invalid login or password');
// }
const passwordIsValid = await checkPassword(password, user.password);
if (!passwordIsValid) {
throw new AccessForbiddenException('Invalid login or password');
}

return user;
}

async signin(payloadUser: JwtUserPayloadDto): Promise<ResponseTokenDto> {
const dbUser: User | null = await this.usersRepository.findOneBy({
id: payloadUser._id,
id: payloadUser.id,
});

if (!dbUser) {
Expand All @@ -67,11 +59,11 @@ export class AuthService {
userPayload: JwtUserPayloadDto,
): Promise<ResponseTokenDto> {
const accessToken = await this.generateAccessToken({
sub: userPayload._id,
sub: userPayload.id,
});

const refreshToken = await this.generateRefreshToken({
sub: userPayload._id,
sub: userPayload.id,
});

return { accessToken, refreshToken };
Expand Down Expand Up @@ -112,21 +104,21 @@ export class AuthService {
expiresIn,
});
} catch (e) {
throw new AccessTokenGenerationException(e.message);
throw new AccessTokenGenerationException((e as Error)?.message);
}
}

async refresh(payloadUser: JwtUserPayloadDto): Promise<ResponseTokenDto> {
const dbUser: User | null = await this.usersRepository.findOneBy({
id: payloadUser._id,
id: payloadUser.id,
});

if (!dbUser) {
throw new AccessForbiddenException('access denied');
}

const updatedPayload: JwtUserPayloadDto = {
_id: String(dbUser.id),
id: String(dbUser.id),
};

return this.generateTokens(updatedPayload);
Expand Down
4 changes: 2 additions & 2 deletions src/modules/auth/dto/auth.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { IsString } from 'class-validator';
export class AuthDto {
@ApiProperty({ example: 'admin@test.com' })
@IsString()
email: string;
email!: string;

@ApiProperty({ example: 'asdfasdf' })
@IsString()
password: string;
password!: string;
}
2 changes: 1 addition & 1 deletion src/modules/auth/dto/jwt-user-payload.dto.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export class JwtUserPayloadDto {
_id: string;
id!: string;
}
4 changes: 2 additions & 2 deletions src/modules/auth/dto/response-token.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ export class ResponseTokenDto {
@ApiProperty()
@IsString()
@Expose()
accessToken: string;
accessToken!: string;

@ApiProperty()
@IsString()
@Expose()
refreshToken: string;
refreshToken!: string;
}
2 changes: 1 addition & 1 deletion src/modules/auth/strategy/jwt-refresh.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ export class JwtRefreshStrategy extends PassportStrategy(
}

validate(req: Request, payload: JwtPayload): JwtUserPayloadDto {
return { _id: payload.sub };
return { id: payload.sub };
}
}
2 changes: 1 addition & 1 deletion src/modules/auth/strategy/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
}

validate(payload: JwtPayload): JwtUserPayloadDto {
return { _id: payload.sub };
return { id: payload.sub };
}
}
9 changes: 5 additions & 4 deletions src/modules/auth/strategy/local.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { Injectable } from '@nestjs/common';

import { AuthService } from '../auth.service';
import { JwtUserPayloadDto } from '../dto/jwt-user-payload.dto';
import { User } from '../../../entities/user.entity';
import { AccessUnauthorizedException } from '../../../exceptions/access-exceptions';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
Expand All @@ -20,13 +21,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
try {
user = await this.authService.validateUser(email, password);
} catch (e) {
throw new UnauthorizedException(e.message);
throw new AccessUnauthorizedException((e as Error)?.message);
}

if (!user) {
throw new UnauthorizedException();
throw new AccessUnauthorizedException();
}

return { _id: String(user.id) };
return { id: String(user.id) };
}
}
8 changes: 4 additions & 4 deletions src/modules/users/dto/user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@ import { IsEmail, IsString, IsUUID, MaxLength } from 'class-validator';
export class UserDto {
@ApiProperty({ example: '123e4567-e89b-12d3-a456-426614174000' })
@IsUUID()
id: string;
id!: string;

@ApiProperty({ example: 'hashedPassword123' })
@IsString()
@MaxLength(255, { message: 'Password too long. Maximum is 255 symbols.' })
password: string;
password!: string;

@ApiProperty({ example: 'Max' })
@IsString()
@MaxLength(255, { message: 'Name too long. Maximum is 255 symbols.' })
name: string;
name!: string;

@ApiProperty({ example: 'someemail@test.com' })
@IsEmail()
@MaxLength(255, { message: 'Email too long. Maximum is 255 symbols.' })
email: string;
email!: string;
}
6 changes: 3 additions & 3 deletions src/modules/users/responses/user.response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { Exclude, Expose } from 'class-transformer';
export class UserResponse {
@Expose()
@ApiProperty({ example: '123e4567-e89b-12d3-a456-426614174000' })
id: string;
id!: string;

@Expose()
@ApiProperty({ example: 'Max' })
name: string;
name!: string;

@Expose()
@ApiProperty({ example: 'someemail@test.com' })
email: string;
email!: string;
}
4 changes: 2 additions & 2 deletions src/responses/typed-list.response.factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ export function TypedListResponseFactory<T>(ListClass: Constructor<T>) {
class TypedList implements IListResponse<T> {
@Expose()
@ApiProperty({ example: 1 })
total: number;
total!: number;

@Expose()
@Type(() => ListClass)
@ApiProperty({ type: ListClass, isArray: true })
data: T[];
data!: T[];
}
return TypedList;
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
"noFallthroughCasesInSwitch": false,
"strict": true
},
"exclude": [
"node_modules",
Expand Down
Loading