c# 获取用户IP4

using System;
using Microsoft.AspNetCore.Mvc;
using Sys.Model;
using Sys.Dao;
using Sys.Tools;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Collections.Generic;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Sys.Tools.Session;

namespace HBAnalysisSystem.Controllers
{
    public class LoginController : Controller
    {
        public const string UserKey = BaseController.UserKey;
        private IHttpContextAccessor _accessor;
        public LoginController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        //
        // GET: /SystemManagement/
        // [RoleFilte
        // r(IsCheck = false)]
        //string u_danger, string p_danger, string c_danger, string returnUrl = null
        public IActionResult Index()
        {
        
            return View();

        }


        /// <summary>
        /// 校验登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <summary>
        /// 校验登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //public async Task<IActionResult> CheckLogin(string userName, string password,string authCode, string verifyCode)
        //{

        //    if (string.IsNullOrEmpty(authCode))
        //    {
        //        //ViewData["c_danger"] = "验证码不能为空";
        //        return RedirectToAction("Index", "Login", new { c_danger = "验证码不能为空" });
        //    }
        //    else
        //    {
        //        authCode = EncryptUtil.MD5Password("V_" + authCode).ToLower();
        //        if (authCode != verifyCode)
        //        {
        //            //ViewData["c_danger"] = "验证码错误";
        //            return RedirectToAction("Index", "Login", new { c_danger = "验证码错误" });
        //        }
        //    }
        //    if (string.IsNullOrEmpty(userName))
        //    {

        //        return RedirectToAction("Index", "Login", new { u_danger = "用户名不能为空" });

        //        //return;
        //    }
        //    else if (string.IsNullOrEmpty(password))
        //    {

        //        return RedirectToAction("Index", "Login", new { p_danger = "密码不能为空" });

        //        //return;
        //    }
  
        //    //1.先Base64位解密
        //    password = Base64Provider.Base64Decode(password);
        //    string message = RegProvider.IsEngName("密码", password);
        //    if (!string.IsNullOrEmpty(message))
        //    {
        //        //await Response.WriteAsync("<script>alert('密码只能包含数字、字母或下划线等');window.location.href ='/Login/Index'</script>");
        //        //ViewData["p_danger"] = "密码只能包含数字、字母或下划线等";

        //        return RedirectToAction("Index", "Login", new { p_danger = "密码只能包含数字、字母或下划线等" });

        //        //return;
        //    }
        //    try
        //    {
        //        Usr _usermodel = Sys_UsrDao.Instance.GetUser(userName);
        //        //如果次数操作3次,且错误时间间隔小于超过15分钟,返回用户锁定
        //        if (_usermodel != null)
        //        {
        //            if (_usermodel.ErrorNum >= 3 && (DateTime.Now.Subtract(Convert.ToDateTime(_usermodel.ErrorLoginTime)).Minutes <= 15))
        //            {
        //                //await Response.WriteAsync("<script>alert('用户已锁定!');window.location.href ='/Login/Index'</script>");
        //                //ViewData["u_danger"] = "用户已锁定";

        //                return RedirectToAction("Index", "Login", new { u_danger = "用户已锁定" });

        //                //return;
        //            }
        //        }
        //        else
        //        {
        //            //await Response.WriteAsync("<script>alert('用户不存在!');window.location.href ='/Login/Index'</script>");
        //            //ViewData["u_danger"] = "用户不存在";


        //            return RedirectToAction("Index", "Login", new { u_danger = "用户不存在" });

        //            //return;
        //        }
        //        //2.MD5加密
        //        password = EncryptUtil.MD5Password(password).ToLower();
        //        Usr user = Sys_UsrDao.Instance.GetUser(userName, password);
        //        if (user != null && user.Id >= 0 && user.IsRun == true)
        //        {
        //            user.ErrorNum = 0;
        //            Sys_UsrDao.Instance.Update(user);
        //            if (user.UserType == 2)
        //            {
        //                if (user.UseDate < Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")))
        //                {
        //                    //await Response.WriteAsync("<script>alert('用户访问权限已到期!');window.location.href ='/Login/Index'</script>");
        //                    ViewData["u_danger"] = "用户访问权限已到期";

        //                    return RedirectToAction("Index", "Login", new { u_danger = "用户访问权限已到期" });

        //                }
        //            }
        //            UserModel model = new UserModel();
        //            model.UserId = user.Id;
        //            model.LoginName = user.Name;
        //            model.Password = password;
        //            model.UserName = user.RealName;
        //            model.IsAdmin = ConvertHelper.FormatDBInt(user.IsAdmin);
        //            model.SessionId = Guid.NewGuid().ToString();
        //            model.GroupID = ConvertHelper.FormatDBInt(user.GroupID);
        //            model.HigherName = user.HigherName;
        //            if (model.IsAdmin == 1)
        //            {
        //                model.UserType = AuditRoleType.Admin;
        //            }
        //            else
        //            {
        //                model.UserType = Sys_UsrDao.Instance.GetUserType(user.Name);
        //            }
                   
        //            string info = JsonHelper.SerializeObject(model);
               
        //            var claims = new List<Claim>() {
        //               new Claim(ClaimTypes.Name,model.LoginName),
        //               new Claim(ClaimTypes.UserData,info),
        //            };
        //            var idendity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        //            var userPrincipal = new ClaimsPrincipal(idendity);
        //            await _accessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
        //            {
        //                ExpiresUtc = DateTime.UtcNow.AddDays(1),
        //                IsPersistent = false,
        //                AllowRefresh = false
        //            });
        //            var expres = DateTime.Now.AddDays(1);
        //            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.GetSection("Authentication:SecurityKey")));
        //            var token = new JwtSecurityToken(
        //                    issuer: ConfigurationManager.GetSection("Authentication:Issure"),           // 发布者
        //                    audience: ConfigurationManager.GetSection("Authentication:Audience"),          // 接收者
        //                    notBefore: DateTime.Now,                                                          // token签发时间
        //                    expires: expres,                                             // token过期时间
        //                    claims: claims,                                                                   // 该token内存储的自定义字段信息
        //                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)    // 用于签发token的秘钥算法
        //                    );
        //            // 返回成功信息,写出token                  
        //            model.Token = new JwtSecurityTokenHandler().WriteToken(token);
        //            //HttpContext.GetTokenAsync(key);
        //            //写入登录日志
        //            WelcomLogs log = new WelcomLogs();
        //            log.Id = Sys_UsrDao.Instance.GetMaxId<WelcomLogs>();
        //            log.Action = "系统登录";
        //            log.UsrName = userName;
        //            log.ActionDate = System.DateTime.Now;
        //            try
        //            {
        //                string ips = _accessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
        //                log.UserIp = ips;
        //            }
        //            catch (Exception ex)
        //            {

        //            }
        //            Sys_UsrDao.Instance.Insert<WelcomLogs>(log);
        //            //Response.WriteAsync("<script>window.location.href ='/Home/Index'</script>");
        //            //RedirectToAction("Index", "Home");
        //            //判断是否是新用户,是新用户弹出密码修改界面,修改之后改成旧用户
        //            if (user.IsNewUser == true)
        //            {
        //                //Response.Redirect("/SysManagement/ChangePassword", true);
        //                return RedirectToAction("ChangePassword", "SysManagement");
        //            }
        //            else
        //            {


        //                //return RedirectToAction("JSCYTHIndex1", "Cockpit");
        //                return RedirectToAction("FlyToEarth", "Cockpit");
        //            }

        //        }
        //        else
        //        {
        //            _usermodel.ErrorNum = _usermodel.ErrorNum == null ? 1 : _usermodel.ErrorNum + 1;
        //            _usermodel.ErrorLoginTime = DateTime.Now;
        //            Sys_UsrDao.Instance.Update(_usermodel);
        //            //CookiesHelper.ClearCookie(UserKey);
        //            //SessionManager.Instance.RemoveSession(UserKey);
        //            // return "账号或密码有误";
        //            //await Response.WriteAsync("<script>alert('账号或密码有误');window.location.href ='/Login/Index'</script>", Encoding.GetEncoding("GB2312"));
        //            //ViewData["p_danger"] = "账号或密码有误";

        //            return RedirectToAction("Index", "Login", new { p_danger = "账号或密码有误" });


        //            //return;
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //        Log4Helper.Error("登录失败" + ex.ToString());
        //        //await Response.WriteAsync("<script>alert('登录失败,请确认账号和密码正确');window.location.href ='/Login/Index'</script>");
        //        //ViewData["p_danger"] = "登录失败,"+ ex.Message;

        //        return RedirectToAction("Index", "Login", new { u_danger = "登录失败,请联系管理员"  });

        //    }
        //}

        public async Task<IActionResult> CheckLogin(string userName, string password, string authCode, string verifyCode)
        {
            try
            {

              
                //1.先Base64位解密
                password = Base64Provider.Base64Decode(password);
       
                //2.MD5加密
                password = EncryptUtil.MD5Password(password).ToLower();

                Usr user = Sys_UsrDao.Instance.GetUser(userName, password);
                if (user != null && user.Id >= 0 && user.IsRun == true)
                {
                    user.ErrorNum = 0;
                    Sys_UsrDao.Instance.Update(user);
                    UserModel model = new UserModel();
                    model.UserId = user.Id;
                    model.LoginName = user.Name;
                    model.Password = password;
                    model.UserName = user.RealName;
                    model.IsAdmin = ConvertHelper.FormatDBInt(user.IsAdmin);
                    model.SessionId = Guid.NewGuid().ToString();
                    model.GroupID = ConvertHelper.FormatDBInt(user.GroupID);
                    model.HigherName = user.HigherName;
                    if (model.IsAdmin == 1)
                    {
                        model.UserType = AuditRoleType.Admin;
                    }
                    else
                    {
                        model.UserType = Sys_UsrDao.Instance.GetUserType(user.Name);
                    }
                    string info = JsonHelper.SerializeObject(model);
                    var claims = new List<Claim>() {
                       new Claim(ClaimTypes.Name,model.LoginName),
                       new Claim(ClaimTypes.UserData,info),
                    };
                    var idendity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var userPrincipal = new ClaimsPrincipal(idendity);
                    await _accessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.Now.AddDays(1),
                        IsPersistent = false,
                        AllowRefresh = false
                    });
                    var expres = DateTime.Now.AddDays(1);
                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.GetSection("Authentication:SecurityKey")));
                    var token = new JwtSecurityToken(
                            issuer: ConfigurationManager.GetSection("Authentication:Issure"),           // 发布者
                            audience: ConfigurationManager.GetSection("Authentication:Audience"),          // 接收者
                            notBefore: DateTime.Now,    
                            // token签发时间
                            expires: expres,                                             // token过期时间
                            claims: claims,                                                                   // 该token内存储的自定义字段信息
                            signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)    // 用于签发token的秘钥算法
                            );
                    // 返回成功信息,写出token                  
                    model.Token = new JwtSecurityTokenHandler().WriteToken(token);
                    string sUserInfo = model.LoginName+"|"+model.Password;
                    sUserInfo = EncryptUtil.DesEncrypt(sUserInfo);
                    Sys.Tools.CookiesHelper.WriteCookie(UserKey, sUserInfo, (DateTime.Now.AddDays(1)-DateTime.Now).TotalMinutes.ToInt());
                    //写入登录日志
                    WelcomLogs log = new WelcomLogs();
                    log.Id = Sys_UsrDao.Instance.GetMaxId<WelcomLogs>();
                    log.Action = "系统登录";
                    log.UsrName = userName;
                    log.ActionDate = System.DateTime.Now;
                    try
                    {
                        string ips = _accessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                        log.UserIp = ips;
                    }
                    catch (Exception ex)
                    {

                    }
                    Sys_UsrDao.Instance.Insert<WelcomLogs>(log);
                   
                    if (user.IsNewUser == true)
                    {
                        //Response.Redirect("/SysManagement/ChangePassword", true);
                        return RedirectToAction("ChangePassword", "SysManagement");
                    }
                    else
                    {
                        if(user.GroupID==15||user.GroupID==7)
                        {
                            return RedirectToAction("FlyToEarth", "Cockpit");
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                
                    }
                }
            }
            catch (System.Exception ex)
            {
            }
            return RedirectToAction("Index", "Login");
        }
        public IActionResult JYCheckLogin(string userName, string password, string authCode, string verifyCode)
        {

            if (string.IsNullOrEmpty(authCode))
            {
                //ViewData["c_danger"] = "验证码不能为空";
                //return RedirectToAction("Index", "Login", new { c_danger = "验证码不能为空" });
                return Json(new { IsSuccess = false, c_danger = "验证码不能为空" });
            }
            else
            {
                authCode = EncryptUtil.MD5Password("V_" + authCode).ToLower();
                if (authCode != verifyCode)
                {
                    //ViewData["c_danger"] = "验证码错误";
                    //return RedirectToAction("Index", "Login", new { c_danger = "验证码错误" });
                    return Json(new { IsSuccess = false, c_danger = "验证码错误" });
                }
            }
            if (string.IsNullOrEmpty(userName))
            {

                //return RedirectToAction("Index", "Login", new { u_danger = "用户名不能为空" });
                return Json(new { IsSuccess = false, u_danger = "用户名不能为空" });
                //return;
            }
            else if (string.IsNullOrEmpty(password))
            {

                //return RedirectToAction("Index", "Login", new { p_danger = "密码不能为空" });
                return Json(new { IsSuccess = false, p_danger = "密码不能为空" });
                //return;
            }

            //1.先Base64位解密
            password = Base64Provider.Base64Decode(password);
            string message = RegProvider.IsEngName("密码", password);
            if (!string.IsNullOrEmpty(message))
            {
                //await Response.WriteAsync("<script>alert('密码只能包含数字、字母或下划线等');window.location.href ='/Login/Index'</script>");
                //ViewData["p_danger"] = "密码只能包含数字、字母或下划线等";

                //return RedirectToAction("Index", "Login", new { p_danger = "密码只能包含数字、字母或下划线等" });
                return Json(new { IsSuccess = false, p_danger = "密码只能包含数字、字母或下划线等" });
                //return;
            }
            try
            {
                Usr _usermodel = Sys_UsrDao.Instance.GetUser(userName);
                //如果次数操作3次,且错误时间间隔小于超过15分钟,返回用户锁定
                if (_usermodel != null)
                {
                    if (_usermodel.ErrorNum >= 3 && (DateTime.Now.Subtract(Convert.ToDateTime(_usermodel.ErrorLoginTime)).Minutes <= 15))
                    {
                        //await Response.WriteAsync("<script>alert('用户已锁定!');window.location.href ='/Login/Index'</script>");
                        //ViewData["u_danger"] = "用户已锁定";

                        //return RedirectToAction("Index", "Login", new { u_danger = "用户已锁定" });
                        return Json(new { IsSuccess = false, u_danger = "用户已锁定" });
                        //return;
                    }
                }
                else
                {
                    //await Response.WriteAsync("<script>alert('用户不存在!');window.location.href ='/Login/Index'</script>");
                    //ViewData["u_danger"] = "用户不存在";


                    //return RedirectToAction("Index", "Login", new { u_danger = "用户不存在" });
                    return Json(new { IsSuccess = false, u_danger = "用户不存在" });
                    //return;
                }
                //2.MD5加密
                password = EncryptUtil.MD5Password(password).ToLower();
                Usr user = Sys_UsrDao.Instance.GetUser(userName, password);
                if (user != null && user.Id > 0 && user.IsRun == true)
                {
                    user.ErrorNum = 0;
                    Sys_UsrDao.Instance.Update(user);
                    if (user.UserType == 2)
                    {
                        if (user.UseDate < Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")))
                        {
                            //await Response.WriteAsync("<script>alert('用户访问权限已到期!');window.location.href ='/Login/Index'</script>");
                            //ViewData["u_danger"] = "用户访问权限已到期";
                            return Json(new { IsSuccess = false, u_danger = "用户访问权限已到期" });
                            //return RedirectToAction("Index", "Login", new { u_danger = "用户访问权限已到期" });

                        }
                    }
                    //UserModel model = new UserModel();
                    //model.UserId = user.Id;
                    //model.LoginName = user.Name;
                    //model.Password = password;
                    //model.UserName = user.RealName;
                    //model.IsAdmin = ConvertHelper.FormatDBInt(user.IsAdmin);
                    //model.SessionId = Guid.NewGuid().ToString();
                    //model.GroupID = ConvertHelper.FormatDBInt(user.GroupID);
                    //model.HigherName = user.HigherName;
                    //if (model.IsAdmin == 1)
                    //{
                    //    model.UserType = AuditRoleType.Admin;
                    //}
                    //else
                    //{
                    //    model.UserType = Sys_UsrDao.Instance.GetUserType(user.Name);
                    //}

                    //string info = JsonHelper.SerializeObject(model);

                    //var claims = new List<Claim>() {
                    //   new Claim(ClaimTypes.Name,model.LoginName),
                    //   new Claim(ClaimTypes.UserData,info),
                    //};
                    //var idendity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    //var userPrincipal = new ClaimsPrincipal(idendity);
                    //await _accessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                    //{
                    //    ExpiresUtc = DateTime.UtcNow.AddDays(1),
                    //    IsPersistent = false,
                    //    AllowRefresh = false
                    //});
                    //var expres = DateTime.Now.AddDays(1);
                    //var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.GetSection("Authentication:SecurityKey")));
                    //var token = new JwtSecurityToken(
                    //        issuer: ConfigurationManager.GetSection("Authentication:Issure"),           // 发布者
                    //        audience: ConfigurationManager.GetSection("Authentication:Audience"),          // 接收者
                    //        notBefore: DateTime.Now,                                                          // token签发时间
                    //        expires: expres,                                             // token过期时间
                    //        claims: claims,                                                                   // 该token内存储的自定义字段信息
                    //        signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)    // 用于签发token的秘钥算法
                    //        );
                     返回成功信息,写出token                  
                    //model.Token = new JwtSecurityTokenHandler().WriteToken(token);
                    HttpContext.GetTokenAsync(key);
                    写入登录日志
                    //WelcomLogs log = new WelcomLogs();
                    //log.Id = Sys_UsrDao.Instance.GetMaxId<WelcomLogs>();
                    //log.Action = "系统登录";
                    //log.UsrName = userName;
                    //log.ActionDate = System.DateTime.Now;
                    //try
                    //{
                    //    string ips = _accessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                    //    log.UserIp = ips;
                    //}
                    //catch (Exception ex)
                    //{

                    //}
                    //Sys_UsrDao.Instance.Insert<WelcomLogs>(log);
                    //Response.WriteAsync("<script>window.location.href ='/Home/Index'</script>");
                    //RedirectToAction("Index", "Home");
                    //判断是否是新用户,是新用户弹出密码修改界面,修改之后改成旧用户
                    //if (user.IsNewUser == true)
                    //{
                    //    //Response.Redirect("/SysManagement/ChangePassword", true);
                    //    return RedirectToAction("ChangePassword", "SysManagement");
                    //}
                    //else
                    //{
                    //    //return RedirectToAction("JSCYTHIndex1", "Cockpit");
                    //    return RedirectToAction("FlyToEarth", "Cockpit");
                    //}
                    return Json(new { IsSuccess = true });
                }
                else
                {
                    _usermodel.ErrorNum = _usermodel.ErrorNum == null ? 1 : _usermodel.ErrorNum + 1;
                    _usermodel.ErrorLoginTime = DateTime.Now;
                    Sys_UsrDao.Instance.Update(_usermodel);
                    //CookiesHelper.ClearCookie(UserKey);
                    //SessionManager.Instance.RemoveSession(UserKey);
                    // return "账号或密码有误";
                    //await Response.WriteAsync("<script>alert('账号或密码有误');window.location.href ='/Login/Index'</script>", Encoding.GetEncoding("GB2312"));
                    //ViewData["p_danger"] = "账号或密码有误";

                    //return RedirectToAction("Index", "Login", new { p_danger = "账号或密码有误" });
                    return Json(new { IsSuccess = false, p_danger = "账号或密码有误" });

                    //return;
                }
            }
            catch (System.Exception ex)
            {
                Log4Helper.Error("登录失败" + ex.ToString());
                //await Response.WriteAsync("<script>alert('登录失败,请确认账号和密码正确');window.location.href ='/Login/Index'</script>");
                //ViewData["p_danger"] = "登录失败,"+ ex.Message;

                //return RedirectToAction("Index", "Login", new { u_danger = "登录失败,请联系管理员" });
                return Json(new { IsSuccess = false, p_danger = "登录失败,请联系管理员" });
            }
        }
        public async Task<IActionResult> LoginOut()
        {
            /// IdentityServer4 退出登录后,默认会跳转到Config.Client配置的PostLogoutRedirectUris地址,
            /// 
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
           

            return RedirectToAction("Index", "Login");
        }
        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <returns></returns>
        public IActionResult GetAuthCode()
        {
            List<string> codelist = new VerifyCode().GenerateCheckCode();
            string checkCode = codelist[0];
            string verifyCode = codelist[1];
            verifyCode = EncryptUtil.MD5Password("V_" + verifyCode).ToLower();
            byte[] image = new VerifyCode().GetVerifyCode(checkCode);
            string base64 = Convert.ToBase64String(image);
            return Json(new { base64 = base64, verifyCode = verifyCode });
            //return File(new VerifyCode().GetVerifyCode(checkCode), @"image/Gif", checkCode);
        }

    }
}
相关推荐
许野平19 分钟前
Rust: 利用 chrono 库实现日期和字符串互相转换
开发语言·后端·rust·字符串·转换·日期·chrono
也无晴也无风雨23 分钟前
在JS中, 0 == [0] 吗
开发语言·javascript
狂奔solar31 分钟前
yelp数据集上识别潜在的热门商家
开发语言·python
blammmp1 小时前
Java:数据结构-枚举
java·开发语言·数据结构
何曾参静谧1 小时前
「C/C++」C/C++ 指针篇 之 指针运算
c语言·开发语言·c++
暗黑起源喵1 小时前
设计模式-工厂设计模式
java·开发语言·设计模式
WaaTong2 小时前
Java反射
java·开发语言·反射
Troc_wangpeng2 小时前
R language 关于二维平面直角坐标系的制作
开发语言·机器学习
努力的家伙是不讨厌的2 小时前
解析json导出csv或者直接入库
开发语言·python·json
Envyᥫᩣ2 小时前
C#语言:从入门到精通
开发语言·c#