UserController.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Identity;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Caching.Memory;
  5. using Microsoft.Extensions.Logging;
  6. using NLog;
  7. using Org.BouncyCastle.Bcpg;
  8. using System;
  9. using WebAPIBase.API.Requests;
  10. using WebAPIBase.Service.Interface;
  11. using Newtonsoft.Json;
  12. using System.Net.Http;
  13. using System.Collections.Generic;
  14. using System.Threading.Tasks;
  15. using System.Net;
  16. using Sugar.Enties;
  17. using System.Text;
  18. using WebAPIBase.Utils;
  19. using Microsoft.Extensions.Configuration;
  20. using System.IO;
  21. using System.Collections.Specialized;
  22. using System.Linq;
  23. using System.Security.Claims;
  24. using System.IdentityModel.Tokens.Jwt;
  25. using Microsoft.IdentityModel.Tokens;
  26. using Newtonsoft.Json;
  27. namespace WebAPIBase.API.Controllers
  28. {
  29. [Produces("application/json;charset=UTF-8")]
  30. [Route("api/User")]
  31. public class UserController : BaseController
  32. {
  33. private string webserviceUrl;
  34. private static Logger Logger = NLog.LogManager.GetCurrentClassLogger();
  35. private readonly IHttpClientFactory _httpclientfactory;
  36. private IMemoryCache _memoryCache;
  37. private readonly SignInManager<AppUser> _signInManager;
  38. private readonly UserManager<AppUser> _userManager;
  39. private readonly IConfiguration _configuration;
  40. public UserController(IMemoryCache memoryCache, IHttpClientFactory httpclientfactory, UserManager<AppUser> userManager,
  41. SignInManager<AppUser> signInManager,
  42. IConfiguration configuration)
  43. {
  44. _httpclientfactory = httpclientfactory;
  45. _memoryCache = memoryCache;
  46. webserviceUrl = Configuration["Logging:AppSettings:webserviceUrl"];
  47. _userManager = userManager;
  48. _signInManager = signInManager;
  49. _configuration = configuration;
  50. }
  51. [AllowAnonymous]
  52. [HttpPost]
  53. [Route("")]
  54. public ActionResult ValidateUser([FromBody] UserLogin request)
  55. {
  56. Console.WriteLine("request:" + JsonConvert.SerializeObject(request));
  57. NameValueCollection values = new NameValueCollection();
  58. values.Add("userid", request.UserName);
  59. values.Add("password", request.Password);
  60. values.Add("dno", "");
  61. values.Add("dtoken", "");
  62. var result = WebClientHelper.ClientPost(webserviceUrl + "/Login", values);
  63. //Console.WriteLine(result);
  64. var login = JsonConvert.DeserializeObject<InterfaceLoginReturn>(result);
  65. Console.WriteLine($"login:{JsonConvert.SerializeObject(login)}");
  66. var user = new SystemUserManager().GetList(m => m.UserID == request.UserName).FirstOrDefault();
  67. var loginUser = new LoginUserDTO();
  68. loginUser.IsSuccess = login.result;
  69. //loginUser.IsSuccess = false;
  70. if (login != null && login.result)
  71. {
  72. var unitManager = new UnitManager();
  73. var userCode = login.data.userCode;
  74. var station = unitManager.GetUserStation(userCode);
  75. loginUser.ErrorMsg = "";
  76. loginUser.roles = new string[1] { "admin" };
  77. loginUser.introduction = login.data.userName;
  78. loginUser.name = login.data.userName;
  79. loginUser.token = login.data.userId;
  80. loginUser.stationCode = station.StationCode;
  81. loginUser.stationName = station.StationName;
  82. loginUser.departmentCode = unitManager.GetUserDepartmentCode(userCode);
  83. loginUser.departmentName = unitManager.GetUserDepartment(userCode);
  84. loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
  85. user = new SystemUser();
  86. user.UserCode = login.data.userCode;
  87. user.UserID = login.data.userId;
  88. user.UserName = login.data.userName;
  89. loginUser.User = user;
  90. }
  91. else
  92. {
  93. loginUser.ErrorMsg = login.msg;
  94. return Json(loginUser);
  95. //var unitManager = new UnitManager();
  96. //var userCode = user.UserCode;
  97. //var station = unitManager.GetUserStation(userCode);
  98. //loginUser.ErrorMsg = "";
  99. //loginUser.roles = new string[1] { "admin" };
  100. //loginUser.introduction = user.UserName;
  101. //loginUser.name = user.UserName;
  102. //loginUser.token = user.UserID;
  103. //loginUser.stationCode = station.StationCode;
  104. //loginUser.stationName = station.StationName;
  105. //loginUser.departmentCode = unitManager.GetUserDepartmentCode(userCode);
  106. //loginUser.departmentName = unitManager.GetUserDepartment(userCode);
  107. //loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
  108. //loginUser.User = user;
  109. }
  110. #region 写入系统日志
  111. var log = new SysBusinessLog();
  112. log.LogClass = "SystemUser";
  113. log.LogTime = DateTime.Now;
  114. log.ApplicationId2 = loginUser.User.UserCode;
  115. log.LogType = "登录";
  116. log.OperatePersonId = Convert.ToInt32(loginUser.User.UserCode);
  117. log.LogRemark = "";
  118. log.OperatePerson = loginUser.name;
  119. new SysBusinessLogManager().Insert(log); //插入系统日志
  120. #endregion
  121. //获取令牌,返回客户端
  122. AppUser appUser = new AppUser();
  123. appUser.UserName = user.UserName;
  124. appUser.Id = user.UserID;
  125. appUser.SystemUser = user;
  126. var token = GenerateJwtToken(appUser);
  127. loginUser.token = token;
  128. new Utils.CacheHelper(_memoryCache).SetCache(loginUser.User.UserID, loginUser.User);
  129. return Json(loginUser);
  130. }
  131. /// <summary>
  132. /// oa用户免密登录入口
  133. /// </summary>
  134. /// <param name="request"></param>
  135. /// <returns></returns>
  136. [AllowAnonymous]
  137. [HttpGet]
  138. [Route("sysloginoa")]
  139. public ActionResult LoginOa(string usercode)
  140. {
  141. var loginUser = new LoginUserDTO();
  142. if (usercode.IsNullOrEmpty())
  143. {
  144. loginUser.IsSuccess = true;
  145. loginUser.ErrorMsg = "请输入用户名";
  146. return Json(loginUser);
  147. }
  148. var user = new SystemUserManager().GetList(m => m.UserID == usercode).FirstOrDefault();
  149. if (user != null)
  150. {
  151. logger.Info($"【LoginOa】user:{JsonConvert.SerializeObject(user)}");
  152. loginUser.IsSuccess = true;
  153. var unitManager = new UnitManager();
  154. var userCode = user.UserCode;
  155. var station = unitManager.GetUserStation(userCode);
  156. loginUser.ErrorMsg = "";
  157. loginUser.roles = new string[1] { "admin" };
  158. loginUser.introduction = user.UserName;
  159. loginUser.name = user.UserName;
  160. loginUser.token = user.UserID;
  161. loginUser.stationCode = station.StationCode;
  162. loginUser.stationName = station.StationName;
  163. loginUser.departmentCode = unitManager.GetUserDepartmentCode(userCode);
  164. loginUser.departmentName = unitManager.GetUserDepartment(userCode);
  165. loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
  166. loginUser.User = user;
  167. }
  168. else
  169. {
  170. loginUser.IsSuccess = false;
  171. loginUser.ErrorMsg = "不存在的用户";
  172. return Json(loginUser);
  173. }
  174. #region 写入系统日志
  175. var log = new SysBusinessLog();
  176. log.LogClass = "SystemUser";
  177. log.LogTime = DateTime.Now;
  178. logger.Info($"【LoginOa】loginUser.User:{JsonConvert.SerializeObject(loginUser.User)}");
  179. log.ApplicationId2 = loginUser.User.UserCode;
  180. log.LogType = "登录";
  181. log.OperatePersonId = Convert.ToInt32(loginUser.User.UserCode);
  182. log.LogRemark = "";
  183. log.OperatePerson = loginUser.name;
  184. new SysBusinessLogManager().Insert(log); //插入系统日志
  185. #endregion
  186. //获取令牌,返回客户端
  187. AppUser appUser = new AppUser();
  188. appUser.UserName = user.UserName;
  189. appUser.Id = user.UserID;
  190. appUser.SystemUser = user;
  191. var token = GenerateJwtToken(appUser);
  192. loginUser.token = token;
  193. new Utils.CacheHelper(_memoryCache).SetCache(loginUser.User.UserID, loginUser.User);
  194. return Json(loginUser);
  195. }
  196. [AllowAnonymous]
  197. [HttpGet]
  198. [Route("getuserinfo")]
  199. public ActionResult GetUserInfo(string token)
  200. {
  201. Console.WriteLine("getuserinfo");
  202. Console.WriteLine("token:" + token);
  203. var ret = new Utils.CacheHelper(_memoryCache).GetCache(token);
  204. //Console.WriteLine("cache:" + JsonConvert.SerializeObject(ret));
  205. var loginUser = new LoginUserDTO();
  206. if (ret == null)
  207. {
  208. loginUser.IsSuccess = false;
  209. loginUser.ErrorMsg = "登录超时,请重新登录";
  210. }
  211. else
  212. {
  213. var user = (SystemUser)ret;
  214. loginUser.User = user;
  215. loginUser.IsSuccess = true;
  216. loginUser.ErrorMsg = "";
  217. loginUser.token = user.UserID;
  218. loginUser.name = user.UserName;
  219. loginUser.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
  220. loginUser.introduction = "";
  221. loginUser.roles = new string[1] { "admin" };
  222. }
  223. //Logger.Info(ret);
  224. return Json(loginUser);
  225. }
  226. [HttpGet]
  227. [Route("logout")]
  228. public ActionResult LogOut(string userid)
  229. {
  230. new Utils.CacheHelper(_memoryCache).DelCache(userid);
  231. return Json(new { code = 20000, data = "success" });
  232. }
  233. [AllowAnonymous]
  234. [HttpPost]
  235. [Route("create")]
  236. public JsonResult InsertUser(string username, string password, string confirmpassword)
  237. {
  238. if (password == confirmpassword)
  239. {
  240. //_userService.InsertUser(username, password);
  241. }
  242. return Json("User Created Successfully! :)");
  243. }
  244. private async Task<string> remoteHelper(string url, HttpContent content)
  245. {
  246. var result = string.Empty;
  247. try
  248. {
  249. using (var client = _httpclientfactory.CreateClient())
  250. using (var response = await client.PostAsync(url, content))
  251. {
  252. if (response.StatusCode == HttpStatusCode.OK)
  253. {
  254. result = await response.Content.ReadAsStringAsync();
  255. }
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. Console.WriteLine(ex);
  261. }
  262. return result;
  263. }
  264. private string GenerateJwtToken(AppUser user)
  265. {
  266. var claimsIdentity = new ClaimsIdentity(new[]
  267. {
  268. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  269. new Claim(ClaimTypes.NameIdentifier, user.Id),
  270. new Claim(ClaimTypes.Name, user.UserName),
  271. new Claim(ClaimTypes.Role, "Admin"),
  272. new Claim(ClaimTypes.UserData,JsonConvert.SerializeObject(user.SystemUser))
  273. }); ;
  274. var tokenHandler = new JwtSecurityTokenHandler();
  275. DateTime expiry = DateTime.UtcNow.AddMinutes(5);
  276. JwtSecurityToken token = tokenHandler.CreateJwtSecurityToken(new SecurityTokenDescriptor
  277. {
  278. Issuer = _configuration["JWT:Issuer"],
  279. Audience = _configuration["JWT:Audience"],
  280. Subject = claimsIdentity,
  281. IssuedAt = DateTime.UtcNow,
  282. Expires = expiry,
  283. SigningCredentials = new SigningCredentials(
  284. new SymmetricSecurityKey(
  285. Encoding.Default.GetBytes(_configuration["JWT:Key"])),
  286. SecurityAlgorithms.HmacSha256Signature)
  287. });
  288. return tokenHandler.WriteToken(token);
  289. }
  290. }
  291. }