增加auth/login接口,遇到Error: data and hash arguments required错误,后来发现其实是没传password参数导致;)

This commit is contained in:
Jeremy Yin 2019-07-02 23:23:07 +08:00
parent f8977de53d
commit b5dc92070f
5 changed files with 37 additions and 2 deletions

View File

@ -1,9 +1,16 @@
import { Controller } from '@nestjs/common';
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './login.dto';
@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
) { }
@Post('login')
async login(@Body() data: LoginDto) {
return await this.authService.login(data)
}
}

View File

@ -1,9 +1,28 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { LoginDto } from './login.dto';
@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
) {}
async login(data: LoginDto) {
const { username, password } = data
const entity = await this.userService.findByUserName(username)
console.log(entity)
if (!entity) {
throw new UnauthorizedException('用户不存在')
}
const match = await entity.comparePassword(password)
console.log(match)
if (!match) {
throw new UnauthorizedException('密码错误')
}
return entity
}
}

View File

@ -0,0 +1,4 @@
export class LoginDto {
readonly username: string;
readonly password: string;
}

View File

@ -27,6 +27,7 @@ export class User {
}
async comparePassword(password: string) {
console.log(password, this.password)
return await bcrypt.compare(password, this.password);
}
}

View File

@ -43,4 +43,8 @@ export class UserService {
entity.password = newPassword
return await this.userRepository.save(entity)
}
async findByUserName(username: string) {
return await this.userRepository.findOne({ username })
}
}