[feature] 建立鉴权项目结构
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SiteManagementSystem_SoftwareEngineering_.Entity;
|
||||
|
||||
namespace SiteManagementSystem_SoftwareEngineering_.Service
|
||||
{
|
||||
public class SQLService : DbContext
|
||||
{
|
||||
public SQLService(DbContextOptions<SQLService> options)
|
||||
: base(options)
|
||||
{
|
||||
Database.EnsureCreated();
|
||||
}
|
||||
public DbSet<User> Users { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
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))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user