刘磊
2025-06-09 dabbcafc629ef87d11ba55ef8cc1cdc776c047d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Const;
using WIDESEA_Core.DB;
using WIDESEA_Core.Helper;
using WIDESEA_Core.Seed;
 
namespace WIDESEA_Core.HttpContextUser
{
    public class AspNetUser : IUser
    {
        private readonly IHttpContextAccessor _accessor;
        //private readonly ILogger<AspNetUser> _logger;
 
        public AspNetUser(IHttpContextAccessor accessor/*, ILogger<AspNetUser> logger*/)
        {
            _accessor = accessor;
            /*_logger = logger;*/
        }
 
        public string UserName => UserInfo.UserName;
 
        //private string GetName()
        //{
        //    if (IsAuthenticated() && _accessor.HttpContext.User.Identity.Name.IsNotEmptyOrNull())
        //    {
        //        return _accessor.HttpContext.User.Identity.Name;
        //    }
        //    else
        //    {
        //        if (!string.IsNullOrEmpty(GetToken()))
        //        {
        //            var getNameType = /*Permissions.IsUseIds4 ? */"name" /*: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"*/;
        //            return GetUserInfoFromToken(getNameType).FirstOrDefault().ObjToString();
        //        }
        //    }
 
        //    return "";
        //}
 
        public int UserId => GetClaimValueByType("jti").FirstOrDefault().ObjToInt();
        public long TenantId => UserInfo.TenantId;
 
        public int RoleId => UserInfo.RoleId;
 
        public string Token => "throw new NotImplementedException()";
 
        public int SystemType => UserInfo.SystemType;
 
        public bool IsAuthenticated()
        {
            return _accessor.HttpContext.User.Identity.IsAuthenticated;
        }
 
 
        public string GetToken()
        {
            return _accessor.HttpContext?.Request?.Headers["Authorization"].ObjToString().Replace("Bearer ", "");
        }
 
        private UserInfo _userInfo { get; set; }
        private UserInfo UserInfo
        {
            get
            {
                if (_userInfo != null)
                    return _userInfo;
 
                SqlSugarClient sqlSugarClient = new SqlSugarClient(new ConnectionConfig
                {
                    ConfigId = MainDb.CurrentDbConnId,
                    DbType = MainDb.DbType,
                    //ConnectionString = AppSettings.app(MainDb.ConnectionString).DecryptDES(AppSecret.DB),
                    ConnectionString = AppSettings.app(MainDb.ConnectionString),
                    IsAutoCloseConnection = true
                });
 
                dynamic userInfo = sqlSugarClient.Queryable(MainDb.UserTableName, "x").Where(MainDb.UserId, "=", UserId).Select(GetUserInfoSelectModels()).First();
                if (userInfo != null)
                {
                    _userInfo = new UserInfo()
                    {
                        RoleId = userInfo.Role_Id,
                        TenantId = userInfo.TenantId,
                        SystemType = userInfo.SystemType,
                        UserName = userInfo.UserName,
                    };
                    return _userInfo;
                }
 
                return new UserInfo();
            }
        }
 
        public bool IsSuperAdmin => IsRoleIdSuperAdmin(RoleId);
 
        public List<Permissions> Permissions => throw new NotImplementedException();
 
        public UserInfo GetCurrentUserInfo()
        {
            return UserInfo;
        }
 
        public List<SelectModel> GetUserInfoSelectModels()
        {
            List<SelectModel> selectModels = new List<SelectModel>()
            {
                new() {
                    FieldName = MainDb.TenantId
                },
                new() {
                    FieldName = MainDb.RoleId,
                },
                new() {
                    FieldName = MainDb.SystemType
                },
                new() {
                    FieldName = MainDb.UserName
                }
            };
            return selectModels;
        }
 
        public List<string> GetUserInfoFromToken(string ClaimType)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var token = "";
 
            token = GetToken();
            // token校验
            if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
 
                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item.Value).ToList();
            }
 
            return new List<string>() { };
        }
 
        //public MessageModel<string> MessageModel { get; set; }
 
        public IEnumerable<Claim> GetClaimsIdentity()
        {
            if (_accessor.HttpContext != null)
            {
 
                var claims = _accessor.HttpContext.User.Claims.ToList();
                var headers = _accessor.HttpContext.Request.Headers;
                foreach (var header in headers)
                {
                    claims.Add(new Claim(header.Key, header.Value));
                }
                return claims;
            }
            return ArraySegment<Claim>.Empty;
        }
 
        public List<string> GetClaimValueByType(string ClaimType)
        {
            return (from item in GetClaimsIdentity()
                    where item.Type == ClaimType
                    select item.Value).ToList();
        }
 
        public bool IsRoleIdSuperAdmin(int roleId)
        {
            return roleId == 1;
        }
    }
 
    public class UserInfo
    {
        public long TenantId { get; set; }
 
        public int RoleId { get; set; }
 
        public int SystemType { get; set; }
 
        public string UserName { get; set; }
 
        public int UserId { get; set; }
 
        public string UserTrueName { get; set; }
 
        public string HeadImageUrl { get; set; }
    }
}