Example #1
0
        public IActionResult UpdatePassword([FromBody] UserCenterUpdatePasswordDto parm)
        {
            if (Convert.ToBoolean(AppSettings.Configuration["AppSettings:Demo"]))
            {
                ToResponse(StatusCodeType.Error, "当前为演示模式 , 您无权修改任何数据");
            }

            var userSession = _tokenManager.GetSessionInfo();

            var userInfo = _usersService.GetId(userSession.UserID);

            // 验证旧密码是否正确
            if (!PasswordUtil.ComparePasswords(userInfo.UserID, userInfo.Password, parm.CurrentPassword.Trim()))
            {
                return(ToResponse(StatusCodeType.Error, "旧密码输入不正确"));
            }

            // 更新用户密码
            var response = _usersService.Update(m => m.UserID == userInfo.UserID, m => new Sys_Users()
            {
                Password = PasswordUtil.CreateDbPassword(userInfo.UserID, parm.ConfirmPassword.Trim())
            });

            // 删除登录会话记录
            _tokenManager.RemoveAllSession(userInfo.UserID);

            return(ToResponse(response));
        }
Example #2
0
        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            // 检查当前密码是否正确
            string oldPass        = tbxOldPassword.Text.Trim();
            string newPass        = tbxNewPassword.Text.Trim();
            string confirmNewPass = tbxConfirmNewPassword.Text.Trim();

            if (newPass != confirmNewPass)
            {
                tbxConfirmNewPassword.MarkInvalid("确认密码和新密码不一致!");
                return;
            }

            IList <ICriterion> qryList = new List <ICriterion>();

            qryList.Add(Expression.Eq("Name", User.Identity.Name));
            users user = Core.Container.Instance.Resolve <IServiceUsers>().GetEntityByFields(qryList);

            //User user = DB.Users.Where(u => u.Name == User.Identity.Name).FirstOrDefault();

            if (user != null)
            {
                if (!PasswordUtil.ComparePasswords(user.Password, oldPass))
                {
                    tbxOldPassword.MarkInvalid("当前密码不正确!");
                    return;
                }

                user.Password = PasswordUtil.CreateDbPassword(newPass);
                Core.Container.Instance.Resolve <IServiceUsers>().Update(user);
                //DB.SaveChanges();

                Alert.ShowInTop("修改密码成功!");
            }
        }
Example #3
0
        public IActionResult Login([FromBody] LoginDto parm)
        {
            var captchaCode = RedisServer.Cache.Get($"Captcha:{parm.Uuid}");

            RedisServer.Cache.Del($"Captcha:{parm.Uuid}");

            if (parm.Code.ToUpper() != captchaCode)
            {
                //return toResponse(StatusCodeType.Error, "输入验证码无效");
            }

            var userInfo = _userService.GetFirst(o => o.UserID == parm.UserName.Trim());

            if (userInfo == null)
            {
                return(toResponse(StatusCodeType.Error, "用户名或密码错误"));
            }

            if (!PasswordUtil.ComparePasswords(userInfo.ID, userInfo.Password, parm.PassWord.Trim()))
            {
                return(toResponse(StatusCodeType.Error, "用户名或密码错误"));
            }

            if (!userInfo.Enabled)
            {
                return(toResponse(StatusCodeType.Error, "用户未启用,请联系管理员!"));
            }

            var userToken = _tokenManager.CreateSession(userInfo, SourceType.Web, Convert.ToInt32(AppSettings.Configuration["AppSettings:WebSessionExpire"]));

            return(toResponse(userToken));
        }
Example #4
0
        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            // 检查当前密码是否正确
            string oldPass        = tbxOldPassword.Text.Trim();
            string newPass        = tbxNewPassword.Text.Trim();
            string confirmNewPass = tbxConfirmNewPassword.Text.Trim();

            if (newPass != confirmNewPass)
            {
                tbxConfirmNewPassword.MarkInvalid("确认密码和新密码不一致!");
                return;
            }

            User user = DB.Users.Where(u => u.Name == User.Identity.Name).FirstOrDefault();

            if (user != null)
            {
                if (!PasswordUtil.ComparePasswords(user.Password, oldPass))
                {
                    tbxOldPassword.MarkInvalid("当前密码不正确!");
                    return;
                }

                user.Password = PasswordUtil.CreateDbPassword(newPass);
                DB.SaveChanges();

                Alert.ShowInTop("修改密码成功!");
            }
        }
Example #5
0
        public async Task <IActionResult> OnPostChangePassword_btnSave_OnClickAsync(string tbxOldPassword, string tbxNewPassword, string tbxConfirmNewPassword)
        {
            int?id = GetIdentityID();

            // 检查当前密码是否正确
            string oldPass        = tbxOldPassword.Trim();
            string newPass        = tbxNewPassword.Trim();
            string confirmNewPass = tbxConfirmNewPassword.Trim();

            if (newPass != confirmNewPass)
            {
                UIHelper.TextBox("tbxConfirmNewPassword").MarkInvalid("确认密码和新密码不一致!");
            }
            else
            {
                User user = await DB.Users.Where(u => u.ID == id).AsNoTracking().FirstOrDefaultAsync();

                if (user != null)
                {
                    if (!PasswordUtil.ComparePasswords(user.Password, oldPass))
                    {
                        UIHelper.TextBox("tbxOldPassword").MarkInvalid("当前密码不正确!");
                    }
                    else
                    {
                        user.Password = PasswordUtil.CreateDbPassword(newPass);
                        await DB.SaveChangesAsync();

                        Alert.ShowInTop("修改密码成功!");
                    }
                }
            }

            return(UIHelper.Result());
        }
Example #6
0
        public async Task <IActionResult> Login([FromBody] LoginDto parm)
        {
            //获取缓存验证码
            var verificationCode = RedisServer.Cache.Get($"VerificationCode:{parm.UUID}");

            //删除缓存
            RedisServer.Cache.Del($"VerificationCode:{parm.UUID}");
            if (parm.VerificationCode.ToUpper() != verificationCode)
            {
                return(ToResponseJson(ResultModel <string> .Fail("验证码无效")));
            }
            var userInfo = await _userService.QuerySingle(t => t.LoginName == parm.LoginName && t.UserType == UserType.Admin && !t.Deleted);

            if (userInfo == null)
            {
                return(ToResponseJson(ResultModel <string> .Fail("用户名或密码错误")));
            }
            //验证密码
            var isPassword = !PasswordUtil.ComparePasswords(userInfo.ID.ToString(), userInfo.Password, parm.PassWord.Trim());

            if (isPassword)
            {
                return(ToResponseJson(ResultModel <string> .Fail("用户名或密码错误")));
            }
            //创建用户Session
            var userSession = _sessionManager.Create(userInfo, 24);

            return(ToResponseJson(ResultModel <string> .Ok(userSession, HttpStatusCode.Success)));
        }
Example #7
0
        public async Task <Boolean> CheckPasswordAsync(Int32 userId, String oldUserPassword)
        {
            Check.IfNullOrZero(userId);
            Check.IfNullOrZero(oldUserPassword);
            var result = await _userContext.GetOldPasswordAsync(userId);

            return(PasswordUtil.ComparePasswords(result, oldUserPassword));
        }
Example #8
0
        //验证与原密码是否匹配
        private bool passwordIsOk(string inputStr)
        {
            string sqlCmd = "select password from OA_Sys_EmployeeInfo where id='" + GetUser() + "'";
            string dbPsw  = SqlSel.GetSqlScale(sqlCmd).ToString();

            if (PasswordUtil.ComparePasswords(dbPsw, inputStr))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #9
0
        /// <summary>
        /// 本地账号验证
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="password"></param>
        /// <param name="failCount"></param>
        /// <returns></returns>
        private string CheckUserInfo(UserDetail userInfo, string password)
        {
            var msg = "";

            // 账号已经停用
            if (!userInfo.enabled)
            {
                return("您的账号已停用");
            }
            // 密码验证
            if (!PasswordUtil.ComparePasswords(userInfo.password, password))
            {
                return("用户名/密码不匹配");
            }
            return(msg);
        }
Example #10
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string userName = tbxUserName.Text.Trim();
            string password = tbxPassword.Text.Trim();

            User user = DB.Users.Where(u => u.Name == userName).FirstOrDefault();

            if (user != null)
            {
                if (PasswordUtil.ComparePasswords(user.Password, password))
                {
                    if (!user.Enabled)
                    {
                        ShowNotify("用户未启用,请联系管理员!", MessageBoxIcon.Error);
                    }
                    else
                    {
                        // 登录成功
                        //logger.Info(String.Format("登录成功:用户“{0}”", user.Name));

                        LoginSuccess(user);

                        return;
                    }
                }
                else
                {
                    //logger.Warn(String.Format("登录失败:用户“{0}”密码错误", userName));
                    ShowNotify("用户名或密码错误!", MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                //logger.Warn(String.Format("登录失败:用户“{0}”不存在", userName));
                ShowNotify("用户名或密码错误!", MessageBoxIcon.Error);
                return;
            }
        }
Example #11
0
        public async Task <Boolean> UnlockScreenAsync(Int32 userId, String unlockPassword)
        {
            Check.IfNullOrZero(userId);
            Check.IfNullOrZero(unlockPassword);

            return(await Task.Run(() =>
            {
                using var mapper = EntityMapper.CreateMapper();
                {
                    #region 获取锁屏密码
                    {
                        var user = mapper.Query <User>()
                                   .Where(w => w.Id == userId && !w.IsDisable)
                                   .Select(a => new { a.LockScreenPassword })
                                   .FirstOrDefault();

                        return PasswordUtil.ComparePasswords(user.LockScreenPassword, unlockPassword);
                    }
                    #endregion
                }
            }));
        }
Example #12
0
        public async Task <IActionResult> OnPostBtnSubmit_ClickAsync(string tbxUserName, string tbxPassword)
        {
            string userName = tbxUserName.Trim();
            string password = tbxPassword.Trim();

            User user = await DB.Users
                        .Include(u => u.RoleUsers)
                        .Where(u => u.Name == userName).AsNoTracking().FirstOrDefaultAsync();

            if (user != null)
            {
                if (PasswordUtil.ComparePasswords(user.Password, password))
                {
                    if (!user.Enabled)
                    {
                        Alert.Show("用户未启用,请联系管理员!");
                    }
                    else
                    {
                        // 登录成功
                        await LoginSuccess(user);

                        // 重定向到登陆后首页
                        return(RedirectToPage("/Index"));
                    }
                }
                else
                {
                    Alert.Show("用户名或密码错误!");
                }
            }
            else
            {
                Alert.Show("用户名或密码错误!");
            }

            return(UIHelper.Result());
        }
        public IActionResult LoginMiniProgram([FromBody] LoginMiniProgramDto parm)
        {
            var userInfo = _userService.GetFirst(o => o.UserID == parm.UserName.Trim());

            if (userInfo == null)
            {
                return(ToResponse(StatusCodeType.Error, "用户名或密码错误"));
            }

            if (!PasswordUtil.ComparePasswords(userInfo.UserID, userInfo.Password, parm.PassWord.Trim()))
            {
                return(ToResponse(StatusCodeType.Error, "用户名或密码错误"));
            }

            if (!userInfo.Enabled)
            {
                return(ToResponse(StatusCodeType.Error, "用户未启用,请联系管理员!"));
            }

            var userToken = _tokenManager.CreateSession(userInfo, SourceType.MiniProgram, Convert.ToInt32(AppSettings.Configuration["AppSettings:MiniProgramSessionExpire"]));

            return(ToResponse(userToken));
        }
        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            // 检查当前密码是否正确
            string oldPass        = tbxOldPassword.Text.Trim();
            string newPass        = tbxNewPassword.Text.Trim();
            string confirmNewPass = tbxConfirmNewPassword.Text.Trim();

            if (newPass != confirmNewPass)
            {
                tbxConfirmNewPassword.MarkInvalid("确认密码和新密码不一致!");
                return;
            }

            UserModel.ID = int.Parse(getUserID(GetIdentityName()));
            DataSet ds = XASYU.BLL.DataBaseQuery.query_SYS_USERS(userBean, UserModel, ref V_ITOTALCOUNT, 0, 20);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                if (!PasswordUtil.ComparePasswords(ds.Tables[0].Rows[0]["Password"].ToString(), oldPass))
                {
                    tbxOldPassword.MarkInvalid("当前密码不正确!");
                    return;
                }
                string NewPassword = PasswordUtil.CreateDbPassword(newPass);
                string strWhere    = "ID=" + UserModel.ID;
                if (Common.UpdateTable("sys_Users", new string[] { "Password" }, new string[, ] {
                    { "" + NewPassword + "", "1" }
                }, strWhere) == 0)
                {
                    Alert.ShowInTop("修改密码成功!");
                }
                else
                {
                    Alert.ShowInTop("修改密码失败!");
                }
            }
        }
Example #15
0
        public ActionResult btnSave_OnClick()
        {
            // 检查当前密码是否正确
            string oldPass        = Request["tbxOldPassword"];
            string newPass        = Request["tbxNewPassword"];
            string confirmNewPass = Request["tbxConfirmNewPassword"];

            if (newPass != confirmNewPass)
            {
                UIHelper.TextBox("tbxConfirmNewPassword").MarkInvalid("确认密码和新密码不一致!");
            }

            if (!PasswordUtil.ComparePasswords(Panda_UserInfoDal.Get(GetIdentityName())["UserPwd"].ToString(), oldPass))
            {
                UIHelper.TextBox("tbxOldPassword").MarkInvalid("当前密码不正确!");
            }

            try
            {
                //string userGH = GetIdentityName();
                //User users = db.users.Where(x => x.Name.Equals(userGH)).FirstOrDefault();
                //users.Password = PasswordUtil.CreateDbPassword(newPass);
                //db.SaveChanges();
                Hashtable hasData = new Hashtable();
                hasData["ID"]      = GetIdentityName();
                hasData["UserPwd"] = PasswordUtil.CreateDbPassword(newPass);
                Panda_UserInfoDal.Update(hasData);
                ShowNotify("修改密码成功!");
            }
            catch
            {
                ShowNotify("修改密码失败,请重新操作!");
            }

            return(UIHelper.Result());
        }
Example #16
0
        public async Task <User> IfNullOrZeroAsync(String userName, String password, String requestIp)
        {
            Check.IfNullOrZero(userName);
            Check.IfNullOrZero(password);

            return(await Task.Run(() =>
            {
                using var mapper = EntityMapper.CreateMapper();
                {
                    User user = null;
                    try
                    {
                        mapper.OpenTransaction();

                        #region 查询用户
                        {
                            user = mapper.Query <User>().InnerJoin <Config>((u, c) => u.Id == c.UserId)
                                   .Where(u => u.Name == userName && !u.IsDisable)
                                   .Select <User, Config>((u, c) => new
                            {
                                u.Id,
                                u.Name,
                                u.LoginPassword,
                                c.UserFace,
                                u.IsAdmin,
                                c.IsModifyUserFace
                            }).FirstOrDefault();

                            if (user == null)
                            {
                                throw new BusinessException($"该用户不存在或被禁用{userName}");
                            }

                            if (!PasswordUtil.ComparePasswords(user.LoginPassword, password))
                            {
                                throw new BusinessException("密码错误");
                            }
                        }
                        #endregion

                        #region 设置用户在线
                        {
                            user.Online();
                            var result = mapper.Update(user, acc => acc.Id == user.Id);
                            if (!result)
                            {
                                throw new BusinessException("设置用户在线状态失败");
                            }
                        }
                        #endregion

                        #region 添加在线用户列表
                        {
                            var online = new Online(requestIp, user.Id);
                            mapper.Add(online);
                            if (online.Id == 0)
                            {
                                throw new BusinessException("添加在线列表失败");
                            }
                        }
                        #endregion

                        mapper.Commit();
                        return user;
                    }
                    catch (Exception)
                    {
                        mapper.Rollback();
                        throw;
                    }
                }
            }));
        }
Example #17
0
        public IHttpActionResult SignIn([FromBody] UserSigninDTO user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid Data"));
            }

            if (user.CompanyCode == null || user.CompanyCode == "")
            {
                return(BadRequest("公司代号不能为空!"));
            }

            if (user.UserName == null || user.UserName == "")
            {
                return(BadRequest("用户名不能为空!"));
            }

            if (user.Password == null || user.Password == "")
            {
                return(BadRequest("密码不能为空!"));
            }

            IInfobasisDataSource db = InfobasisDataSource.Create();
            int?companyID           = db.ExecuteScalar("SELECT ID FROM SYtbCompany WHERE CompanyCode = @CompanyCode", user.CompanyCode) as int?;

            var existedUser = _repository.Get(includeProperties: "Company")
                              .Where(u => u.Name == user.UserName && u.CompanyID == companyID)
                              .FirstOrDefault();

            if (existedUser == null)
            {
                return(BadRequest("用户或密码错误,请重新输入!"));
            }

            string currentPasswordHash = existedUser.Password;

            if (!PasswordUtil.ComparePasswords(currentPasswordHash, user.Password))
            {
                updateUserInfo(existedUser, null, false);
                return(BadRequest("用户或密码错误,请重新输入!"));
            }

            if (!existedUser.Enabled)
            {
                updateUserInfo(existedUser, null, false);
                return(BadRequest("该用户帐号已经被停用,请与系统管理员联系!"));
            }

            /*
             *          string authInfo = user.Name + ":" + user.Password; //user.Name + ":" + token;
             *          byte[] byteValue = System.Text.Encoding.Default.GetBytes(authInfo);
             *          string accessToken = Convert.ToBase64String(byteValue);
             */
            var payload = new Dictionary <string, object>()
            {
                { "id", existedUser.ID },
                { "companyID", existedUser.CompanyID },
                { "userName", existedUser.Name }
            };
            var    secretKey = WebApiApplication.SECRETKEY;
            string token     = JWT.JsonWebToken.Encode(payload, secretKey, JWT.JwtHashAlgorithm.HS256);

            if (token == null)
            {
                return(BadRequest("Token获取失败, 请与系统管理员联系!"));
            }

            updateUserInfo(existedUser, token, true);

            var currentUser = new SqlParameter {
                ParameterName = "UserID", Value = existedUser.ID
            };
            var levelParam = new SqlParameter {
                ParameterName = "Level", Value = 1
            };
            //var privileges = _repository.ExecuteStoredProcedureList<UserPermissionRolePrivilege>("EXEC usp_EasyHR_GetPermissionRolePrivilegeByUser", currentUser, levelParam);

            LoginResultDTO loginResult = buildUserInfoToClient(existedUser, token, null);

            return(Ok <LoginResultDTO>(loginResult));
        }