Skip to content

Commit

Permalink
lint and format
Browse files Browse the repository at this point in the history
  • Loading branch information
ruslanguns committed Aug 31, 2020
1 parent 2a5d428 commit 80c8758
Show file tree
Hide file tree
Showing 29 changed files with 189 additions and 211 deletions.
14 changes: 10 additions & 4 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config'
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AccessControlModule } from 'nest-access-control';

Expand All @@ -8,7 +8,13 @@ import { AppService } from './app.service';
import { PostModule } from './post/post.module';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import { DATABASE_HOST, DATABASE_PORT, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME } from './config/constants';
import {
DATABASE_HOST,
DATABASE_PORT,
DATABASE_USERNAME,
DATABASE_PASSWORD,
DATABASE_NAME,
} from './config/constants';
import { roles } from './app.roles';

@Module({
Expand All @@ -27,11 +33,11 @@ import { roles } from './app.roles';
synchronize: true,
logging: true,
logger: 'file',
})
}),
}),
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env'
envFilePath: '.env',
}),
AccessControlModule.forRoles(roles),
AuthModule,
Expand Down
9 changes: 4 additions & 5 deletions src/app.roles.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { RolesBuilder } from "nest-access-control";
import { RolesBuilder } from 'nest-access-control';

export enum AppRoles {
AUTHOR = 'AUTHOR',
ADMIN = 'ADMIN'
ADMIN = 'ADMIN',
}

export enum AppResource {
USER = 'USER',
POST = 'POST'
POST = 'POST',
}

export const roles: RolesBuilder = new RolesBuilder();
Expand All @@ -25,5 +25,4 @@ roles
.extend(AppRoles.AUTHOR)
.createAny([AppResource.USER])
.updateAny([AppResource.POST, AppResource.USER])
.deleteAny([AppResource.POST, AppResource.USER])

.deleteAny([AppResource.POST, AppResource.USER]);
31 changes: 10 additions & 21 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,45 +9,34 @@ import { LoginDto } from './dtos/login.dto';
@ApiTags('Auth routes')
@Controller('auth')
export class AuthController {

constructor(
private readonly authService: AuthService
) {}
constructor(private readonly authService: AuthService) {}

@UseGuards(LocalAuthGuard)
@Post('login')
async login(
@Body() loginDto: LoginDto,
@User() user: UserEntity
) {
async login(@Body() loginDto: LoginDto, @User() user: UserEntity) {
const data = await this.authService.login(user);
return {
message: 'Login exitoso',
data
}
data,
};
}

@Auth()
@Get('profile')
profile(
@User() user: UserEntity
) {
profile(@User() user: UserEntity) {
return {
message: 'Petición correcta',
user
}
user,
};
}

@Auth()
@Get('refresh')
refreshToken(
@User() user: UserEntity
) {
refreshToken(@User() user: UserEntity) {
const data = this.authService.login(user);
return {
message: 'Refresh exitoso',
data
}
data,
};
}

}
10 changes: 5 additions & 5 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';

import { JWT_SECRET } from '../config/constants'
import { JWT_SECRET } from '../config/constants';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UserModule } from 'src/user/user.module';
Expand All @@ -12,16 +12,16 @@ import { LocalStrategy, JwtStrategy } from './strategies';
@Module({
imports: [
PassportModule.register({
defaultStrategy: 'jwt'
defaultStrategy: 'jwt',
}),
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.get<string>(JWT_SECRET),
signOptions: { expiresIn: '60m' }
})
signOptions: { expiresIn: '60m' },
}),
}),
UserModule
UserModule,
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy],
Expand Down
10 changes: 4 additions & 6 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,20 @@ import { User } from 'src/user/entities';

@Injectable()
export class AuthService {

constructor(
private readonly userService: UserService,
private readonly jwtService: JwtService
private readonly jwtService: JwtService,
) {}

async validateUser(email: string, pass: string): Promise<any> {
const user = await this.userService.findOne({ email });

if(user && await compare(pass, user.password)) {
if (user && (await compare(pass, user.password))) {
const { password, ...rest } = user;
return rest;
}

return null;

}

login(user: User) {
Expand All @@ -30,7 +28,7 @@ export class AuthService {

return {
user,
accessToken: this.jwtService.sign(payload)
}
accessToken: this.jwtService.sign(payload),
};
}
}
4 changes: 1 addition & 3 deletions src/auth/dtos/login.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@


export class LoginDto {
email: string;
password: string;
}
}
2 changes: 1 addition & 1 deletion src/auth/guards/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './jwt-auth.guard';
export * from './local-auth.guard';
export * from './local-auth.guard';
8 changes: 3 additions & 5 deletions src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {

handleRequest(err, user, info) {
// You can throw an exception based on either "info" or "err" arguments
if (err || !user) {
throw err || new UnauthorizedException('NO ESTAS AUTHENTICADO');
}
return user;
}
}
}
6 changes: 3 additions & 3 deletions src/auth/guards/local-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AuthGuard } from "@nestjs/passport";
import { Injectable } from "@nestjs/common";
import { AuthGuard } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}
export class LocalAuthGuard extends AuthGuard('local') {}
2 changes: 1 addition & 1 deletion src/auth/strategies/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './local.strategy';
export * from './jwt.strategy';
export * from './jwt.strategy';
7 changes: 2 additions & 5 deletions src/auth/strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ import { JWT_SECRET } from 'src/config/constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private userService: UserService,
private config: ConfigService,
) {
constructor(private userService: UserService, private config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
Expand All @@ -22,4 +19,4 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
const { sub: id } = payload;
return await this.userService.getOne(id);
}
}
}
21 changes: 9 additions & 12 deletions src/auth/strategies/local.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import { Strategy } from "passport-local";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { AuthService } from "../auth.service";

import { Strategy } from 'passport-local';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { AuthService } from '../auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly authService: AuthService
) {
constructor(private readonly authService: AuthService) {
super({
usernameField: 'email', // 'username'
passwordField: 'password' // 'passport'
passwordField: 'password', // 'passport'
});
}

async validate(email: string, password: string) {
const user = await this.authService.validateUser(email, password);
if (!user) throw new UnauthorizedException('Login user or password does not match.');
if (!user)
throw new UnauthorizedException('Login user or password does not match.');
return user;
}

}
}
15 changes: 7 additions & 8 deletions src/common/decorators/auth.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { applyDecorators, UseGuards } from "@nestjs/common";
import { ApiBearerAuth } from "@nestjs/swagger";
import { JwtAuthGuard } from "src/auth/guards";
import { ACGuard, Role, UseRoles } from "nest-access-control";

import { applyDecorators, UseGuards } from '@nestjs/common';
import { ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from 'src/auth/guards';
import { ACGuard, Role, UseRoles } from 'nest-access-control';

export function Auth(...roles: Role[]) {
return applyDecorators(
UseGuards(JwtAuthGuard, ACGuard),
UseRoles(...roles),
ApiBearerAuth()
)
}
ApiBearerAuth(),
);
}
2 changes: 1 addition & 1 deletion src/common/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './user.decorator';
export * from './auth.decorator';
export * from './auth.decorator';
2 changes: 1 addition & 1 deletion src/common/decorators/user.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ export const User = createParamDecorator(

return data ? user && user[data] : user;
},
);
);
2 changes: 1 addition & 1 deletion src/config/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ export const DATABASE_USERNAME = 'DATABASE_USERNAME';
export const DATABASE_PASSWORD = 'DATABASE_PASSWORD';
export const DATABASE_NAME = 'DATABASE_NAME';
export const DEFAULT_USER_EMAIL = 'DEFAULT_USER_EMAIL';
export const DEFAULT_USER_PASSWORD = 'DEFAULT_USER_PASSWORD';
export const DEFAULT_USER_PASSWORD = 'DEFAULT_USER_PASSWORD';
26 changes: 14 additions & 12 deletions src/config/default-user.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import { getRepository } from 'typeorm'
import { ConfigService } from '@nestjs/config'
import { DEFAULT_USER_EMAIL, DEFAULT_USER_PASSWORD } from './constants'
import { User } from 'src/user/entities'
import { getRepository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { DEFAULT_USER_EMAIL, DEFAULT_USER_PASSWORD } from './constants';
import { User } from 'src/user/entities';

export const setDefaultUser = async (config: ConfigService) => {
const userRepository = getRepository<User>(User)
const userRepository = getRepository<User>(User);

const defaultUser = await userRepository
.createQueryBuilder()
.where('email = :email', { email: config.get<string>('DEFAULT_USER_EMAIL') })
.getOne()

.where('email = :email', {
email: config.get<string>('DEFAULT_USER_EMAIL'),
})
.getOne();

if (!defaultUser) {
const adminUser = userRepository.create({
email: config.get<string>(DEFAULT_USER_EMAIL),
password: config.get<string>(DEFAULT_USER_PASSWORD),
roles: ['ADMIN']
})
roles: ['ADMIN'],
});

return await userRepository.save(adminUser)
return await userRepository.save(adminUser);
}
}
};
6 changes: 5 additions & 1 deletion src/post/entities/post.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ export class Post {
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date;

@ManyToOne(_ => User, (user) => user.posts, { eager: true })
@ManyToOne(
() => User,
user => user.posts,
{ eager: true },
)
@JoinColumn({ name: 'author' })
author: User;
}
Loading

0 comments on commit 80c8758

Please sign in to comment.