Exemple #1
0
        public ActionResult EditPassword(Entities.ModifyModel modela, string returnUrl = null)
        {
            ModelState.Remove("Id");
            ViewBag.ReturnUrl = Url.IsLocalUrl(returnUrl) ? returnUrl : Url.RouteUrl("mainIndex");
            if (!ModelState.IsValid)
            {
                return(View(modela));
            }
            var model = _sysUserService.getById(WorkContext.CurrentUser.Id);

            if (model.Password == EncryptorHelper.GetMD5(modela.OriginalPassword.Trim() + model.Salt))
            {
                if (modela.ConfirmedPassword == modela.ModifiedPassword)
                {
                    model.Password = EncryptorHelper.GetMD5(modela.ConfirmedPassword.Trim() + model.Salt); //model.Name.Trim();;
                                                                                                           //model.Modifier = WorkContext.CurrentUser.Id;
                    _sysUserService.updatePassword(model);
                }
                else
                {
                    return(Redirect(Url.IsLocalUrl(returnUrl) ? returnUrl : Url.RouteUrl("password")));
                }
            }
            else
            {
                return(Redirect(Url.IsLocalUrl(returnUrl) ? returnUrl : Url.RouteUrl("password")));
            }
            return(Redirect(ViewBag.ReturnUrl));
        }
Exemple #2
0
        /// <summary>
        /// 修改密码,重置密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="oldPwd"></param>
        /// <param name="newPwd"></param>
        /// <param name="modifier"></param>
        /// <param name="reset">重置密码,只有管理员的操作</param>
        /// <returns></returns>
        public (bool Status, string Message) UpdatePwd(Guid userId, string oldPwd, string newPwd, Guid modifier, bool reset = false)
        {
            var user = _dbContext.Sys_User.Find(userId);

            if (user == null)
            {
                return(false, "用户不存在");
            }
            string oldJson = JsonConvert.SerializeObject(user);

            if (reset)
            {
                user.Password = EncryptorHelper.GetMD5(user.Account + user.Salt);
            }
            else
            {
                if (user.Password.Equals(oldPwd, StringComparison.InvariantCultureIgnoreCase))
                {
                    user.Password = newPwd;
                }
                else
                {
                    return(false, "原密码错误");
                }
            }
            _dbContext.SaveChanges();
            string newJson = JsonConvert.SerializeObject(user);

            _activityLogService.InsertedEntity <Entities.Sys_User>(userId, oldJson, newJson, modifier);
            return(true, "修改成功");
        }
Exemple #3
0
        public IActionResult UserEdit(Sys_UserMapping SysUser, List <string> RoleIds)
        {
            (bool Status, string Message)res;
            var item = _mapper.Map <Entities.sys_user>(SysUser);

            if (!String.IsNullOrEmpty(SysUser.id))
            {
                res = _sysUserService.UpdateUser(SysUser, UserId);
            }
            else
            {
                item.account       = item.account.TrimSpace();
                item.id            = CombGuid.NewGuidAsString();
                item.creation_time = DateTime.Now;
                item.creator       = UserId;
                item.salt          = EncryptorHelper.CreateSaltKey();
                item.password      = (EncryptorHelper.GetMD5(item.account + item.salt));
                res = _sysUserService.AddUser(item);
            }
            AjaxData.Message = res.Message;
            AjaxData.Success = res.Status;
            if (res.Status)
            {
                _sysRoleService.SetUserRoles(item.id, RoleIds, UserId);
            }
            return(Json(AjaxData));
        }
Exemple #4
0
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(NotValid());
            }
            (bool Status, string Message)res;
            var item = _mapper.Map <Entities.Sys_User>(SysUser);

            if (SysUser.Id != Guid.Empty)
            {
                res = _sysUserService.UpdateUser(SysUser, UserId);
            }
            else
            {
                item.Account      = item.Account.TrimSpace();
                item.Id           = CombGuid.NewGuid();
                item.CreationTime = DateTime.Now;
                item.Creator      = UserId;
                item.Salt         = EncryptorHelper.CreateSaltKey();
                item.Password     = (EncryptorHelper.GetMD5(item.Account + item.Salt));
                res = _sysUserService.AddUser(item);
            }
            AjaxData.Message = res.Message;
            AjaxData.Code    = res.Status ? 0 : 2001;
            if (res.Status)
            {
                _sysRoleService.SetUserRoles(item.Id, RoleIds, UserId);
            }
            return(Json(AjaxData));
        }
Exemple #5
0
        public ActionResult EditUser(Entities.SysUser model, string returnUrl = null)
        {
            ModelState.Remove("Id");
            ViewBag.ReturnUrl = Url.IsLocalUrl(returnUrl) ? returnUrl : Url.RouteUrl("userIndex");
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            if (!String.IsNullOrEmpty(model.MobilePhone))
            {
                model.MobilePhone = StringUitls.toDBC(model.MobilePhone);
            }
            model.Name = model.Name.Trim();

            if (model.Id == Guid.Empty)
            {
                model.Id           = Guid.NewGuid();
                model.CreationTime = DateTime.Now;
                model.Salt         = EncryptorHelper.CreateSaltKey();
                model.Account      = StringUitls.toDBC(model.Account.Trim());
                model.Enabled      = true;
                model.IsAdmin      = false;
                model.Password     = EncryptorHelper.GetMD5(model.Account + model.Salt);
                model.Creator      = WorkContext.CurrentUser.Id;
                _sysUserService.insertSysUser(model);
            }
            else
            {
                model.ModifiedTime = DateTime.Now;
                model.Modifier     = WorkContext.CurrentUser.Id;
                _sysUserService.updateSysUser(model);
            }
            return(Redirect(ViewBag.ReturnUrl));
        }
Exemple #6
0
        /// <summary>
        /// 重置密码。默认重置成账号一样
        /// </summary>
        /// <param name="id"></param>
        /// <param name="modifer"></param>
        public void resetPassword(Guid id, Guid modifer)
        {
            var sysUser = _sysUserRepository.getById(id);

            sysUser.Password = EncryptorHelper.GetMD5(sysUser.Account + sysUser.Salt);
            sysUser.Modifier = modifer;
            _sysUserRepository.update(sysUser);
        }
Exemple #7
0
        /// <summary>
        /// 用户自己修改密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="password"></param>
        public void changePassword(Guid id, string password)
        {
            var sysUser = _sysUserRepository.getById(id);

            sysUser.Password = EncryptorHelper.GetMD5(password + sysUser.Salt);
            sysUser.Modifier = sysUser.Id;
            _sysUserRepository.update(sysUser);
        }
Exemple #8
0
        public void changePassword(Guid id, string password)
        {
            var user       = _sysUserRepository.getById(id);
            var mdPassword = EncryptorHelper.GetMD5(password + user.Salt);

            user.Password = mdPassword;
            _sysUserRepository.update(user);
        }
Exemple #9
0
        /// <summary>
        /// 重置密码。默认重置成账号一样
        /// </summary>
        /// <param name="id"></param>
        /// <param name="modifer"></param>
        public void resetPassword(Guid id, Guid modifer)
        {
            var user = _sysUserRepository.getById(id);

            user.Password     = EncryptorHelper.GetMD5(user.Account.Trim() + user.Salt);
            user.Modifier     = modifer;
            user.ModifiedTime = DateTime.Now;

            _sysUserRepository.update(user);
        }
Exemple #10
0
        public IActionResult LoginIndex()
        {
            string r = EncryptorHelper.GetMD5(Guid.NewGuid().ToString());

            HttpContext.Session.SetString(Login_Key, r);
            LoginModel loginModel = new LoginModel {
                R = r
            };

            return(View(loginModel));
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="password">新密码</param>
        public void ChangePassword(Guid id, string password)
        {
            var user = _sysUserRepository.GetById(id);

            if (user != null)
            {
                user.Password     = EncryptorHelper.GetMD5(password + user.Salt);
                user.ModifiedTime = DateTime.Now;
                user.Modifier     = user.Id;
                _sysUserRepository.DbContext.SaveChanges();
            }
        }
Exemple #12
0
        public ActionResult ResetPassword(Guid id)
        {
            var modelpass = _sysUserService.getById(id);

            modelpass.Password = EncryptorHelper.GetMD5("Sacc2020" + modelpass.Salt);
            modelpass.Modifier = WorkContext.CurrentUser.Id;
            _sysUserService.resetPassword(modelpass);
            AjaxData.Status  = true;
            AjaxData.Message = "用户密码已重置为原始密码";
            // return Json(AjaxData);
            return(Redirect(Url.IsLocalUrl(null) ? null : Url.RouteUrl("userIndex")));
        }
Exemple #13
0
        public static void InitData(this IApplicationBuilder app)
        {
            #region 自动创建数据库
            // Microsoft.EntityFrameworkCore.Tools Microsoft.EntityFrameworkCore.SqlServer.Design
            //dotnet ef migrations add InitialEFDbContext -c EFDbContext -o Data/Migrations/DemoDB
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService <EFDbContext>();

                /*
                 * System.Data.SqlClient.SqlException:“将 FOREIGN KEY 约束 'FK_SysPermission_SysRole_RoleId' 引入表 'SysPermission'
                 * 可能会导致循环或多重级联路径。请指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
                 * 无法创建约束。请参阅前面的错误消息。
                 */
                context.Database.Migrate();
            }
            #endregion

            #region 初始化数据
            var _sysUserService = EnginContext.Current.Resolve <ISysUserService>();
            var _sysRoleService = EnginContext.Current.Resolve <ISysRoleService>();

            SysUser sysUser = new SysUser();
            if (!_sysUserService.ExistUser())
            {
                sysUser.Id           = Guid.NewGuid();
                sysUser.Account      = "admin";
                sysUser.Name         = "超级管理员";
                sysUser.Email        = "";
                sysUser.MobilePhone  = "";
                sysUser.Salt         = EncryptorHelper.CreateSaltKey();
                sysUser.Password     = EncryptorHelper.GetMD5(sysUser.Account + sysUser.Salt);
                sysUser.Enabled      = true;
                sysUser.IsAdmin      = true;
                sysUser.CreationTime = DateTime.Now;
                sysUser.LoginLock    = false;
                sysUser.IsDeleted    = false;
                _sysUserService.InsertSysUser(sysUser);
            }

            if (!_sysRoleService.ExistRole())
            {
                SysRole sysRole = new SysRole()
                {
                    Id           = Guid.NewGuid(),
                    Name         = "超级管理员",
                    Creator      = sysUser.Id,
                    CreationTime = DateTime.Now
                };
                _sysRoleService.InsertRole(sysRole);
            }
            #endregion
        }
Exemple #14
0
        public IActionResult Login()
        {
            var r = EncryptorHelper.GetMD5(Guid.NewGuid().ToString());

            HttpContext.Session.SetString(S_KEY, r);
            string     ramdom = HttpContext.Session.GetString(S_KEY);
            LoginModel model  = new LoginModel()
            {
                R = r
            };

            return(View(model));
        }
        public IActionResult ChangePassword(string password)
        {
            if (_adminAuthService.getCurrentUser() == null)
            {
                Redirect(Url.RouteUrl("publicLogin"));
            }
            var user = _adminAuthService.getCurrentUser();

            user.Password = EncryptorHelper.GetMD5(password + user.Salt);
            _sysUserService.updateSysUser(user);


            return(Json(new { status = true, Message = "密码修改成功!" }));
        }
Exemple #16
0
        /// <summary>
        /// 用户登陆验证
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <param name="platform">0:web,1:app</param>
        /// <returns></returns>
        public (bool Status, string Message, Entities.Sys_User User, Entities.Sys_UserJwt Jwt) ValidateUser(string account, string password, int platform = 0)
        {
            var user = _dbContext.Sys_User.Where(o => o.Account == account && !o.IsDeleted).FirstOrDefault();

            if (user == null)
            {
                return(false, "账号或密码错误", null, null);
            }

            var r_item = _dbContext.Sys_UserR.FirstOrDefault(o => o.UserId == user.Id && o.Platform == platform);

            if (r_item == null)
            {
                return(false, "非法操作,因子不存在,请重试", null, null);
            }

            var pwd = EncryptorHelper.GetMD5((user.Password ?? "") + r_item.R);
            var log = new Sys_UserLogin()
            {
                Id        = CombGuid.NewGuid(),
                UserId    = user.Id,
                IpAddress = _webHelper.GetIPAddress(),
                LoginTime = DateTime.Now,
                Status    = false
            };

            Entities.Sys_UserJwt jwt = null;
            string msg = "账号或密码错误";

            if (password.Equals(pwd, StringComparison.InvariantCultureIgnoreCase))
            {
                log.Status         = true;
                msg                = "登陆成功";
                user.LastIpAddress = log.IpAddress;
                _dbContext.Sys_UserR.Remove(r_item);
                jwt = new Sys_UserJwt()
                {
                    Jti          = EncryptorHelper.GetMD5(Guid.NewGuid().ToString()),
                    Expiration   = DateTime.Now.AddDays(30),
                    RefreshToken = EncryptorHelper.GetMD5(Guid.NewGuid().ToString()),
                    Platform     = platform,
                    UserId       = user.Id
                };
                _dbContext.Sys_UserJwt.Add(jwt);
            }
            _dbContext.Sys_UserLogin.Add(log);
            _dbContext.SaveChanges();
            return(log.Status, msg, user, jwt);
        }
Exemple #17
0
        public IActionResult LoginIndex()
        {
            string r = EncryptorHelper.GetMD5(Guid.NewGuid().ToString());

            HttpContext.Session.SetString(R_KEY, r);
            LoginModel loginModel = new LoginModel()
            {
                R = r
            };

            //为啥不找自己的视图呢?
            return(View(loginModel));

            //return View();
        }
Exemple #18
0
        public IActionResult Index()
        {
            var Salt     = EncryptorHelper.CreateSaltKey();
            var Password = EncryptorHelper.GetMD5("bobo" + Salt);

            string r = EncryptorHelper.GetMD5(Guid.NewGuid().ToString());

            HttpContext.Session.SetString(R_KEY, r);
            LoginModel loginModel = new LoginModel()
            {
                R = r
            };

            return(View(loginModel));
        }
        /// <summary>
        /// 重置密码(默认重置成和账号一样)
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="modifer">修改人Id</param>
        public void ResetPassword(Guid id, Guid modifer)
        {
            var user = _sysUserRepository.GetById(id);

            if (user != null)
            {
                if (string.IsNullOrEmpty(user.Salt))
                {
                    user.Salt = EncryptorHelper.CreateSaltKey();
                }
                user.Password     = EncryptorHelper.GetMD5(user.Account + user.Salt);
                user.ModifiedTime = DateTime.Now;
                user.Modifier     = modifer;
                _sysUserRepository.DbContext.SaveChanges();
            }
        }
Exemple #20
0
 /// <summary>
 /// 初始化用户表
 /// </summary>
 public void Init_SysUser()
 {
     try
     {
         _sysUserService.Insert(new SysUser()
         {
             Account  = "Admin",
             Password = EncryptorHelper.GetMD5("Admin"),
             Name     = "张三",
         });
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        public ValidLoginModel <Base_User> ChangePassword(ChangePasswordModel model)
        {
            ValidLoginModel <Base_User> loginModel = new ValidLoginModel <Base_User>();

            loginModel.Success = false;
            loginModel.Token   = model.token;
            loginModel.User    = null;
            var user = GetUserInfoByAccount(model.Accont);

            user.Password = EncryptorHelper.GetMD5(model.NewPassword + user.Salt);
            _sysUserRepository.update(user, true);
            //缓存
            _cache.SetCache(String.Format(MODEL_KEY, user.Id), user, DateTimeOffset.Now.AddHours(4));
            loginModel.User = user;
            return(loginModel);
        }
Exemple #22
0
 /// <summary>
 /// 验证登陆时获取
 /// </summary>
 /// <param name="account"></param>
 /// <returns></returns>
 public (string Salt, string R) GetSalt(string account, int platform = 0)
 {
     using (var trans = _dbContext.Database.BeginTransaction())
     {
         var user = _dbContext.Sys_User.Where(o => o.Account == account && !o.IsDeleted).Select(item => new { Id = item.Id, Salt = item.Salt }).FirstOrDefault();
         if (user == null)
         {
             return(null, null);
         }
         //删除原有记录再新增
         string r = EncryptorHelper.GetMD5(Guid.NewGuid().ToString());
         _dbContext.Database.ExecuteSqlRaw($"DELETE FROM [Sys_UserR] WHERE [UserId]='{user.Id}' AND [Platform]={platform};");
         _dbContext.Database.ExecuteSqlRaw($"INSERT INTO [Sys_UserR]([Id],[UserId],[R],[Platform])VALUES('{CombGuid.NewGuid()}','{user.Id}','{r}',{platform});");
         trans.Commit();
         return(user.Salt, r);
     }
 }
Exemple #23
0
        public IActionResult register(Entities.RegisterModel model)
        {
            if (_sysUserService.existAccount(model.Account))
            {
                AjaxData.Status  = false;
                AjaxData.Message = "该账号已存在";
                return(Json(AjaxData));
            }

            if (_sysUserService.existEmail(model.Email))
            {
                AjaxData.Status  = false;
                AjaxData.Message = "该邮箱已被注册";
                return(Json(AjaxData));
            }

            if (_sysUserService.existMobilePhone(model.MobilePhone))
            {
                AjaxData.Status  = false;
                AjaxData.Message = "该手机号码已被注册";
                return(Json(AjaxData));
            }


            Entities.SysUser user = new Entities.SysUser();
            user.Account     = model.Account;
            user.Name        = model.Name;
            user.Email       = model.Email;
            user.MobilePhone = model.MobilePhone;

            user.Id           = Guid.NewGuid();
            user.CreationTime = DateTime.Now;
            user.Salt         = EncryptorHelper.CreateSaltKey();
            user.Account      = user.Account.Trim();
            user.Enabled      = true;
            user.IsAdmin      = false;
            user.Password     = EncryptorHelper.GetMD5(model.Password + user.Salt);
            user.Creator      = user.Id;
            _sysUserService.insertSysUser(user);

            AjaxData.Status  = true;
            AjaxData.Message = "注册成功";

            return(Json(AjaxData));
        }
Exemple #24
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new GeneralDbContext(serviceProvider.GetRequiredService <DbContextOptions <GeneralDbContext> >()))
            {
                if (context.SysUsers.Any())
                {
                    return;
                }
                var salt = EncryptorHelper.CreateSaltKey();

                context.SysUsers.AddRange(
                    new Entities.SysUser
                {
                    Id          = Guid.NewGuid(),
                    Account     = "41606217",
                    Name        = "吴宗锦",
                    Salt        = salt,
                    Password    = EncryptorHelper.GetMD5("15160296867" + salt),
                    IsAdmin     = true,
                    Email       = "*****@*****.**",
                    MobilePhone = "18229065977",


                    Sex              = "男",
                    Enabled          = true,
                    CreationTime     = DateTime.Now,
                    LoginFailedNum   = 0,
                    AllowLoginTime   = null,
                    LoginLock        = false,
                    LastLoginTime    = null,
                    LastIpAddress    = "",
                    LastActivityTime = DateTime.Now,
                    IsDeleted        = false,
                    DeletedTime      = null,
                    ModifiedTime     = null,
                    Modifier         = null,
                    Creator          = null,
                    Avatar           = new byte[0],
                }
                    );
                context.SaveChanges();
            }
        }
 public IActionResult EditUser(SysUser model, string sysRole, string returnUrl = null)
 {
     ViewBag.ReturnUrl   = Url.IsLocalUrl(returnUrl) ? returnUrl : Url.RouteUrl("userIndex");
     ViewBag.SysRoleList = _sysRoleService.GetAllRoles().Select(o => new SelectListItem()
     {
         Value = o.Id.ToString(), Text = o.Name, Selected = (o.Id.ToString() == sysRole)
     }).ToList();
     ModelState.Remove("Id");
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     if (!string.IsNullOrEmpty(model.MobilePhone))
     {
         model.MobilePhone = StringUitls.toDBC(model.MobilePhone);
     }
     model.Name = model.Name.Trim();
     if (model.Id == Guid.Empty)
     {
         model.Id           = Guid.NewGuid();
         model.CreationTime = DateTime.Now;
         model.Salt         = EncryptorHelper.CreateSaltKey();
         model.Account      = StringUitls.toDBC(model.Account);
         model.Enabled      = true;
         model.IsAdmin      = false;
         model.Password     = EncryptorHelper.GetMD5(model.Account + model.Salt);
         model.Creator      = _workContext.CurrentUser().Id;
         _sysUserService.InsertSysUser(model);
     }
     else
     {
         model.ModifiedTime = DateTime.Now;
         model.Modifier     = _workContext.CurrentUser().Id;
         _sysUserService.UpdateSysUser(model);
     }
     if (!string.IsNullOrEmpty(sysRole))
     {
         _sysUserRoleService.InsertOrUpdateSysUserRole(model.Id, new Guid(sysRole));
     }
     return(Redirect(ViewBag.ReturnUrl));
 }
Exemple #26
0
        public string CheckLogin(string Account, string Pwd)
        {
            Pwd = EncryptorHelper.GetMD5(Pwd);
            SysUser user = _sysUserService.CheckUser(Account, Pwd);

            if (user != null)
            {
                WebHelper.WebHelper.UserSession = user;
                if (HttpContext.Session.GetString("Url") != null)
                {
                    string url = HttpContext.Session.GetString("Url").ToString();
                    HttpContext.Session.Remove("Url");
                    return(url);
                }
                return("1");
            }
            else
            {
                return("0");
            }
        }
Exemple #27
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // base.OnModelCreating(modelBuilder);
            var salt = EncryptorHelper.CreateSaltKey();

            modelBuilder.Entity <SysUser>().HasData(new SysUser()
            {
                Id               = Guid.NewGuid(),
                Account          = "admin",
                Name             = "超级管理员",
                Salt             = salt,
                Password         = EncryptorHelper.GetMD5("123456" + salt),
                Enabled          = true,
                IsAdmin          = true,
                CreationTime     = DateTime.Now,
                LoginFailedNum   = 0,
                LoginLock        = false,
                LastActivityTime = null,
                IsDeleted        = false
            });
        }
Exemple #28
0
        //[HttpPost, Route("api")]
        public ActionResult Login(string Account, string Password)
        {
            string r = EncryptorHelper.GetMD5(Guid.NewGuid().ToString());

            if (!ModelState.IsValid)
            {
                AjaxData.Message = "请输入用户账号和密码";
                return(Json(AjaxData));
            }

            var result = sysUserService.validateUser(Account, Password, r, true);

            AjaxData.Status  = result.Status;
            AjaxData.Message = result.Message;

            string token = "";

            if (result.Status)
            {
                authenticateService.IsAuthenticated(result.Token, out token);
                AjaxData.Data = token;
            }
            return(Json(AjaxData));
        }
        /// <summary>
        /// 验证登录状态
        /// </summary>
        /// <param name="account">登录账号</param>
        /// <param name="password">登录密码</param>
        /// <param name="r">登录随机数</param>
        /// <returns></returns>
        public ValidLoginModel <Base_User> ValidateUser(string account, string password, string r)
        {
            ValidLoginModel <Base_User> loginModel = new ValidLoginModel <Base_User>();

            loginModel.Success = false;
            loginModel.Token   = "";
            loginModel.User    = null;
            var user = GetUserInfoByAccount(account);

            if (user == null)
            {
                loginModel.Message = "未找到对应帐号";
                return(loginModel);
            }
            if (!user.Enabled)
            {
                loginModel.Message = "你的账号已被冻结";
                return(loginModel);
            }
            if (user.LoginLock)
            {
                if (user.AllowLoginTime > DateTime.Now)
                {
                    loginModel.Message = "账号已被锁定" + ((int)(user.AllowLoginTime - DateTime.Now).Value.TotalSeconds + 1) + "秒。";
                    return(loginModel);
                }
            }
            var md5Password = EncryptorHelper.GetMD5(user.Password + r);

            //匹配密码
            if (password.Equals(md5Password, StringComparison.InvariantCultureIgnoreCase))
            {
                user.LoginLock      = false;
                user.LoginFailedNum = 0;
                user.AllowLoginTime = null;
                user.LastLoginTime  = DateTime.Now;
                user.LastIpAddress  = "";
                loginModel.Success  = true;
                loginModel.Message  = "登录成功";
                loginModel.Token    = Guid.NewGuid().ToString();
                loginModel.User     = user;
                _sysUserTokenRepository.DbContext.Add(new Base_UserToken()
                {
                    Id         = loginModel.Token,
                    ExpireTime = DateTime.Now.AddDays(15),
                    UserId     = user.Id
                });
                _sysOperateLogRepository.DbContext.Add(new Base_OperateLog()
                {
                    Id            = Guid.NewGuid().ToString(),
                    UserId        = user.Id,
                    CreateTime    = DateTime.Now,
                    OperateCotent = "登录成功",
                    OperateType   = "LoginIn",
                    IpAddress     = this._httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()
                });
            }
            else
            {
                user.LoginFailedNum++;
                if (user.LoginFailedNum > 4)
                {
                    user.LoginLock      = true;
                    user.AllowLoginTime = DateTime.Now.AddMinutes(2);
                    user.LoginFailedNum = 0;
                    loginModel.Message  = "账号已被锁定,请2分钟后再登录";
                }
                else
                {
                    loginModel.Message = $"登录密码错误,还有{5-user.LoginFailedNum}次机会";
                }
            }
            _sysUserRepository.DbContext.SaveChanges();
            return(loginModel);
        }
Exemple #30
0
        /// <summary>
        /// 验证登录状态
        /// </summary>
        /// <param name="account">登录账号</param>
        /// <param name="password">登录密码</param>
        /// <param name="r">登录随机数</param>
        /// <returns></returns>
        public (bool Status, string Message, string Token, Entities.SysUser User) validateUser(string account, string password, string r)
        {
            var user = getByAccount(account);

            if (user == null)
            {
                return(false, "用户名或密码错误", null, null);
            }
            if (!user.Enabled)
            {
                return(false, "你的账号已被冻结", null, null);
            }

            if (user.LoginLock)
            {
                if (user.AllowLoginTime > DateTime.Now)
                {
                    return(false, "账号已被锁定" + ((int)(user.AllowLoginTime - DateTime.Now).Value.TotalMinutes + 1) + "分钟。", null, null);
                }
            }

            var md5Password = EncryptorHelper.GetMD5(user.Password + r);

            //匹配密码
            if (password.Equals(md5Password, StringComparison.InvariantCultureIgnoreCase))
            {
                user.LoginLock      = false;
                user.LoginFailedNum = 0;
                user.AllowLoginTime = null;
                user.LastLoginTime  = DateTime.Now;
                user.LastIpAddress  = "";

                // _sysUserRepository.DbContext.SaveChanges();

                //登录日志
                var userLoginLog = new SysUserLoginLog()
                {
                    Id        = Guid.NewGuid(),
                    IpAddress = "",
                    UserId    = user.Id,
                    LoginTime = DateTime.Now,
                    Message   = "登录:成功"
                };
                // user.SysUserLoginLogs.Add(userLoginLog);

                _sysUserLogRepository.insert(userLoginLog);
                // _sysUserLogRepository.SaveChanges();

                //单点登录,移除旧的登录token
                var userToken = new SysUserToken()
                {
                    Id         = Guid.NewGuid(),
                    SysUserId  = user.Id,
                    ExpireTime = DateTime.Now.AddDays(15)
                };

                // user.SysUserTokens.Add(userToken);
                _sysUserTokenRepository.insert(userToken);

                _sysUserRepository.DbContext.SaveChanges();

                return(true, "登录成功", userToken.Id.ToString(), user);
            }
            else
            {
                //登录日志
                user.SysUserLoginLogs.Add(new SysUserLoginLog()
                {
                    Id        = Guid.NewGuid(),
                    IpAddress = "",
                    LoginTime = DateTime.Now,
                    Message   = "登录:密码错误"
                });

                user.LoginFailedNum++;

                if (user.LoginFailedNum > 5)
                {
                    user.LoginLock      = true;
                    user.AllowLoginTime = DateTime.Now.AddHours(2);
                }

                _sysUserRepository.DbContext.SaveChanges();
            }
            return(false, "用户名或密码错误", null, null);
        }