| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136 |
-
- using Flurl.Http.Configuration;
- using Microsoft.AspNetCore.SignalR;
- using Microsoft.EntityFrameworkCore.Metadata.Internal;
- using NPOI.SS.Formula.Functions;
- using OASystem.API.OAMethodLib;
- using OASystem.API.OAMethodLib.Hotmail;
- using OASystem.API.OAMethodLib.Hub.HubClients;
- using OASystem.API.OAMethodLib.Hub.Hubs;
- using OASystem.API.OAMethodLib.QiYeWeChatAPI;
- using OASystem.Domain.AesEncryption;
- using OASystem.Domain.Attributes;
- using OASystem.Domain.Dtos.UserDto;
- using OASystem.Domain.Entities.Customer;
- using OASystem.Domain.Entities.Groups;
- using OASystem.Infrastructure.Repositories.Login;
- using System.IdentityModel.Tokens.Jwt;
- using System.Text.Json;
- using static OASystem.API.OAMethodLib.Hotmail.HotmailService;
- using static OASystem.API.OAMethodLib.JWTHelper;
- namespace OASystem.API.Controllers
- {
- /// <summary>
- /// 鉴权相关
- /// </summary>
- [Route("api/")]
- public class AuthController : ControllerBase
- {
- private readonly IMapper _mapper;
- private readonly IConfiguration _config;
- private readonly LoginRepository _loginRep;
- private readonly MessageRepository _message;
- private readonly SystemMenuPermissionRepository _sysMenuPermRep;
- private readonly MessageRepository _messageRep;
- private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
- private readonly IHubContext<ChatHub, IChatClient> _hubContext;
- private readonly DeviceTokenRepository _deviceTokenRep;
- private readonly HotmailService _hotmailService;
- private readonly System.Net.Http.IHttpClientFactory _httpClientFactory;
- /// <summary>
- ///
- /// </summary>
- /// <param name="config"></param>
- /// <param name="loginRep"></param>
- /// <param name="mapper"></param>
- /// <param name="message"></param>
- /// <param name="sysMenuPermRep"></param>
- /// <param name="qiYeWeChatApiService"></param>
- /// <param name="messageRep"></param>
- /// <param name="deviceRep"></param>
- /// <param name="hubContext"></param>
- /// <param name="hotmailService"></param>
- /// <param name="httpClientFactory"></param>
- public AuthController(
- IConfiguration config,
- LoginRepository loginRep,
- IMapper mapper,
- MessageRepository message,
- SystemMenuPermissionRepository sysMenuPermRep,
- IQiYeWeChatApiService qiYeWeChatApiService,
- MessageRepository messageRep,
- DeviceTokenRepository deviceRep,
- IHubContext<ChatHub,IChatClient> hubContext,
- HotmailService hotmailService,
- System.Net.Http.IHttpClientFactory httpClientFactory)
- {
- _config = config;
- _loginRep = loginRep;
- _mapper = mapper;
- _message = message;
- _sysMenuPermRep = sysMenuPermRep;
- _qiYeWeChatApiService = qiYeWeChatApiService;
- _messageRep = messageRep;
- _deviceTokenRep = deviceRep;
- _hubContext = hubContext;
- _hotmailService = hotmailService;
- _httpClientFactory = httpClientFactory;
- }
- /// <summary>
- /// 用户登录
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [Route("login")]
- [HttpPost]
- [ApiLog("Login", OperationEnum.Login)]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> LoginAsync(LoginDto dto)
- {
- if (string.IsNullOrWhiteSpace(dto.Number) || string.IsNullOrWhiteSpace(dto.Password))
- {
- return Ok(JsonView(false, "账号或密码不能为空!!"));
- }
- #region 校验用户信息
- var userData = _loginRep.Login(dto).Result;
- if (userData.Code != 0) return Ok(JsonView(false, userData.Msg));
- #endregion
- #region 限制销售部门 除gyy外可登录
- var userInfo = userData.Data as UserLoginInfoView;
- if (userInfo == null) return Ok(JsonView(false, userData.Msg));
- if (userInfo.DepName.Contains("市场部"))
- {
- var noLoginAuth = _config.GetSection("NoLoginAuth").Get<List<string>>();
- if (noLoginAuth.Any())
- {
- if (noLoginAuth.Contains(userInfo.CnName)) return Ok(JsonView(false, "NO ACCESS!!"));
- }
- //其他市场部人员 限制登录时间段
- var currentDateTime = DateTime.Now;
- var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
- var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
- if (currentDateTime < startTime && currentDateTime > endTime) return Ok(JsonView(false, "NO ACCESS!!"));
- }
- #endregion
- Result authData = null;
- string uName = string.Empty,
- role = string.Empty,
- depName = string.Empty;
- int uId = 0;
- int unReadCount = 0;
- int announcementUnReadCount = 0;
- if (userData.Data != null)
- {
- uId = (userData.Data as UserLoginInfoView).UserId;
- uName = (userData.Data as UserLoginInfoView).CnName;
- depName = (userData.Data as UserLoginInfoView).DepName;
- role = (userData.Data as UserLoginInfoView).JobName;
- authData = _sysMenuPermRep.QueryMenuLoad(uId, dto.PortType);
- unReadCount = await _messageRep.GetUnReadCount(uId);
- announcementUnReadCount = await _messageRep.GetAnnouncementUnReadCount(uId);
- }
- //_hubContext.Login(uId, uName);
- var view = new LoginView
- {
- UserInfo = userData?.Data,
- AuthData = authData?.Data,
- UnReadCount = unReadCount,
- AnnouncementUnReadCount = announcementUnReadCount
- };
- DateTime createZebraTime = DateTime.Now;
- string authorId = dto.Number + "Token";
- string authorToken = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>(authorId);//string 取
- if (authorToken != null)
- {
- #region 解析出过期时间
- var jwtHandler = new JwtSecurityTokenHandler();
- JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(authorToken);
- DateTime expDt = (securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
- #endregion
- if (expDt >= createZebraTime) //超时重新获取token
- {
- authorToken = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Department = depName, Role = role }); //
- }
- view.Expires = expDt;
- view.Token = authorToken;
- }
- else
- {
- view.Expires = createZebraTime.AddMinutes(30);
- //view.Token = await GeneralMethod.GetToken(_config, dto.Number, uId, uName, createZebraTime); //JwtHelper
- view.Token = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Department = depName, Role = role }); //
- TimeSpan ts = view.Expires.AddMinutes(-1) - createZebraTime; //设置redis 过期时间 比 jwt 时间 快一分钟
- await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(authorId, view.Token, ts);//string 存
- }
- //#region 添加登录用户上线信息
- //_hubContext.SignalRLogin(uId);
- //#endregion
- #region 测试添加系统消息
- //await _message.AddMsg(new MessageDto()
- //{
- // Type = 1,
- // IssuerId = 208,
- // Title = "测试添加消息标题",
- // Content = "消息体测试",
- // ReleaseTime = DateTime.Now,
- // UIdList = new List<int> {
- // 5,
- // 208,
- // 219
- // }
- //});
- #endregion
- return Ok(JsonView(view));
- }
- /// <summary>
- /// 移动端用户登录
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [Route("MobileLogin")]
- [HttpPost]
- [ApiLog("Login", OperationEnum.Login)]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> MobileLoginAsync(LoginDto dto)
- {
- if (string.IsNullOrWhiteSpace(dto.Number) || string.IsNullOrWhiteSpace(dto.Password))
- {
- return Ok(JsonView(false, "账号或密码不能为空!!"));
- }
- #region 校验用户信息
- var userData = _loginRep.Login(dto).Result;
- if (userData.Code != 0) return Ok(JsonView(false, userData.Msg));
- #endregion
- Result authData = null;
- string uName = string.Empty;
- string role = string.Empty;
- int uId = 0;
- int unReadCount = 0;
- int announcementUnReadCount = 0;
- if (userData.Data != null)
- {
- uId = (userData.Data as UserLoginInfoView).UserId;
- uName = (userData.Data as UserLoginInfoView).CnName;
- role = (userData.Data as UserLoginInfoView).JobName;
- authData = _sysMenuPermRep.MobileMenuLoad(uId, dto.PortType);
- unReadCount = await _messageRep.GetUnReadCount(uId);
- announcementUnReadCount = await _messageRep.GetAnnouncementUnReadCount(uId);
- }
- //_hubContext.Login(uId, uName);
- var view = new LoginView
- {
- UserInfo = userData?.Data,
- AuthData = authData?.Data,
- UnReadCount = unReadCount,
- AnnouncementUnReadCount = announcementUnReadCount
- };
- DateTime createZebraTime = DateTime.Now;
- string authorId = dto.Number + "Token";
- string authorToken = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>(authorId);//string 取
- if (authorToken != null)
- {
- #region 解析出过期时间
- var jwtHandler = new JwtSecurityTokenHandler();
- JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(authorToken);
- DateTime expDt = (securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
- #endregion
- if (expDt >= createZebraTime) //超时重新获取token
- {
- authorToken = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Role = role }); //
- }
- view.Expires = expDt;
- view.Token = authorToken;
- }
- else
- {
- view.Expires = createZebraTime.AddMinutes(30);
- //view.Token = await GeneralMethod.GetToken(_config, dto.Number, uId, uName, createZebraTime); //JwtHelper
- view.Token = await JwtHelper.IssueJwtAsync(new TokenModelJwt() { UserId = uId, UserName = uName, Role = role }); //
- TimeSpan ts = view.Expires.AddMinutes(-1) - createZebraTime; //设置redis 过期时间 比 jwt 时间 快一分钟
- await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(authorId, view.Token, ts);//string 存
- }
- //#region 添加登录用户上线信息
- //_hubContext.SignalRLogin(uId);
- //#endregion
- #region 测试添加系统消息
- //await _message.AddMsg(new MessageDto()
- //{
- // Type = 1,
- // IssuerId = 208,
- // Title = "测试添加消息标题",
- // Content = "消息体测试",
- // ReleaseTime = DateTime.Now,
- // UIdList = new List<int> {
- // 5,
- // 208,
- // 219
- // }
- //});
- #endregion
- return Ok(JsonView(view));
- }
- /// <summary>
- /// 申请注册 数据Data
- /// </summary>
- /// <returns></returns>
- //[Authorize]
- [HttpPost]
- [Route("register/daraSource")]
- public async Task<IActionResult> RegisterDataSource()
- {
- string sql = string.Format(@"Select sc.Id CompanyId,sc.CompanyName,sd.Id DepId,sd.DepName,sjp.Id JobId,sjp.JobName From Sys_Company sc
- Left Join Sys_Department sd On sd.IsDel = 0 And sc.Id = sd.CompanyId
- Left Join Sys_JobPost sjp On sjp.IsDel = 0 And sjp.DepId = sd.Id
- Where sc.IsDel = 0");
- var companyDetails = _loginRep._sqlSugar.SqlQueryable<CompanyDetailsView>(sql).ToList();
- var detailsView1 = new List<CompanyDetailsView1>();
- if (companyDetails.Count > 0)
- {
- var companyDetails1 = companyDetails.GroupBy(it => it.CompanyId).Select(it => it.First()).ToList();
- detailsView1 = companyDetails1.Select(it =>
- {
- var itemCompany = new CompanyDetailsView1();
- var depDetailsView = new List<DepDetailsView>();
- var companyDetails2 = companyDetails.GroupBy(it => it.DepId).Select(it => it.First()).ToList();
- //部门
- depDetailsView = companyDetails2.Where(depIt => depIt.CompanyId == it.CompanyId).Select(depIt =>
- {
- var depDetails = new DepDetailsView();
- var jobDetails = new List<JobDetailsView>();
- //岗位
- jobDetails = companyDetails.Where(jobIt => jobIt.DepId == depIt.DepId).Select(jobIt =>
- {
- var jobDetail = new JobDetailsView()
- {
- JobId = jobIt.JobId,
- JobName = jobIt.JobName,
- };
- return jobDetail;
- }).ToList();
- depDetails.DepId = depIt.DepId;
- depDetails.DepName = depIt.DepName;
- depDetails.SubJob = jobDetails;
- return depDetails;
- }).ToList();
- itemCompany.CompanyId = it.CompanyId;
- itemCompany.CompanyName = it.CompanyName;
- itemCompany.SubDep = depDetailsView;
- return itemCompany;
- }).ToList();
- }
- return Ok(new { Code = 200, Msg = "查询成功!", Data = detailsView1 });
- }
- /// <summary>
- /// 申请注册
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- //[Authorize]
- [HttpPost]
- [Route("register")]
- public async Task<IActionResult> Register(RegisterDto dto)
- {
- #region 企业微信添加员工
- //string lastName = dto.CnName.Substring(0, 1);
- //string lastNamePy = string.Empty;
- //if (PinyinHelper.IsChinese(Convert.ToChar(lastName)))
- //{
- // lastNamePy = PinyinHelper.GetPinyin(lastName);
- //}
- //string userId = string.Format("{0}.{1}", dto.EnName, lastNamePy.ToLower());
- //Create_Request request = new Create_Request()
- //{
- // userid = userId,
- // name = dto.CnName,
- // mobile = dto.Phone,
- // department = new List<long>() { dto.DepId },
- // position = dto.JobPostId.ToString(),
- // gender = dto.Sex == 0 ? 1 : dto.Sex == 1 ? 2 : 1,
- // biz_mail = dto.Email
- //};
- //var qiYeWeChatCreateData = await _qiYeWeChatApiServic.CreateAsync(request);
- #endregion
- var userData = _loginRep.Register(dto);
- if (userData.Result.Code != 0)
- {
- return Ok(JsonView(false, userData.Result.Msg));
- }
- return Ok(JsonView(true, userData.Result.Msg));
- }
- /// <summary>
- /// 修改密码
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [Authorize]
- [HttpPost]
- [Route("UpdPassword")]
- public async Task<IActionResult> UpdateUserPassword(UpdateDto dto)
- {
- //Result result = new Result();
- //var httpContext = HttpContext.User.Claims.FirstOrDefault(it => it.Type == ClaimTypes.Name)?.Value;
- //Sys_Users sys_Users = _mapper.Map<Sys_Users>(dto);
- var _view = await _loginRep.ChangePassword(dto.UserId, dto.Password);
- if (_view.Code == 0) return Ok(JsonView(true, "操作成功!"));
- return Ok(JsonView(false, _view.Msg));
- }
- /// <summary>
- /// 保存deviceToken
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [HttpPost("SaveDeviceToken")]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> SaveDeviceToken(SaveDeviceToken dto)
- {
- var view = await _deviceTokenRep.SaveToken(dto);
- if (view.Code == 0) return Ok(JsonView(true, "操作成功!"));
- return Ok(JsonView(false, view.Msg));
- }
- /// <summary>
- /// 获取deviceToken
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [HttpPost("GetDeviceToken")]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> GetDeviceToken(GetDeviceToken dto)
- {
- var view = await _deviceTokenRep.GetToken(dto.account);
- if (view.Code == 0) return Ok(JsonView(true, "操作成功!", view.Data));
- return Ok(JsonView(false, view.Msg));
- }
- #region microsoft 鉴权验证
- /// <summary>
- /// microsoft - hotmail 鉴权验证
- /// </summary>
- /// <returns></returns>
- [HttpGet("microsoft/auth/verify/{currUserId}")]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> MicrosoftHotmailPrepareAuth(int currUserId)
- {
- var (code, message) = await _hotmailService.PrepareAuth(currUserId);
- return code switch
- {
- // 无需授权
- 0 => Ok(JsonView(true, "已通过验证", new { isAuth = false })),
- // 需要跳转授权 (1)
- 1 => Ok(JsonView(true, "请点击链接进行 Auth 验证!", new { isAuth = true, url = message })),
- //1 => Redirect(message),
- // 配置错误或异常 (-1)
- _ => Ok(JsonView(false, message))
- };
- }
- /// <summary>
- /// microsoft auth 回调
- /// </summary>
- /// <param name="code"></param>
- /// <param name="state"></param>
- /// <returns></returns>
- [HttpGet("microsoft/auth/callback")]
- public async Task<IActionResult> HandleCallback([FromQuery] string code, [FromQuery] string state)
- {
- if (string.IsNullOrEmpty(code)) return BadRequest("授权码无效");
- // 1. 状态与配置校验
- if (!int.TryParse(state, out int userId)) return BadRequest("非法的 state 标识");
- var config = await _hotmailService.GetUserMailConfig(userId);
- if (config == null) return BadRequest("对应配置信息不存在");
- try
- {
- // 2. 换取令牌 (使用严格的参数清洗)
- var httpClient = _httpClientFactory.CreateClient();
- var tokenRequest = new Dictionary<string, string>
- {
- { "client_id", config.ClientId.Trim() },
- { "client_secret", config.ClientSecret.Trim() },
- { "code", code },
- { "redirect_uri", config.RedirectUri.Trim() }, // 确保与 PrepareAuth 阶段完全一致
- { "grant_type", "authorization_code" },
- // 换取时再次明确 scope
- { "scope", "offline_access Mail.Read Mail.Send User.Read" }
- };
- var response = await httpClient.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", new FormUrlEncodedContent(tokenRequest));
- var responseContent = await response.Content.ReadAsStringAsync();
- if (!response.IsSuccessStatusCode) return BadRequest($"令牌交换失败: {responseContent}");
- var root = JsonDocument.Parse(responseContent).RootElement;
- // 3. 提取令牌 (准则:确保 refresh_token 存在)
- var accessToken = root.GetProperty("access_token").GetString()!;
- var refreshToken = root.TryGetProperty("refresh_token", out var rt) ? rt.GetString()! : null;
- var expiresIn = root.GetProperty("expires_in").GetInt32();
- if (string.IsNullOrEmpty(refreshToken))
- return BadRequest("未能获取长效刷新令牌,请检查 offline_access 权限。");
- // 4. 获取用户信息
- string userEmail = await GetEmailFromGraphApiAsync(accessToken);
- // 5. 缓存 (准则 2 & 3)
- var userToken = new UserToken
- {
- Email = userEmail,
- AccessToken = accessToken,
- RefreshToken = refreshToken,
- ExpiresAt = DateTime.UtcNow.AddSeconds(expiresIn),
- Source = "Microsoft_Graph" // 准则 3: 增加标识
- };
- // Redis 缓存 (用于 API 快速调用)
- var redisKey = HotmailService.GetRedisKey(userEmail);
- await RedisRepository.RedisFactory.CreateRedisRepository()
- .StringSetAsync(redisKey, userToken, TimeSpan.FromDays(90));
- // 6. 返回结果
- return Ok(new
- {
- status = "Success",
- account = userEmail,
- expiresInSeconds = expiresIn,
- source = userToken.Source
- });
- }
- catch (Exception ex)
- {
- // _logger.LogError(ex, "Callback processing failed");
- return StatusCode(500, "回调失败,请检查控制台日志");
- }
- }
- private async Task<string> GetEmailFromGraphApiAsync(string accessToken)
- {
- // 1. 使用 HttpClientFactory 获取预设或独立的 Client
- var httpClient = _httpClientFactory.CreateClient("MicrosoftGraph");
- // 2. 构造请求头
- var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
- request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
- // 3. 发送请求并确保成功
- var response = await httpClient.SendAsync(request);
- if (!response.IsSuccessStatusCode)
- {
- var errorContent = await response.Content.ReadAsStringAsync();
- throw new Exception($"Graph API 身份验证失败: {response.StatusCode}, {errorContent}");
- }
- // 4. 安全解析 JSON
- using var doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
- var root = doc.RootElement;
- // 优先序:mail (邮箱) > userPrincipalName (登录名)
- string? email = null;
- if (root.TryGetProperty("mail", out var mailProp))
- email = mailProp.GetString();
- if (string.IsNullOrEmpty(email) && root.TryGetProperty("userPrincipalName", out var upnProp))
- email = upnProp.GetString();
- if (string.IsNullOrWhiteSpace(email))
- throw new Exception("Graph API 返回结果中缺失有效的身份标识 (mail/upn)");
- return email.Trim().ToLower(); // 准则:归一化存储,避免大小写导致的缓存失效
- }
- #endregion
- /// <summary>
- /// 测试auth
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [OASystemAuthentication]
- [HttpPost("TestToken")]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> TestToken(LoginDto dto)
- {
- string authorId = dto.Number + "Token";
- // 从Redis里面取数据
- //string userToken = _redis.StringGet(authorId);
- string userToken = "";
- var view = new LoginView
- {
- Token = authorId + ":" + userToken
- };
- return Ok(JsonView(view));
- }
- /// <summary>
- /// 限流测试
- /// </summary>
- /// <returns></returns>
- [HttpGet("rate-test")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public IActionResult RateTest()
- {
- return Ok(JsonView(true, $"限流测试 - IP:{HttpContext.Connection.RemoteIpAddress?.ToString()}", null, GetRequestCount()));
- }
- private static int _requestCount = 0;
- private int GetRequestCount()
- {
- return ++_requestCount;
- }
- ///// <summary>
- ///// 员工信息 迁移
- ///// Old OA To New OA
- ///// </summary>
- ///// <returns></returns>
- //[HttpPost("UpdateUserDataOldOAToNewOA")]
- //[ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- //public async Task<IActionResult> UpdateUserDataOldOAToNewOA()
- //{
- // dynamic view = null;
- // try
- // {
- // var _sqlSuar = _loginRep._sqlSugar;
- // var oldOaUsersData = await _sqlSuar.Queryable<OA2014UsersView>().AS("OA2014.dbo.Users").ToListAsync();
- // var newOaCompanyData = await _sqlSuar.Queryable<Sys_Company>().ToListAsync();
- // var newOaDepartmentData = await _sqlSuar.Queryable<Sys_Department>().ToListAsync();
- // var newOaJobPostData = await _sqlSuar.Queryable<Sys_JobPost>().ToListAsync();
- // List<Sys_Users> newOaUserDatas = new List<Sys_Users>();
- // foreach (var oldUser in oldOaUsersData)
- // {
- // int depId = 0, postId = 0;
- // #region 处理部门岗位
- // int did = oldUser.Did;
- // string post = oldUser.Post;
- // switch (did)
- // {
- // case 1 : //信息部
- // depId = 2;
- // if (post.Equals("信息部经理")) postId = 4;
- // else if (post.Equals("美工")) { depId = 5; postId = 18; }
- // else if(post.Equals("网络推广")) postId = 46;
- // else if (post.Equals("软件开发")) postId = 5;
- // else if (post.Equals("平面设计师")) { depId = 5; postId = 18; }
- // else if (post.Equals("平面设计")) { depId = 5; postId = 18; }
- // else if (post.Equals("平面设计师")) { depId = 5; postId = 18; }
- // else if (post.Equals("软件工程师")) postId = 5;
- // else if (post.Equals("OP操作")) { depId = 7; postId = 28; }
- // else if (post.Equals("软件工程师.")) postId = 5;
- // else if (post.Equals(".net工程师")) postId = 5;
- // else if (post.Equals("安卓开发工程师")) postId = 7;
- // else if (post.Equals("web前端")) postId = 6;
- // else if (post.Equals("Web后端开发")) postId = 5;
- // break;
- // case 2 : //财务部
- // depId=3;
- // if (post.Equals("主管")) postId = 47;
- // else if (post.Equals("财务总监")) { postId = 9; }
- // else if (post.Equals("会计")) { postId = 10; }
- // else if (post.Equals("财务经理")) { postId = 47; }
- // else if (post.Equals("财务助理")) { postId = 50; }
- // else if (post.Equals("出纳")) { postId = 48; }
- // else { postId = 10; }
- // break;
- // case 3: //人事部
- // depId = 4;
- // if (post.Equals("主管")) postId = 51;
- // else if (post.Equals("人事部主管")) { postId = 51; }
- // else if (post.Equals("人事行政主管")) { postId = 51; }
- // else if (post.Equals("行政人事助理")) { postId = 52; }
- // else if (post.Equals("人事助理")) { postId = 52; }
- // else if (post.Equals("人事主管")) { postId = 51; }
- // else if (post.Equals("行政人事专员")) { postId = 12; }
- // else if (post.Equals("行政司机")) { postId = 14; }
- // else if (post.Equals("司机")) { postId = 14; }
- // else if (post.Equals("统筹执行")) { postId = 12; }
- // else if (post.Equals("培训专员")) { postId = 13; }
- // else if (post.Equals("人事经理")) { postId = 11; }
- // else if (post.Equals("前台")) { postId = 33; }
- // else if (post.Equals("人事行政经理")) { postId = 11; }
- // else if (post.Equals("人事部经理")) { postId = 11; }
- // else if (post.Equals("人事专员")) { postId = 12; }
- // else if (post.Equals("人事经理")) { postId = 11; }
- // else postId = 12;
- // break;
- // case 4: //国交部
- // //22 7 主管
- // //23 7 计调
- // //24 7 机票
- // //25 7 酒店
- // //26 7 签证
- // //27 7 商邀
- // //28 7 OP
- // //32 7 经理
- // depId = 7;
- // if (post.Equals("酒店")) postId = 25;
- // else if (post.Equals("经理")) { postId = 32; }
- // else if (post.Equals("OP专员")) { postId = 28; }
- // else if (post.Equals("酒店预订")) { postId = 25; }
- // else if (post.Equals("商务邀请")) { postId = 27; }
- // else if (post.Equals("-")) { postId = 0; }
- // else if (post.Equals("签证专员")) { postId = 26; }
- // else if (post.Equals("OP操作")) { postId = 28; }
- // else if (post.Equals("司机")) { postId = 14; }
- // else if (post.Equals("国际交流部经理")) { postId = 32; }
- // else if (post.Equals("机票酒店")) { postId = 24; }
- // else if (post.Equals("签证")) { postId = 26; }
- // else if (post.Equals("票房")) { postId = 24; }
- // else if (post.Equals("票务专员")) { postId = 24; }
- // else if (post.Equals("酒店/机票")) { postId = 24; }
- // else if (post.Equals("OP")) { postId = 28; }
- // else if (post.Equals("主管")) { postId = 22; }
- // else if (post.Equals("订票专员")) { postId = 24; }
- // else if (post.Equals("机票")) { postId = 24; }
- // else if (post.Equals("国交部经理")) { postId = 32; }
- // else if (post.Equals("计调")) { postId = 23; }
- // else if (post.Equals("票务")) { postId = 24; }
- // else if (post.Equals("国交部主管")) { postId = 22; }
- // else if (post.Equals("暂无")) { postId = 22; }
- // else if (post.Equals("初级OP")) { postId = 28; }
- // else if (post.Equals("计调")) { postId = 23; }
- // else { postId = 0; }
- // break;
- // case 5: //会展部
- // //15 5 经理
- // //16 5 文案策划
- // //17 5 活动执行
- // //18 5 平面设计师
- // //19 5 3D设计师
- // depId = 5;
- // if (post.Equals("-")) postId = 16;
- // break;
- // case 6: //市场销售部
- // //20 6 经理
- // //21 6 市场专员
- // //53 6 主管
- // depId = 6;
- // if (post.Equals("主管")) postId = 53;
- // else if (post.Equals("-")) postId = 21;
- // else if (post.Equals("销售总监")) postId = 53;
- // else if (post.Equals("市场专员")) postId = 21;
- // else if (post.Equals("销售专员")) postId = 54;
- // else if (post.Equals("市场助理")) postId = 55;
- // else if (post.Equals("销售")) postId = 54;
- // break;
- // case 99: //总经办
- // //1 1 总经理
- // //2 1 副总经理
- // //3 1 总经理助理
- // depId = 1;
- // if (post.Equals("总经理")) postId = 1;
- // else if (post.Equals("副总")) postId = 2;
- // break;
- // case 107: //会议会展策划部
- // //15 5 经理
- // //16 5 文案策划
- // //17 5 活动执行
- // //18 5 平面设计师
- // //19 5 3D设计师
- // //56 5 销售
- // //46 5 网络推广
- // //57 5 市场推广
- // depId = 5;
- // if (post.Equals("销售")) postId = 56;
- // else if (post.Equals("策划执行")) postId = 16;
- // else if (post.Equals("策活动划")) postId = 16;
- // else if (post.Equals("活动执行")) postId = 17;
- // else if (post.Equals("网络媒介推广")) postId = 46;
- // else if (post.Equals("媒介主任")) postId = 46;
- // else if (post.Equals("公关部经理")) postId = 15;
- // else if (post.Equals("项目执行")) postId = 17;
- // else if (post.Equals("市场推广")) postId = 57;
- // else if (post.Equals("策划")) postId = 16;
- // else if (post.Equals("3D设计师")) postId = 19;
- // else if (post.Equals("平面设计")) postId = 18;
- // else if (post.Equals("设计")) postId = 18;
- // else if (post.Equals("活动策划")) postId = 16;
- // else if (post.Equals("活动策划执行")) postId = 17;
- // else if (post.Equals("高级活动策划")) postId = 16;
- // else postId = 0;
- // break;
- // case 115:
- // if (post.Equals("系统管理员")) { depId = 9; postId = 31; }
- // else if (post.Equals("后勤专员")) { depId = 5; postId = 58; }
- // break;
- // case 287: //会展部
- // //59 2 17 经理
- // //60 2 17 主管
- // //61 2 17 会展专员
- // //62 2 17 会展销售
- // //63 2 17 会展策划
- // //64 2 17 招商专员
- // //65 2 17 媒介专员
- // depId = 17;
- // if (post.Equals("会展部经理")) postId = 59;
- // else if (post.Equals("会展专员")) postId = 61;
- // else if (post.Equals("会展销售")) postId = 62;
- // else if (post.Equals("招商招展")) postId = 63;
- // else if (post.Equals("会展部主管")) postId = 60;
- // else if (post.Equals("媒介专员")) postId = 65;
- // else if (post.Equals("会展策划")) postId = 63;
- // else if (post.Equals("招商专员")) postId = 64;
- // else postId = 61;
- // break;
- // case 304: //总经理助理
- // //1 1 总经理
- // //2 1 副总经理
- // //3 1 总经理助理
- // depId = 1;
- // postId = 3;
- // break;
- // case 323: //海外游学部
- // //66 3 19 游学顾问
- // depId = 19;
- // postId = 66;
- // break;
- // case 335: //会议会展策划部
- // //15 5 经理
- // //16 5 文案策划
- // //17 5 活动执行
- // //18 5 平面设计师
- // //19 5 3D设计师
- // //56 5 销售
- // //46 5 网络推广
- // //57 5 市场推广
- // //67 5 策划主管
- // depId = 5;
- // if (post.Equals("会展专员")) { depId = 17; postId = 61; }
- // else if (post.Equals("策划执行")) postId = 16;
- // else if (post.Equals("策划主管")) postId = 67;
- // else if (post.Equals("策划")) postId = 16;
- // else if (post.Equals("文案")) postId = 16;
- // else if (post.Equals("策划执行")) postId = 17;
- // else if (post.Equals("执行专员 ")) postId = 17;
- // break;
- // case 761://项目部
- // //20 6 经理
- // //21 6 市场专员
- // //53 6 主管
- // if (post.Equals("销售主管")) { depId = 6; postId = 20; }
- // else if (post.Equals("场站经理")) { depId = 6; postId = 53; }
- // else if (post.Equals("暂无")) { depId = 5; postId = 58; }
- // else
- // {
- // if (oldUser.CnName.Equals("许婷"))
- // {
- // depId = 5; postId = 16;
- // }
- // else if (oldUser.CnName.Equals("陈雪"))
- // {
- // depId = 5; postId = 17;
- // }
- // }
- // break;
- // default:
- // break;
- // }
- // #endregion
- // string idCrad = string.Empty;
- // string idCradNumber = string.Empty;
- // DateTime? birthday = null;
- // if (!string.IsNullOrEmpty(oldUser.IDCard))
- // {
- // idCrad = oldUser.IDCard.Trim();
- // #region 处理身份证Number 出生日期
- // if (idCrad.ValidateIdNumber())
- // {
- // idCradNumber = idCrad.ToString();
- // string birthDate = idCrad.Substring(6, 8); // 提取从第6位开始的8个字符,即出生日期部分
- // birthday = new DateTime(int.Parse(birthDate.Substring(0, 4)), int.Parse(birthDate.Substring(4, 2)), int.Parse(birthDate.Substring(6, 2)));
- // }
- // #endregion
- // }
- // DateTime? startWorkDate = null;
- // #region 判断是否是日期格式的字符串
- // string format = "yyyy-MM-dd"; // 日期格式
- // DateTime date;
- // bool isParsed = DateTime.TryParseExact(oldUser.StartWorkDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
- // if (isParsed)
- // {
- // startWorkDate = date;
- // }
- // #endregion
- // int education = 0;
- // #region 处理学历
- // if (!string.IsNullOrEmpty(oldUser.Education))
- // {
- // //0 未设置 1 小学、2 初中、3 高中、4 专科、5 本科、6 研究生
- // if (oldUser.Education.Equals("本科")) education = 5;
- // else if (oldUser.Education.Equals("大学专科")) education = 4;
- // else if (oldUser.Education.Equals("大专")) education = 4;
- // else if (oldUser.Education.Equals("全日制本科")) education = 5;
- // else if (oldUser.Education.Equals("硕士")) education = 6;
- // else if (oldUser.Education.Equals("硕士研究生")) education = 6;
- // else if (oldUser.Education.Equals("学士")) education = 6;
- // else if (oldUser.Education.Equals("研究生")) education = 6;
- // else if (oldUser.Education.Equals("专科")) education = 4;
- // }
- // #endregion
- // int theOrAdultEducation = 0;
- // #region 处理统招/成人
- // if (!string.IsNullOrEmpty(oldUser.TheOrAdultEducation))
- // {
- // //0 未设置 1 成教 2 统招 3 留学
- // if (oldUser.TheOrAdultEducation.Equals("成教")) theOrAdultEducation = 1;
- // if (oldUser.TheOrAdultEducation.Equals("自考")) theOrAdultEducation = 1;
- // else if (oldUser.TheOrAdultEducation.Equals("统招")) theOrAdultEducation = 2;
- // else if (oldUser.TheOrAdultEducation.Equals("留学")) theOrAdultEducation = 3;
- // }
- // #endregion
- // Sys_Users user = new Sys_Users()
- // {
- // Id = oldUser.Id,
- // CnName = oldUser.CnName,
- // EnName = oldUser.EnName,
- // Number = oldUser.Number,
- // CompanyId = 2,
- // DepId = depId,
- // JobPostId = postId,
- // Password = oldUser.Password,
- // Sex = oldUser.Sex,
- // Ext = oldUser.Ext,
- // Phone = oldUser.Phone,
- // UrgentPhone = oldUser.UrgentPhone,
- // Email = oldUser.Email,
- // Address = oldUser.Address,
- // Edate = oldUser.Edate,
- // Rdate = oldUser.Rdate,
- // Seniority = oldUser.Seniority,
- // Birthday = birthday,
- // IDCard = idCradNumber,
- // StartWorkDate = startWorkDate,
- // GraduateInstitutions = oldUser.GraduateInstitutions,
- // Professional = oldUser.Professional,
- // Education = education,
- // TheOrAdultEducation = theOrAdultEducation,
- // MaritalStatus = oldUser.MaritalStatus,
- // HomeAddress = oldUser.HomeAddress,
- // UsePeriod = oldUser.UsePeriod,
- // WorkExperience = oldUser.WorkExperience,
- // Certificate = oldUser.Certificate,
- // HrAudit = 1,
- // CreateUserId = 208,
- // CreateTime = DateTime.Now,
- // DeleteUserId = null,
- // DeleteTime = string.Empty,
- // Remark = oldUser.Remark,
- // IsDel = oldUser.IsDel,
- // };
- // newOaUserDatas.Add(user);
- // }
- // if (newOaUserDatas.Count > 0)
- // {
- // //执行删除
- // bool resetStatus = _sqlSuar.DbMaintenance.TruncateTable<Sys_Users>();
- // //执行批量添加
- // int addTotal = await _sqlSuar.Insertable(newOaUserDatas).IgnoreColumns(it => it.Id).ExecuteCommandAsync();
- // }
- // view = new
- // {
- // Code = 200,
- // Msg = "操作成功!",
- // Data = newOaUserDatas
- // };
- // }
- // catch (Exception ex)
- // {
- // view = new
- // {
- // Code = 400,
- // Msg = ex.Message
- // };
- // }
- // return Ok(JsonView(view));
- //}
- /// <summary>
- /// 测试
- /// 创建员工号
- /// </summary>
- /// <param name="depId">部门Id</param>
- /// <returns></returns>
- [HttpPost("TestCreateUserNumber")]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> TestCreateUserNumber(int depId)
- {
- try
- {
- var number = await _loginRep.CreateNumber(depId);
- return Ok(JsonView(true, "操作成功!", number));
- }
- catch (Exception ex)
- {
- return Ok(JsonView(false, "操作失败!", ex.Message));
- }
- }
- /// <summary>
- /// ClientTest
- /// </summary>
- /// <returns></returns>
- [HttpPost("ClientTest")]
- [ProducesResponseType(typeof(LoginView), StatusCodes.Status200OK)]
- public async Task<IActionResult> ClientTest()
- {
- var _sqlsugar = _loginRep._sqlSugar;
- var groups = await _sqlsugar.Queryable<Grp_DelegationInfo>()
- .Where(x => x.IsDel == 0 && x.VisitDate >= Convert.ToDateTime("2024-01-01") && x.VisitDate <= Convert.ToDateTime("2024-12-31"))
- .Select(x => new { x.Id, x.TeamName, x.ClientUnit, x.ClientName, x.VisitDate })
- .ToListAsync();
- var newClients = await _sqlsugar.Queryable<Crm_NewClientData>()
- .Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Contact))
- .Select(x => new Crm_NewClientData() { Contact = x.Contact, Telephone = x.Telephone, Phone = x.Phone })
- .ToListAsync();
- foreach (var item in newClients) EncryptionProcessor.DecryptProperties(item);
- var datas = new List<NewClientInfo>();
- foreach (var group in groups)
- {
- var clientName = group.ClientName;
- var clientInfo = newClients.Find(x => !string.IsNullOrEmpty(clientName) && !string.IsNullOrEmpty(x.Contact) && clientName.Contains(x.Contact));
- if (clientInfo != null)
- {
- datas.Add(new NewClientInfo()
- {
- TeamName = group.TeamName,
- ClientUnit = group.ClientUnit,
- ClientName = group.ClientName,
- VisitDate = group.VisitDate,
- NewClientContact = clientInfo?.Contact ?? "",
- Telephone = clientInfo?.Telephone ?? "",
- Phone = clientInfo?.Phone ?? "",
- });
- }
- }
- datas = datas.OrderBy(x => x.VisitDate).ToList();
- return Ok(JsonView(datas));
- }
- public class NewClientInfo
- {
- public string TeamName { get; set; }
- public string ClientUnit { get; set; }
- public string ClientName { get; set; }
- public DateTime VisitDate { get; set; }
- public string NewClientContact { get; set; }
- public string Telephone { get; set; }
- public string Phone { get; set; }
- }
- }
- }
|