重构项目结构,移除Assignment相关功能,优化Submission模块
Some checks failed
TechAct / explore-gitea-actions (push) Failing after 12s
Some checks failed
TechAct / explore-gitea-actions (push) Failing after 12s
This commit is contained in:
164
TechHelper.Server/Services/User/AuthenticationService.cs
Normal file
164
TechHelper.Server/Services/User/AuthenticationService.cs
Normal file
@@ -0,0 +1,164 @@
|
||||
using Entities.Configuration;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Entities.DTO;
|
||||
|
||||
namespace TechHelper.Services.Beta
|
||||
{
|
||||
/// <summary>
|
||||
/// 用户认证服务,实现 JWT 令牌生成、刷新令牌生成、过期令牌解析等功能。
|
||||
/// </summary>
|
||||
public class AuthenticationService : IAuthenticationService
|
||||
{
|
||||
private readonly JwtConfiguration _jwtSettings;
|
||||
private readonly JwtSecurityTokenHandler _jwtHandler;
|
||||
private readonly UserManager<Entities.Contracts.User> _userManager;
|
||||
private readonly IClassService _classService;
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数,注入 JWT 配置、用户管理器和班级服务。
|
||||
/// </summary>
|
||||
public AuthenticationService(IOptions<JwtConfiguration> jwtSettings, UserManager<Entities.Contracts.User> userManager, IClassService classService)
|
||||
{
|
||||
_jwtSettings = jwtSettings.Value;
|
||||
_jwtHandler = new JwtSecurityTokenHandler();
|
||||
_userManager = userManager;
|
||||
_classService = classService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成指定用户的 JWT 访问令牌。
|
||||
/// </summary>
|
||||
/// <param name="user">用户实体</param>
|
||||
/// <returns>JWT 字符串</returns>
|
||||
public async Task<string> GetToken(Entities.Contracts.User user)
|
||||
{
|
||||
var signingCredentials = GetSigningCredentials();
|
||||
var claims = await GetClaims(user);
|
||||
var tokenOptions = GenerateTokenOptions(signingCredentials, claims);
|
||||
return _jwtHandler.WriteToken(tokenOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 JWT 签名凭证。
|
||||
/// </summary>
|
||||
/// <returns>签名凭证</returns>
|
||||
private SigningCredentials GetSigningCredentials()
|
||||
{
|
||||
var key = Encoding.UTF8.GetBytes(_jwtSettings.SecurityKey);
|
||||
var secret = new SymmetricSecurityKey(key);
|
||||
return new SigningCredentials(secret, SecurityAlgorithms.HmacSha256);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取用户的声明信息,包括角色和班级信息。
|
||||
/// </summary>
|
||||
/// <param name="user">用户实体</param>
|
||||
/// <returns>声明集合</returns>
|
||||
private async Task<IEnumerable<Claim>> GetClaims(Entities.Contracts.User user)
|
||||
{
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Email)
|
||||
};
|
||||
|
||||
// 添加用户角色声明
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
foreach (var role in roles)
|
||||
{
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
}
|
||||
|
||||
#region ClassInfo
|
||||
// 添加用户班级信息声明
|
||||
var classInfo = await _classService.GetUserInjoinedClasses(user.Id);
|
||||
if (classInfo.Status)
|
||||
{
|
||||
var classs = classInfo.Result as UserClassDetailInfoDto;
|
||||
if (classs == null) return claims;
|
||||
foreach (var c in classs.UserClassInfos)
|
||||
{
|
||||
claims.Add(new Claim("Grade", c.Grade.ToString()));
|
||||
claims.Add(new Claim("Class", c.Class.ToString()));
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
return claims;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成 JWT 令牌对象。
|
||||
/// </summary>
|
||||
/// <param name="signingCredentials">签名凭证</param>
|
||||
/// <param name="claims">声明集合</param>
|
||||
/// <returns>JWT 令牌对象</returns>
|
||||
private JwtSecurityToken GenerateTokenOptions(SigningCredentials signingCredentials, IEnumerable<Claim> claims)
|
||||
{
|
||||
var tokenOptions = new JwtSecurityToken(
|
||||
issuer: _jwtSettings.ValidIssuer,
|
||||
audience: _jwtSettings.ValidAudience,
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(
|
||||
_jwtSettings.ExpiryInMinutes)),
|
||||
signingCredentials: signingCredentials);
|
||||
|
||||
return tokenOptions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成安全的刷新令牌(Base64 字符串)。
|
||||
/// </summary>
|
||||
/// <returns>刷新令牌</returns>
|
||||
public string GenerateRefreshToken()
|
||||
{
|
||||
var randomNumber = new byte[32];
|
||||
using (var rng = RandomNumberGenerator.Create())
|
||||
{
|
||||
rng.GetBytes(randomNumber);
|
||||
return Convert.ToBase64String(randomNumber);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从过期的 JWT 令牌中获取声明主体(不验证过期时间)。
|
||||
/// </summary>
|
||||
/// <param name="token">过期的 JWT 令牌</param>
|
||||
/// <returns>声明主体</returns>
|
||||
/// <exception cref="SecurityTokenException">令牌无效时抛出</exception>
|
||||
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
|
||||
{
|
||||
var tokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateAudience = true,
|
||||
ValidateIssuer = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(_jwtSettings.SecurityKey)),
|
||||
ValidateLifetime = false, // 不验证过期时间
|
||||
ValidIssuer = _jwtSettings.ValidIssuer,
|
||||
ValidAudience = _jwtSettings.ValidAudience,
|
||||
};
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
SecurityToken securityToken;
|
||||
|
||||
var principal = tokenHandler.ValidateToken(token,
|
||||
tokenValidationParameters, out securityToken);
|
||||
|
||||
var jwtSecurityToken = securityToken as JwtSecurityToken;
|
||||
if (jwtSecurityToken == null ||
|
||||
!jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,
|
||||
StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
throw new SecurityTokenException("Invalid token");
|
||||
}
|
||||
|
||||
return principal;
|
||||
}
|
||||
}
|
||||
}
|
||||
14
TechHelper.Server/Services/User/IAuthenticationService.cs
Normal file
14
TechHelper.Server/Services/User/IAuthenticationService.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using TechHelper.Context;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using System.Security.Claims;
|
||||
using Entities.Contracts;
|
||||
|
||||
namespace TechHelper.Services.Beta
|
||||
{
|
||||
public interface IAuthenticationService
|
||||
{
|
||||
public Task<string> GetToken(Entities.Contracts.User user);
|
||||
public string GenerateRefreshToken();
|
||||
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token);
|
||||
}
|
||||
}
|
||||
20
TechHelper.Server/Services/User/IUserSerivces.cs
Normal file
20
TechHelper.Server/Services/User/IUserSerivces.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using Entities.Contracts;
|
||||
using Entities.DTO;
|
||||
|
||||
namespace TechHelper.Services.Beta
|
||||
{
|
||||
public interface IUserSerivces : IBaseService<UserDto, Guid>
|
||||
{
|
||||
Task<ApiResponse> GetStudentDetailInfo(Guid userId);
|
||||
Task<ApiResponse> RestoreUserRoleInformation(User user);
|
||||
Task<ApiResponse> VerifyUserInformation(Guid userId);
|
||||
/// <summary>
|
||||
/// 注册新用户,并根据角色关联到班级
|
||||
/// </summary>
|
||||
/// <param name="registrationDto">用户注册数据</param>
|
||||
/// <returns>操作结果</returns>
|
||||
Task<ApiResponse> RegisterNewUserAsync(UserForRegistrationDto registrationDto);
|
||||
|
||||
Task<ApiResponse> InitAdminUser(UserForAdmin registrationDto);
|
||||
}
|
||||
}
|
||||
421
TechHelper.Server/Services/User/UserServices.cs
Normal file
421
TechHelper.Server/Services/User/UserServices.cs
Normal file
@@ -0,0 +1,421 @@
|
||||
using AutoMapper;
|
||||
using Entities.Contracts;
|
||||
using Entities.DTO;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using SharedDATA.Api;
|
||||
using TechHelper.Features;
|
||||
|
||||
namespace TechHelper.Services.Beta
|
||||
{
|
||||
/// <summary>
|
||||
/// 用户服务实现类
|
||||
/// 处理用户相关的业务逻辑操作
|
||||
/// </summary>
|
||||
public class UserServices : IUserSerivces
|
||||
{
|
||||
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IClassService _classService;
|
||||
private readonly UserManager<User> _userManager;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly TechHelper.Features.IEmailSender _emailSender;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化用户服务
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">工作单元实例</param>
|
||||
/// <param name="classService">班级服务实例</param>
|
||||
/// <param name="userManager">用户管理实例</param>
|
||||
/// <param name="mapper">对象映射实例</param>
|
||||
/// <param name="emailSender">邮件发送实例</param>
|
||||
public UserServices(IUnitOfWork unitOfWork, IClassService classService, UserManager<User> userManager, IMapper mapper, IEmailSender emailSender)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_classService = classService;
|
||||
_userManager = userManager;
|
||||
_mapper = mapper;
|
||||
_emailSender = emailSender;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加新用户
|
||||
/// </summary>
|
||||
/// <param name="model">用户实体对象</param>
|
||||
/// <returns>操作结果响应</returns>
|
||||
public async Task<ApiResponse> AddAsync(UserDto model)
|
||||
{
|
||||
try
|
||||
{
|
||||
//var user = _mapper.Map<User>(model);
|
||||
//user.UserName = model.Email;
|
||||
//user.EmailConfirmed = true;
|
||||
|
||||
//var result = await _userManager.CreateAsync(user, model.Password ?? "TempPassword123!");
|
||||
|
||||
//if (!result.Succeeded)
|
||||
//{
|
||||
// var errors = result.Errors.Select(e => e.Description).ToList();
|
||||
// return new ApiResponse(false, errors);
|
||||
//}
|
||||
|
||||
return new ApiResponse(true, "用户添加成功");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ApiResponse(false, $"添加用户失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除指定用户
|
||||
/// </summary>
|
||||
/// <param name="id">用户唯一标识符</param>
|
||||
/// <returns>操作结果响应</returns>
|
||||
public async Task<ApiResponse> DeleteAsync(Guid id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user == null)
|
||||
{
|
||||
return new ApiResponse(false, "用户不存在");
|
||||
}
|
||||
|
||||
var result = await _userManager.DeleteAsync(user);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = result.Errors.Select(e => e.Description).ToList();
|
||||
return new ApiResponse(false, errors);
|
||||
}
|
||||
|
||||
return new ApiResponse(true, "用户删除成功");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ApiResponse(false, $"删除用户失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有用户列表
|
||||
/// </summary>
|
||||
/// <param name="query">查询参数对象</param>
|
||||
/// <returns>用户列表响应</returns>
|
||||
public async Task<ApiResponse> GetAllAsync(QueryParameter query)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
var repository = _unitOfWork.GetRepository<User>();
|
||||
|
||||
if (query.Search != null && !string.IsNullOrWhiteSpace(query.Search))
|
||||
{
|
||||
var users = await repository.GetPagedListAsync(
|
||||
predicate: u => u.Email.Contains(query.Search) || u.DisplayName.Contains(query.Search),
|
||||
pageSize: query.PageSize,
|
||||
pageIndex: query.PageIndex
|
||||
);
|
||||
var userDtosFiltered = _mapper.Map<IEnumerable<UserListDto>>(users.Items);
|
||||
return new ApiResponse(true, userDtosFiltered);
|
||||
}
|
||||
else
|
||||
{
|
||||
var users = await repository.GetPagedListAsync(
|
||||
pageSize: query.PageSize,
|
||||
pageIndex: query.PageIndex
|
||||
);
|
||||
var userDtos = _mapper.Map<IEnumerable<UserListDto>>(users.Items);
|
||||
return new ApiResponse(true, userDtos);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ApiResponse($"获取所有用户时发生错误: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定用户信息
|
||||
/// </summary>
|
||||
/// <param name="id">用户唯一标识符</param>
|
||||
/// <returns>用户信息响应</returns>
|
||||
public async Task<ApiResponse> GetAsync(Guid id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user == null)
|
||||
{
|
||||
return new ApiResponse(false, "用户不存在");
|
||||
}
|
||||
|
||||
var userDto = _mapper.Map<UserDto>(user);
|
||||
return new ApiResponse(true, userDto);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ApiResponse(false, $"获取用户信息失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取学生详细信息
|
||||
/// </summary>
|
||||
/// <param name="userId">用户唯一标识符</param>
|
||||
/// <returns>学生详细信息响应</returns>
|
||||
public async Task<ApiResponse> GetStudentDetailInfo(Guid userId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString());
|
||||
if (user == null)
|
||||
{
|
||||
return new ApiResponse(false, "用户不存在");
|
||||
}
|
||||
|
||||
var studentDetail = new
|
||||
{
|
||||
user.Id,
|
||||
user.Email,
|
||||
user.DisplayName,
|
||||
user.PhoneNumber,
|
||||
user.Role,
|
||||
IsEmailConfirmed = user.EmailConfirmed,
|
||||
UserStatus = user.EmailConfirmed ? "Verified" : "Pending Verification"
|
||||
};
|
||||
|
||||
return new ApiResponse(true, studentDetail);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ApiResponse(false, $"获取学生详细信息失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复用户角色信息
|
||||
/// 根据用户所在班级信息恢复用户的角色权限
|
||||
/// </summary>
|
||||
/// <param name="user">用户实体对象</param>
|
||||
/// <returns>操作结果响应</returns>
|
||||
public async Task<ApiResponse> RestoreUserRoleInformation(User user)
|
||||
{
|
||||
var result = await _classService.GetUserClassRole(user.Id);
|
||||
if (result.Status)
|
||||
{
|
||||
var classRole = result.Result as string;
|
||||
if (classRole != null)
|
||||
{
|
||||
if (!await _userManager.IsInRoleAsync(user, classRole))
|
||||
{
|
||||
await _userManager.AddToRoleAsync(user, classRole);
|
||||
|
||||
return ApiResponse.Success();
|
||||
}
|
||||
}
|
||||
}
|
||||
return ApiResponse.Error();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新用户信息
|
||||
/// </summary>
|
||||
/// <param name="model">用户实体对象</param>
|
||||
/// <returns>操作结果响应</returns>
|
||||
public async Task<ApiResponse> UpdateAsync(UserDto model)
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(model.Id.ToString());
|
||||
if (user == null)
|
||||
{
|
||||
return new ApiResponse(false, "用户不存在");
|
||||
}
|
||||
|
||||
user.DisplayName = model.DisplayName;
|
||||
user.PhoneNumber = model.PhoneNumber;
|
||||
|
||||
var result = await _userManager.UpdateAsync(user);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = result.Errors.Select(e => e.Description).ToList();
|
||||
return new ApiResponse(false, errors);
|
||||
}
|
||||
|
||||
return new ApiResponse(true, "用户信息更新成功");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ApiResponse(false, $"更新用户信息失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证用户信息
|
||||
/// </summary>
|
||||
/// <param name="userId">用户唯一标识符</param>
|
||||
/// <returns>验证结果响应</returns>
|
||||
public async Task<ApiResponse> VerifyUserInformation(Guid userId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString());
|
||||
if (user == null)
|
||||
{
|
||||
return new ApiResponse(false, "用户不存在");
|
||||
}
|
||||
|
||||
// 验证邮箱确认状态
|
||||
var isEmailConfirmed = user.EmailConfirmed;
|
||||
|
||||
// 验证用户角色
|
||||
var isInRole = await _userManager.IsInRoleAsync(user, "Student") ||
|
||||
await _userManager.IsInRoleAsync(user, "Teacher");
|
||||
|
||||
var verificationResult = new
|
||||
{
|
||||
UserId = user.Id,
|
||||
Email = user.Email,
|
||||
IsEmailConfirmed = isEmailConfirmed,
|
||||
HasValidRole = isInRole,
|
||||
DisplayName = user.DisplayName,
|
||||
Role = user.Role
|
||||
};
|
||||
|
||||
if (isEmailConfirmed && isInRole)
|
||||
{
|
||||
return new ApiResponse(true, "用户信息验证成功");
|
||||
}
|
||||
else
|
||||
{
|
||||
return new ApiResponse(false, "用户信息验证失败");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ApiResponse(false, $"验证用户信息失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册新用户,并根据角色关联到班级
|
||||
/// </summary>
|
||||
/// <param name="registrationDto">用户注册数据</param>
|
||||
/// <returns>操作结果</returns>
|
||||
public async Task<ApiResponse> RegisterNewUserAsync(UserForRegistrationDto registrationDto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var existingUserByEmail = await _userManager.FindByEmailAsync(registrationDto.Email);
|
||||
if (existingUserByEmail != null)
|
||||
{
|
||||
return new ApiResponse("此电子邮件地址已被注册。");
|
||||
}
|
||||
|
||||
var user = _mapper.Map<User>(registrationDto);
|
||||
|
||||
user.UserName = registrationDto.Email;
|
||||
user.DisplayName = registrationDto.DisplayName;
|
||||
user.Role = registrationDto.Roles;
|
||||
user.EmailConfirmed = false;
|
||||
user.TeachSubjectId = registrationDto.RegisterUserToClassDto.SubjectArea;
|
||||
|
||||
var result = await _userManager.CreateAsync(user, registrationDto.Password);
|
||||
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = result.Errors.Select(e => e.Description).ToList();
|
||||
return new ApiResponse(false, errors);
|
||||
}
|
||||
|
||||
var userResult = await _userManager.FindByEmailAsync(user.Email);
|
||||
if (userResult == null)
|
||||
return ApiResponse.Error("注册失败,请联系管理员。");
|
||||
|
||||
var roleResult = await _userManager.AddToRoleAsync(userResult, registrationDto.Roles.ToString());
|
||||
|
||||
if (!roleResult.Succeeded)
|
||||
{
|
||||
var errors = roleResult.Errors.Select(e => e.Description).ToList();
|
||||
return new ApiResponse(false, errors);
|
||||
}
|
||||
|
||||
registrationDto.RegisterUserToClassDto.UserId = userResult.Id;
|
||||
var classRegisterResult = await _classService.UserRegister(registrationDto.RegisterUserToClassDto);
|
||||
|
||||
if (!classRegisterResult.Status)
|
||||
{
|
||||
if (userResult != null)
|
||||
await _userManager.DeleteAsync(userResult);
|
||||
|
||||
return new ApiResponse(false, classRegisterResult.Message ?? "Class registration failed");
|
||||
}
|
||||
|
||||
return new ApiResponse(true, "操作成功。");
|
||||
|
||||
//var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
|
||||
//var encodedToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(emailConfirmationToken));
|
||||
//var callbackUrl = QueryHelpers.AddQueryString(registrationDto.ClientURI, new Dictionary<string, string>
|
||||
//{
|
||||
// {"token", encodedToken},
|
||||
// {"email", user.Email}
|
||||
//});
|
||||
|
||||
//try
|
||||
//{
|
||||
// await _emailSender.SendEmailAsync(user.Email, "请确认您的邮箱", $"请点击此链接确认您的邮箱: {callbackUrl}");
|
||||
//}
|
||||
//catch (Exception ex)
|
||||
//{
|
||||
// Console.Error.WriteLine($"发送邮箱确认邮件失败: {ex.Message}");
|
||||
//}
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var userResult = await _userManager.FindByEmailAsync(registrationDto.Email);
|
||||
if (userResult != null)
|
||||
await _userManager.DeleteAsync(userResult);
|
||||
return new ApiResponse(false, "注册过程中发生错误");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ApiResponse> InitAdminUser(UserForAdmin admin)
|
||||
{
|
||||
try
|
||||
{
|
||||
var existingUserByEmail = await _userManager.FindByEmailAsync(admin.Email);
|
||||
if (existingUserByEmail != null)
|
||||
{
|
||||
return new ApiResponse("此电子邮件地址已被注册。");
|
||||
}
|
||||
var user = new User { Role = UserRoles.Admin, DisplayName = admin.DisplayName, Email = admin.Email, UserName = admin.Email };
|
||||
|
||||
var result = await _userManager.CreateAsync(user, admin.Password);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
return ApiResponse.Error("管理员用户创建失败, 用户注册时失败");
|
||||
}
|
||||
|
||||
await _userManager.AddToRoleAsync(user, UserRoles.Admin.ToString());
|
||||
|
||||
await _unitOfWork.GetRepository<School>().InsertAsync(new School { SchoolName = admin.SchoolName, CreateTime = DateTime.Now, Address = admin.Address });
|
||||
|
||||
if (await _unitOfWork.SaveChangesAsync() > 0)
|
||||
{
|
||||
return ApiResponse.Success("管理员用户创建成功");
|
||||
}
|
||||
return ApiResponse.Error("管理员用户创建失败");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ApiResponse.Error($"创建失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user