OAuthService.cs
32 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
using NCC.Common.Configuration;
using NCC.Common.Const;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Util;
using NCC.DataEncryption;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.EventBridge;
using NCC.FriendlyException;
using NCC.JsonSerialization;
using NCC.OAuth.Service.Dto;
using NCC.RemoteRequest.Extensions;
using NCC.System.Entitys.Dto.Permission.User;
using NCC.System.Entitys.Dto.System.SysConfig;
using NCC.System.Entitys.Dto.System.SysLog;
using NCC.System.Entitys.Permission;
using NCC.System.Entitys.System;
using NCC.System.Interfaces.Permission;
using NCC.System.Interfaces.System;
using NCC.UnifyResult;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using UAParser;
using Yitter.IdGenerator;
using NCC.Expand.Thirdparty.Sms;
using NCC.Expand.Thirdparty.Sms.Model;
using NCC.Core.Pay.Wechat;
namespace NCC.OAuth.Service
{
/// <summary>
/// 业务实现:身份认证模块
/// </summary>
[ApiDescriptionSettings(Tag = "OAuth", Name = "OAuth", Order = 160)]
[Route("api/[controller]")]
public class OAuthService : IDynamicApiController, ITransient
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISqlSugarRepository<UserEntity> _userRepository; // 用户表仓储
private readonly IUsersService _userService; // 用户表仓储
private readonly ISysConfigService _sysConfigService; //系统配置仓储
private readonly IModuleService _moduleService;//功能模块
private readonly IModuleColumnService _columnService; //功能列
private readonly IModuleButtonService _moduleButtonService;//功能按钮
private readonly IModuleFormService _formService;//表单
private readonly IModuleDataAuthorizeSchemeService _moduleDataAuthorizeSchemeService;
private readonly IUserManager _userManager; // 用户管理
private readonly ISysCacheService _sysCacheService;
private readonly IUserRelationService _userRelationService; // 用户关系表服务
private readonly SqlSugarScope _db;
private readonly ITenant _tenant;
/// <summary>
/// 初始化一个<see cref="OAuthService"/>类型的新实例
/// </summary>
public OAuthService(IUsersService userService,
ISqlSugarRepository<UserEntity> userRepository,
IHttpContextAccessor httpContextAccessor,
ISysConfigService sysConfigService,
IModuleService moduleService,
IModuleColumnService columnService,
IModuleButtonService moduleButtonService,
IModuleFormService formService,
IModuleDataAuthorizeSchemeService moduleDataAuthorizeSchemeService,
IUserManager userManager,
ISysCacheService sysCacheService,
IUserRelationService userRelationService,
ISqlSugarClient db)
{
_httpContextAccessor = httpContextAccessor;
_userRepository = userRepository;
_userService = userService;
_sysConfigService = sysConfigService;
_moduleService = moduleService;
_columnService = columnService;
_formService = formService;
_moduleButtonService = moduleButtonService;
_moduleDataAuthorizeSchemeService = moduleDataAuthorizeSchemeService;
_userManager = userManager;
_sysCacheService = sysCacheService;
_userRelationService = userRelationService;
_db = (SqlSugarScope)db;
_tenant = (ITenant)_db;
}
/// <summary>
/// 用户登录
/// </summary>
/// <param name="input">登录输入参数</param>
/// <returns></returns>
[HttpPost("Login")]
[AllowAnonymous]
[Consumes("application/x-www-form-urlencoded")]
public async Task<LoginOutput> Login([FromForm] LoginInput input)
{
string tenantDbName = App.Configuration["ConnectionStrings:DBName"];
string tenantId = App.Configuration["ConnectionStrings:ConfigId"];
string tenantAccout = string.Empty;
if (KeyVariable.MultiTenancy)
{
//分割账号
var tenantAccount = input.account.Split('@');
tenantId = tenantAccount.FirstOrDefault();
if (tenantAccount.Length == 1)
input.account = "admin";
else
input.account = tenantAccount[1];
tenantAccout = input.account;
var interFace = App.Configuration["NCC_App:MultiTenancyDBInterFace"] + tenantId;
var response = await interFace.GetAsStringAsync();
var data = JSON.Deserialize<RESTfulResult<TenantInterFaceOutput>>(response);
if (data == null)
throw NCCException.Oh(ErrorCode.D1024);
else if (data.data == null)
throw NCCException.Oh(ErrorCode.D1023);
else
tenantDbName = data.data.dotnet;
_tenant.AddConnection(new ConnectionConfig()
{
DbType = (DbType)Enum.Parse(typeof(DbType), App.Configuration["ConnectionStrings:DBType"]),
ConfigId = tenantId,//设置库的唯一标识
IsAutoCloseConnection = true,
ConnectionString = string.Format($"{App.Configuration["ConnectionStrings:DefaultConnection"]}", tenantDbName)
});
_tenant.ChangeDatabase(tenantId);
}
//根据用户账号获取用户秘钥
var user = await _userService.GetInfoByAccount(input.account);
_ = user ?? throw NCCException.Oh(ErrorCode.D5002);
bool isMoble = false;
if (input.account == user.MobilePhone) isMoble = true;
//获取加密后的密码
var encryptPasswod = MD5Encryption.Encrypt(input.password + user.Secretkey);
var userAnyPwd = await _userService.GetInfoByLogin(input.account, encryptPasswod, isMoble);
_ = userAnyPwd ?? throw NCCException.Oh(ErrorCode.D1000);
// 验证账号是否未被激活
if (user.EnabledMark == null)
throw NCCException.Oh(ErrorCode.D1018);
// 验证账号是否被禁用
if (user.EnabledMark == 0)
throw NCCException.Oh(ErrorCode.D1019);
// 验证账号是否被删除
if (user.DeleteMark == 1)
throw NCCException.Oh(ErrorCode.D1017);
// app权限验证
if (NetUtil.isMobileBrowser && user.IsAdministrator == 0 && !ExistRoleByApp(user.RoleId))
throw NCCException.Oh(ErrorCode.D1022);
//登录成功时 判断单点登录信息
//token过期时间
var tokenTimeout = await _sysConfigService.GetInfo("SysConfig", "tokentimeout");
var accessToken = string.Empty;
// 生成Token令牌
if (KeyVariable.MultiTenancy)
{
accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
{
{ ClaimConst.CLAINM_USERID, userAnyPwd.Id },
{ ClaimConst.CLAINM_ACCOUNT, userAnyPwd.Account },
{ ClaimConst.CLAINM_REALNAME, userAnyPwd.RealName },
{ ClaimConst.CLAINM_ADMINISTRATOR, userAnyPwd.IsAdministrator },
{ ClaimConst.TENANT_ID, tenantId },
{ ClaimConst.TENANT_DB_NAME, tenantDbName }
}, long.Parse(tokenTimeout.Value));
}
else
{
accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
{
{ ClaimConst.CLAINM_USERID, userAnyPwd.Id },
{ ClaimConst.CLAINM_ACCOUNT, userAnyPwd.Account },
{ ClaimConst.CLAINM_REALNAME, userAnyPwd.RealName },
{ ClaimConst.CLAINM_ADMINISTRATOR, userAnyPwd.IsAdministrator },
{ ClaimConst.TENANT_ID, tenantId },
{ ClaimConst.TENANT_DB_NAME, tenantDbName }
}, long.Parse(tokenTimeout.Value));
}
var httpContext = _httpContextAccessor.HttpContext;
// 设置Swagger自动登录
httpContext.SigninToSwagger(accessToken);
// 生成刷新Token令牌
var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 30);
// 设置刷新Token令牌
httpContext.Response.Headers["x-access-token"] = refreshToken;
var ip = httpContext.GetRemoteIpAddressToIPv4();
// 修改用户登录信息
await Event.EmitAsync("User:UpdateUserLoginInfo", new UserEventDealWithInput
{
tenantId = tenantId,
tenantDbName = tenantDbName,
entity = new UserEntity()
{
Id = user.Id,
FirstLogIP = user.FirstLogIP ?? ip,
FirstLogTime = user.FirstLogTime ?? DateTime.Now,
PrevLogTime = user.LastLogTime,
PrevLogIP = user.LastLogIP,
LastLogTime = DateTime.Now,
LastLogIP = ip,
LogSuccessCount = user.LogSuccessCount + 1
}
});
//登录时间
var clent = Parser.GetDefault().Parse(httpContext.Request.Headers["User-Agent"]);
// 增加登录日志
await Event.EmitAsync("Log:CreateVisLog", new LogEventBridgeCrInput
{
tenantId = tenantId,
tenantDbName = tenantDbName,
entity = new SysLogEntity
{
Id = YitIdHelper.NextId().ToString(),
UserId = user.Id,
UserName = user.RealName,
Category = 1,
IPAddress = ip,
Abstracts = "登录成功",
PlatForm = clent.String,
CreatorTime = DateTime.Now
}
});
return new LoginOutput()
{
theme = user.Theme == null ? "classic" : user.Theme,
token = "Bearer " + accessToken
};
}
/// <summary>
/// 小程序用户登录
/// </summary>
/// <param name="input">登录输入参数</param>
/// <returns></returns>
[HttpPost("AppleteLogin")]
[AllowAnonymous]
[Consumes("application/x-www-form-urlencoded")]
public async Task<LoginOutput> AppleteLogin([FromForm] AppleteLoginInput input)
{
if (input == null || input.code.IsNullOrEmpty()) throw NCCException.Oh("访问异常!");
//var dd = App.GetConfig<Common.Extensions.PaymentSettingsOptions>("PaymentSettings", true);
var appuser = new AppleteHelper().GetUserOpenIdForCode(input.code);
if (appuser == null || appuser.openid.IsNullOrEmpty()) throw NCCException.Oh("用户信息拉取失败!");
string tenantDbName = App.Configuration["ConnectionStrings:DBName"];
string tenantId = App.Configuration["ConnectionStrings:ConfigId"];
string tenantAccout = string.Empty;
var user = await _userRepository.Entities.FirstAsync(o => (o.OpenId == appuser.OpenId || o.Account == appuser.OpenId) && (o.DeleteMark != 1 || o.DeleteMark == null));
if (user == null)
{
//注册
UserEntity adduser = new UserEntity
{
Account = appuser.OpenId,
NickName = input.nickName,
RealName = input.nickName,
HeadIcon = input.HeadIcon,
Password = "99999999",
OpenId = appuser.openid,
IsAdministrator = 0,
OrganizeId = "274772725216576773" //小程序用户
};
var isExist = await _userRepository.AnyAsync(u => u.Account == adduser.Account && u.DeleteMark == null);
if (isExist) throw NCCException.Oh(ErrorCode.D1003);
var entity = adduser.Adapt<UserEntity>();
#region 用户表单
entity.IsAdministrator = 0;
entity.EntryDate = DateTime.Now;
entity.Birthday = DateTime.Now;
entity.Secretkey = Guid.NewGuid().ToString();
entity.Password = MD5Encryption.Encrypt(MD5Encryption.Encrypt(entity.Password ?? CommonConst.DEFAULT_PASSWORD) + entity.Secretkey);
entity.EnabledMark = 1;
#endregion
//新增用户记录
user = await _userRepository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteReturnEntityAsync();
}
//登录成功时 判断单点登录信息
//token过期时间
var tokenTimeout = await _sysConfigService.GetInfo("SysConfig", "tokentimeout");
var accessToken = string.Empty;
// 生成Token令牌
if (KeyVariable.MultiTenancy)
{
accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
{
{ ClaimConst.CLAINM_USERID, user.Id },
{ ClaimConst.CLAINM_ACCOUNT, user.Account },
{ ClaimConst.CLAINM_REALNAME, user.RealName },
{ ClaimConst.CLAINM_ADMINISTRATOR, user.IsAdministrator },
{ ClaimConst.TENANT_ID, tenantId },
{ ClaimConst.TENANT_DB_NAME, tenantDbName }
}, long.Parse(tokenTimeout.Value));
}
else
{
accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
{
{ ClaimConst.CLAINM_USERID, user.Id },
{ ClaimConst.CLAINM_ACCOUNT, user.Account },
{ ClaimConst.CLAINM_REALNAME, user.RealName },
{ ClaimConst.CLAINM_ADMINISTRATOR, user.IsAdministrator },
{ ClaimConst.TENANT_ID, tenantId },
{ ClaimConst.TENANT_DB_NAME, tenantDbName }
}, long.Parse(tokenTimeout.Value));
}
var httpContext = _httpContextAccessor.HttpContext;
// 设置Swagger自动登录
//httpContext.SigninToSwagger(accessToken);
// 生成刷新Token令牌
var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 30);
// 设置刷新Token令牌
httpContext.Response.Headers["x-access-token"] = refreshToken;
var ip = httpContext.GetRemoteIpAddressToIPv4();
// 修改用户登录信息
await Event.EmitAsync("User:UpdateUserLoginInfo", new UserEventDealWithInput
{
tenantId = tenantId,
tenantDbName = tenantDbName,
entity = new UserEntity()
{
Id = user.Id,
FirstLogIP = user.FirstLogIP ?? ip,
FirstLogTime = user.FirstLogTime ?? DateTime.Now,
PrevLogTime = user.LastLogTime,
PrevLogIP = user.LastLogIP,
LastLogTime = DateTime.Now,
LastLogIP = ip,
LogSuccessCount = user.LogSuccessCount + 1
}
});
//登录时间
var clent = Parser.GetDefault().Parse(httpContext.Request.Headers["User-Agent"]);
// 增加登录日志
await Event.EmitAsync("Log:CreateVisLog", new LogEventBridgeCrInput
{
tenantId = tenantId,
tenantDbName = tenantDbName,
entity = new SysLogEntity
{
Id = YitIdHelper.NextId().ToString(),
UserId = user.Id,
UserName = user.RealName,
Category = 1,
IPAddress = ip,
Abstracts = "登录成功",
PlatForm = clent.String,
CreatorTime = DateTime.Now
}
});
return new LoginOutput()
{
theme = user.Theme == null ? "classic" : user.Theme,
token = "Bearer " + accessToken,
user = new
{
id = user.Id,
openid = user.OpenId,
realname = user.RealName,
headicon = user.HeadIcon
}
};
}
/// <summary>
/// 系统信息获取
/// </summary>
/// <returns></returns>
[HttpPost("SystemInfo")]
[AllowAnonymous]
public object SystemInfo()
{
return new
{
//httpUrl = "http://disk.fengshiyun.com/api",
httpUrl = "http://localhost:8061/api",
Version = "1.0.1"
};
}
[HttpPost("PisLogin")]
[AllowAnonymous]
[Consumes("application/x-www-form-urlencoded")]
public async Task<LoginOutput> PisLogin([FromForm] PisLoginInput input)
{
string tenantDbName = App.Configuration["ConnectionStrings:DBName"];
string tenantId = App.Configuration["ConnectionStrings:ConfigId"];
string tenantAccout = string.Empty;
if (KeyVariable.MultiTenancy)
{
//分割账号
var tenantAccount = input.account.Split('@');
tenantId = tenantAccount.FirstOrDefault();
if (tenantAccount.Length == 1)
input.account = "admin";
else
input.account = tenantAccount[1];
tenantAccout = input.account;
var interFace = App.Configuration["NCC_App:MultiTenancyDBInterFace"] + tenantId;
var response = await interFace.GetAsStringAsync();
var data = JSON.Deserialize<RESTfulResult<TenantInterFaceOutput>>(response);
if (data == null)
throw NCCException.Oh(ErrorCode.D1024);
else if (data.data == null)
throw NCCException.Oh(ErrorCode.D1023);
else
tenantDbName = data.data.dotnet;
_tenant.AddConnection(new ConnectionConfig()
{
DbType = (DbType)Enum.Parse(typeof(DbType), App.Configuration["ConnectionStrings:DBType"]),
ConfigId = tenantId,//设置库的唯一标识
IsAutoCloseConnection = true,
ConnectionString = string.Format($"{App.Configuration["ConnectionStrings:DefaultConnection"]}", tenantDbName)
});
_tenant.ChangeDatabase(tenantId);
}
//根据用户账号获取用户秘钥
var user = await _userService.GetInfoByAccount(input.account);
_ = user ?? throw NCCException.Oh(ErrorCode.D5002);
bool isMoble = false;
if (input.account == user.MobilePhone) isMoble = true;
//获取加密后的密码
// var encryptPasswod = MD5Encryption.Encrypt(input.password + user.Secretkey);
//var userAnyPwd = await _userService.GetInfoByLogin(input.account, encryptPasswod, isMoble);
//_ = userAnyPwd ?? throw NCCException.Oh(ErrorCode.D1000);
// 验证账号是否未被激活
if (user.EnabledMark == null)
throw NCCException.Oh(ErrorCode.D1018);
// 验证账号是否被禁用
if (user.EnabledMark == 0)
throw NCCException.Oh(ErrorCode.D1019);
// 验证账号是否被删除
if (user.DeleteMark == 1)
throw NCCException.Oh(ErrorCode.D1017);
// app权限验证
if (NetUtil.isMobileBrowser && user.IsAdministrator == 0 && !ExistRoleByApp(user.RoleId))
throw NCCException.Oh(ErrorCode.D1022);
//登录成功时 判断单点登录信息
//token过期时间
var tokenTimeout = await _sysConfigService.GetInfo("SysConfig", "tokentimeout");
var accessToken = string.Empty;
// 生成Token令牌
if (KeyVariable.MultiTenancy)
{
//accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
//{
// { ClaimConst.CLAINM_USERID, userAnyPwd.Id },
// { ClaimConst.CLAINM_ACCOUNT, userAnyPwd.Account },
// { ClaimConst.CLAINM_REALNAME, userAnyPwd.RealName },
// { ClaimConst.CLAINM_ADMINISTRATOR, userAnyPwd.IsAdministrator },
// { ClaimConst.TENANT_ID, tenantId },
// { ClaimConst.TENANT_DB_NAME, tenantDbName }
//}, long.Parse(tokenTimeout.Value));
}
else
{
accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
{
{ ClaimConst.CLAINM_USERID, user.Id },
{ ClaimConst.CLAINM_ACCOUNT, input.account },
{ ClaimConst.CLAINM_REALNAME, user.RealName },
{ ClaimConst.CLAINM_ADMINISTRATOR, 0 },
{ ClaimConst.TENANT_ID, tenantId },
{ ClaimConst.TENANT_DB_NAME, tenantDbName }
}, long.Parse(tokenTimeout.Value));
}
var httpContext = _httpContextAccessor.HttpContext;
// 设置Swagger自动登录
httpContext.SigninToSwagger(accessToken);
// 生成刷新Token令牌
var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 30);
// 设置刷新Token令牌
httpContext.Response.Headers["x-access-token"] = refreshToken;
var ip = httpContext.GetRemoteIpAddressToIPv4();
// 修改用户登录信息
await Event.EmitAsync("User:UpdateUserLoginInfo", new UserEventDealWithInput
{
tenantId = tenantId,
tenantDbName = tenantDbName,
entity = new UserEntity()
{
Id = user.Id,
FirstLogIP = user.FirstLogIP ?? ip,
FirstLogTime = user.FirstLogTime ?? DateTime.Now,
PrevLogTime = user.LastLogTime,
PrevLogIP = user.LastLogIP,
LastLogTime = DateTime.Now,
LastLogIP = ip,
Description = input.hospitalname,
LogSuccessCount = user.LogSuccessCount + 1
}
}); ;
//登录时间
var clent = Parser.GetDefault().Parse(httpContext.Request.Headers["User-Agent"]);
// 增加登录日志
await Event.EmitAsync("Log:CreateVisLog", new LogEventBridgeCrInput
{
tenantId = tenantId,
tenantDbName = tenantDbName,
entity = new SysLogEntity
{
Id = YitIdHelper.NextId().ToString(),
UserId = user.Id,
UserName = user.RealName,
Category = 1,
IPAddress = ip,
Abstracts = "登录成功",
PlatForm = clent.String,
CreatorTime = DateTime.Now
}
});
return new LoginOutput()
{
theme = user.Theme == null ? "classic" : user.Theme,
token = "Bearer " + accessToken
};
}
/// <summary>
/// 锁屏解锁登录
/// </summary>
/// <param name="input">登录输入参数</param>
/// <returns></returns>
[HttpPost("LockScreen")]
public async Task LockScreen([Required] LoginInput input)
{
var users = await _userService.GetInfoByAccount(input.account);
_ = users ?? throw NCCException.Oh(ErrorCode.D5002);
//根据用户账号获取用户秘钥
var secretkey = (await _userService.GetInfoByAccount(input.account)).Secretkey;
//获取加密后的密码
var encryptPasswod = MD5Encryption.Encrypt(input.password + secretkey);
bool isMoble = false;
if (input.account == users.MobilePhone) isMoble = true;
var user = await _userService.GetInfoByLogin(input.account, encryptPasswod, isMoble);
_ = user ?? throw NCCException.Oh(ErrorCode.D1000);
}
/// <summary>
/// 获取当前登录用户信息
/// </summary>
/// <returns></returns>
[HttpGet("CurrentUser")]
public async Task<CurrentUserOutput> GetCurrentUser()
{
var user = await _userManager.GetUserInfo();
var userId = user.userId;
var userContext = App.User;
var httpContext = _httpContextAccessor.HttpContext;
var tenantId = userContext?.FindFirstValue(ClaimConst.TENANT_ID);
var tenantDbName = userContext?.FindFirstValue(ClaimConst.TENANT_DB_NAME);
var loginOutput = new CurrentUserOutput();
loginOutput.userInfo = user;
//菜单
loginOutput.menuList = await _moduleService.GetUserTreeModuleList(_userManager.IsAdministrator, userId);
var currentUserModel = new CurrentUserModelOutput();
currentUserModel.moduleList = await _moduleService.GetUserModueList(_userManager.IsAdministrator, userId);
currentUserModel.buttonList = await _moduleButtonService.GetUserModuleButtonList(_userManager.IsAdministrator, userId);
currentUserModel.columnList = await _columnService.GetUserModuleColumnList(_userManager.IsAdministrator, userId);
currentUserModel.formList = await _formService.GetUserModuleFormList(_userManager.IsAdministrator, userId);
currentUserModel.resourceList = await _moduleDataAuthorizeSchemeService.GetResourceList(_userManager.IsAdministrator, userId);
//权限信息
var permissionList = new List<PermissionModel>();
currentUserModel.moduleList.ForEach(menu =>
{
var permissionModel = new PermissionModel();
permissionModel.modelId = menu.id;
permissionModel.moduleName = menu.fullName;
permissionModel.button = currentUserModel.buttonList.FindAll(t => t.moduleId.Equals(menu.id)).Adapt<List<AuthorizeModuleButtonModel>>();
permissionModel.column = currentUserModel.columnList.FindAll(t => t.moduleId.Equals(menu.id)).Adapt<List<AuthorizeModuleColumnModel>>();
permissionModel.form = currentUserModel.formList.FindAll(t => t.moduleId.Equals(menu.id)).Adapt<List<AuthorizeModuleFormModel>>();
permissionModel.resource = currentUserModel.resourceList.FindAll(t => t.moduleId.Equals(menu.id)).Adapt<List<AuthorizeModuleResourceModel>>();
permissionList.Add(permissionModel);
});
//await _sysCacheService.SetAsync(CommonConst.CACHE_KEY_PERMISSION + "");
loginOutput.permissionList = permissionList;
return loginOutput;
}
/// <summary>
/// 获取当前登录用户信息(简单信息)
/// </summary>
/// <returns></returns>
[HttpGet("GetSimpleCurrentUser")]
public async Task<CurrentUserOutput> GetSimpleCurrentUser()
{
var user = await _userManager.GetUserInfo();
//var userId = user.userId;
//var userContext = App.User;
//var httpContext = _httpContextAccessor.HttpContext;
var loginOutput = new CurrentUserOutput();
loginOutput.userInfo = user;
return loginOutput;
}
/// <summary>
/// 退出
/// </summary>
/// <returns></returns>
[HttpGet("Logout")]
public async Task Logout()
{
var httpContext = _httpContextAccessor.HttpContext;
httpContext.SignoutToSwagger();
var user = _userManager.User;
await _sysCacheService.DelUserInfo(_userManager.TenantId + "_" + user.Id);
var clent = Parser.GetDefault().Parse(httpContext.Request.Headers["User-Agent"]);
var userContext = App.User;
var tenantId = userContext?.FindFirstValue(ClaimConst.TENANT_ID);
var tenantDbName = userContext?.FindFirstValue(ClaimConst.TENANT_DB_NAME);
//清除IM中的webSocket
//var list = _sysCacheService.GetOnlineUserList(tenantId);
//var onlineUser = list.Find(it => it.tenantId == tenantId && it.userId == user.Id);
//list.RemoveAll((x) => x.connectionId == onlineUser.connectionId);
//_sysCacheService.SetOnlineUserList(tenantId, list);
//// 增加退出日记
//Event.Emit("Log:CreateVisLog", new LogEventBridgeCrInput
//{
// tenantId = tenantId,
// tenantDbName = tenantDbName,
// entity = new SysLogEntity
// {
// Id = YitIdHelper.NextId().ToString(),
// UserId = user.Id,
// UserName = user.RealName,
// Category = 1,
// IPAddress = httpContext.GetRemoteIpAddressToIPv4(),
// Abstracts = "退出成功",
// PlatForm = clent.String,
// CreatorTime = DateTime.Now
// }
//});
}
#region PrivateMethod
/// <summary>
/// 判断app用户角色是否存在且有效
/// </summary>
/// <param name="roleIds"></param>
/// <returns></returns>
private bool ExistRoleByApp(string roleIds)
{
if (roleIds.IsEmpty())
{
return false;
}
var roleIdList1 = roleIds.Split(",").ToList();
var roleIdList2 = _db.Queryable<RoleEntity>().Where(x => x.DeleteMark == null && x.EnabledMark == 1).Select(x => x.Id).ToList();
return roleIdList1.Intersect(roleIdList2).ToList().Count > 0;
}
/// <summary>
/// 短信
/// </summary>
/// <param name="code"></param>
/// <param name="mobile"></param>
/// <param name="sysconfig"></param>
private void SmsSend(string code, string mobile, SysConfigOutput sysconfig)
{
var telList = new List<string>();
var smsModel = new SmsModel()
{
keyId = sysconfig.smsKeyId,
keySecret = sysconfig.smsKeySecret,
signName = sysconfig.smsSignName,
appId = sysconfig.smsAppId,
templateId = sysconfig.smsTemplateId,
region = "ap-guangzhou",
mobileAli = mobile,
mobileTx = null,
templateParamAli = "{\"code\":\"" + code + "\"}",
templateParamTx = new string[] { "12345" }
};
if (sysconfig.smsCompany.Equals("2"))
{
Sms.SendSmsByTencent(smsModel);
}
else
{
Sms.SendSmsByAli(smsModel);
}
}
/// <summary>
/// 获取随机6位数字
/// </summary>
/// <returns></returns>
private int getKey()
{
Random rd = new Random();
int key = (int)(rd.NextDouble() * 999999);
return key;
}
#endregion
}
}