add jwt
This commit is contained in:
+16
-2
@@ -3,13 +3,27 @@ import { UserService } from './user.service';
|
||||
import { UserController } from './user.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
|
||||
@Module({
|
||||
imports:[
|
||||
imports: [
|
||||
JwtModule.registerAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: async (configService: ConfigService) => {
|
||||
return {
|
||||
global: true,
|
||||
secret: configService.get('JWT_SECRET'),
|
||||
signOptions: { expiresIn: '1h' },
|
||||
};
|
||||
},
|
||||
|
||||
}),
|
||||
|
||||
TypeOrmModule.forFeature([User])
|
||||
],
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
exports: [UserService],
|
||||
})
|
||||
export class UserModule {}
|
||||
export class UserModule { }
|
||||
|
||||
@@ -1,23 +1,25 @@
|
||||
import { Injectable, Logger, NotFoundException, UnauthorizedException } from '@nestjs/common';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
@InjectRepository(User)
|
||||
private userRepository: Repository<User>,
|
||||
|
||||
private jwtService: JwtService
|
||||
) { }
|
||||
|
||||
async findOneByNameandPassword(data:CreateUserDto): Promise<User> {
|
||||
async findOneByNameandPassword(data: CreateUserDto): Promise<User> {
|
||||
|
||||
const { usuario, password } = data
|
||||
|
||||
const user = await this.userRepository.findOne({
|
||||
where: { usuario,password }
|
||||
where: { usuario, password }
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
@@ -29,10 +31,13 @@ export class UserService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async Login(data: CreateUserDto) {
|
||||
|
||||
async Login(data: CreateUserDto): Promise<{ access_token: string }> {
|
||||
const user = await this.findOneByNameandPassword(data);
|
||||
return user
|
||||
|
||||
const payload = { id: user.id_usuario, usuario: user.usuario };
|
||||
return {
|
||||
access_token: await this.jwtService.signAsync(payload),
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user