create simpel login
This commit is contained in:
+9
-1
@@ -12,6 +12,9 @@ import { EjeEstrategico } from './entities/ejesEstrategicos.entity';
|
||||
import { LineaProgramatica } from './entities/LineaProgramatica.entity';
|
||||
import { TipoUsuarioEntity } from './entities/tipoUsuario.entity';
|
||||
import { UsuarioEntity } from './entities/usuario.entity';
|
||||
import { UsuarioController } from './usuario/usuario.controller';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import * as process from "node:process";
|
||||
config({ path: '.env' });
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -37,8 +40,13 @@ config({ path: '.env' });
|
||||
UsuarioEntity,
|
||||
],
|
||||
}),
|
||||
JwtModule.register({
|
||||
global: true,
|
||||
secret: process.env.JWT_SECRET,
|
||||
signOptions: { expiresIn: process.env.JWT_EXPIRES },
|
||||
}),
|
||||
],
|
||||
controllers: [AppController],
|
||||
controllers: [AppController, UsuarioController],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -1,4 +1,27 @@
|
||||
import { Controller } from '@nestjs/common';
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDTO } from '../dtos/loginDTO';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {}
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('login')
|
||||
login(@Body() loginDto: LoginDTO): Promise<any> {
|
||||
Logger.log('/auth/loin/', 'requested');
|
||||
if (loginDto) {
|
||||
return this.authService.signIn(loginDto);
|
||||
} else {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
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, {
|
||||
secret: process.env.JWT_SECRET,
|
||||
});
|
||||
// 💡 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;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UsuarioEntity } from '../entities/usuario.entity';
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule, TypeOrmModule.forFeature([UsuarioEntity])],
|
||||
providers: [AuthService, UsersService],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService]
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -1,4 +1,47 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { LoginDTO } from '../dtos/loginDTO';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UsuarioEntity } from "../entities/usuario.entity";
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {}
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private usersService: UsersService,
|
||||
private jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async signIn(loginDto: LoginDTO): Promise<any> {
|
||||
let user: UsuarioEntity;
|
||||
switch (loginDto.tipo_usuario) {
|
||||
case 1:
|
||||
// Administrador
|
||||
break;
|
||||
case 2:
|
||||
// Alumno
|
||||
user = await this.usersService.findStudent(loginDto);
|
||||
break;
|
||||
|
||||
case 3:
|
||||
// Trabajadores académicos o base
|
||||
user = await this.usersService.findWorker(loginDto);
|
||||
default:
|
||||
throw new BadRequestException();
|
||||
break;
|
||||
}
|
||||
|
||||
if (user === null) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
const payload = { id: user.id, userType: user.tipo_usuario_id };
|
||||
|
||||
const access_token = await this.jwtService.signAsync(payload);
|
||||
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { IsDefined, IsNotEmpty, IsNumber, IsString } from "@nestjs/class-validator";
|
||||
|
||||
export class LoginDTO {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@IsDefined()
|
||||
readonly numero_identificacion: string;
|
||||
|
||||
@IsString()
|
||||
readonly rfc: string;
|
||||
|
||||
@IsString()
|
||||
readonly fecha_nacimiento: string;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
readonly tipo_usuario: number;
|
||||
}
|
||||
@@ -18,12 +18,15 @@ export class UsuarioEntity {
|
||||
@Column('text')
|
||||
numero_identificacion: string;
|
||||
|
||||
@Column('date', { nullable: true })
|
||||
fecha_nacimiento: Date;
|
||||
@Column('text')
|
||||
fecha_nacimiento: string;
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
rfc: string;
|
||||
|
||||
@Column({ name: 'tipo_usuario_id' })
|
||||
tipo_usuario_id: number;
|
||||
|
||||
@ManyToOne(() => Carrera, (carrera) => carrera.usuarios, { nullable: true })
|
||||
@JoinColumn({ name: 'carrera_id' })
|
||||
carrera: Carrera;
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersService } from './users.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UsuarioEntity } from '../entities/usuario.entity';
|
||||
import { UsuarioController } from '../usuario/usuario.controller';
|
||||
|
||||
@Module({
|
||||
providers: [UsersService]
|
||||
imports: [TypeOrmModule.forFeature([UsuarioEntity])],
|
||||
providers: [UsersService],
|
||||
controllers: [UsuarioController],
|
||||
})
|
||||
export class UsersModule {}
|
||||
|
||||
@@ -1,7 +1,43 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { UsuarioEntity } from '../entities/usuario.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
import { LoginDTO } from '../dtos/loginDTO';
|
||||
|
||||
export type User = any;
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(
|
||||
@InjectRepository(UsuarioEntity)
|
||||
private usersRepository: Repository<UsuarioEntity>,
|
||||
) {}
|
||||
|
||||
// findAll(): Promise<UsuarioEntity[]> {
|
||||
// return this.usersRepository.find();
|
||||
// }
|
||||
|
||||
findStudent(loginDto: LoginDTO): Promise<UsuarioEntity | null> {
|
||||
const numero_identificacion = loginDto.numero_identificacion;
|
||||
const fecha_nacimiento = loginDto.fecha_nacimiento;
|
||||
return this.usersRepository.findOneBy({
|
||||
numero_identificacion,
|
||||
fecha_nacimiento,
|
||||
});
|
||||
}
|
||||
|
||||
findWorker(loginDto: LoginDTO): Promise<UsuarioEntity | null> {
|
||||
const numero_identificacion = loginDto.numero_identificacion;
|
||||
const rfc = loginDto.rfc;
|
||||
return this.usersRepository.findOneBy({
|
||||
numero_identificacion,
|
||||
rfc,
|
||||
});
|
||||
}
|
||||
|
||||
// findOne(id: number): Promise<UsuarioEntity | null> {
|
||||
// return this.usersRepository.findOneBy({ id });
|
||||
// }
|
||||
//
|
||||
// async remove(id: number): Promise<void> {
|
||||
// await this.usersRepository.delete(id);
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UsuarioController } from './usuario.controller';
|
||||
|
||||
describe('UsuarioController', () => {
|
||||
let controller: UsuarioController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [UsuarioController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UsuarioController>(UsuarioController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import { Controller } from '@nestjs/common';
|
||||
|
||||
@Controller('usuario')
|
||||
export class UsuarioController {}
|
||||
Reference in New Issue
Block a user