/// <summary> /// 创建Token值 /// </summary> /// <param name="entity">实体</param> /// <returns>返回token 数据</returns> public dynamic CreateToken(UserEntity entity) { DateTime expirteTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(ConfigHelper.GetSectionValue("expiresAt"))); Dictionary <string, object> payload = new Dictionary <string, object>(); payload.Add("ID", entity.ID); payload.Add("UserName", entity.UserName); payload.Add("Email", entity.Email); payload.Add("RolesID", entity.RoleID); var tokenacces = new { UserId = entity.ID, //RolesID=entity.RoleID, entity.UserName, AccessToken = Encrypts.CreateToken(payload, Convert.ToInt32(ConfigHelper.GetSectionValue("expiresAt"))), Expires = new DateTimeOffset(expirteTime).ToUnixTimeSeconds(), Success = true }; if (tokenacces.Success) { _cacheService.Add(entity.ID, tokenacces.AccessToken); } return(tokenacces); }
public ActionResult CheckEmail(ResetEmailOldViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { SecurityVerify.Verify <ResetEmailOldVerification>(model.Email.Replace("@", "_"), null, model.Code); } catch (ApplicationException ex) { ModelState.AddModelError("", ex.Message); return(View(model)); } catch (Exception) { ModelState.AddModelError("", GeneralResource.SaveFailed); return(View(model)); } var emailToken = SecurityVerify.SendCode <ResetEmailOldTokenVerification>(model.Email.Replace("@", "_"), model.Email); var timeTicks = Encrypts.GenerateTicksInTenTime(); var token = HttpUtility.UrlEncode(PasswordHasher.HashPassword(emailToken + timeTicks)); return(RedirectToAction("ResetEmail", new { token })); }
public JObject Update([FromBody] UserEntity _userEntity) { DataResult result = new DataResult { Verifiaction = false }; try { //if (_userRepsonsityService.IsExists(x => x.UserName == _userEntity.UserName)) //{ // result.Message = "修改失败,已存在该账号!"; // return JObject.FromObject(result); //} UserEntity userEntity = _userRepsonsityService.Find(_userEntity.ID); if (userEntity != null) { userEntity.ID = _userEntity.ID; userEntity.RoleID = _userEntity.RoleID; //UserName = _userEntity.UserName, if (!string.IsNullOrEmpty(_userEntity.PassWord)) { userEntity.PassWord = Encrypts.EncryptPassword(_userEntity.PassWord); } userEntity.Email = _userEntity.Email; userEntity.Remark = _userEntity.Remark; } //UserEntity userEntity = new UserEntity //{ // ID = _userEntity.ID, // RoleID=_userEntity.RoleID, // //UserName = _userEntity.UserName, // PassWord = Encrypts.EncryptPassword(_userEntity.PassWord), // Email = _userEntity.Email, // Remark=_userEntity.Remark //}; int a = _userRepsonsityService.Update(userEntity, new Expression <Func <UserEntity, object> >[] { //m=>m.UserName, m => m.RoleID, m => m.PassWord, m => m.Email, m => m.Remark }); //_userRepsonsityService.SaveChange(); result.Verifiaction = true; result.Message = "写入成功!"; } finally { } return(JObject.FromObject(result)); }
/// <summary> /// 刷新token /// </summary> /// <param name="token"></param> /// <returns></returns> public dynamic UpdateToken(string token) { JwtSecurityToken readtoken = new JwtSecurityTokenHandler().ReadJwtToken(token); //加入黑名单 if (!_cacheService.Exists(readtoken.Payload["ID"].ToString())) { _cacheService.Add(readtoken.Payload["ID"].ToString(), token); } DateTime expirteTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(ConfigHelper.GetSectionValue("expiresAt"))); Dictionary <string, object> payload = new Dictionary <string, object>(); payload.Add("ID", readtoken.Payload["ID"]); payload.Add("UserName", readtoken.Payload["UserName"]); payload.Add("RolesID", readtoken.Payload["RolesID"]); payload.Add("Email", readtoken.Payload["Email"]); var tokenacces = new { UserId = readtoken.Payload["ID"], AccessToken = Encrypts.CreateToken(payload, Convert.ToInt32(ConfigHelper.GetSectionValue("expiresAt"))), Expires = new DateTimeOffset(expirteTime).ToUnixTimeSeconds(), Success = true }; return(tokenacces); }
public void ProcessRequest(HttpContext context) { string token = "loginuser"; var loginId = context.Request.Cookies["LoginUser"]; var cookieValue = Encrypts.GetDecryptString(loginId.Value); var cookieValues = cookieValue.Split(new char[] { '_' }); if (cookieValues == null || cookieValues.Length != 2) { return; } var userId = int.Parse(cookieValues[0]); var ticks = long.Parse(cookieValues[1]); DateTime dtNow = DateTime.UtcNow; DateTime dtToken = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ticks); var totalMinutes = (dtNow - dtToken).TotalMinutes; if ((dtNow - dtToken).TotalMinutes > 35)//长时间没访问 { return; } token += userId; var loginSession = RedisHelper.Get <LoginUser>(token); if (loginSession == null) { return; } string saveType = context.Request["savetype"]; string callback = context.Request["callback"]; string json; if (saveType != null && saveType.ToLower() == "local") { json = UploadToLocal(context); } else { json = UploadToCDN(context); } context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.ContentType = "text/html"; if (callback != null) { context.Response.Write(String.Format("<script>{0}(JSON.parse(\"{1}\"));</script>", callback, json)); } else { context.Response.Write(json); } }
public static string MediaFileName(string fileName) { fileName = UCS2Lower(fileName); if (fileName.Length > 50) { fileName = fileName.Remove(0, fileName.Length - 50); } fileName = fileName.Replace("img", "i"); return(Encrypts.MD5(DateTime.Now.ToString("yyMMddHHmmss")).Substring(0, 9) + "_" + fileName); }
protected void btAdd_Click(object sender, EventArgs e) { var _User = new Users(); _User.Email = txtEmail.Text.Trim().ToLower(); _User.FullName = txtFullName.Text.Trim(); _User.Password = Encrypts.MD5(txtPassword.Text); _User.Status = Convert.ToInt32(chkIsActive.Checked); _User.Add(); Response.Redirect(Constant.ADMIN_PATH + Resources.Url.UsersEdit); }
public string LoginUser(ViewUser viewUserModel) { var dbUser = context.Users.Find(viewUserModel.Login); if (dbUser != null && dbUser.Password == Encrypts.EncryptPassword(viewUserModel.Password, dbUser.Salt)) { string encoded = Encrypts.GenerateToken(); return(encoded); } return(string.Empty); }
public void RegisterUser(ViewUser viewUserModel) { var contextUser = new User(); if (context.Users.Find(viewUserModel.Login) == null) { contextUser.Role = Settings.Roles.User; contextUser.Login = viewUserModel.Login; contextUser.Salt = Encrypts.GenerateSalt(); contextUser.Password = Encrypts.EncryptPassword(viewUserModel.Password, contextUser.Salt); context.Users.Add(contextUser); } context.SaveChanges(); }
public JObject Token1([FromBody] Post_UserViewModel obj) { DataResult result = new DataResult(); result.verifiaction = false; try { string name = obj.name; string password = obj.password; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password)) { result.message = "账号或者密码不能为空!"; return(JObject.FromObject(result)); } var entity = _userRepsonsityService.Login(name, password); if (entity != null) { Dictionary <string, object> payload = new Dictionary <string, object>(); payload.Add("ID", entity.ID); payload.Add("UserName", entity.UserName); payload.Add("Email", entity.Email); var tokenacces = new { AccessToken = Encrypts.CreateToken(payload, 30), Expires = 3600 }; result.rows = tokenacces; result.verifiaction = true; result.message = "登陆成功!"; } else { result.message = "获取token令牌失败!"; result.verifiaction = true; } } catch (Exception ex) { result.message = "非法登陆!"; return(JObject.FromObject(result)); } finally { } return(JObject.FromObject(result)); }
public void ProcessRequest(HttpContext context) { string token = $"{Configs.PlateForm}:AccountInfo:"; var loginId = context.Request.Cookies["_LoginInfo"]; var cookieValue = Encrypts.GetDecryptString(loginId.Value); var cookieValues = cookieValue.Split(new char[] { '_' }); if (cookieValues == null || cookieValues.Length != 3) { return; } var userId = Guid.Parse(cookieValues[0]); token += userId; var loginSession = RedisHelper.Get <LoginUser>(token); if (loginSession == null) { return; } string saveType = context.Request["savetype"]; string callback = context.Request["callback"]; string json; if (saveType != null && saveType.ToLower() == "local") { json = UploadToLocal(context); } else { json = UploadToCDN(context); } context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.ContentType = "text/html"; if (callback != null) { context.Response.Write(String.Format("<script>{0}(JSON.parse(\"{1}\"));</script>", callback, json)); } else { context.Response.Write(json); } }
private async Task <bool> ValidUser(User user) { var dbUser = await _context.UsersRegister .Include(x => x.Person) .FirstOrDefaultAsync(x => x.Login == user.Login); if (dbUser == null) { return(false); } var encryptedPasswordUser = Encrypts.EncryptPassword(user.Password, dbUser.Salt); if (!string.Equals(dbUser.Password, encryptedPasswordUser)) { return(false); } return(true); }
protected void btSubmit_Click(object sender, EventArgs e) { Users _User = new Users() { UserID = AppUtils.UserID() }; _User = _User.Get(); if (Encrypts.MD5(txtPasswordOld.Text.Trim()) != _User.Password) { Message.Alert(Page, "Mật khẩu cũ không chính xác!"); return; } _User.Password = Encrypts.MD5(txtPassword.Text.Trim()); _User.Update(); Message.Alert(Page, "Đổi mật khẩu thành công!"); }
public async Task <bool> Register(UserRegister user) { var dbUser = _context.Users.Find(user.Login); if (dbUser != null) { return(false); } var salt = Encrypts.GenerateSalt(); user.Password = Encrypts.EncryptPassword(user.Password, salt); user.Salt = salt; await _context.UsersRegister.AddAsync(user); await _context.SaveChangesAsync(); return(true); }
protected void btUpdate_Click(object sender, EventArgs e) { var _User = new Users() { UserID = AppUtils.Request("id") }; _User = _User.Get(); if (txtPassword.Text.Length > 0) { _User.Password = Encrypts.MD5(txtPassword.Text); } _User.FullName = txtFullName.Text; _User.Status = Convert.ToInt32(chkIsActive.Checked); _User.GroupID = Convert.ToInt32(drpGroup.SelectedValue); _User.Update(); Response.Redirect(Constant.ADMIN_PATH + Resources.Url.UsersList); }
/// <summary> /// 登陆方法 /// </summary> /// <param name="username">账号</param> /// <param name="password">密码</param> /// <returns></returns> public UserEntity Login(string username, string password) { UserEntity model = new UserEntity(); try { Expression <Func <UserEntity, bool> > pression = null; pression = pres => pres.UserName == username && pres.PassWord == Encrypts.EncryptPassword(password); model = this.GetFirstOrDefault(pression, null, null, false); if (model != null) { return(model); } } finally { this.dbcontext.Dispose(); } return(null); }
public JObject Register([FromBody] UserEntity _userEntity) { DataResult result = new DataResult(); result.verifiaction = false; try { Expression <Func <UserEntity, bool> > presseion = null; presseion = expres => expres.UserName == _userEntity.UserName; if (_userRepsonsityService.IsExists(presseion)) { result.message = "已存在该账号!"; return(JObject.FromObject(result)); } UserEntity userEntity = new UserEntity(); userEntity.ID = Guid.NewGuid().ToString(); userEntity.UserName = _userEntity.UserName; userEntity.PassWord = Encrypts.EncryptPassword(_userEntity.PassWord); userEntity.Email = _userEntity.Email; userEntity.IsLock = 0; userEntity.LoginLastDate = DateTime.Now.ToString(); userEntity.CreateDate = DateTime.Now.ToString(); userEntity.Remark = _userEntity.Remark; _userRepsonsityService.Insert(userEntity); result.verifiaction = true; result.message = "写入成功!"; } catch (Exception ex) { result.message = ex.Message.ToString(); } finally { } return(JObject.FromObject(result)); }
public JObject Register([FromBody] UserEntity _userEntity) { DataResult result = new DataResult() { Verifiaction = false }; try { if (_userRepsonsityService.IsExists(x => x.UserName == _userEntity.UserName)) { result.Message = "已存在该账号!"; return(JObject.FromObject(result)); } UserEntity userEntity = new UserEntity { ID = Guid.NewGuid().ToString(), UserName = _userEntity.UserName, PassWord = Encrypts.EncryptPassword(_userEntity.PassWord), RoleID = _userEntity.RoleID, Email = _userEntity.Email, IsLock = 0, LoginLastDate = DateTime.Now.ToString(), CreateDate = DateTime.Now.ToString(), Remark = _userEntity.Remark }; _userRepsonsityService.Insert(userEntity); _userRepsonsityService.SaveChange(); result.Verifiaction = true; result.Message = "写入成功!"; } finally { } return(JObject.FromObject(result)); }
protected void btSignIn_Click(object sender, EventArgs e) { Session.RemoveAll(); var _User = new Users(); _User = _User.Authentication(txtUserName.Text, Encrypts.MD5(txtPassword.Text)); if (_User != null) { Session.Timeout = 120; Session["UserID"] = _User.UserID; Session["Email"] = _User.Email; Session["FullName"] = _User.FullName; Session["LastestTime"] = _User.LastestTime.ToString(); string url = Request["u"]; url = url == null ? Constant.ADMIN_PATH + Resources.Url.Intro : url; Response.Redirect(url); } else { PanelMessage.Visible = true; lblMessage.Text = "Mật khẩu hoặc tên đăng nhập không hợp lệ"; txtPassword.Focus(); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { var logininfo = httpContext.Request.Cookies[Configs.CookieKey_LoginInfo]; if (logininfo == null) { return(false); } var cookieValue = Encrypts.GetDecryptString(logininfo.Value.ToString()); var cookieValues = cookieValue.Split(new char[] { '_' }); if (cookieValues == null || cookieValues.Length != 3) { return(false); } try { var accountId = Guid.Parse(cookieValues[0]); var randomString = cookieValues[1].ToString(); var ticks = long.Parse(cookieValues[2]); DateTime dtNow = DateTime.UtcNow; DateTime dtToken = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ticks); var totalMinutes = (dtNow - dtToken).TotalMinutes; if ((dtNow - dtToken).TotalMinutes > 35)//长时间没访问 { return(false); } string redisKey = $"{Configs.PlateForm}:AccountInfo:{accountId}"; accountInfo = RedisHelper.Get <AccountInfo>(Configs.RedisIndex_Web, redisKey); if (accountInfo == null) { return(false); } if (accountInfo.Token != randomString) { return(false); } if (accountInfo.Status == (byte)AccountStatus.Disabled) { return(false); } if ((dtNow - dtToken).TotalMinutes > 5)//最少5分钟更新一次cookie和Redis { httpContext.Response.Cookies.Add(httpContext.Request.Cookies[Configs.CookieKey_LoginInfo]); httpContext.Response.Cookies[Configs.CookieKey_LoginInfo].Value = Encrypts.GetEncryptString(accountId.ToString() + "_" + randomString); httpContext.Response.Cookies[Configs.CookieKey_LoginInfo].HttpOnly = true; RedisHelper.KeyExpire(Configs.RedisIndex_Web, redisKey, TimeSpan.FromDays(1)); } httpContext.Request.Headers.Add("useraccountId", accountId.ToString()); return(AuthorizeRedirect(httpContext, accountInfo.Status)); } catch (Exception ex) { return(false); } }
public ActionResult Index(Account account, string TokenGid, string VerificationCode) { var securityVerify = new SecurityVerification(SystemPlatform.BackOffice); var loginBll = new LoginBLL(); string loginMessage = String.Empty; try { var loginErrorCountsInt = securityVerify.CheckErrorCount(SecurityMethod.Password, account.Username); var cacheCode = RedisHelper.StringGet(TokenGid); if (string.IsNullOrEmpty(cacheCode)) { loginMessage = "Verification code was expired"; securityVerify.IncreaseErrorCount(SecurityMethod.Password, account.Username); } if (VerificationCode.ToUpper() != cacheCode.ToUpper()) { loginMessage = "Verification code is wrong"; securityVerify.IncreaseErrorCount(SecurityMethod.Password, account.Username); } bool checkResult = loginBll.CheckUser(account.Username, account.Password, out account, ref loginMessage); if (!checkResult) { securityVerify.IncreaseErrorCount(SecurityMethod.Password, account.Username); } RedisHelper.KeyDelete(TokenGid); securityVerify.DeleteErrorCount(SecurityMethod.Password, account.Username); } catch (Framework.Exceptions.CommonException ex) { ViewBag.LoginMessage = string.IsNullOrEmpty(loginMessage) ? ex.Message : loginMessage; return(View(account)); } LoginUser lu = new LoginUser(); int roleId = account.RoleId.Value; lu.UserId = account.Id; lu.UserName = account.Username; lu.RoleId = roleId; lu.IsAdmin = false;// account.Username == "fiiipayadmin"; if (lu.IsAdmin) { lu.PerimissionList = loginBll.GetAllPermission(roleId); } else { lu.PerimissionList = loginBll.GetUserPermissionByRoleId(roleId); } RedisHelper.Set("loginuser" + account.Id, lu, new TimeSpan(1, 0, 0)); var userCookie = Request.Cookies["LoginUser"]; if (userCookie == null) { var cookie = Response.Cookies["LoginUser"]; cookie.Value = Encrypts.GetEncryptString(account.Id.ToString()); cookie.HttpOnly = true; cookie.Expires = DateTime.Now.AddDays(1); } else { Response.Cookies.Add(Request.Cookies["LoginUser"]); Response.Cookies["LoginUser"].Value = Encrypts.GetEncryptString(account.Id.ToString()); Response.Cookies["LoginUser"].Expires = DateTime.Now.AddDays(1); Response.Cookies["LoginUser"].HttpOnly = true; } return(RedirectToAction("Index", "Home")); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { string token = "loginuser"; var loginId = httpContext.Request.Cookies["LoginUser"]; if (loginId == null) { return(false); } var cookieValue = Encrypts.GetDecryptString(loginId.Value); var cookieValues = cookieValue.Split(new char[] { '_' }); if (cookieValues == null || cookieValues.Length != 2) { return(false); } var userId = int.Parse(cookieValues[0]); var ticks = long.Parse(cookieValues[1]); DateTime dtNow = DateTime.UtcNow; DateTime dtToken = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ticks); var totalMinutes = (dtNow - dtToken).TotalMinutes; if ((dtNow - dtToken).TotalMinutes > 125)//长时间没访问 { return(false); } token += userId; var loginSession = RedisHelper.Get <LoginUser>(token); if (loginSession == null) { if (httpContext.Request.IsAjaxRequest()) { httpContext.Response.AddHeader("sessionstatus", "timeout"); return(false); } return(false); } if ((dtNow - dtToken).TotalMinutes > 5)//最少5分钟更新一次Redis { httpContext.Response.Cookies.Add(httpContext.Request.Cookies["LoginUser"]); httpContext.Response.Cookies["LoginUser"].Value = Encrypts.GetEncryptString(userId.ToString()); httpContext.Response.Cookies["LoginUser"].HttpOnly = true; httpContext.Response.Cookies["LoginUser"].Expires = DateTime.Now.AddDays(1); RedisHelper.KeyExpire(token, new TimeSpan(1, 0, 0)); } if (PerimCode == null) { return(loginSession != null); } if (loginSession.IsAdmin) { return(true); } var perimList = loginSession.PerimissionList; if (perimList == null || perimList.Count <= 0) { return(false); } var result = perimList.Any(t => PerimCode.Contains(t.PerimCode) && t.Value > 0); return(result); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } var account = await new AccountComponent().GetAccountByUsernameAsync(model.MerchantId); if (account == null) { ModelState.AddModelError("", AccountLogin.MerchantIdNotExist); return(View(model)); } try { SecurityVerify.Verify <PasswordVerification>(account.Id.ToString(), account.Password, model.Password); } catch (ApplicationException ex) { ModelState.AddModelError("", ex.Message); return(View(model)); } catch (Exception) { ModelState.AddModelError("", AccountLogin.Loginfailed); return(View(model)); } if (account.Status == (byte)AccountStatus.Disabled) { ModelState.AddModelError("", AccountLogin.AccountDisabed); return(View(model)); } string accountId = account.Id.ToString(); string randomString = Framework.RandomAlphaNumericGenerator.Generate(8); var userCookie = Request.Cookies[Configs.CookieKey_LoginInfo]; if (userCookie == null) { var cookie = Response.Cookies[Configs.CookieKey_LoginInfo]; cookie.Value = Encrypts.GetEncryptString(accountId + "_" + randomString); cookie.HttpOnly = true; } else { Response.Cookies.Add(Request.Cookies[Configs.CookieKey_LoginInfo]); Response.Cookies[Configs.CookieKey_LoginInfo].Value = Encrypts.GetEncryptString(accountId + "_" + randomString); Response.Cookies[Configs.CookieKey_LoginInfo].HttpOnly = true; } if (account.Status == (byte)AccountStatus.Registered) { returnUrl = $"/{CurrentLanguage}/firstsetting"; } AccountInfo accountInfo = new AccountInfo { Id = account.Id, Username = account.Username, MerchantName = account.MerchantName, // Currency = account.Currency, Status = account.Status, Token = randomString }; RefreshAccountInfo(accountInfo); return(RedirectToLocal(returnUrl)); }
public static string MediaPath(string fileName) { fileName = UCS2Lower(fileName); return(Encrypts.MD5(DateTime.Now.ToString("yyMMddHHmmss")).Substring(0, 9) + "_" + fileName); }
protected void btMD5_Click(object sender, EventArgs e) { txtResult.Text = Encrypts.MD5(txtData.Text.Trim()); }