Merge branch 'dev_add_auth_1029' of http://192.168.5.200:8081/ql/apismnagaer_backend into dev_add_auth_1029

This commit is contained in:
南浔 2024-11-04 09:34:58 +08:00
commit 44c82129a4
8 changed files with 124 additions and 79 deletions

View File

@ -13,6 +13,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.0" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />

View File

@ -1,6 +1,8 @@
using Apimanager_backend.Services;
using Apimanager_backend.Dtos;
using Apimanager_backend.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using StackExchange.Redis;
using System.ComponentModel;
using System.Runtime.CompilerServices;
@ -29,6 +31,7 @@ namespace Apimanager_backend.Config
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//jwt参数
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
@ -39,11 +42,45 @@ namespace Apimanager_backend.Config
ValidAudience = jwtSettings["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
//添加自定义响应处理函数
options.Events = new JwtBearerEvents
{
OnChallenge = new Func<JwtBearerChallengeContext, Task>(JwtTokenErrorEventFunc),
OnForbidden = new Func<ForbiddenContext, Task>(JwtPermissionEventFunc)
};
});
//redis配置
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(configuration["Redis:ConnectionString"]));
return services;
}
/// <summary>
/// token无效事件处理函数
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async static Task JwtTokenErrorEventFunc(JwtBearerChallengeContext context)
{
context.Response.ContentType = "application/json";
var res = new ResponseBase<object?>(
code: 1002,
message: "用户未登录或认证失败",
data: null
);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync(JsonConvert.SerializeObject(res));
context.HandleResponse();
}
public async static Task JwtPermissionEventFunc(ForbiddenContext context)
{
context.Response.ContentType = "application/json";
var res = new ResponseBase<object?>(
code: 2006,
message: "用户无权限进行该操作",
data: null
);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync(JsonConvert.SerializeObject(res));
}
}
}

View File

@ -100,31 +100,31 @@ namespace Apimanager_backend.Controllers
if (isUsernameExist)
{
var errorRes = new ResponseBase<UserInfoDto?>(
code:2003,
message:"用户名已存在",
data:null
code: 2003,
message: "用户名已存在",
data: null
);
return StatusCode(409,errorRes);
return StatusCode(409, errorRes);
}
try
{
var userInfo = await authService.RegisterAsync(requestDto);
var res = new ResponseBase<UserInfoDto?>(
code:1000,
message:"Success",
data:userInfo
code: 1000,
message: "Success",
data: userInfo
);
return Ok(res);
}catch(BaseException e)
}
catch (BaseException e)
{
var res = new ResponseBase<UserInfoDto?>(
code:e.code,
message:e.message,
code: e.code,
message: e.message,
data: null
);
return StatusCode(500,res);
return StatusCode(500, res);
}
}
/// <summary>
/// 发送邮箱校验码

View File

@ -4,6 +4,9 @@ using Apimanager_backend.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Apimanager_backend.Filters;
using Microsoft.AspNetCore.Authorization;
using Apimanager_backend.Models;
using System.Security.Claims;
namespace Apimanager_backend.Controllers
{
@ -16,6 +19,18 @@ namespace Apimanager_backend.Controllers
{
this.userService = userService;
}
[HttpGet]
[Authorize(Roles = "User")]
public async Task<ActionResult<ResponseBase<UserInfoDto>>> UserInfo()
{
var userId = User.Claims.First(x => x.Type == "userId").Value;
var userInfo = await userService.GetUserAsync(int.Parse(userId));
var res = new ResponseBase<UserInfoDto>(
code:1000,
message:"Success",
data:userInfo
);
return Ok(res);
}
}
}

View File

@ -1,6 +1,10 @@
namespace Apimanager_backend.Dtos
using System.ComponentModel.DataAnnotations;
namespace Apimanager_backend.Dtos
{
public class UpdateUserDto
{
public int? userId { get; set; }
public string? password { get; set; }
}
}

View File

@ -0,0 +1,40 @@
using Apimanager_backend.Dtos;
namespace Apimanager_backend.Services
{
public interface IAdminService
{
/// <summary>
/// 禁用用户,使其无法登录。
/// </summary>
/// <param name="userId">要禁用的用户ID</param>
/// <returns>异步操作</returns>
Task BanUserAsync(int userId);
/// <summary>
/// 取消禁用用户,恢复登录权限。
/// </summary>
/// <param name="userId">要取消禁用的用户ID</param>
/// <returns>异步操作</returns>
Task UnbanUserAsync(int userId);
/// <summary>
/// 获取分页的用户列表。
/// </summary>
/// <param name="page">要获取的页码从1开始</param>
/// <param name="pageSize">每页的用户数量</param>
/// <param name="desc">是否按降序排序</param>
/// <returns>包含用户信息的 <see cref="List{UserInfoDto}"/></returns>
Task<List<UserInfoDto>> GetUsersAsync(int page, int pageSize, bool desc);
/// <summary>
/// 创建新用户。
/// </summary>
/// <param name="user">包含新用户信息的 <see cref="CreateUserDto"/></param>
/// <returns>创建成功的用户信息 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> CreateUserAsync(CreateUserDto user);
/// <summary>
/// 删除指定的用户。
/// </summary>
/// <param name="userId">用户ID</param>
/// <returns>异步操作</returns>
Task DeleteUserAsync(int userId);
}
}

View File

@ -35,43 +35,6 @@ namespace Apimanager_backend.Services
/// <param name="user">包含更新信息的 <see cref="UpdateUserDto"/></param>
/// <returns>更新后的 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> UpdateUserAsync(UpdateUserDto user);
/// <summary>
/// 删除指定的用户。
/// </summary>
/// <param name="username">要删除的用户名</param>
/// <returns>异步操作</returns>
Task DeleteUserAsync(string username);
/// <summary>
/// 创建新用户。
/// </summary>
/// <param name="user">包含新用户信息的 <see cref="CreateUserDto"/></param>
/// <returns>创建成功的用户信息 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> CreateUserAsync(CreateUserDto user);
/// <summary>
/// 禁用用户,使其无法登录。
/// </summary>
/// <param name="username">要禁用的用户名</param>
/// <returns>异步操作</returns>
Task BanUserAsync(string username);
/// <summary>
/// 取消禁用用户,恢复登录权限。
/// </summary>
/// <param name="username">要取消禁用的用户名</param>
/// <returns>异步操作</returns>
Task UnbanUserAsync(string username);
/// <summary>
/// 获取分页的用户列表。
/// </summary>
/// <param name="page">要获取的页码从1开始</param>
/// <param name="pageSize">每页的用户数量</param>
/// <param name="desc">是否按降序排序</param>
/// <returns>包含用户信息的 <see cref="List{UserInfoDto}"/></returns>
Task<List<UserInfoDto>> GetUsersAsync(int page, int pageSize, bool desc);
/// <summary>
/// 检测用户名是否被使用
/// </summary>

View File

@ -19,21 +19,6 @@ namespace Apimanager_backend.Services
this.apiContext = apiContext;
this.mapper = automapper;
}
public Task BanUserAsync(string username)
{
throw new NotImplementedException();
}
public Task<UserInfoDto> CreateUserAsync(CreateUserDto user)
{
throw new NotImplementedException();
}
public Task DeleteUserAsync(string username)
{
throw new NotImplementedException();
}
public async Task<UserInfoDto> GetUserAsync(int userId)
{
User? user = await apiContext.Users.SingleOrDefaultAsync(x => x.Id == userId);
@ -45,11 +30,6 @@ namespace Apimanager_backend.Services
return mapper.Map<UserInfoDto>(user);
}
public Task<List<UserInfoDto>> GetUsersAsync(int page, int pageSize, bool desc)
{
throw new NotImplementedException();
}
public async Task<bool> IsEmailExist(string email)
{
return await apiContext.Users.AnyAsync(x => x.Email == email);
@ -70,14 +50,19 @@ namespace Apimanager_backend.Services
throw new NotImplementedException();
}
public Task UnbanUserAsync(string username)
{
throw new NotImplementedException();
}
public Task<UserInfoDto> UpdateUserAsync(UpdateUserDto user)
public async Task<UserInfoDto> UpdateUserAsync(UpdateUserDto dto)
{
throw new NotImplementedException();
var user = await apiContext.Users.FirstOrDefaultAsync(x => x.Id == dto.userId);
if (user == null)
{
throw new BaseException(2004, "用户不存在");
}
user.PassHash = dto.password == null ? user.PassHash : dto.password;
apiContext.Users.Update(user);
await apiContext.SaveChangesAsync();
return mapper.Map<UserInfoDto>(user);
}
}
}