using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Api.SignToken; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; using Microsoft.Extensions.Configuration; using MadRunFabric.Common; using Microsoft.Extensions.Logging; using SignTokenApi.IRepositories; using Microsoft.Extensions.Caching.Distributed; using MongoDB.Bson; using SignTokenApi.Repositories; using NLog; using MadRunFabric.Model; using System.Linq; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace SignTokenApi.Controllers { [Authorize] [Route("api/[controller]")] public class TokenController : BaseController { private readonly IConfiguration _configuration; private readonly ILogger _logger; private readonly IDistributedCache _cache; private readonly ISys_User_AccountRepository _sys_user_accountRepository; private readonly ISys_Role_InfoRepository _sys_roleinfoRepository; private readonly ISys_Login_LogsRepository _sys_login_logsRepository; static Logger Logger = LogManager.GetCurrentClassLogger(); public TokenController(IConfiguration configuration, IDistributedCache cache, ISys_User_AccountRepository sys_user_accountRepository, ISys_Role_InfoRepository sys_roleinfoRepository, ISys_Login_LogsRepository sys_login_logsRepository, ILogger logger) { _configuration = configuration; _cache = cache; _sys_user_accountRepository = sys_user_accountRepository; _sys_roleinfoRepository = sys_roleinfoRepository; _sys_login_logsRepository = sys_login_logsRepository; _logger = logger; } /// /// 用户登录 /// /// 账号 /// MD5加密后的密码 /// 渠道来源 1表示PC 2表示安卓 3表示IOS 4表示微信 /// 跳转的url /// [AllowAnonymous] [HttpPost("login")] public async Task Login(string usercode, string password, int channel = 1, string returnUrl = null) { if (_configuration["IsLogin"] == "0") { return Error("系统异常,请稍后重试"); } #region 获取ip地址 var ip = IPHelper.GetIp(this.HttpContext); #endregion #region 用户信息判断及查找 if (!ValidateHelper.IsAllPlumpString(usercode, password)) { return Error("用户名或密码不能为空!"); } var user = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode && x.password == password && x.delete_flag==false); if (user == null) { return Error("用户名或密码错误!"); } //判断禁用标志是否true if (user.lock_flag) { await AddLogAsync(user.username, usercode, "被禁止访问", ip, channel); return Error("当前账户被禁止登录访问!"); } #endregion #region 角色判断 var roleinfo = await _sys_roleinfoRepository.GetSingle(x => x.id == user.role_id); //查询角色 如若查询不到,反馈 不要直接反馈明显信息 if (roleinfo == null) { await AddLogAsync(user.username, usercode, "无相关角色信息", ip, channel); return Error("当前用户涉嫌非法访问!"); } if (roleinfo.role_lock == 1) { await AddLogAsync(user.username, usercode, "当前角色被禁止访问", ip, channel); return Error("当前用户角色权限被禁止登录!"); } #endregion #region JWT token生成 var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"].ToString())); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var role_name = roleinfo.role_name; var permissionRequirement = new PermissionRequirement( "/api/denied", ClaimTypes.Role, _configuration["Jwt:Issuer"].ToString(), _configuration["Jwt:Audience"].ToString(), signingCredentials, expiration: TimeSpan.FromDays(Convert.ToInt32(_configuration["Jwt:Expiration"])) ); var claims = new Claim[] { new Claim(ClaimTypes.PrimarySid, user.id),//用户id new Claim(ClaimTypes.GroupSid,channel.ToString()),//渠道来源 new Claim(ClaimTypes.Sid, user.usercode),//用户账号 new Claim(ClaimTypes.Name, user.username),//用户名字 new Claim(ClaimTypes.Role, user.role_id),//角色id new Claim("RoleCode", roleinfo.role_code),//角色code new Claim(ClaimTypes.DenyOnlySid, ""),//微信id new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(permissionRequirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var jwt_token = JwtToken.BuildJwtToken(claims, permissionRequirement); #endregion await AddLogAsync(user.username, usercode, "登录成功", ip, channel); var info = ""; //#region 判断属于哪个坐席 ////zxz是364 kfz365 ////获取坐席组信息 //var groupinfo = user.groupid; //#endregion ////提示授权到期还有多少天 //string info = ""; //DateTime dateauth = DateTime.Parse(_configuration["AuthDate"]); //int Reminddays = int.Parse(_configuration["Reminddays"]); //var days = (dateauth - DateTime.Now).TotalDays; //if (days < Reminddays) //{ // info = "距离授权到期还有"+ days + "天,请联系厂家"; //} var result = new { username = user.username, usercode = user.usercode, token = jwt_token, type = user.type, seat_flag = user.seat_flag, group = user.groupid,// "364",// user.group, role_name = role_name, role_id = user.role_id, role_code= roleinfo.role_code, dept_id = user.dept_id, team_id = user.team_id, mobile = user.mobile, head_img = user.head_img, weixin = user.weixin, weixin_name = user.weixin_name, weixin_img = user.weixin_img, remark=user.remark, returninfo=info }; return Success("登录成功!", result); } [HttpPost("update_token")] public async Task Update_Token(int channel = 1) { #region 获取ip地址 var ip = IPHelper.GetIp(this.HttpContext); #endregion #region 用户信息判断及查找 string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; var user = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode && x.delete_flag==false); if (user == null) { return Error("当前用户资料被删除!"); } //判断删除标志及禁用标志是否true if (user.delete_flag || user.lock_flag) { await AddLogAsync(user.username, usercode, "被禁止访问", ip, channel); return Error("当前账户被禁止登录访问!"); } #endregion #region 角色判断 var roleinfo = await _sys_roleinfoRepository.GetSingle(x => x.id == user.role_id); //查询角色 如若查询不到,反馈 不要直接反馈明显信息 if (roleinfo == null) { await AddLogAsync(user.username, usercode, "无相关角色信息", ip, channel); return Error("当前用户涉嫌非法访问!"); } if (roleinfo.role_lock == 1) { await AddLogAsync(user.username, usercode, "当前角色被禁止访问", ip, channel); return Error("当前用户角色权限被禁止登录!"); } #endregion #region JWT token生成 var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"].ToString())); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var role_name = roleinfo.role_name; var permissionRequirement = new PermissionRequirement( "/api/denied", ClaimTypes.Role, _configuration["Jwt:Issuer"].ToString(), _configuration["Jwt:Audience"].ToString(), signingCredentials, expiration: TimeSpan.FromDays(Convert.ToInt32(_configuration["Jwt:Expiration"])) ); var claims = new Claim[] { new Claim(ClaimTypes.PrimarySid, user.id),//用户id new Claim(ClaimTypes.GroupSid,channel.ToString()),//渠道来源 new Claim(ClaimTypes.Sid, user.usercode),//用户账号 new Claim(ClaimTypes.Name, user.username),//用户名字 new Claim(ClaimTypes.Role, user.role_id),//角色id new Claim("RoleCode", roleinfo.role_code),//角色code new Claim(ClaimTypes.DenyOnlySid, ""),//微信id new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(permissionRequirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var jwt_token = JwtToken.BuildJwtToken(claims, permissionRequirement); #endregion await AddLogAsync(user.username, usercode, "token更新成功", ip, channel); var result = new { username = user.username, usercode = user.usercode, token = jwt_token, type = user.type, seat_flag = user.seat_flag, group = user.group, role_name = role_name, role_id = user.role_id, role_code = roleinfo.role_code, dept_id = user.dept_id, team_id = user.team_id, mobile = user.mobile, head_img = user.head_img, weixin = user.weixin, weixin_name = user.weixin_name, weixin_img = user.weixin_img }; return Success("token更新成功!", result); } ///// ///// 微信诺达用户登录 ///// ///// ///// ///// ///// ///// ///// ///// //[AllowAnonymous] //[HttpPost("wechat_admin_login")] //public async Task Wechat_Admin_Login(string usercode, string password, string weixin, string weixin_name, string weixin_img, int channel = 4, string returnUrl = null) //{ // #region 获取ip地址 // var ip = IPHelper.GetIp(this.HttpContext); // #endregion // #region 用户信息判断及查找 // if (!ValidateHelper.IsAllPlumpString(usercode, password)) // { // return Error("用户名或密码不能为空!"); // } // var user = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode && x.password == password); // if (user == null) { return Error("用户名或密码错误!"); } // //判断删除标志及禁用标志是否true // if (user.delete_flag || user.lock_flag) // { // _logger.LogWarning($"{user.usercode}被禁止访问"); // await AddLogAsync(user.username, usercode, "被禁止访问", ip, channel); // return Error("当前账户被禁止登录访问!"); // } // #endregion // #region 角色判断 // var roleinfo = await _sys_roleinfoRepository.GetSingle(x => x.id == user.role_id); // //查询角色 如若查询不到,反馈 不要直接反馈明显信息 // if (roleinfo == null) // { // _logger.LogWarning($"{user.usercode}登录因查询不到角色{user.role_id}被禁止访问"); // await AddLogAsync(user.username, usercode, "无相关角色信息", ip, channel); // return Error("当前用户涉嫌非法访问!"); // } // if (roleinfo.role_lock == 1) // { // _logger.LogWarning($"{user.usercode}登录因角色{user.role_id}上锁被禁止访问"); // await AddLogAsync(user.username, usercode, "当前角色被禁止访问", ip, channel); // return Error("当前用户角色权限被禁止登录!"); // } // #endregion // #region 更新当前用户的微信账号 // user.weixin = weixin; // user.weixin_name = weixin_name; // user.weixin_img = weixin_img; // if (user.head_img == "") // { // user.head_img = user.weixin_img; // } // await _sys_user_accountRepository.UpdateOne(user); // #endregion // #region JWT token生成 // var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"].ToString())); // var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); // var role_name = roleinfo.role_name; // var permissionRequirement = new PermissionRequirement( // "/api/denied", // ClaimTypes.Role, // _configuration["Jwt:Issuer"].ToString(), // _configuration["Jwt:Audience"].ToString(), // signingCredentials, // expiration: TimeSpan.FromDays(Convert.ToInt32(_configuration["Jwt:Expiration"])) // ); // var claims = new Claim[] { // new Claim(ClaimTypes.PrimarySid, user.id),//用户id // new Claim(ClaimTypes.GroupSid,channel.ToString()),//渠道来源 // new Claim(ClaimTypes.Sid, user.usercode),//用户账号 // new Claim(ClaimTypes.Name, user.username),//用户名字 // new Claim(ClaimTypes.Role, user.role_id),//角色id // new Claim(ClaimTypes.DenyOnlySid, weixin),//微信id // new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(permissionRequirement.Expiration.TotalSeconds).ToString()) // }; // //用户标识 // var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); // identity.AddClaims(claims); // var jwt_token = JwtToken.BuildJwtToken(claims, permissionRequirement); // #endregion // await AddLogAsync(user.username, usercode, "登录成功", ip, channel); // var result = new // { // username = user.username, // usercode = user.usercode, // token = jwt_token, // type = user.type, // seat_flag = user.seat_flag, // group = user.group, // role_name = role_name, // role_id = user.role_id, // dept_id = user.dept_id, // team_id = user.team_id, // mobile = user.mobile, // head_img = user.head_img, // weixin = user.weixin, // weixin_name = user.weixin_name, // weixin_img = user.weixin_img // }; // return Success("登录成功!", result); //} /// /// 微信诺达用户登录 /// /// /// /// /// /// /// /// [AllowAnonymous] [HttpPost("wechat_admin_login")] public async Task Wechat_Admin_Login(string usercode, string password, int channel = 4, string returnUrl = null) { #region 获取ip地址 var ip = IPHelper.GetIp(this.HttpContext); #endregion #region 用户信息判断及查找 if (!ValidateHelper.IsAllPlumpString(usercode, password)) { return Error("用户名或密码不能为空!"); } var user = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode && x.password == password && x.delete_flag==false); if (user == null) { return Error("用户名或密码错误!"); } //判断删除标志及禁用标志是否true if (user.delete_flag || user.lock_flag) { _logger.LogWarning($"{user.usercode}被禁止访问"); await AddLogAsync(user.username, usercode, "被禁止访问", ip, channel); return Error("当前账户被禁止登录访问!"); } #endregion #region 角色判断 var roleinfo = await _sys_roleinfoRepository.GetSingle(x => x.id == user.role_id); //查询角色 如若查询不到,反馈 不要直接反馈明显信息 if (roleinfo == null) { _logger.LogWarning($"{user.usercode}登录因查询不到角色{user.role_id}被禁止访问"); await AddLogAsync(user.username, usercode, "无相关角色信息", ip, channel); return Error("当前用户涉嫌非法访问!"); } if (roleinfo.role_lock == 1) { _logger.LogWarning($"{user.usercode}登录因角色{user.role_id}上锁被禁止访问"); await AddLogAsync(user.username, usercode, "当前角色被禁止访问", ip, channel); return Error("当前用户角色权限被禁止登录!"); } #endregion #region 更新当前用户的微信账号 string weixin = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; var wxuserold = await _sys_user_accountRepository.GetSingle(x => x.weixin == weixin && x.type != 2); wxuserold.weixin = ""; wxuserold.weixin_name = ""; wxuserold.weixin_img = ""; await _sys_user_accountRepository.UpdateOne(wxuserold); var wxuser = await _sys_user_accountRepository.GetSingle(x => x.usercode == weixin); user.weixin = weixin; user.weixin_name = wxuser.weixin_name; user.weixin_img = wxuser.weixin_img; if (user.head_img == "") { user.head_img = user.weixin_img; } await _sys_user_accountRepository.UpdateOne(user); #endregion #region JWT token生成 var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"].ToString())); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var role_name = roleinfo.role_name; var permissionRequirement = new PermissionRequirement( "/api/denied", ClaimTypes.Role, _configuration["Jwt:Issuer"].ToString(), _configuration["Jwt:Audience"].ToString(), signingCredentials, expiration: TimeSpan.FromDays(Convert.ToInt32(_configuration["Jwt:Expiration"])) ); var claims = new Claim[] { new Claim(ClaimTypes.PrimarySid, user.id),//用户id new Claim(ClaimTypes.GroupSid,channel.ToString()),//渠道来源 new Claim(ClaimTypes.Sid, user.usercode),//用户账号 new Claim(ClaimTypes.Name, user.username),//用户名字 new Claim(ClaimTypes.Role, user.role_id),//角色id new Claim("RoleCode", roleinfo.role_code),//角色code new Claim(ClaimTypes.DenyOnlySid, weixin),//微信id new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(permissionRequirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var jwt_token = JwtToken.BuildJwtToken(claims, permissionRequirement); #endregion await AddLogAsync(user.username, usercode, "登录成功", ip, channel); var result = new { username = user.username, usercode = user.usercode, token = jwt_token, type = user.type, seat_flag = user.seat_flag, group = user.group, role_name = role_name, role_code = roleinfo.role_code, role_id = user.role_id, dept_id = user.dept_id, team_id = user.team_id, mobile = user.mobile, head_img = user.head_img, weixin = user.weixin, weixin_name = user.weixin_name, weixin_img = user.weixin_img }; return Success("登录成功!", result); } [AllowAnonymous] [HttpPost("wechat_login")] public async Task Wechat_Login(string weixin, string weixin_name, string weixin_img, int channel = 4, string returnUrl = null) { #region 获取ip地址 var ip = IPHelper.GetIp(this.HttpContext); #endregion #region 用户信息判断及查找 var user = await _sys_user_accountRepository.GetSingle(x => x.usercode == weixin && x.delete_flag == false); if (user == null) { user = new Sys_User_Account(); user.id = ObjectId.GenerateNewId().ToString(); user.weixin = weixin; user.usercode = weixin; user.weixin_img = weixin_img; user.weixin_name = weixin_name; user.username = weixin_name; user.head_img = user.weixin_img; user.head_small_img= user.weixin_img; user.type = 2; user.certificate = new System.Collections.Generic.List(); user.idcard = new System.Collections.Generic.List(); user.projectlist = new System.Collections.Generic.List(); user.postlist = new System.Collections.Generic.List(); await _sys_user_accountRepository.Add(user); } else { user.weixin = weixin; user.weixin_name = weixin_name; user.weixin_img = weixin_img; user.username = weixin_name; if (string.IsNullOrEmpty(user.head_img)) { user.head_img = user.weixin_img; user.head_small_img = user.weixin_img; } await _sys_user_accountRepository.UpdateOne(user); } var bduser = await _sys_user_accountRepository.GetSingle(x => x.weixin == weixin && x.type != 2 && x.delete_flag == false); if (user != null) { user.weixin = weixin; user.weixin_name = weixin_name; user.weixin_img = weixin_img; if (string.IsNullOrEmpty(user.head_img)) { user.head_img = user.weixin_img; user.head_small_img = user.weixin_img; } await _sys_user_accountRepository.UpdateOne(user); } #endregion #region JWT token生成 var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"].ToString())); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var role = "weixin"; var permissionRequirement = new PermissionRequirement( "/api/denied", ClaimTypes.Role, _configuration["Jwt:Issuer"].ToString(), _configuration["Jwt:Audience"].ToString(), signingCredentials, expiration: TimeSpan.FromDays(Convert.ToInt32(_configuration["Jwt:Expiration"])) ); var claims = new Claim[] { new Claim(ClaimTypes.PrimarySid, user.id),//用户id new Claim(ClaimTypes.GroupSid,channel.ToString()),//渠道来源 new Claim(ClaimTypes.Sid, user.usercode),//用户账号 new Claim(ClaimTypes.Name, user.username),//用户名字 new Claim(ClaimTypes.Role, ""),//角色id new Claim("RoleCode", ""),//角色code new Claim(ClaimTypes.DenyOnlySid, weixin),//微信id new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(permissionRequirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var jwt_token = JwtToken.BuildJwtToken(claims, permissionRequirement); #endregion await AddLogAsync(user.username, user.usercode, "登录成功", ip, channel); var result = new { username = user.username, usercode = user.usercode, token = jwt_token, type = user.type, seat_flag = user.seat_flag, group = user.group, role_name = "", role_code = "", role_id = user.role_id, dept_id = user.dept_id, team_id = user.team_id, mobile = user.mobile, head_img = user.head_img, weixin = user.weixin, weixin_name = user.weixin_name, weixin_img = user.weixin_img }; return Success("登录成功!", result); } /// /// 微信绑定 /// /// /// /// /// [AllowAnonymous] [HttpPost("wechat_bind")] public async Task Wechat_Bind(string usercode, string openid, int channel = 4) { var user = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode && x.delete_flag == false); if (user != null && string.IsNullOrEmpty(user.weixin)) { user.weixin = openid; var wxuser = await _sys_user_accountRepository.GetSingle(x => x.usercode == openid && x.delete_flag == false); if (wxuser != null) { user.weixin_name = wxuser.weixin_name; user.weixin_img = wxuser.weixin_img; if (user.head_img == "") { user.head_img = wxuser.weixin_img; } } bool b = await _sys_user_accountRepository.UpdateOne(user); if (b) return Success("绑定成功!"); return Error("绑定失败"); } else { return Error("绑定失败"); } } /// /// 微信解绑 /// /// /// /// [HttpPost("wechat_unbind")] public async Task Wechat_UnBind(string usercode, int channel = 4) { var user = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode && x.delete_flag == false); if (user != null) { user.weixin = ""; user.weixin_name = ""; user.weixin_img = ""; bool b = await _sys_user_accountRepository.UpdateOne(user); if (b) return Success("解绑成功!"); return Error("解绑失败"); } else { return Error("解绑失败"); } } /// /// 存储登录日志 /// /// /// /// /// /// /// private async Task AddLogAsync(string name, string code, string log, string ip, int channel) { var login_log = new Sys_Login_Logs() { username = name, usercode = code, result = log, login_ip = ip, channel = channel }; if (!await _sys_login_logsRepository.Add(login_log)) { _logger.LogError($"{code}登录日志存储异常,登录IP地址为{ip}"); } } private IActionResult SaveLoginLog() { return Ok(); } [HttpPost("/api/logout")] public IActionResult Logout() { return Ok(); } [AllowAnonymous] [HttpGet("/api/denied")] public IActionResult Denied() { return new JsonResult(new { Status = false, Message = "你无权限访问" }); } } }