public void LogOutSuccessful() { Mock <HttpContextBase> moqContext = new Mock <HttpContextBase>(); Mock <HttpRequestBase> moqRequest = new Mock <HttpRequestBase>(); Mock <HttpPostedFileBase> moqPostedFile = new Mock <HttpPostedFileBase>(); moqRequest.Setup(r => r.Files.Count).Returns(0); moqContext.Setup(x => x.Request).Returns(moqRequest.Object); var controller = new HomeController(); var user = new LoginModels() { UserName = "******", Password = "******" }; var validationResults = TestModelHelper.ValidateModel(controller, user); controller.ControllerContext = new ControllerContext(moqContext.Object, new RouteData(), controller); moqContext.SetupGet(x => x.Session["ID"]).Returns(39); moqContext.SetupGet(x => x.Session["Role"]).Returns(2); var redirectRoute = controller.Login(user) as RedirectToRouteResult; var redirectRouteResult = controller.Logout() as RedirectToRouteResult; Assert.AreEqual(0, validationResults.Count); Assert.AreEqual("Course", redirectRouteResult.RouteValues["action"]); Assert.AreEqual("Home", redirectRouteResult.RouteValues["controller"]); }
public ActionResult LoginPage(LoginModels loginAccount) { if (loginAccount.LoginEmail == null) { ViewBag.Message = "Please enter a valid email address for login"; return(View("SignUpView")); } string password = signUpManager.GetPassword(loginAccount.LoginEmail); if (password == null) { ViewBag.Message = "No Account of that email Account exist"; return(View("SignUpView")); } if (!password.Equals(loginAccount.LoginPassword)) { ViewBag.Message = "Password Did not Match"; return(View("SignUpView")); } Session["Id"] = signUpManager.GetPersonID(loginAccount.LoginEmail); Authentication authentication = new Authentication(); authentication.Id = Convert.ToInt32(Session["Id"].ToString()); authentication.Password = loginAccount.LoginPassword; Session["authentication"] = authentication; Session["authenticationId"] = authentication.Id; var authenticationId = (int)Session["authenticationId"]; return(RedirectToAction("HomePage", "Home", new { authenticationInfo = authenticationId })); }
public void TestThatUserUnsuccessfullyLoginBecauseDontHaveAccount() { Mock <HttpContextBase> moqContext = new Mock <HttpContextBase>(); Mock <HttpRequestBase> moqRequest = new Mock <HttpRequestBase>(); Mock <HttpPostedFileBase> moqPostedFile = new Mock <HttpPostedFileBase>(); moqRequest.Setup(r => r.Files.Count).Returns(0); moqContext.Setup(x => x.Request).Returns(moqRequest.Object); var controller = new HomeController(); var user = new LoginModels() { UserName = "******", Password = "******" }; var validationResults = TestModelHelper.ValidateModel(controller, user); controller.ControllerContext = new ControllerContext(moqContext.Object, new RouteData(), controller); var viewResult = controller.Login(user) as ViewResult; //moqContext.SetupGet(x => x.Session["ID"]).Returns(1); //moqContext.SetupGet(x => x.Session["Role"]).Returns(1); var result = controller.Login("t1555501", "123456789"); Assert.IsFalse(viewResult.ViewData.ModelState.IsValid); Assert.AreEqual(0, validationResults.Count); Assert.AreEqual(0, result); }
public JObject AutenticarUsuario(LoginModels model) { try { string senhaCriptografada = UtilController.GetHash(model.senha); ASPNETMVC.Contexto.Contexto cntx = new ASPNETMVC.Contexto.Contexto(); Usuario usuario = cntx.database.Usuarios.Where(x => x.Email == model.email && x.Senha == senhaCriptografada).FirstOrDefault(); if (usuario == null) { throw new Exception("Email ou senha incorreta :/"); } usuario.UltimoLogin = DateTime.Now; cntx.database.Usuarios.Attach(usuario); cntx.database.SaveChanges(); return(new JObject() { { "processado", true }, { "mensagem", "" } }); } catch (Exception e) { return(new JObject() { { "processado", false }, { "mensagem", e.Message } }); } }
public ActionResult Login(LoginModels User, string returnUrl) { if (this.ModelState.IsValid) { //SysUserMInfo info = SysUserMBiz.GetInfo(User.UserId); if (!string.IsNullOrWhiteSpace(User.UserId) && User.Pwd == User.Pwd) { SessionModels sessionModel = new SessionModels(); sessionModel.UserId = User.UserId; HttpContext.Session[AuthorizeUserAttribute.SessionId] = sessionModel; if (string.IsNullOrWhiteSpace(returnUrl)) { return(RedirectToAction("Index")); } else { if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } } } } return(View()); }
public IActionResult Login(LoginModels user) { //тестовое использование ComputerService // var manufacturers = _advansedComputerService.GetComputerManufacturers(); var manufacturers = _computerService.GetComputerManufacturers(); if (user == null) { return(BadRequest("Invalid data")); } if (user.UserName == "jon" && user.Password == "123") { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var tokenOptions = new JwtSecurityToken( issuer: "http://localhost:5000", audience: "http://localhost:5000", claims: new List <Claim>(), expires: DateTime.Now.AddMinutes(5), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions); return(Ok(new{ Token = tokenString })); } else { return(Unauthorized()); } }
public ActionResult login(LoginModels login) { try { if ((!String.IsNullOrEmpty(login.Email)) && (!String.IsNullOrEmpty(login.Password)))// Null or empty controller { string Email = login.Email; string Password = login.Password; string yanit = ReDecryptAndControlLogin(Email, Password); if (yanit == "Doğru") { ViewData["loginmsg1"] = "Sisteme başarıyla giriş yaptınız!"; return(View("anasayfa")); } // pass true else if (yanit == "Yanlış" || yanit == "Email Yok") { ViewData["loginmsg2"] = "Gecersiz email adresi veya şifre!"; return(View("login")); } // pass wrong else { ViewData["loginmsg3"] = "Sisteme giriş yaparken hata oluştu!"; return(View("login")); } } else { ViewData["loginmsg4"] = "Email ve şifre alanı boş bırakılamaz!"; return(View("login")); } } catch (Exception e) { ViewData["loginmsg5"] = "Sisteme giriş yaparken hata oluştu!"; return(View("login")); } }
public ActionResult Login(LoginModels model) { if (ModelState.IsValid) { var dao = new UserDAO(); var result = dao.Login(model.UserName, Encryptior.MD5Hash(model.PassWord)); if (result == 1) { var user = dao.GetbyID(model.UserName); var userSession = new UserLogin(); userSession.UserName = user.UserName; userSession.UserID = user.ID; Session.Add(CommonConstants.USER_SESSION, userSession); return(RedirectToAction("Index", "Home")); } else if (result == 0) { ViewBag.ErrorMessage = "tài khoản không tồn tại ! "; //ModelState.AddModelError("", "tài khoản không tồn tại ! "); } else if (result == -1) { ViewBag.ErrorMessage = "tài khoản bị khóa ! "; } else if (result == -2) { ViewBag.ErrorMessage = "Sai mật khẩu ! "; } else { ViewBag.ErrorMessage = "Sai mật khẩu ! "; } } return(View("Index")); }
public async Task <IActionResult> Index(LoginModels model) { //await CreateRolesAsync(this.serviceProvider); if (ModelState.IsValid) { var result = await LUsuario.userLoginAsync(model); if (result.Succeeded) { return(Redirect("/Principal/Principal/Principal")); } else if (result.IsLockedOut) { model.Error = "Cuenta de usuario bloqueada"; _model = model; return(Redirect("/")); } else { model.Error = "Correo o Contraseña Inválidos"; _model = model; return(Redirect("/")); } } return(View()); }
public IHttpActionResult IsUserValid(LoginModels loginUser) { cmd = new SqlCommand(); cmd.Connection = sqlConnection; cmd.CommandType = System.Data.CommandType.StoredProcedure; const string procName = "AuthenticateUser"; cmd.CommandText = procName; SqlParameter paramEmail = new SqlParameter("@username", System.Data.SqlDbType.VarChar); paramEmail.Direction = System.Data.ParameterDirection.Input; paramEmail.Value = loginUser.EmailId; SqlParameter paramPassword = new SqlParameter("@password", System.Data.SqlDbType.VarChar); paramPassword.Direction = System.Data.ParameterDirection.Input; paramPassword.Value = loginUser.Password; SqlParameter paramisUserValid = new SqlParameter("@isUserValid", System.Data.SqlDbType.Bit); paramisUserValid.Direction = System.Data.ParameterDirection.Output; cmd.Parameters.Add(paramEmail); cmd.Parameters.Add(paramPassword); cmd.Parameters.Add(paramisUserValid); cmd.ExecuteNonQuery(); if (bool.Parse(paramisUserValid.Value.ToString())) { return(Ok("User is valid")); } return(NotFound()); }
public void TestThatUserUnsuccessfullyLoginWithNoInputPassword() { Mock <HttpContextBase> moqContext = new Mock <HttpContextBase>(); Mock <HttpRequestBase> moqRequest = new Mock <HttpRequestBase>(); Mock <HttpPostedFileBase> moqPostedFile = new Mock <HttpPostedFileBase>(); moqRequest.Setup(r => r.Files.Count).Returns(0); moqContext.Setup(x => x.Request).Returns(moqRequest.Object); var controller = new HomeController(); var user = new LoginModels() { UserName = "******", Password = "" }; var validationResults = TestModelHelper.ValidateModel(controller, user); controller.ControllerContext = new ControllerContext(moqContext.Object, new RouteData(), controller); var viewResult = controller.Login(user) as ViewResult; //moqContext.SetupGet(x => x.Session["ID"]).Returns(1); //moqContext.SetupGet(x => x.Session["Role"]).Returns(1); Assert.IsFalse(viewResult.ViewData.ModelState.IsValid); Assert.AreEqual(1, validationResults.Count); Assert.IsTrue(validationResults[0].ErrorMessage.Equals("Hãy điền mật khẩu")); }
public ActionResult HandleLogin(LoginModels login) { if (ModelState.IsValid) { var checkLogin = AccountService.CheckAccount(login.Email, login.Password); if (checkLogin == "invalid") { ViewBag.Error = "Tên tài khoản hoặc Mật khẩu không chính xác."; login.Password = ""; return(View("Account.Login", login)); } if (checkLogin == "not_active") { var activeAccountUrl = string.Format("{0}account/active", ConfigHelper.WebDomain); ViewBag.Error = string.Format( "Tài khoản của bạn chưa được kích hoạt, click vào <a href='{0}' title='Kích hoạt tài khoản' style='color: #007FF0'> đây</a> để kích hoạt tài khoản của bạn.", activeAccountUrl); login.Password = ""; return(View("Account.Login", login)); } AuthenticationHelper.SignIn(login); return(RedirectToUrl(login.ReturnUrl)); } return(View("Account.Login", login)); }
public ActionResult Login(LoginModels model) { if (ModelState.IsValid) { var session = (UserLogin)Session[WebsiteFPT.Common.CommonConstants.USER_SSESION]; var dao = new UserDao(); var result = dao.Login(model.UserName, Encryptor.MD5Hash(model.Password)); if (result) { var user = dao.GetByID(model.UserName); if (user.IdRole == 1) { var userSession = new UserLogin(); userSession.UserName = user.UserName; userSession.UserID = user.ID; Session.Add(CommonConstants.USER_SSESION, userSession); return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "Account is not valid"); } } return(View("Index")); }
public ActionResult Index(networkusuario dto) { //dto.Cpf = StringHelper.FormatarCpf(dto.Cpf); var retorno = this.usuarioApp.Login(dto.Cpf, dto.Senha); if (retorno != null) { LoginModels.SetLoginModel(new LoginModels { IdUsuario = retorno.IdUsuario, NomeFuncionario = retorno.NomeFuncionario, Bairro = retorno.Bairro, CarteiraMotorista = retorno.CarteiraMotorista, Carteiratrabalho = retorno.Carteiratrabalho, Cidade = retorno.Cidade, CodigoFuncionario = retorno.CodigoFuncionario, Cpf = retorno.Cpf, DataEmaissao = retorno.DataEmaissao, Endereco = retorno.Endereco, Fone1 = retorno.Fone1, Fone2 = retorno.Fone2, Perfil = retorno.Perfil }); } if (LoginModels.IsLogado()) { return(RedirectToAction("index", "home")); } else { TempData["error"] = "Nenhum usuário encontrado."; return(View(dto)); } }
public ActionResult Login(LoginModels _login) { if (ModelState.IsValid) //validating the user inputs { var loginUser = new dto_login { nombre = string.Empty, pass = Cryption.Encrypt(_login.Password, ConfigurationManager.AppSettings["claveEncriptacion"]), vendedor = string.Empty, cod_agente = _login.Cedula.ToString(), estado = string.Empty, correo = string.Empty }; //Manager.ClientPostRequest(loginUser, AppSettings.urlApi, AppSettings.controladorLogin); //Manager.SendRequestAsync(AppSettings.urlApi , AppSettings.controladorLogin, loginUser); ManagerUser mang = new ManagerUser(); var dto_retorno = mang.Login(loginUser); // var result = await _signInManager.PasswordSignInAsync(Input.Cedula, Input.Password, Input.RememberMe, lockoutOnFailure: true); if (dto_retorno.Any()) {
public ActionResult Index(LoginModels login) { LoginModels result = new LoginModels(); result = login; return(RedirectToAction("Success", "KYLIELogin", login)); }
public ActionResult Index(CadastroDTO dto) { dto.Cpf = StringHelper.FormatarCpf(dto.Cpf); var retorno = this.business.Login(dto.Senha, dto.Cpf); if (retorno != null) { LoginModels.SetLoginModel(new LoginModels { IdCadastro = retorno.IdCadastro, PrimeiroNome = retorno.PrimeiroNome, UltimoNome = retorno.UltimoNome, Cep = retorno.Cep, Complemento = retorno.Complemento, Cpf = retorno.Cpf, Email = retorno.Email, Endereco = retorno.Endereco, Numero = retorno.Numero, Rua = retorno.Rua, Senha = retorno.Senha, Sexo = retorno.Sexo, }); } if (LoginModels.IsLogado()) { return(RedirectToAction("index", "Cadastro")); } else { TempData["error"] = "Nenhum usuário encontrado."; return(View(dto)); } }
public Models.LoginModels ValidarLogin(string email, string senha) { var metodo = "api/logins?email=" + email + "&senha=" + senha; LoginModels login = null; ClienteModel cliente = null; var retornoApi = ExecutarApiGet(metodo); if (retornoApi.Status == HttpStatusCode.OK) { login = JsonConvert.DeserializeObject <LoginModels>(retornoApi.Objeto); if (login != null) { // Obter dados do Cliente metodo = "api/Clientes/" + login.IdLogin; retornoApi = ExecutarApiGet(metodo); if (retornoApi.Status == HttpStatusCode.OK) { cliente = JsonConvert.DeserializeObject <ClienteModel>(retornoApi.Objeto); if (cliente != null) { login.Cliente = cliente; } } } } return(login); }
/// <summary> /// Comprueba en la base de datos que exista un usuario con dichas credenciales. /// </summary> /// <param name="lm"></param> /// <returns>El usuario completo que se ha logueado o en su defecto el valor null.</returns> public Usuario EsValido(LoginModels lm) { dtsUsuarios dts = MappingUsuario.ToDtsUsuarios(lm); Dictionary <DataColumn, Object> parametros = new Dictionary <DataColumn, object>(); parametros.Add(dts.Usuarios.UsuarioColumn, lm.User); parametros.Add(dts.Usuarios.ContrasenaColumn, lm.Password); // Realizamos un merge con al tabla vacia del dtsUsuario con los resultados de la tabla obtenida dtsUsuarios.UsuariosDataTable dt = (dtsUsuarios.UsuariosDataTable)Repo.Leer(dts.Usuarios, parametros); Usuario user; if (dt.Rows.Count > 0) { user = MappingUsuario.ToUsuario(dt, 0); } else { user = null; } return(user); }
public ActionResult Login(string Username, string Password, LoginModels login) { if (!ModelState.IsValid) { var W = loginsCollection.AsQueryable <LoginModels>().Where(w => w.Username == Username && w.Password == Password).FirstOrDefault(); try { if (Username == W.Username && Password == W.Password) { return(RedirectToAction("Index", "Animals")); } else { return(View("Index")); } } catch (NullReferenceException) { ModelState.AddModelError("", "Tài khoản hoặc mật khẩu không chính xác !"); return(View("Login")); } } else { ModelState.AddModelError("", "Tài khoản hoặc mật khẩu không chính xác !"); } return(View("Login")); }
public IActionResult Login([BindAttribute("Email", "Clave")] LoginModels model) { if (ModelState.IsValid) { var db = new GoMeetContext(); var usuario = db.Usuarios.Where(o => o.Email == model.Email && o.Clave == model.Clave).FirstOrDefault(); if (usuario != null) { var claims = new List <Claim>(); claims.Add(new Claim( ClaimTypes.Name, usuario.Nombre, ClaimValueTypes.String, string.Empty)); var userIdentity = new ClaimsIdentity("SuperSecureLogin"); userIdentity.AddClaims(claims); var userPrincipal = new ClaimsPrincipal(userIdentity); HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false }); return(RedirectToAction("Index", "Intranet")); } } return(RedirectToAction("Login", "Home")); }
public ActionResult Login(LoginModels model) { if (ModelState.IsValid) { var dao = new UserDao(); var result = dao.Login(model.UserName, Encryptor.MD5Hash(model.Password)); if (result == 1) { var user = dao.GetByID(model.UserName); var userSession = new UserLogin(); userSession.UserName = user.Username; userSession.UserID = user.ID; Session.Add(CommonConstants.USER_SESSION, userSession); return(RedirectToAction("Index", "Home")); } else if (result == 0) { ModelState.AddModelError("", "Tài khoản không tồn tại"); } else if (result == -1) { ModelState.AddModelError("", "Tài khoản đang bị khóa"); } else if (result == -2) { ModelState.AddModelError("", "Mật khẩu không đúng"); } else { ModelState.AddModelError("", "Đăng nhập không thành công"); } } return(View(model)); }
public ActionResult Login(LoginModels models) { try { if (ModelState.IsValid) { ResponseModels result = clsLoginBL.Login(models); if (result.Response == MethodResponse.Success) { Session[SessionVariable.LoginUserDetails] = result; Session["FirstName"] = result.FirstName; Session[SessionVariable.UserID] = result.UserID; return(RedirectToAction("Index", "Test")); } else { ModelState.AddModelError("", "Invalid Email or Password."); } } } catch (Exception ex) { ViewBag.Error = ex.ToString(); } models.InstituteList = clsLoginBL.GetInstituteList(); return(View(models)); }
public ActionResult SelectLine(LoginModels model) { // セッションにラインをセット Session["LineID"] = model.CondLineID; return(RedirectToAction("Index", "InspStart")); }
public ActionResult Login() { LoginModels model = new LoginModels(); model.SetDropDownListLine(); return(View(model)); }
[ValidateAntiForgeryToken] //检测服务器请求是否被篡改 该特性只能用于post请求,get请求无效 防止CSRF攻击 public ActionResult Index(LoginModels model, string returnUrl) { //验证输入信息 if (!ModelState.IsValid) { return(View(model)); } LogEntity logEntity = new LogEntity(); logEntity.F_ModuleName = "系统登录"; logEntity.F_Type = DbLogType.Login.ToString(); try { UserEntity userEntity = new UserApp().CheckLogin(model.UserName, model.Password); if (userEntity != null) { OperatorModel operatorModel = new OperatorModel(); operatorModel.UserId = userEntity.F_Id; operatorModel.UserCode = userEntity.F_Account; operatorModel.UserName = userEntity.F_RealName; operatorModel.CompanyId = userEntity.F_OrganizeId; operatorModel.DepartmentId = userEntity.F_DepartmentId; operatorModel.RoleId = userEntity.F_RoleId; operatorModel.LoginIPAddress = Net.Ip; operatorModel.LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress); operatorModel.LoginTime = DateTime.Now; operatorModel.LoginToken = DESEncrypt.Encrypt(Guid.NewGuid().ToString()); if (userEntity.F_Account == "admin") { operatorModel.IsSystem = true; } else { operatorModel.IsSystem = false; } OperatorProvider.Provider.AddCurrent(operatorModel); logEntity.F_Account = userEntity.F_Account; logEntity.F_NickName = userEntity.F_RealName; logEntity.F_Result = true; logEntity.F_Description = "登录成功"; new LogApp().WriteDbLog(logEntity); } //return Content(new AjaxResult { state = ResultType.success.ToString(), message = "登录成功。" }.ToJson()); } catch (Exception ex) { logEntity.F_Account = model.UserName; logEntity.F_NickName = model.UserName; logEntity.F_Result = false; logEntity.F_Description = "登录失败," + ex.Message; new LogApp().WriteDbLog(logEntity); return(Content(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson())); } return(RedirectToAction("Index", "Home")); }
public MemberModels Authenticate(LoginModels member) { string data = new JavaScriptSerializer().Serialize(member); HttpResponseMessage response = APIHelper.Post(GlobalKeyHelper.MemberLoginUrl, data); MemberModels result = response.Content.ReadAsAsync <MemberModels>().Result; return(result); }
public ActionResult Login() { LoginModels models = new LoginModels(); models.InstituteList = clsLoginBL.GetInstituteList(); return(View(models)); }
public ActionResult Login(LoginModels login) { if (!ModelState.IsValid) { return(View("Login", login)); } logins.Add(login); return(RedirectToAction("Index")); }
public ActionResult Login(LoginModels model) { // ライン選択用のドロップダウンリストをモデルにセット model.SetDropDownListLine(); // 認証(担当者はIDが登録されていればOK) // ユーザーの存在確認 UserInfo userInfo = new UserInfo(model.Id); if (string.IsNullOrEmpty(userInfo.ID)) { ModelState.AddModelError(string.Empty, "ID、または Password が違います"); return(View(model)); } // 管理者の場合は要パスワード if (userInfo.AuthorityKbn == "1") { // パスワード未入力はエラー if (String.IsNullOrWhiteSpace(model.Password)) { ModelState.AddModelError(string.Empty, "管理者はpasswordが必要です"); return(View(model)); } // 管理者認証 if (userInfo.Password != model.Password) { ModelState.AddModelError(string.Empty, "ID、または Password が違います"); return(View(model)); } } // ユーザー認証 成功 // 認証クッキーにユーザーIDをセット FormsAuthentication.SetAuthCookie(model.Id, false); // ユーザーID、ユーザー名をセッションにセット Session["ID"] = model.Id; Session["UserName"] = userInfo.UserName; // 権限情報をモデルにセット model.AuthorityKbn = userInfo.AuthorityKbn; // 管理者はホワイトボード、管理者以外はライン選択へ if (userInfo.AuthorityKbn == "1") { return(RedirectToAction("WhiteBoard", "WhiteBoard")); } else { // ライン選択モードをオンに設定 ViewBag.ControllAction = "LineSelect"; return(View(model)); } }