public static Validate ( User user ) : IEnumerable |
||
user | User | |
return | IEnumerable |
protected void btnSave_Click(object sender, EventArgs e) { int ErrCode = 0; svr.Validate(base.LoginUserName, txtOld.Text.Trim(), ref ErrCode); if (ErrCode > 0) { ShowMessage(GetREMes("MsgChangePwdFail")); return; } try { CRMUser u; u = (CRMUser)svr.LoadById(typeof(CRMUser), "UserID", base.LoginUserID.ToString()); if (txtPwd.Text.Trim() != "") { u.Password = svr.Encypt(u.UserName, txtPwd.Text.Trim()); } else { u.Password = u.Password; } u.ModifyDate = DateTime.Now; u.ModifyUser = base.LoginUserID; svr.Save(u); this.ShowSaveOK(); } catch (Exception ex) { ShowSaveFail(ex.Message); } }
public async Task <IActionResult> Login(LoginViewModel model) { if (ModelState.IsValid) { var check = _userService.Validate(model.Email, model.Password); switch (check) { case UserService.ValidationResult.Success: await Authenticate(model.Email.ToLower()); return(RedirectToAction("Index", "Home")); case UserService.ValidationResult.UserNotExist: ModelState.AddModelError("Email", "Аккаунт с таким e-mail не существует"); break; case UserService.ValidationResult.PasswordNotMatch: ModelState.AddModelError("Password", "Пароль введен неверно"); break; case UserService.ValidationResult.UserNotConfirmed: ModelState.AddModelError("Email", "Аккаунт не подтвержден"); break; } } return(View(model)); }
public async Task <IActionResult> Login(LoginViewModel model) { var validationResult = _userService.Validate(model.Email, model.Password); switch (validationResult) { case UserService.ValidationResult.Success: await Authenticate(model.Email); return(Ok("Авторизация прошла успешно")); case UserService.ValidationResult.UserNotExist: ModelState.AddModelError("Email", "Аккаунт с таким e-mail не существует"); break; case UserService.ValidationResult.PasswordNotMatch: ModelState.AddModelError("Password", "Пароль введен неверно"); break; case UserService.ValidationResult.UserNotConfirmed: ModelState.AddModelError("Email", "Аккаунт не подтвержден"); break; } return(BadRequest(ModelState)); }
public IActionResult Login([FromBody] LoginInputModel model) { var response = _userService.Validate(model.UserName, model.Password); if (response.Object == null) { return(BadRequest("Username or password is incorrect")); } return(Ok(new LoginViewModel(response.Object))); }
protected void btnLogin_Click(object sender, ImageClickEventArgs e) { int ErrCode = 0; vw_CRMUser user; if (svr.CRMUsers.Count() == 0) { user = new vw_CRMUser() { UserID = 0, UserFullName = "admin", Role = "admin", RoleID = 1, RoleGrade = 9 } } ; else { user = svr.Validate(txtloginid.Text.Trim(), txtpwd.Text.Trim(), ref ErrCode); } if (ErrCode == 0) { string LoginUserName = txtloginid.Text.Trim().ToUpper(); if (LoginUserName != "ADMIN") { InsertLoginHistory(user.UserID, 0); } AddOnlineUserList(LoginUserName); //---save login user info into session------ LogUserInfo usrInfo = new LogUserInfo(); usrInfo.LoginUserID = user.UserID; usrInfo.LoginUserName = LoginUserName; usrInfo.LoginUserFullName = user.UserFullName; usrInfo.LoginUserRoleID = (long)user.RoleID; usrInfo.LoginUserRoleGrade = (int)user.RoleGrade; usrInfo.LoginUserCompany = user.SYSID.ToString(); Session[Session_ID] = usrInfo; base.StrCulture = ddlLanguage.SelectedValue; Response.Cookies["TerryCRMLang"].Value = ddlLanguage.SelectedValue; base.LastLoginUser = txtloginid.Text; FormsAuthentication.RedirectFromLoginPage(usrInfo.LoginUserID.ToString(), false); //Response.Redirect("~/default.aspx"); } else { if (user != null) { InsertLoginHistory(user.UserID, 2); //2=密码错误 } ((Label)this.FindControl("lblJScript")).Text = GetREMes("MsgLoginError"); //Page.ClientScript.RegisterClientScriptBlock(typeof(string),"loginfail", // string.Format("<script>jAlert('{0}');</script>", GetREMes("MsgLoginError"))); } }
public ActionResult Save(Parent parent) { entity = new Contexts.MealEntities(); try { parent.Status = entity.Status.FirstOrDefault(s => s.Id == STATUS_WAITING_EVALUATION); var errors = service.Validate(parent); if (errors.Count() > 0) { return(Json(errors)); } if (parent.Id != 0) { parent.Password = entity.Parent.First(s => s.Id == parent.Id).Password; } else { parent.Password = BCrypt.Net.BCrypt.HashPassword(parent.Password); } parent = service.Insert(parent); //Send email to all admins advising about the new user waiting for their evaluation var subject = "Novo usuário cadastrado - Aguardando liberação"; var message = System.IO.File.ReadAllText(Server.MapPath("~/ViewsEmails/WaitingEvaluation.html")).Replace("##NAME##", parent.Name); var admins = entity.User.Where(s => s.Type.Id == 2).ToList(); admins.ForEach(s => { var email = new Email { Mailto = s.Email, Subject = subject, Body = message }; try { new Mailer(email).Send(); } catch (Exception ex) { } }); return(new HttpStatusCodeResult(HttpStatusCode.Created));//201 } catch (Exception ex) { //Something wrong was caught when trying to save user return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Uma falha ocorreu ao salvar os dados do cadastro.")); //500 } }
public IActionResult Login([FromBody] LogInputModel model) { var user = _userService.Validate(model.UserName, model.Password); if (user == null) { return(BadRequest("Username or password is incorrect")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public IActionResult Login(LoginInputModel model) { var user = _userService.Validate(model.Username, model.Password); if (user == null) { return(BadRequest("Usuario o Contraseña esta mal escrita")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public IActionResult Login([FromBody] UserInputModel model) { var user = _userService.Validate(model.UserName, model.Password); if (user == null) { return(BadRequest("Acceso Denegado Usuario y/o contraseña incorrectos")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public ActionResult Update(Parent parent) { var _parent = new Parent(); List <DbValidationError> errors = service.Validate(parent); if (errors.Count != 0) { return(Json(new { errors = errors, parent = _parent })); } _parent = service.Update(parent); //If the parent status is active must send an email advising about it if (_parent.Status.Id == STATUS_ACTIVE) { var subject = "Acesso liberado ao Portal Vovó Chiquita. Uhuuul."; string message = System.IO.File.ReadAllText(Server.MapPath("~/ViewsEmails/AccessGranted.html")).Replace("##PARENT-NAME##", parent.Name); List <User> admins = new MealEntities().User.Where(s => s.Type.Id == USER_TYPE_ADMIN).ToList(); var email = new Email { Mailto = _parent.Email, Subject = subject, Body = message }; try { new Mailer(email).Send(); } catch (Exception ex) { var msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message; errors.Add(new DbValidationError( "Erro no envio do email", "O status do usuário foi alterado com sucesso. Porém o erro abaixo ocorreu ao enviar o e-mail ao usuário.")); errors.Add(new DbValidationError( "Mensagem do erro", msg)); } } return(Json(new { errors = errors, parent = _parent })); }
public IActionResult Authenticate([FromBody] credentials usercredentials) { System.Console.WriteLine("*** Ravish says :: username " + usercredentials.username + " :: password " + usercredentials.password); // var _user = _availableusers.Find(a => ((a.username == usercredentials.username) && (a.password == usercredentials.password))); var _user = _userService.Validate(usercredentials.username, usercredentials.password); if (_user == null) { return(BadRequest(new { message = "there is an issue with username or password" })); } else { return(Ok(_user)); } }
public void Validate_LoginInputModelNull_ThrowsArgumentNullException() { //Arrange LoginInputModel invalidLoginInputModel = null; Mock <IAuthenticationHelper> authenticationHelper = new Mock <IAuthenticationHelper>(); Mock <IUserRepository> userRepository = new Mock <IUserRepository>(); IUserService userService = new UserService(userRepository.Object, authenticationHelper.Object); //Act Action actual = () => userService.Validate(invalidLoginInputModel); //Assert Assert.Throws <ArgumentNullException>(actual); }
public IActionResult Login(LoginInputModel model) { var user = _userService.Validate(model.UserName, model.Password); if (user == null) { ModelState.AddModelError("Acceso Denegado", "Username or password is incorrect"); var problemDetails = new ValidationProblemDetails(ModelState) { Status = StatusCodes.Status400BadRequest, }; return(BadRequest(problemDetails)); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public ActionResult Login(UsuarioInputModel model) { var user = _servicioUsuario.Validate(model.Password, model.Username); if (user == null) { ModelState.AddModelError("Acceso Denegado", "Usuario y/o contraseña incorrectos"); var problemDetails = new ValidationProblemDetails(ModelState) { Status = StatusCodes.Status401Unauthorized, }; return(Unauthorized(problemDetails)); } var response = _servicioJwt.GenerarToken(user); return(Ok(response)); }
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { return(Task.Factory.StartNew(() => { totalizatorEntities db = new totalizatorEntities(); var email = context.UserName; var password = context.Password; var userService = new UserService(db); var user = userService.Validate(email, password); if (user != null) { var claims = new List <Claim>() { new Claim(ClaimTypes.Sid, Convert.ToString(user.Id)), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Email, user.Email) }; foreach (var role in user.Roles) { claims.Add(new Claim(ClaimTypes.Role, role.Name.ToString())); } var data = new Dictionary <string, string> { { "userName", user.UserName }, { "roles", string.Join(",", user.Roles) } }; var properties = new AuthenticationProperties(data); ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims, Startup.OAuthOptions.AuthenticationType); var ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); } else { context.SetError("invalid_grant", "Either email or password is incorrect"); } })); }
public void Validate_UsernameEmpty_ThrowsArgumentException() { //Arrange LoginInputModel invalidLoginInputModel = new LoginInputModel { Username = "", Password = "******" }; Mock <IAuthenticationHelper> authenticationHelper = new Mock <IAuthenticationHelper>(); Mock <IUserRepository> userRepository = new Mock <IUserRepository>(); IUserService userService = new UserService(userRepository.Object, authenticationHelper.Object); //Act Action actual = () => userService.Validate(invalidLoginInputModel); //Assert Assert.Throws <ArgumentException>(actual); }
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var service = new UserService(); var user = await service.Validate(username.Text, password.Password); if (user.Expires != null && user.Expires < DateTime.Now) { ExpiredLable.Visibility = Visibility.Visible; user = null; } if (user == null) { loginFailedLabel.Visibility = Visibility.Visible; } else { ExpiredLable.Visibility = Visibility.Hidden; GlobalContainer.CurrentUser = user; this.LogInGrid.Visibility = Visibility.Collapsed; this.contentTabControl.Visibility = Visibility.Visible; } }
public void Validate_LoginInputModelValid_ReturnsUserWithSpecifiedCredentials() { //Arrange LoginInputModel validLoginInputModel = new LoginInputModel { Username = "******", Password = "******" }; User expected = new User { Id = 1, Username = validLoginInputModel.Username, IsAdmin = true }; using (var hmac = new System.Security.Cryptography.HMACSHA512()) { expected.PasswordSalt = hmac.Key; expected.PasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(validLoginInputModel.Password)); } Mock <IAuthenticationHelper> authenticationHelper = new Mock <IAuthenticationHelper>(); authenticationHelper.Setup(auth => auth.VerifyPasswordHash(validLoginInputModel.Password, expected.PasswordHash, expected.PasswordSalt)). Returns(true); Mock <IUserRepository> userRepository = new Mock <IUserRepository>(); userRepository.Setup(repo => repo.Read(validLoginInputModel.Username)). Returns(expected); IUserService userService = new UserService(userRepository.Object, authenticationHelper.Object); //Act User actual = userService.Validate(validLoginInputModel); //Assert Assert.Equal(expected, actual); }
public void OnLogIn(string username, string password) { logger.Info("Logging in with user: "******"Got respone from database."); IsLoading = false; var user = task.Result; if (user == null) { logger.Info("Username and Passowrd combination was not recognized."); NeedLogIn = true; LogInFailed = true; } else { if (user.Expires != null && user.Expires < DateTime.Now) { logger.Info("Login Expired."); NeedLogIn = true; LogInFailed = false; LogInExpired = true; ShowControls = false; } else { logger.Info("Login Ok."); GlobalContainer.CurrentUser = user; saveAuthData(user); NeedLogIn = false; LogInFailed = false; LogInExpired = false; ShowControls = true; } } }); }
public ActionResult Login(string username, string password, string returnUrl) { try { UserService service = new UserService(new UserRepository()); var user = service.Validate(username, password); if (user != null) { CojacSession.Current.CurrentUser = user; return new RedirectResult(returnUrl); } else { return View(new LoginViewModel(returnUrl, "Invalid Username and/or password, Try again.")); } } catch (Exception ex) { return View(new LoginViewModel(returnUrl, "Something broke, here it is : " + ex.ToString())); } }
public IActionResult OnPostAppLogin() { //TODO: implement login logic here //UserProfile_ProductID = 1111; //UserProfile_ComponentID = 2222; //UserProfile_UserName = "******"; //UserProfile_UILanguage = "EN"; //UserProfile_UserID = 3; if (uSvc.Validate(LoginUser.UserName, LoginUser.Password)) { user = uSvc.GetByName(LoginUser.UserName); UserProfile_UserName = user.UserName; UserProfile_UILanguage = "EN"; UserProfile_UserID = user.Id; return(RedirectToPage("/AppMenu")); } else { return(Page()); } }
public ActionResult <User> LogIn(string email, string password) { try { User user = _userService.Validate(email, password); if (user == null) { return(NotFound("Usuario no encontrado.")); } //Log de log in _logService.Create(new Log { UserId = user.Id, TimeStamp = DateTime.Now, Action = "Inicio de Sesion." }); return(Ok(user)); } catch (Exception ex) { _logger.LogError(ex.Message); return(Problem(ex.ToString())); } }
public string Validate(string uid, string password) { var result = new AjaxLoginResultModel { code = 400, success = false, message = "登录失败" }; try { if (String.IsNullOrWhiteSpace(uid)) { throw new Exception("用户名不能为空。"); } uid = uid.Trim(); if (String.IsNullOrWhiteSpace(password)) { throw new Exception("密码不能为空。"); } var uResult = _userService.Validate(uid, password); switch (uResult) { case LoginResult.Successful: break; case LoginResult.NotExist: throw new Exception("用户名不存在。"); case LoginResult.NotEnabled: throw new Exception("用户已禁用,请与管理员联系。"); case LoginResult.Expired: throw new Exception("用户已过期,请与管理员联系。"); case LoginResult.WrongPassword: throw new Exception("密码错误,登录失败。"); default: throw new Exception("未知错误,登录失败。"); } var current = _userService.GetUser(uid); var rResult = _roleService.Validate(current.GroupId); switch (rResult) { case LoginResult.Successful: var token = Guid.NewGuid().ToString("N"); if (current.LastId == 0) { current.GroupId = 10078; } _cacheManager.Set <User>(token, current, TimeSpan.FromSeconds(600)); result.code = 200; result.success = true; result.message = token; result.roleId = current.GroupId; break; case LoginResult.RoleNotExist: throw new Exception("角色不存在。"); case LoginResult.RoleNotEnabled: throw new Exception("角色已禁用,请与管理员联系。"); default: throw new Exception("未知错误,登录失败。"); } } catch (Exception exc) { result.code = 400; result.success = false; result.message = exc.Message; } return(JsonConvert.SerializeObject(result, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Include })); }
public ActionResult iLogin(string returnUrl) { try { var uid = ConfigurationManager.AppSettings["OUid"]; if (String.IsNullOrWhiteSpace(uid)) { ModelState.AddModelError("", "接口用户名未配置。"); } var password = ConfigurationManager.AppSettings["OPwd"]; if (ModelState.IsValid && String.IsNullOrWhiteSpace(password)) { ModelState.AddModelError("", "接口密码未配置。"); } if (ModelState.IsValid) { var loginResult = _userService.Validate(uid, password); switch (loginResult) { case LoginResult.Successful: break; case LoginResult.NotExist: ModelState.AddModelError("", "用户名不存在。"); break; case LoginResult.NotEnabled: ModelState.AddModelError("", "用户已禁用,请与管理员联系。"); break; case LoginResult.Expired: ModelState.AddModelError("", "用户已过期,请与管理员联系。"); break; case LoginResult.WrongPassword: default: ModelState.AddModelError("", "密码错误,登录失败。"); break; } } if (ModelState.IsValid) { var current = _userService.GetUser(uid); var loginResult = _roleService.Validate(current.GroupId); switch (loginResult) { case LoginResult.Successful: break; case LoginResult.RoleNotExist: ModelState.AddModelError("", "角色不存在。"); break; case LoginResult.RoleNotEnabled: ModelState.AddModelError("", "角色已禁用,请与管理员联系。"); break; default: ModelState.AddModelError("", "角色错误。"); break; } } if (ModelState.IsValid) { var current = _userService.GetUser(uid); var now = DateTime.Now; var ticket = new FormsAuthenticationTicket( 1, uid, now, now.Add(FormsAuthentication.Timeout), false, current.LastId == 0 ? "10078" : current.GroupId.ToString(), FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.HttpOnly = true; authCookie.Path = FormsAuthentication.FormsCookiePath; if (ticket.IsPersistent) { authCookie.Expires = ticket.Expiration; } if (FormsAuthentication.CookieDomain != null) { authCookie.Domain = FormsAuthentication.CookieDomain; } Response.Cookies.Add(authCookie); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToRoute("HomePage")); } } } catch (Exception exc) { ModelState.AddModelError("", exc.Message); } return(View()); }
public ActionResult Login(string uid, string password, string captcha, string returnUrl) { try { if (String.IsNullOrWhiteSpace(uid)) { ModelState.AddModelError("", "用户名不能为空。"); } uid = uid.Trim(); ViewBag.Uid = uid; if (ModelState.IsValid && String.IsNullOrWhiteSpace(password)) { ModelState.AddModelError("", "密码不能为空。"); } if (ModelState.IsValid && String.IsNullOrWhiteSpace(captcha)) { ModelState.AddModelError("", "验证码不能为空。"); } if (ModelState.IsValid && Request.Cookies[CommonHelper.CaptchaId] == null) { ModelState.AddModelError("", "您的浏览器禁用了JavaScript,启用后才能使用本系统。"); } if (ModelState.IsValid) { var code = Request.Cookies[CommonHelper.CaptchaId].Value; captcha = CommonHelper.CreateHash(captcha.ToLowerInvariant().Trim(), CommonHelper.CaptchaSalt); if (captcha != code) { ModelState.AddModelError("", "验证码错误。"); } } if (ModelState.IsValid) { var loginResult = _userService.Validate(uid, password); switch (loginResult) { case LoginResult.Successful: break; case LoginResult.NotExist: ModelState.AddModelError("", "用户名不存在。"); break; case LoginResult.NotEnabled: ModelState.AddModelError("", "用户已禁用,请与管理员联系。"); break; case LoginResult.Expired: ModelState.AddModelError("", "用户已过期,请与管理员联系。"); break; case LoginResult.WrongPassword: default: ModelState.AddModelError("", "密码错误,登录失败。"); break; } } if (ModelState.IsValid) { var current = _userService.GetUser(uid); var loginResult = _roleService.Validate(current.GroupId); switch (loginResult) { case LoginResult.Successful: break; case LoginResult.RoleNotExist: ModelState.AddModelError("", "角色不存在。"); break; case LoginResult.RoleNotEnabled: ModelState.AddModelError("", "角色已禁用,请与管理员联系。"); break; default: ModelState.AddModelError("", "角色错误。"); break; } } if (ModelState.IsValid) { var current = _userService.GetUser(uid); var now = DateTime.Now; var ticket = new FormsAuthenticationTicket( 1, uid, now, now.Add(FormsAuthentication.Timeout), false, current.LastId == 0 ? "10078" : current.GroupId.ToString(), FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.HttpOnly = true; authCookie.Path = FormsAuthentication.FormsCookiePath; if (ticket.IsPersistent) { authCookie.Expires = ticket.Expiration; } if (FormsAuthentication.CookieDomain != null) { authCookie.Domain = FormsAuthentication.CookieDomain; } Response.Cookies.Add(authCookie); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToRoute("HomePage")); } } } catch (Exception exc) { ModelState.AddModelError("", exc.Message); } return(View()); }