42 lines
1.2 KiB
C#
42 lines
1.2 KiB
C#
using Apimanager_backend.Data;
|
|
using Apimanager_backend.Dtos;
|
|
using Apimanager_backend.Exceptions;
|
|
using Apimanager_backend.Models;
|
|
using AutoMapper;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Apimanager_backend.Services
|
|
{
|
|
public class AuthService:IAuthService
|
|
{
|
|
private readonly ApiContext apiContext;
|
|
private readonly IMapper mapper;
|
|
public AuthService(ApiContext apiContext, IMapper automapper)
|
|
{
|
|
this.apiContext = apiContext;
|
|
this.mapper = automapper;
|
|
}
|
|
public async Task<UserInfoDto> LoginAsync(string username, string password)
|
|
{
|
|
//查找用户
|
|
User? user = await apiContext.Users.Include(x => x.Roles).SingleOrDefaultAsync(x =>
|
|
x.Username == username && x.PassHash == password
|
|
);
|
|
|
|
//用户不存在或密码错误都为登录失败
|
|
if (user == null)
|
|
{
|
|
throw new BaseException(2001, "Invalid username or password");
|
|
}
|
|
|
|
//用户被禁用
|
|
if (user.IsBan)
|
|
{
|
|
throw new BaseException(2002, "User account is disabled");
|
|
}
|
|
|
|
return mapper.Map<UserInfoDto>(user);
|
|
}
|
|
}
|
|
}
|