AuthController.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. 
  2. using Flurl.Http.Configuration;
  3. using Microsoft.AspNetCore.SignalR;
  4. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  5. using NPOI.SS.Formula.Functions;
  6. using OASystem.API.OAMethodLib;
  7. using OASystem.API.OAMethodLib.Hotmail;
  8. using OASystem.API.OAMethodLib.Hub.HubClients;
  9. using OASystem.API.OAMethodLib.Hub.Hubs;
  10. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  11. using OASystem.Domain.AesEncryption;
  12. using OASystem.Domain.Attributes;
  13. using OASystem.Domain.Dtos.UserDto;
  14. using OASystem.Domain.Entities.Customer;
  15. using OASystem.Domain.Entities.Groups;
  16. using OASystem.Infrastructure.Repositories.Login;
  17. using System.IdentityModel.Tokens.Jwt;
  18. using System.Text.Json;
  19. using static OASystem.API.OAMethodLib.Hotmail.HotmailService;
  20. using static OASystem.API.OAMethodLib.JWTHelper;
  21. namespace OASystem.API.Controllers
  22. {
  23. /// <summary>
  24. /// 鉴权相关
  25. /// </summary>
  26. [Route("api/")]
  27. public class AuthController : ControllerBase
  28. {
  29. private readonly IMapper _mapper;
  30. private readonly IConfiguration _config;
  31. private readonly LoginRepository _loginRep;
  32. private readonly MessageRepository _message;
  33. private readonly SystemMenuPermissionRepository _sysMenuPermRep;
  34. private readonly MessageRepository _messageRep;
  35. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  36. private readonly IHubContext<ChatHub, IChatClient> _hubContext;
  37. private readonly DeviceTokenRepository _deviceTokenRep;
  38. private readonly HotmailService _hotmailService;
  39. private readonly System.Net.Http.IHttpClientFactory _httpClientFactory;
  40. /// <summary>
  41. ///
  42. /// </summary>
  43. /// <param name="config"></param>
  44. /// <param name="loginRep"></param>
  45. /// <param name="mapper"></param>
  46. /// <param name="message"></param>
  47. /// <param name="sysMenuPermRep"></param>
  48. /// <param name="qiYeWeChatApiService"></param>
  49. /// <param name="messageRep"></param>
  50. /// <param name="deviceRep"></param>
  51. /// <param name="hubContext"></param>
  52. /// <param name="hotmailService"></param>
  53. /// <param name="httpClientFactory"></param>
  54. public AuthController(
  55. IConfiguration config,
  56. LoginRepository loginRep,
  57. IMapper mapper,
  58. MessageRepository message,
  59. SystemMenuPermissionRepository sysMenuPermRep,
  60. IQiYeWeChatApiService qiYeWeChatApiService,
  61. MessageRepository messageRep,
  62. DeviceTokenRepository deviceRep,
  63. IHubContext<ChatHub,IChatClient> hubContext,
  64. HotmailService hotmailService,
  65. System.Net.Http.IHttpClientFactory httpClientFactory)
  66. {
  67. _config = config;
  68. _loginRep = loginRep;
  69. _mapper = mapper;
  70. _message = message;
  71. _sysMenuPermRep = sysMenuPermRep;
  72. _qiYeWeChatApiService = qiYeWeChatApiService;
  73. _messageRep = messageRep;
  74. _deviceTokenRep = deviceRep;
  75. _hubContext = hubContext;
  76. _hotmailService = hotmailService;
  77. _httpClientFactory = httpClientFactory;
  78. }
  79. /// <summary>
  80. /// 用户登录
  81. /// </summary>
  82. /// <param name="dto"></param>
  83. /// <returns></returns>
  84. [Route("login")]
  85. [HttpPost]
  86. [ApiLog("Login", OperationEnum.Login)]
  87. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  88. public async Task<IActionResult> LoginAsync(LoginDto dto)
  89. {
  90. if (string.IsNullOrWhiteSpace(dto.Number) || string.IsNullOrWhiteSpace(dto.Password))
  91. {
  92. return Ok(JsonView(false, "账号或密码不能为空!!"));
  93. }
  94. #region 校验用户信息
  95. var userData = _loginRep.Login(dto).Result;
  96. if (userData.Code != 0) return Ok(JsonView(false, userData.Msg));
  97. #endregion
  98. #region 限制销售部门 除gyy外可登录
  99. var userInfo = userData.Data as UserLoginInfoView;
  100. if (userInfo == null) return Ok(JsonView(false, userData.Msg));
  101. if (userInfo.DepName.Contains("市场部"))
  102. {
  103. var noLoginAuth = _config.GetSection("NoLoginAuth").Get<List<string>>();
  104. if (noLoginAuth.Any())
  105. {
  106. if (noLoginAuth.Contains(userInfo.CnName)) return Ok(JsonView(false, "NO ACCESS!!"));
  107. }
  108. //其他市场部人员 限制登录时间段
  109. var currentDateTime = DateTime.Now;
  110. var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  111. var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  112. if (currentDateTime < startTime && currentDateTime > endTime) return Ok(JsonView(false, "NO ACCESS!!"));
  113. }
  114. #endregion
  115. Result authData = null;
  116. string uName = string.Empty,
  117. role = string.Empty,
  118. depName = string.Empty;
  119. int uId = 0;
  120. int unReadCount = 0;
  121. int announcementUnReadCount = 0;
  122. if (userData.Data != null)
  123. {
  124. uId = (userData.Data as UserLoginInfoView).UserId;
  125. uName = (userData.Data as UserLoginInfoView).CnName;
  126. depName = (userData.Data as UserLoginInfoView).DepName;
  127. role = (userData.Data as UserLoginInfoView).JobName;
  128. authData = _sysMenuPermRep.QueryMenuLoad(uId, dto.PortType);
  129. unReadCount = await _messageRep.GetUnReadCount(uId);
  130. announcementUnReadCount = await _messageRep.GetAnnouncementUnReadCount(uId);
  131. }
  132. //_hubContext.Login(uId, uName);
  133. var view = new LoginView
  134. {
  135. UserInfo = userData?.Data,
  136. AuthData = authData?.Data,
  137. UnReadCount = unReadCount,
  138. AnnouncementUnReadCount = announcementUnReadCount
  139. };
  140. DateTime createZebraTime = DateTime.Now;
  141. string authorId = dto.Number + "Token";
  142. string authorToken = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>(authorId);//string 取
  143. if (authorToken != null)
  144. {
  145. #region 解析出过期时间
  146. var jwtHandler = new JwtSecurityTokenHandler();
  147. JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(authorToken);
  148. DateTime expDt = (securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
  149. #endregion
  150. if (expDt >= createZebraTime) //超时重新获取token
  151. {
  152. authorToken = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Department = depName, Role = role }); //
  153. }
  154. view.Expires = expDt;
  155. view.Token = authorToken;
  156. }
  157. else
  158. {
  159. view.Expires = createZebraTime.AddMinutes(30);
  160. //view.Token = await GeneralMethod.GetToken(_config, dto.Number, uId, uName, createZebraTime); //JwtHelper
  161. view.Token = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Department = depName, Role = role }); //
  162. TimeSpan ts = view.Expires.AddMinutes(-1) - createZebraTime; //设置redis 过期时间 比 jwt 时间 快一分钟
  163. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(authorId, view.Token, ts);//string 存
  164. }
  165. //#region 添加登录用户上线信息
  166. //_hubContext.SignalRLogin(uId);
  167. //#endregion
  168. #region 测试添加系统消息
  169. //await _message.AddMsg(new MessageDto()
  170. //{
  171. // Type = 1,
  172. // IssuerId = 208,
  173. // Title = "测试添加消息标题",
  174. // Content = "消息体测试",
  175. // ReleaseTime = DateTime.Now,
  176. // UIdList = new List<int> {
  177. // 5,
  178. // 208,
  179. // 219
  180. // }
  181. //});
  182. #endregion
  183. return Ok(JsonView(view));
  184. }
  185. /// <summary>
  186. /// 移动端用户登录
  187. /// </summary>
  188. /// <param name="dto"></param>
  189. /// <returns></returns>
  190. [Route("MobileLogin")]
  191. [HttpPost]
  192. [ApiLog("Login", OperationEnum.Login)]
  193. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  194. public async Task<IActionResult> MobileLoginAsync(LoginDto dto)
  195. {
  196. if (string.IsNullOrWhiteSpace(dto.Number) || string.IsNullOrWhiteSpace(dto.Password))
  197. {
  198. return Ok(JsonView(false, "账号或密码不能为空!!"));
  199. }
  200. #region 校验用户信息
  201. var userData = _loginRep.Login(dto).Result;
  202. if (userData.Code != 0) return Ok(JsonView(false, userData.Msg));
  203. #endregion
  204. Result authData = null;
  205. string uName = string.Empty;
  206. string role = string.Empty;
  207. int uId = 0;
  208. int unReadCount = 0;
  209. int announcementUnReadCount = 0;
  210. if (userData.Data != null)
  211. {
  212. uId = (userData.Data as UserLoginInfoView).UserId;
  213. uName = (userData.Data as UserLoginInfoView).CnName;
  214. role = (userData.Data as UserLoginInfoView).JobName;
  215. authData = _sysMenuPermRep.MobileMenuLoad(uId, dto.PortType);
  216. unReadCount = await _messageRep.GetUnReadCount(uId);
  217. announcementUnReadCount = await _messageRep.GetAnnouncementUnReadCount(uId);
  218. }
  219. //_hubContext.Login(uId, uName);
  220. var view = new LoginView
  221. {
  222. UserInfo = userData?.Data,
  223. AuthData = authData?.Data,
  224. UnReadCount = unReadCount,
  225. AnnouncementUnReadCount = announcementUnReadCount
  226. };
  227. DateTime createZebraTime = DateTime.Now;
  228. string authorId = dto.Number + "Token";
  229. string authorToken = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>(authorId);//string 取
  230. if (authorToken != null)
  231. {
  232. #region 解析出过期时间
  233. var jwtHandler = new JwtSecurityTokenHandler();
  234. JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(authorToken);
  235. DateTime expDt = (securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
  236. #endregion
  237. if (expDt >= createZebraTime) //超时重新获取token
  238. {
  239. authorToken = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Role = role }); //
  240. }
  241. view.Expires = expDt;
  242. view.Token = authorToken;
  243. }
  244. else
  245. {
  246. view.Expires = createZebraTime.AddMinutes(30);
  247. //view.Token = await GeneralMethod.GetToken(_config, dto.Number, uId, uName, createZebraTime); //JwtHelper
  248. view.Token = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Role = role }); //
  249. TimeSpan ts = view.Expires.AddMinutes(-1) - createZebraTime; //设置redis 过期时间 比 jwt 时间 快一分钟
  250. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(authorId, view.Token, ts);//string 存
  251. }
  252. //#region 添加登录用户上线信息
  253. //_hubContext.SignalRLogin(uId);
  254. //#endregion
  255. #region 测试添加系统消息
  256. //await _message.AddMsg(new MessageDto()
  257. //{
  258. // Type = 1,
  259. // IssuerId = 208,
  260. // Title = "测试添加消息标题",
  261. // Content = "消息体测试",
  262. // ReleaseTime = DateTime.Now,
  263. // UIdList = new List<int> {
  264. // 5,
  265. // 208,
  266. // 219
  267. // }
  268. //});
  269. #endregion
  270. return Ok(JsonView(view));
  271. }
  272. /// <summary>
  273. /// 申请注册 数据Data
  274. /// </summary>
  275. /// <returns></returns>
  276. //[Authorize]
  277. [HttpPost]
  278. [Route("register/daraSource")]
  279. public async Task<IActionResult> RegisterDataSource()
  280. {
  281. string sql = string.Format(@"Select sc.Id CompanyId,sc.CompanyName,sd.Id DepId,sd.DepName,sjp.Id JobId,sjp.JobName From Sys_Company sc
  282. Left Join Sys_Department sd On sd.IsDel = 0 And sc.Id = sd.CompanyId
  283. Left Join Sys_JobPost sjp On sjp.IsDel = 0 And sjp.DepId = sd.Id
  284. Where sc.IsDel = 0");
  285. var companyDetails = _loginRep._sqlSugar.SqlQueryable<CompanyDetailsView>(sql).ToList();
  286. var detailsView1 = new List<CompanyDetailsView1>();
  287. if (companyDetails.Count > 0)
  288. {
  289. var companyDetails1 = companyDetails.GroupBy(it => it.CompanyId).Select(it => it.First()).ToList();
  290. detailsView1 = companyDetails1.Select(it =>
  291. {
  292. var itemCompany = new CompanyDetailsView1();
  293. var depDetailsView = new List<DepDetailsView>();
  294. var companyDetails2 = companyDetails.GroupBy(it => it.DepId).Select(it => it.First()).ToList();
  295. //部门
  296. depDetailsView = companyDetails2.Where(depIt => depIt.CompanyId == it.CompanyId).Select(depIt =>
  297. {
  298. var depDetails = new DepDetailsView();
  299. var jobDetails = new List<JobDetailsView>();
  300. //岗位
  301. jobDetails = companyDetails.Where(jobIt => jobIt.DepId == depIt.DepId).Select(jobIt =>
  302. {
  303. var jobDetail = new JobDetailsView()
  304. {
  305. JobId = jobIt.JobId,
  306. JobName = jobIt.JobName,
  307. };
  308. return jobDetail;
  309. }).ToList();
  310. depDetails.DepId = depIt.DepId;
  311. depDetails.DepName = depIt.DepName;
  312. depDetails.SubJob = jobDetails;
  313. return depDetails;
  314. }).ToList();
  315. itemCompany.CompanyId = it.CompanyId;
  316. itemCompany.CompanyName = it.CompanyName;
  317. itemCompany.SubDep = depDetailsView;
  318. return itemCompany;
  319. }).ToList();
  320. }
  321. return Ok(new { Code = 200, Msg = "查询成功!", Data = detailsView1 });
  322. }
  323. /// <summary>
  324. /// 申请注册
  325. /// </summary>
  326. /// <param name="dto"></param>
  327. /// <returns></returns>
  328. //[Authorize]
  329. [HttpPost]
  330. [Route("register")]
  331. public async Task<IActionResult> Register(RegisterDto dto)
  332. {
  333. #region 企业微信添加员工
  334. //string lastName = dto.CnName.Substring(0, 1);
  335. //string lastNamePy = string.Empty;
  336. //if (PinyinHelper.IsChinese(Convert.ToChar(lastName)))
  337. //{
  338. // lastNamePy = PinyinHelper.GetPinyin(lastName);
  339. //}
  340. //string userId = string.Format("{0}.{1}", dto.EnName, lastNamePy.ToLower());
  341. //Create_Request request = new Create_Request()
  342. //{
  343. // userid = userId,
  344. // name = dto.CnName,
  345. // mobile = dto.Phone,
  346. // department = new List<long>() { dto.DepId },
  347. // position = dto.JobPostId.ToString(),
  348. // gender = dto.Sex == 0 ? 1 : dto.Sex == 1 ? 2 : 1,
  349. // biz_mail = dto.Email
  350. //};
  351. //var qiYeWeChatCreateData = await _qiYeWeChatApiServic.CreateAsync(request);
  352. #endregion
  353. var userData = _loginRep.Register(dto);
  354. if (userData.Result.Code != 0)
  355. {
  356. return Ok(JsonView(false, userData.Result.Msg));
  357. }
  358. return Ok(JsonView(true, userData.Result.Msg));
  359. }
  360. /// <summary>
  361. /// 修改密码
  362. /// </summary>
  363. /// <param name="dto"></param>
  364. /// <returns></returns>
  365. [Authorize]
  366. [HttpPost]
  367. [Route("UpdPassword")]
  368. public async Task<IActionResult> UpdateUserPassword(UpdateDto dto)
  369. {
  370. //Result result = new Result();
  371. //var httpContext = HttpContext.User.Claims.FirstOrDefault(it => it.Type == ClaimTypes.Name)?.Value;
  372. //Sys_Users sys_Users = _mapper.Map<Sys_Users>(dto);
  373. var _view = await _loginRep.ChangePassword(dto.UserId, dto.Password);
  374. if (_view.Code == 0) return Ok(JsonView(true, "操作成功!"));
  375. return Ok(JsonView(false, _view.Msg));
  376. }
  377. /// <summary>
  378. /// 保存deviceToken
  379. /// </summary>
  380. /// <param name="dto"></param>
  381. /// <returns></returns>
  382. [HttpPost("SaveDeviceToken")]
  383. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  384. public async Task<IActionResult> SaveDeviceToken(SaveDeviceToken dto)
  385. {
  386. var view = await _deviceTokenRep.SaveToken(dto);
  387. if (view.Code == 0) return Ok(JsonView(true, "操作成功!"));
  388. return Ok(JsonView(false, view.Msg));
  389. }
  390. /// <summary>
  391. /// 获取deviceToken
  392. /// </summary>
  393. /// <param name="dto"></param>
  394. /// <returns></returns>
  395. [HttpPost("GetDeviceToken")]
  396. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  397. public async Task<IActionResult> GetDeviceToken(GetDeviceToken dto)
  398. {
  399. var view = await _deviceTokenRep.GetToken(dto.account);
  400. if (view.Code == 0) return Ok(JsonView(true, "操作成功!", view.Data));
  401. return Ok(JsonView(false, view.Msg));
  402. }
  403. #region microsoft 鉴权验证
  404. /// <summary>
  405. /// microsoft - hotmail 鉴权验证
  406. /// </summary>
  407. /// <returns></returns>
  408. [HttpGet("microsoft/auth/verify/{currUserId}")]
  409. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  410. public async Task<IActionResult> MicrosoftHotmailPrepareAuth(int currUserId)
  411. {
  412. var (code, message) = await _hotmailService.PrepareAuth(currUserId);
  413. return code switch
  414. {
  415. // 无需授权
  416. 0 => Ok(JsonView(true, "已通过验证", new { isAuth = false })),
  417. // 需要跳转授权 (1)
  418. 1 => Ok(JsonView(true, "请点击链接进行 Auth 验证!", new { isAuth = true, url = message })),
  419. //1 => Redirect(message),
  420. // 配置错误或异常 (-1)
  421. _ => Ok(JsonView(false, message))
  422. };
  423. }
  424. /// <summary>
  425. /// microsoft 回调地址
  426. /// </summary>
  427. /// <param name="code"></param>
  428. /// <param name="state"></param>
  429. /// <returns></returns>
  430. [HttpGet("microsoft/auth/callback")]
  431. public async Task<IActionResult> HandleCallback([FromQuery] string code, [FromQuery] string state)
  432. {
  433. if (string.IsNullOrEmpty(code)) return BadRequest("授权码无效");
  434. // 1. 从 state 中解析出真正的 userId
  435. if (!int.TryParse(state, out int userId))
  436. {
  437. return BadRequest("非法的 state 标识");
  438. }
  439. var config = await _hotmailService.GetUserMailConfig(userId);
  440. if (config == null)
  441. {
  442. return BadRequest("state标识无效");
  443. }
  444. // 1. 换取令牌
  445. var httpClient = _httpClientFactory.CreateClient();
  446. var tokenRequest = new FormUrlEncodedContent(new Dictionary<string, string>
  447. {
  448. { "client_id",config.ClientId },
  449. { "client_secret", config.ClientSecret },
  450. { "code", code },
  451. { "redirect_uri", config.RedirectUri },
  452. { "grant_type", "authorization_code" }
  453. });
  454. var response = await httpClient.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", tokenRequest);
  455. var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
  456. if (!response.IsSuccessStatusCode) return BadRequest(json.RootElement.ToString());
  457. var root = json.RootElement;
  458. var accessToken = root.GetProperty("access_token").GetString()!;
  459. var refreshToken = root.GetProperty("refresh_token").GetString()!;
  460. var expiresIn = root.GetProperty("expires_in").GetInt32();
  461. // 2. 自动识别账户身份 【核心重构】:不再手动解析 JWT,而是请求 Graph 的 /me 接口
  462. string userEmail = await GetEmailFromGraphApiAsync(accessToken);
  463. // 3. 构造并存入 Redis
  464. var userToken = new UserToken
  465. {
  466. Email = userEmail,
  467. AccessToken = accessToken,
  468. RefreshToken = refreshToken,
  469. ExpiresAt = DateTime.UtcNow.AddSeconds(expiresIn)
  470. };
  471. // 存入 Redis
  472. var redisKey = $"MailAlchemy:Token:{userEmail}";
  473. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(redisKey, System.Text.Json.JsonSerializer.Serialize(userToken), TimeSpan.FromDays(90));
  474. return Ok(new
  475. {
  476. status = "Success",
  477. account = userEmail,
  478. message = "该个人账户已成功集成并启用分布式存储"
  479. });
  480. }
  481. private async Task<string> GetEmailFromGraphApiAsync(string accessToken)
  482. {
  483. var httpClient = _httpClientFactory.CreateClient();
  484. // 使用 AccessToken 调用 Graph API 的个人信息接口
  485. httpClient.DefaultRequestHeaders.Authorization =
  486. new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
  487. var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me");
  488. if (!response.IsSuccessStatusCode)
  489. throw new Exception("无法通过 Graph API 获取用户信息");
  490. using var doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
  491. var root = doc.RootElement;
  492. // 个人账户优先取 mail,如果没有则取 userPrincipalName
  493. return root.GetProperty("mail").GetString()
  494. ?? root.GetProperty("userPrincipalName").GetString()
  495. ?? throw new Exception("未能获取有效的 Email 地址");
  496. }
  497. #endregion
  498. /// <summary>
  499. /// 测试auth
  500. /// </summary>
  501. /// <param name="dto"></param>
  502. /// <returns></returns>
  503. [OASystemAuthentication]
  504. [HttpPost("TestToken")]
  505. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  506. public async Task<IActionResult> TestToken(LoginDto dto)
  507. {
  508. string authorId = dto.Number + "Token";
  509. // 从Redis里面取数据
  510. //string userToken = _redis.StringGet(authorId);
  511. string userToken = "";
  512. var view = new LoginView
  513. {
  514. Token = authorId + ":" + userToken
  515. };
  516. return Ok(JsonView(view));
  517. }
  518. /// <summary>
  519. /// 限流测试
  520. /// </summary>
  521. /// <returns></returns>
  522. [HttpGet("rate-test")]
  523. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  524. public IActionResult RateTest()
  525. {
  526. return Ok(JsonView(true, $"限流测试 - IP:{HttpContext.Connection.RemoteIpAddress?.ToString()}", null, GetRequestCount()));
  527. }
  528. private static int _requestCount = 0;
  529. private int GetRequestCount()
  530. {
  531. return ++_requestCount;
  532. }
  533. ///// <summary>
  534. ///// 员工信息 迁移
  535. ///// Old OA To New OA
  536. ///// </summary>
  537. ///// <returns></returns>
  538. //[HttpPost("UpdateUserDataOldOAToNewOA")]
  539. //[ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  540. //public async Task<IActionResult> UpdateUserDataOldOAToNewOA()
  541. //{
  542. // dynamic view = null;
  543. // try
  544. // {
  545. // var _sqlSuar = _loginRep._sqlSugar;
  546. // var oldOaUsersData = await _sqlSuar.Queryable<OA2014UsersView>().AS("OA2014.dbo.Users").ToListAsync();
  547. // var newOaCompanyData = await _sqlSuar.Queryable<Sys_Company>().ToListAsync();
  548. // var newOaDepartmentData = await _sqlSuar.Queryable<Sys_Department>().ToListAsync();
  549. // var newOaJobPostData = await _sqlSuar.Queryable<Sys_JobPost>().ToListAsync();
  550. // List<Sys_Users> newOaUserDatas = new List<Sys_Users>();
  551. // foreach (var oldUser in oldOaUsersData)
  552. // {
  553. // int depId = 0, postId = 0;
  554. // #region 处理部门岗位
  555. // int did = oldUser.Did;
  556. // string post = oldUser.Post;
  557. // switch (did)
  558. // {
  559. // case 1 : //信息部
  560. // depId = 2;
  561. // if (post.Equals("信息部经理")) postId = 4;
  562. // else if (post.Equals("美工")) { depId = 5; postId = 18; }
  563. // else if(post.Equals("网络推广")) postId = 46;
  564. // else if (post.Equals("软件开发")) postId = 5;
  565. // else if (post.Equals("平面设计师")) { depId = 5; postId = 18; }
  566. // else if (post.Equals("平面设计")) { depId = 5; postId = 18; }
  567. // else if (post.Equals("平面设计师")) { depId = 5; postId = 18; }
  568. // else if (post.Equals("软件工程师")) postId = 5;
  569. // else if (post.Equals("OP操作")) { depId = 7; postId = 28; }
  570. // else if (post.Equals("软件工程师.")) postId = 5;
  571. // else if (post.Equals(".net工程师")) postId = 5;
  572. // else if (post.Equals("安卓开发工程师")) postId = 7;
  573. // else if (post.Equals("web前端")) postId = 6;
  574. // else if (post.Equals("Web后端开发")) postId = 5;
  575. // break;
  576. // case 2 : //财务部
  577. // depId=3;
  578. // if (post.Equals("主管")) postId = 47;
  579. // else if (post.Equals("财务总监")) { postId = 9; }
  580. // else if (post.Equals("会计")) { postId = 10; }
  581. // else if (post.Equals("财务经理")) { postId = 47; }
  582. // else if (post.Equals("财务助理")) { postId = 50; }
  583. // else if (post.Equals("出纳")) { postId = 48; }
  584. // else { postId = 10; }
  585. // break;
  586. // case 3: //人事部
  587. // depId = 4;
  588. // if (post.Equals("主管")) postId = 51;
  589. // else if (post.Equals("人事部主管")) { postId = 51; }
  590. // else if (post.Equals("人事行政主管")) { postId = 51; }
  591. // else if (post.Equals("行政人事助理")) { postId = 52; }
  592. // else if (post.Equals("人事助理")) { postId = 52; }
  593. // else if (post.Equals("人事主管")) { postId = 51; }
  594. // else if (post.Equals("行政人事专员")) { postId = 12; }
  595. // else if (post.Equals("行政司机")) { postId = 14; }
  596. // else if (post.Equals("司机")) { postId = 14; }
  597. // else if (post.Equals("统筹执行")) { postId = 12; }
  598. // else if (post.Equals("培训专员")) { postId = 13; }
  599. // else if (post.Equals("人事经理")) { postId = 11; }
  600. // else if (post.Equals("前台")) { postId = 33; }
  601. // else if (post.Equals("人事行政经理")) { postId = 11; }
  602. // else if (post.Equals("人事部经理")) { postId = 11; }
  603. // else if (post.Equals("人事专员")) { postId = 12; }
  604. // else if (post.Equals("人事经理")) { postId = 11; }
  605. // else postId = 12;
  606. // break;
  607. // case 4: //国交部
  608. // //22 7 主管
  609. // //23 7 计调
  610. // //24 7 机票
  611. // //25 7 酒店
  612. // //26 7 签证
  613. // //27 7 商邀
  614. // //28 7 OP
  615. // //32 7 经理
  616. // depId = 7;
  617. // if (post.Equals("酒店")) postId = 25;
  618. // else if (post.Equals("经理")) { postId = 32; }
  619. // else if (post.Equals("OP专员")) { postId = 28; }
  620. // else if (post.Equals("酒店预订")) { postId = 25; }
  621. // else if (post.Equals("商务邀请")) { postId = 27; }
  622. // else if (post.Equals("-")) { postId = 0; }
  623. // else if (post.Equals("签证专员")) { postId = 26; }
  624. // else if (post.Equals("OP操作")) { postId = 28; }
  625. // else if (post.Equals("司机")) { postId = 14; }
  626. // else if (post.Equals("国际交流部经理")) { postId = 32; }
  627. // else if (post.Equals("机票酒店")) { postId = 24; }
  628. // else if (post.Equals("签证")) { postId = 26; }
  629. // else if (post.Equals("票房")) { postId = 24; }
  630. // else if (post.Equals("票务专员")) { postId = 24; }
  631. // else if (post.Equals("酒店/机票")) { postId = 24; }
  632. // else if (post.Equals("OP")) { postId = 28; }
  633. // else if (post.Equals("主管")) { postId = 22; }
  634. // else if (post.Equals("订票专员")) { postId = 24; }
  635. // else if (post.Equals("机票")) { postId = 24; }
  636. // else if (post.Equals("国交部经理")) { postId = 32; }
  637. // else if (post.Equals("计调")) { postId = 23; }
  638. // else if (post.Equals("票务")) { postId = 24; }
  639. // else if (post.Equals("国交部主管")) { postId = 22; }
  640. // else if (post.Equals("暂无")) { postId = 22; }
  641. // else if (post.Equals("初级OP")) { postId = 28; }
  642. // else if (post.Equals("计调")) { postId = 23; }
  643. // else { postId = 0; }
  644. // break;
  645. // case 5: //会展部
  646. // //15 5 经理
  647. // //16 5 文案策划
  648. // //17 5 活动执行
  649. // //18 5 平面设计师
  650. // //19 5 3D设计师
  651. // depId = 5;
  652. // if (post.Equals("-")) postId = 16;
  653. // break;
  654. // case 6: //市场销售部
  655. // //20 6 经理
  656. // //21 6 市场专员
  657. // //53 6 主管
  658. // depId = 6;
  659. // if (post.Equals("主管")) postId = 53;
  660. // else if (post.Equals("-")) postId = 21;
  661. // else if (post.Equals("销售总监")) postId = 53;
  662. // else if (post.Equals("市场专员")) postId = 21;
  663. // else if (post.Equals("销售专员")) postId = 54;
  664. // else if (post.Equals("市场助理")) postId = 55;
  665. // else if (post.Equals("销售")) postId = 54;
  666. // break;
  667. // case 99: //总经办
  668. // //1 1 总经理
  669. // //2 1 副总经理
  670. // //3 1 总经理助理
  671. // depId = 1;
  672. // if (post.Equals("总经理")) postId = 1;
  673. // else if (post.Equals("副总")) postId = 2;
  674. // break;
  675. // case 107: //会议会展策划部
  676. // //15 5 经理
  677. // //16 5 文案策划
  678. // //17 5 活动执行
  679. // //18 5 平面设计师
  680. // //19 5 3D设计师
  681. // //56 5 销售
  682. // //46 5 网络推广
  683. // //57 5 市场推广
  684. // depId = 5;
  685. // if (post.Equals("销售")) postId = 56;
  686. // else if (post.Equals("策划执行")) postId = 16;
  687. // else if (post.Equals("策活动划")) postId = 16;
  688. // else if (post.Equals("活动执行")) postId = 17;
  689. // else if (post.Equals("网络媒介推广")) postId = 46;
  690. // else if (post.Equals("媒介主任")) postId = 46;
  691. // else if (post.Equals("公关部经理")) postId = 15;
  692. // else if (post.Equals("项目执行")) postId = 17;
  693. // else if (post.Equals("市场推广")) postId = 57;
  694. // else if (post.Equals("策划")) postId = 16;
  695. // else if (post.Equals("3D设计师")) postId = 19;
  696. // else if (post.Equals("平面设计")) postId = 18;
  697. // else if (post.Equals("设计")) postId = 18;
  698. // else if (post.Equals("活动策划")) postId = 16;
  699. // else if (post.Equals("活动策划执行")) postId = 17;
  700. // else if (post.Equals("高级活动策划")) postId = 16;
  701. // else postId = 0;
  702. // break;
  703. // case 115:
  704. // if (post.Equals("系统管理员")) { depId = 9; postId = 31; }
  705. // else if (post.Equals("后勤专员")) { depId = 5; postId = 58; }
  706. // break;
  707. // case 287: //会展部
  708. // //59 2 17 经理
  709. // //60 2 17 主管
  710. // //61 2 17 会展专员
  711. // //62 2 17 会展销售
  712. // //63 2 17 会展策划
  713. // //64 2 17 招商专员
  714. // //65 2 17 媒介专员
  715. // depId = 17;
  716. // if (post.Equals("会展部经理")) postId = 59;
  717. // else if (post.Equals("会展专员")) postId = 61;
  718. // else if (post.Equals("会展销售")) postId = 62;
  719. // else if (post.Equals("招商招展")) postId = 63;
  720. // else if (post.Equals("会展部主管")) postId = 60;
  721. // else if (post.Equals("媒介专员")) postId = 65;
  722. // else if (post.Equals("会展策划")) postId = 63;
  723. // else if (post.Equals("招商专员")) postId = 64;
  724. // else postId = 61;
  725. // break;
  726. // case 304: //总经理助理
  727. // //1 1 总经理
  728. // //2 1 副总经理
  729. // //3 1 总经理助理
  730. // depId = 1;
  731. // postId = 3;
  732. // break;
  733. // case 323: //海外游学部
  734. // //66 3 19 游学顾问
  735. // depId = 19;
  736. // postId = 66;
  737. // break;
  738. // case 335: //会议会展策划部
  739. // //15 5 经理
  740. // //16 5 文案策划
  741. // //17 5 活动执行
  742. // //18 5 平面设计师
  743. // //19 5 3D设计师
  744. // //56 5 销售
  745. // //46 5 网络推广
  746. // //57 5 市场推广
  747. // //67 5 策划主管
  748. // depId = 5;
  749. // if (post.Equals("会展专员")) { depId = 17; postId = 61; }
  750. // else if (post.Equals("策划执行")) postId = 16;
  751. // else if (post.Equals("策划主管")) postId = 67;
  752. // else if (post.Equals("策划")) postId = 16;
  753. // else if (post.Equals("文案")) postId = 16;
  754. // else if (post.Equals("策划执行")) postId = 17;
  755. // else if (post.Equals("执行专员 ")) postId = 17;
  756. // break;
  757. // case 761://项目部
  758. // //20 6 经理
  759. // //21 6 市场专员
  760. // //53 6 主管
  761. // if (post.Equals("销售主管")) { depId = 6; postId = 20; }
  762. // else if (post.Equals("场站经理")) { depId = 6; postId = 53; }
  763. // else if (post.Equals("暂无")) { depId = 5; postId = 58; }
  764. // else
  765. // {
  766. // if (oldUser.CnName.Equals("许婷"))
  767. // {
  768. // depId = 5; postId = 16;
  769. // }
  770. // else if (oldUser.CnName.Equals("陈雪"))
  771. // {
  772. // depId = 5; postId = 17;
  773. // }
  774. // }
  775. // break;
  776. // default:
  777. // break;
  778. // }
  779. // #endregion
  780. // string idCrad = string.Empty;
  781. // string idCradNumber = string.Empty;
  782. // DateTime? birthday = null;
  783. // if (!string.IsNullOrEmpty(oldUser.IDCard))
  784. // {
  785. // idCrad = oldUser.IDCard.Trim();
  786. // #region 处理身份证Number 出生日期
  787. // if (idCrad.ValidateIdNumber())
  788. // {
  789. // idCradNumber = idCrad.ToString();
  790. // string birthDate = idCrad.Substring(6, 8); // 提取从第6位开始的8个字符,即出生日期部分
  791. // birthday = new DateTime(int.Parse(birthDate.Substring(0, 4)), int.Parse(birthDate.Substring(4, 2)), int.Parse(birthDate.Substring(6, 2)));
  792. // }
  793. // #endregion
  794. // }
  795. // DateTime? startWorkDate = null;
  796. // #region 判断是否是日期格式的字符串
  797. // string format = "yyyy-MM-dd"; // 日期格式
  798. // DateTime date;
  799. // bool isParsed = DateTime.TryParseExact(oldUser.StartWorkDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
  800. // if (isParsed)
  801. // {
  802. // startWorkDate = date;
  803. // }
  804. // #endregion
  805. // int education = 0;
  806. // #region 处理学历
  807. // if (!string.IsNullOrEmpty(oldUser.Education))
  808. // {
  809. // //0 未设置 1 小学、2 初中、3 高中、4 专科、5 本科、6 研究生
  810. // if (oldUser.Education.Equals("本科")) education = 5;
  811. // else if (oldUser.Education.Equals("大学专科")) education = 4;
  812. // else if (oldUser.Education.Equals("大专")) education = 4;
  813. // else if (oldUser.Education.Equals("全日制本科")) education = 5;
  814. // else if (oldUser.Education.Equals("硕士")) education = 6;
  815. // else if (oldUser.Education.Equals("硕士研究生")) education = 6;
  816. // else if (oldUser.Education.Equals("学士")) education = 6;
  817. // else if (oldUser.Education.Equals("研究生")) education = 6;
  818. // else if (oldUser.Education.Equals("专科")) education = 4;
  819. // }
  820. // #endregion
  821. // int theOrAdultEducation = 0;
  822. // #region 处理统招/成人
  823. // if (!string.IsNullOrEmpty(oldUser.TheOrAdultEducation))
  824. // {
  825. // //0 未设置 1 成教 2 统招 3 留学
  826. // if (oldUser.TheOrAdultEducation.Equals("成教")) theOrAdultEducation = 1;
  827. // if (oldUser.TheOrAdultEducation.Equals("自考")) theOrAdultEducation = 1;
  828. // else if (oldUser.TheOrAdultEducation.Equals("统招")) theOrAdultEducation = 2;
  829. // else if (oldUser.TheOrAdultEducation.Equals("留学")) theOrAdultEducation = 3;
  830. // }
  831. // #endregion
  832. // Sys_Users user = new Sys_Users()
  833. // {
  834. // Id = oldUser.Id,
  835. // CnName = oldUser.CnName,
  836. // EnName = oldUser.EnName,
  837. // Number = oldUser.Number,
  838. // CompanyId = 2,
  839. // DepId = depId,
  840. // JobPostId = postId,
  841. // Password = oldUser.Password,
  842. // Sex = oldUser.Sex,
  843. // Ext = oldUser.Ext,
  844. // Phone = oldUser.Phone,
  845. // UrgentPhone = oldUser.UrgentPhone,
  846. // Email = oldUser.Email,
  847. // Address = oldUser.Address,
  848. // Edate = oldUser.Edate,
  849. // Rdate = oldUser.Rdate,
  850. // Seniority = oldUser.Seniority,
  851. // Birthday = birthday,
  852. // IDCard = idCradNumber,
  853. // StartWorkDate = startWorkDate,
  854. // GraduateInstitutions = oldUser.GraduateInstitutions,
  855. // Professional = oldUser.Professional,
  856. // Education = education,
  857. // TheOrAdultEducation = theOrAdultEducation,
  858. // MaritalStatus = oldUser.MaritalStatus,
  859. // HomeAddress = oldUser.HomeAddress,
  860. // UsePeriod = oldUser.UsePeriod,
  861. // WorkExperience = oldUser.WorkExperience,
  862. // Certificate = oldUser.Certificate,
  863. // HrAudit = 1,
  864. // CreateUserId = 208,
  865. // CreateTime = DateTime.Now,
  866. // DeleteUserId = null,
  867. // DeleteTime = string.Empty,
  868. // Remark = oldUser.Remark,
  869. // IsDel = oldUser.IsDel,
  870. // };
  871. // newOaUserDatas.Add(user);
  872. // }
  873. // if (newOaUserDatas.Count > 0)
  874. // {
  875. // //执行删除
  876. // bool resetStatus = _sqlSuar.DbMaintenance.TruncateTable<Sys_Users>();
  877. // //执行批量添加
  878. // int addTotal = await _sqlSuar.Insertable(newOaUserDatas).IgnoreColumns(it => it.Id).ExecuteCommandAsync();
  879. // }
  880. // view = new
  881. // {
  882. // Code = 200,
  883. // Msg = "操作成功!",
  884. // Data = newOaUserDatas
  885. // };
  886. // }
  887. // catch (Exception ex)
  888. // {
  889. // view = new
  890. // {
  891. // Code = 400,
  892. // Msg = ex.Message
  893. // };
  894. // }
  895. // return Ok(JsonView(view));
  896. //}
  897. /// <summary>
  898. /// 测试
  899. /// 创建员工号
  900. /// </summary>
  901. /// <param name="depId">部门Id</param>
  902. /// <returns></returns>
  903. [HttpPost("TestCreateUserNumber")]
  904. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  905. public async Task<IActionResult> TestCreateUserNumber(int depId)
  906. {
  907. try
  908. {
  909. var number = await _loginRep.CreateNumber(depId);
  910. return Ok(JsonView(true, "操作成功!", number));
  911. }
  912. catch (Exception ex)
  913. {
  914. return Ok(JsonView(false, "操作失败!", ex.Message));
  915. }
  916. }
  917. /// <summary>
  918. /// ClientTest
  919. /// </summary>
  920. /// <returns></returns>
  921. [HttpPost("ClientTest")]
  922. [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
  923. public async Task<IActionResult> ClientTest()
  924. {
  925. var _sqlsugar = _loginRep._sqlSugar;
  926. var groups = await _sqlsugar.Queryable<Grp_DelegationInfo>()
  927. .Where(x => x.IsDel == 0 && x.VisitDate >= Convert.ToDateTime("2024-01-01") && x.VisitDate <= Convert.ToDateTime("2024-12-31"))
  928. .Select(x => new { x.Id, x.TeamName, x.ClientUnit, x.ClientName, x.VisitDate })
  929. .ToListAsync();
  930. var newClients = await _sqlsugar.Queryable<Crm_NewClientData>()
  931. .Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Contact))
  932. .Select(x => new Crm_NewClientData() { Contact = x.Contact, Telephone = x.Telephone, Phone = x.Phone })
  933. .ToListAsync();
  934. foreach (var item in newClients) EncryptionProcessor.DecryptProperties(item);
  935. var datas = new List<NewClientInfo>();
  936. foreach (var group in groups)
  937. {
  938. var clientName = group.ClientName;
  939. var clientInfo = newClients.Find(x => !string.IsNullOrEmpty(clientName) && !string.IsNullOrEmpty(x.Contact) && clientName.Contains(x.Contact));
  940. if (clientInfo != null)
  941. {
  942. datas.Add(new NewClientInfo()
  943. {
  944. TeamName = group.TeamName,
  945. ClientUnit = group.ClientUnit,
  946. ClientName = group.ClientName,
  947. VisitDate = group.VisitDate,
  948. NewClientContact = clientInfo?.Contact ?? "",
  949. Telephone = clientInfo?.Telephone ?? "",
  950. Phone = clientInfo?.Phone ?? "",
  951. });
  952. }
  953. }
  954. datas = datas.OrderBy(x => x.VisitDate).ToList();
  955. return Ok(JsonView(datas));
  956. }
  957. public class NewClientInfo
  958. {
  959. public string TeamName { get; set; }
  960. public string ClientUnit { get; set; }
  961. public string ClientName { get; set; }
  962. public DateTime VisitDate { get; set; }
  963. public string NewClientContact { get; set; }
  964. public string Telephone { get; set; }
  965. public string Phone { get; set; }
  966. }
  967. }
  968. }