AuthContextFactory.cs 3.07 KB
// ***********************************************************************
// <summary>
// 用户权限策略工厂
//</summary>
// ***********************************************************************


using Hh.Mes.POJO.Entity;
using Hh.Mes.Service.Repository;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Text.Json;


namespace Hh.Mes.Service.SystemAuth
{
    /// <summary>
    ///  加载用户所有可访问的资源/机构/模块
    /// </summary>
    public class AuthContextFactory : RepositorySqlSugar<SysUser>
    {
        private SystemAuthStrategy _systemAuth;
        private NormalAuthStrategy _normalAuthStrategy;
        private readonly IDistributedCache _cache;

        public AuthContextFactory(SystemAuthStrategy sysStrategy, NormalAuthStrategy normalAuthStrategy, IDistributedCache cache)
        {
            _systemAuth = sysStrategy;
            _normalAuthStrategy = normalAuthStrategy;
            _cache = cache;
        }

        /// <summary>
        /// 生成授权信息
        /// System给开发者用的,普通管理员只能看到System授权过的模块,普通管理员即使能新增模块,保存后也看不到。
        /// 想了很久才明白,普通管理员是用于授权给其他用户,模块的增加、修改、删除只能由System来进行。
        /// 组织管理,这个确实架构有天生的bug,组织本来就该由管理员设置,居然设置后不能看到。
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public AuthStrategyContext GetAuthStrategyContext(string username)
        {
            //var cl = new RedisBase();


            var authStrategyBytes = _cache.Get(username);
            if (authStrategyBytes != null)
            {
                return JsonSerializer.Deserialize<AuthStrategyContext>(authStrategyBytes);
            }

            var authStrategy = new AuthStrategyContext();
            var user = Context.Queryable<SysUser>().First(t => t.Account == username);
            if (user != null)
            {
                if (username == "System")
                {
                    _systemAuth.User = user;
                    authStrategy.Modules = _systemAuth.Modules;
                    authStrategy.Roles = _systemAuth.Roles;
                    authStrategy.Orgs = _systemAuth.Orgs;
                    authStrategy.User = _systemAuth.User;
                }
                else
                {
                    _normalAuthStrategy.User = user;
                    authStrategy.Modules = _normalAuthStrategy.Modules;
                    authStrategy.Roles = _normalAuthStrategy.Roles;
                    authStrategy.Orgs = _normalAuthStrategy.Orgs;
                    authStrategy.User = _normalAuthStrategy.User;
                }
                var cacheOption = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(1));
                _cache.Set(username, JsonSerializer.SerializeToUtf8Bytes(authStrategy), cacheOption);
            }
            return authStrategy;
        }
    }
}