71 lines
2.7 KiB
C#
71 lines
2.7 KiB
C#
|
using Microsoft.EntityFrameworkCore;
|
|||
|
using Microsoft.IdentityModel.Tokens;
|
|||
|
using SiteManagementSystem_SoftwareEngineering_.Entity;
|
|||
|
using SiteManagementSystem_SoftwareEngineering_.Interface;
|
|||
|
using System.Security.Cryptography;
|
|||
|
using System.Text;
|
|||
|
|
|||
|
namespace SiteManagementSystem_SoftwareEngineering_.Service
|
|||
|
{
|
|||
|
public enum IdentityPolicyNames
|
|||
|
{
|
|||
|
NotSupport,
|
|||
|
CommonUser,
|
|||
|
Administrator
|
|||
|
}
|
|||
|
public class UserManagerService
|
|||
|
{
|
|||
|
public class UserManageService(
|
|||
|
SQLService storageService,
|
|||
|
ILogger<UserManageService> logger,
|
|||
|
string secretSalt
|
|||
|
) : IUserManageService
|
|||
|
{
|
|||
|
private readonly SQLService _storageService = storageService;
|
|||
|
private readonly ILogger<UserManageService> _logger = logger;
|
|||
|
private readonly string _salt = secretSalt;
|
|||
|
private static readonly object _lock = new();
|
|||
|
public void AddUser(User user)
|
|||
|
{
|
|||
|
if (user.Name is null)
|
|||
|
throw new ArgumentException("Miss Name!");
|
|||
|
if (user.RoleName is null)
|
|||
|
throw new ArgumentException("Miss PolicyName!");
|
|||
|
if (user.Role is IdentityPolicyNames.NotSupport)
|
|||
|
throw new ArgumentException("PolicyName not support");
|
|||
|
if (user.Secret is null)
|
|||
|
throw new ArgumentException("Miss Secret!");
|
|||
|
user.HashSecret = ComputeHash(user.Secret);
|
|||
|
if (_storageService.Users.Where(x => x.Name==user.Name).Any())
|
|||
|
throw new InvalidOperationException($"已存在名字为{user.Name}的用户");
|
|||
|
lock (_lock)
|
|||
|
{
|
|||
|
_storageService.Users.Add(user);
|
|||
|
_storageService.SaveChanges();
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public (bool, string) IsUserExist(ref User user)
|
|||
|
{
|
|||
|
string name = user.Name;
|
|||
|
var result = _storageService.Users.Where(x => x.Name == name);
|
|||
|
if (!result.Any())
|
|||
|
return (false, "账号不存在");
|
|||
|
if (result.First().HashSecret != ComputeHash(user.Secret))
|
|||
|
return (false, "密码不匹配");
|
|||
|
user = (User)result.First().Clone();
|
|||
|
return (true, "");
|
|||
|
}
|
|||
|
|
|||
|
private string ComputeHash(string key)
|
|||
|
{
|
|||
|
if (key.IsNullOrEmpty())
|
|||
|
throw new ArgumentException("ComputeHash: Key is null or empty.");
|
|||
|
return Convert.ToBase64String(
|
|||
|
SHA256.HashData(Encoding.UTF8.GetBytes(_salt + key + _salt))
|
|||
|
);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|