public ActionResult Register(LoginFormModel item) { if (ModelState.IsValid) { string email = item.email; var obj = _accountService.GetAllAccounts().Where(p => p.Email.Equals(email)).FirstOrDefault(); if (obj != null) { Session["user"] = null; return(Json(new { result = "Your email has been used by an existing user." })); } Account user = new Account(); user.Email = email; user.Password = item.pass; user.Username = item.name; _accountService.AddAccount(user); Session["user"] = item.name; Session["idUser"] = _accountService.GetAllAccounts().LastOrDefault().Id; return(Json(new { result = "ok" })); } else { return(View("Index", item)); } }
public ActionResult Login(LoginFormModel formModel) { if (ModelState.IsValidField("Email") && ModelState.IsValidField("Password")) { // TODO Get the user record from the database by their email. User user = new User() { Email = "*****@*****.**", HashedPassword = "******" }; // If we didn't get a user back from the database // or if the provided password doesn't match the password stored in the database // then login failed. if (user == null || !BCrypt.Net.BCrypt.Verify(formModel.Password, user.HashedPassword)) { ModelState.AddModelError("", "Login failed."); } } if (ModelState.IsValid) { // Login the user. FormsAuthentication.SetAuthCookie(formModel.Email, false); // Send them to the home page. return(RedirectToAction("Index", "Home")); } return(View(formModel)); }
// // GET: /Login/ public ActionResult Index() { var model = new LoginFormModel(); var listLogin = new List <LdapDto>(); EntityConnectionStringBuilder e = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["FMSEntities"].ConnectionString); string connectionString = e.ProviderConnectionString; SqlConnection con = new SqlConnection(connectionString); con.Open(); SqlCommand query = new SqlCommand("SELECT LOGIN, CONCAT(LOGIN,'-',SUBSTRING(AD_GROUP,23,10)) AS DISPLAY_LOGIN FROM LOGIN_FOR_VTI", con); SqlDataReader reader = query.ExecuteReader(); while (reader.Read()) { var item = new LdapDto(); item.Login = reader[0].ToString(); item.DisplayName = reader[1].ToString(); listLogin.Add(item); } reader.Close(); con.Close(); model.Users = new SelectList(listLogin, "Login", "DisplayName"); return(View(model)); }
public async Task <IActionResult> Login(LoginFormModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var result = await this.signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure : false); if (result.Succeeded) { this.logger.LogInformation("User logged in."); return(RedirectToLocal(returnUrl)); } if (result.RequiresTwoFactor) { return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe })); } if (result.IsLockedOut) { this.logger.LogWarning("User account locked out."); return(RedirectToAction(nameof(Lockout))); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(View(model)); } } return(View(model)); }
public static RequestResult GetAccount(LoginFormModel loginFormModel) { RequestResult requestResult = new RequestResult(); try { using (CFContext context = new CFContext()) { var person = context.People.FirstOrDefault(x => x.LoginId == loginFormModel.LoginId); if (person != null) { requestResult.ReturnData(person); } else { requestResult.ReturnFailedMessage(Resources.Resource.LoginIdNotExist); } } } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); } return(requestResult); }
public async Task <IActionResult> Login(LoginFormModel vm) { ModelState.Clear(); if (ModelState.IsValid) { var user = await this.userManager.FindByEmailAsync(vm.UserName); bool isLogin = await this.userManager.CheckPasswordAsync(user, vm.Password); if (user != null && isLogin) { var identity = new ClaimsIdentity(IdentityConstants.ApplicationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(identity)); return(RedirectToAction(nameof(HomeController.Pages), Infrastructure.Section.Controllers.HOME)); } else { ModelState.AddModelError("", "Invalid UserName or Password"); } } return(View(vm)); }
public async Task <ResponseResult <User> > ValidateUserLogin(LoginFormModel login) { string message; bool errFlag = true; var user = await _context.Users.FirstOrDefaultAsync(u => u.Email == login.Email); if (user != null) { if (user.Password != login.Password) { message = "Password does not match"; user = null; } else { message = "Logged in successfully"; errFlag = false; } } else { message = "There are no users with that email"; } return(new ResponseResult <User> { Error = errFlag, Message = message, ReturnResult = user }); }
public void AuthenticateUser_IdentityHasClaimTypes() { const string UserName = "******"; const string Password = "******"; SecurityManager.Logout(); SitefinityTestUtilities.ServerOperations.Users().CreateUser(UserName, Password, "*****@*****.**", "test", "test", true, "AuthenticateUser", "IdentityHasClaimTypes", SecurityConstants.AppRoles.FrontendUsers); try { var model = new LoginFormModel(); model.Authenticate(new LoginFormViewModel() { UserName = UserName, Password = Password }, SystemManager.CurrentHttpContext); var currentIdentity = ClaimsManager.GetCurrentIdentity(); Assert.AreEqual(UserName, currentIdentity.Name, "The name of the current identity did not match the user."); Assert.IsNotNull(currentIdentity.NameClaimType, "NameClaimType was not set in the current identity."); Assert.IsNotNull(currentIdentity.RoleClaimType, "RoleClaimType was not set in the current identity."); Assert.AreEqual("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", currentIdentity.NameClaimType, "NameClaimType did not have the expected value."); Assert.AreEqual("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", currentIdentity.RoleClaimType, "RoleClaimType did not have the expected value."); } finally { SecurityManager.Logout(); SitefinityTestUtilities.ServerOperations.Users().DeleteUsers(new[] { UserName }); } }
public async Task <IActionResult> Login(LoginFormModel model) { return(await this.Handle( async() => { try { var loginModel = model.MapTo <UserInputModel>(); var result = await this.identityService .Login(loginModel); this.Response.Cookies.Append( InfrastructureConstants.AuthenticationCookieName, result.Content.Token, new CookieOptions { HttpOnly = true, Secure = false, MaxAge = TimeSpan.FromDays(1) }); } catch (Exception ex) { ; throw; } }, success : RedirectToAction(nameof(HomeController.Index), "Home"), failure : View("../Home/Index", model))); }
public async Task <IActionResult> Login(LoginFormModel model) { if (!this.ModelState.IsValid) { return(this.View(model)); } try { var result = await this.identity.Login(model, true); if (result != null && !string.IsNullOrEmpty(result.Token)) { this.Response.Cookies.Append(WebConstants.AuthCookieKey, result.Token, new CookieOptions() { HttpOnly = true, //Secure = true, MaxAge = TimeSpan.FromDays(1) }); return(this.RedirectToHome()); } this.ModelState.AddModelError(string.Empty, WebConstants.Messages.GeneralError); return(this.View(model)); } catch (ApiException ex) { this.ModelState.AddModelError(string.Empty, string.Join(Environment.NewLine, ex.Content.Split(new string[] { ",", "\"", "[", "]" }, StringSplitOptions.RemoveEmptyEntries))); return(this.View(model)); } }
async public Task <IActionResult> Login(LoginFormModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await userManager.FindByNameAsync(model.UserName); if (user == null) { TempData["message"] = "Istifadeci adi ve ya sifre sehvdir"; return(View(model)); } var signInResult = await signInManager.PasswordSignInAsync(user, model.Password, true, true); if (!signInResult.Succeeded) { TempData["message"] = "Istifadeci adi ve ya sifre sehvdir"; return(View(model)); } string redirectLink = Request.Query["ReturnUrl"]; if (!string.IsNullOrWhiteSpace(redirectLink)) { return(Redirect(redirectLink)); } return(RedirectToAction("Index", "DashBoard")); }
public ActionResult PerformLogin(LoginFormModel model) { if (ModelState.IsValid == false) { return(CurrentUmbracoPage()); } if (Members.Login(model.Username, model.Password) == false) { ModelState.AddModelError("Model", "The Username/Password combination provided is not a valid login."); return(CurrentUmbracoPage()); } if (Response.Cookies[FormsAuthentication.FormsCookieName] != null) { var cookieDurationInMinutes = model.RememberMe ? RememberMeLoginCookieDurationInMinutes : NonRememberMeLoginCookieDurationInMinutes; Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddMinutes(cookieDurationInMinutes); } if (Request.RawUrl == CurrentPage.Url) { return(Redirect("/")); } return(RedirectToCurrentUmbracoUrl()); }
public async Task <ActionResult <TokenResult> > Login([FromBody] LoginFormModel model) { var person = PersonService.GetByEmail(model.Email); if (person == null) { return(BadRequest("Email lub hasło jest nieprawidłowe")); } if (!person.EmailConfirmed) { return(BadRequest("Konto nie zostało potwierdzone")); } var result = await _signInManager.CheckPasswordSignInAsync(person, model.Password, true); if (result.Succeeded) { var loggedInUser = new TokenResult() { UserName = person.UserName, Token = AuthService.GenerateToken(person, tokenExpires), Expires = tokenExpires }; return(Ok(loggedInUser)); } return(BadRequest("Email lub hasło jest nieprawidłowe")); }
public async Task <IActionResult> Login(LoginFormModel model) => await this.Handle( async() => { UserInputModel user = new UserInputModel() { Email = model.Email, Password = model.Password }; var result = await this.identityService .Login(user); this.Response.Cookies.Append( AuthenticationCookieName, result.Token, new CookieOptions { HttpOnly = true, Secure = false, //for docker MaxAge = TimeSpan.FromDays(1) }); }, //todo change back to this //success: RedirectToAction("Profile", "Users"), success : RedirectToAction("Index", "Home"), failure : RedirectToAction("Index", "Home"));
public ValidationLogin validaLogin(LoginFormModel dadosUser) { ValidationLogin retorno = new ValidationLogin(); try { var validaLogin = contexto.TabelaUsuarios.Include(r => r.UsuarioAcesso).Where(r => r.Login == dadosUser.login && r.Senha == dadosUser.senha).FirstOrDefault(); if (validaLogin == null) { retorno.validado = false; retorno.messageErrors.Add(new string("Usuario ou senha incorretas !")); } else { retorno.validado = true; retorno.roles = validaLogin.UsuarioAcesso; retorno.messageErrors = null; } } catch (Exception e) { throw e; } return(retorno); }
private Dictionary <string, string> ConstructLoginParams(LoginFormModel input) { return(new Dictionary <string, string> { { LOGIN_USERNAME_PARAM_KEY, input.Email }, { LOGIN_CUSTOMER_PASSWORD_PARAM_KEY, input.Password } }); }
// GET: Account public ActionResult Login() { LoginFormModel model = new LoginFormModel(); model.ErrorMessage = ""; return(View(model)); }
public ApiResponse Login([FromBody] LoginFormModel form) { if (_userService.UserExists(form.Username, form.Password)) { return(new ApiResponse <string>(_authService.GenerateToken(form.Username))); } return(new ApiResponse <string>(null, "Invalid username or password.")); }
public JsonResult Login(LoginFormModel viewModel) { if (string.IsNullOrEmpty(viewModel.ReturnUrl)) { viewModel.ReturnUrl = Url.Action("Index", "Dashboard"); } viewModel.Submit(); return(Json(JsonConvert.SerializeObject(viewModel))); }
public ActionResult Logout() { FusionAppContext.Current.User = null; LoginFormModel model = new LoginFormModel(); model.ErrorMessage = ""; return(View("Login", model)); }
// // GET: /Admin/ public ActionResult Index() { // var list = _roleGroupService.GetAllRoleGroups().ToSelectListItems(-1); LoginFormModel obj = new LoginFormModel(); //obj.ListRoleGroup = list; string ip = Request.UserHostName; LoginClass.Member member = LoginClass.GetMember(ip); obj.name = member.shortId; return(View(obj)); }
public async Task <IActionResult> Login([FromBody] LoginFormModel model) { await _repository.Add(model); _logger.LogWarning(HttpContext.Request.Path); // _logger.LogInformation($"Model with id = {model.Id} is aded"); // _logger.LogInformation($" Model email: {model.Email} and Model password: {model.Password}"); return(StatusCode(StatusCodes.Status200OK)); }
public async Task <IActionResult> Login(LoginFormModel model) { ErrorCode errorCode = await ProcessLoginAsync(model.EMail, model.Password, model.TimeZoneOffsetFromUTC); ViewData["ErrorCode"] = errorCode; if (errorCode == ErrorCode.Success) { return(Redirect(Url.Action("Index", "Dashboard"))); } return(View()); }
// GET public ActionResult Index() { var formModel = new LoginFormModel(); if (Session["UserName"] != null) { formModel.UserName = Session["UserName"].ToString(); } formModel.Roles = GetRoleSelectList(); return(View(formModel)); }
public HttpResponse Login(LoginFormModel model) { var userId = this.usersService.GetUserId(model.Username, model.Password); if (userId == null) { return(Error("Invalid username or password.")); } this.SignIn(userId); return(Redirect("/Trips/All")); }
public ActionResult Login(LoginFormModel login) { var user = dbContext.Set <User>().FirstOrDefault(u => u.LoginId.Equals(login.Username, System.StringComparison.InvariantCultureIgnoreCase)); if (user == null || user.LoginPwd != login.Password) { ViewBag.Msg = "Wrong name or password!"; return(View(login)); } //return Redirect(string.IsNullOrEmpty(redirect)?"/": redirect); ViewBag.Msg = "Login sucessufull!"; return(View(login)); }
public ActionResult Login([FromBody] LoginFormModel loginCredentials) { // try to perform login string token = null; try { token = AuthService.Login(loginCredentials); } catch { return(Unauthorized()); } // respond with temporary session token Object response = new { SessionToken = token }; return(Json(response)); }
private IActionResult HandleLoginFailAction(int apiResponseCode, LoginFormModel input) { if (apiResponseCode == USER_NOT_REGISTERED_LOGIN_API_ERR_CODE) { SetSingleViewData(USERNAME_ERROR_MSG_KEY, USERNAME_ERROR_MSG); return(View(input)); } else { SetSingleViewData(PASSWORD_ERROR_MSG_KEY, PASSWORD_ERROR_MSG); return(View(input)); } }
public ActionResult Login(LoginFormModel model, string returnUrl) { C_CLIENT logged; if (ModelState.IsValid) { using (ProjetWEBEntities context = new ProjetWEBEntities()) { try { logged = context.C_CLIENT.Where(client => client.CLI_EMAIL.Equals(model.UserName) && client.CLI_PASSWORD.Equals(model.Password)).First(); } catch { logged = null; } } if (logged != null) { Session.Clear(); Session["FirstName"] = logged.CLI_FNAME; Session["LastName"] = logged.CLI_LNAME; Session["Acronym"] = logged.CLI_ACRONYM; Session["ClientId"] = logged.CLI_ID; var ticket = LoginHelper.CreateAuthenticationTicket(logged.CLI_ACRONYM, logged.CLI_GROUP, false); var encrypetedTicket = FormsAuthentication.Encrypt(ticket); FormsAuthentication.SetAuthCookie(encrypetedTicket, false); if (String.IsNullOrEmpty(returnUrl)) { return(RedirectToAction("Index", "Home")); } else { returnUrl = Server.UrlDecode(returnUrl); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } } } else { ModelState.AddModelError("", "Nom d'utilisateur ou mot de passe incorrect"); return(View(model)); } } else { return(View(model)); } }
public ActionResult Login(LoginFormModel loginFormModel) { RequestResult requestResult = AccountDataAccessor.GetAccount(loginFormModel); if (requestResult.IsSuccess) { var person = requestResult.Data as Person; if (Config.HaveLDAPSettings) { return(View()); } else { if (string.Compare(person.Password, loginFormModel.Password) == 0) { var organizations = HttpRuntime.Cache.GetOrInsert("organizations", () => OrganizationDataAccessor.GetAllOrganizations()); requestResult = AccountDataAccessor.GetAccount(organizations, person); if (requestResult.IsSuccess) { var account = requestResult.Data as Account; var ticket = new FormsAuthenticationTicket(1, account.Id, DateTime.Now, DateTime.Now.AddHours(24), true, account.Id, FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); Session["Account"] = account; return(RedirectToAction("Index")); } else { ModelState.AddModelError("LoginId", requestResult.Message); return(View()); } } else { ModelState.AddModelError("Password", Resources.Resource.WrongPassword); return(View()); } } } else { ModelState.AddModelError("LoginId", requestResult.Message); return(View()); } }
public ActionResult Login(LoginFormModel model) { if (ModelState.IsValid) { var emp = GetSession.QueryOver<Employee>().Where(x => x.Email == model.Username && x.Password == model.Password && x.IsActive == true).SingleOrDefault(); /* if (emp != null) { if (emp.IsAdmin) { } else { } } */ //return Content("Password:"******"Username: "******"/login" && emp.IsAdmin == false) //{ // return Redirect("/"); //} FormsAuthentication.SetAuthCookie(emp.Username, false); //add cookie for auto login next time Response.Cookies["user"].Value = model.Username; Response.Cookies["user"].Expires = DateTime.MaxValue; Response.Cookies["password"].Value = model.Password; Response.Cookies["password"].Expires = DateTime.MaxValue; Response.Cookies["user_name"].Value = emp.Username; Response.Cookies["user_name"].Expires = DateTime.MaxValue; return Redirect(FormsAuthentication.GetRedirectUrl(emp.Username, false)); } else if (adm != null) { if (model.Username == MvcApplication.Config("admin.Username") && model.Password == MvcApplication.Config("admin.Password")) { Response.Cookies["user"].Value = model.Username; Response.Cookies["user"].Expires = DateTime.MaxValue; Response.Cookies["password"].Value = model.Password; Response.Cookies["password"].Expires = DateTime.MaxValue; Response.Cookies["user_name"].Value = model.Username; Response.Cookies["user_name"].Expires = DateTime.MaxValue; FormsAuthentication.SetAuthCookie(model.Username, false); return Redirect(FormsAuthentication.GetRedirectUrl(model.Username, false)); } } } HttpCookie currentUserCookie = Request.Cookies["user"]; if (currentUserCookie != null) { Response.Cookies.Remove("user"); Response.Cookies.Remove("password"); currentUserCookie.Expires = DateTime.Now.AddDays(-10); currentUserCookie.Value = null; Response.SetCookie(currentUserCookie); } return View(model); }
public ActionResult Login() { string[] allowed = MvcApplication.Config("allowed").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); //if (!allowed.Contains(HttpContext.Request.UserHostAddress.ToString())) //{ // Response.Redirect("http://www.shekelgroup.co.il/"); //} //string[] temp = Convert.ToString(WindowsIdentity.GetCurrent().Name).Split('\\'); //ViewBag.login_name = temp[1]; var model = new LoginFormModel(); //SSO string ssoConfig = MvcApplication.Config("sso.enabled"); if (!String.IsNullOrEmpty(ssoConfig)) { bool ssoEnabled = bool.Parse(ssoConfig); if (ssoEnabled) { using (HostingEnvironment.Impersonate()) { SSOClient ssoClient = new SSOClient(); //string ssoLoginName = ssoClient.GetCurrentLoginName(); string ssoLoginName = User.Identity.Name; if (ssoLoginName.Contains("\\")) { ssoLoginName = ssoLoginName.Split('\\')[1]; } if (!String.IsNullOrEmpty(ssoLoginName)) { string ssoPropertyName = MvcApplication.Config("sso.id_property"); if (!String.IsNullOrEmpty(ssoPropertyName)) { string ssoPropertyValue = ssoClient.GetProperty(ssoLoginName, ssoPropertyName); if (!String.IsNullOrEmpty(ssoPropertyValue)) { //Int64 localId = 2065; Int64 localId = Int64.Parse(ssoPropertyValue); if (localId > 0) { var emp = GetSession.QueryOver<Employee>().Where(x => x.Id == localId).SingleOrDefault(); if (emp != null) { if (String.IsNullOrWhiteSpace(emp.Email) || emp.Email.Equals("*****@*****.**", StringComparison.InvariantCultureIgnoreCase) || String.IsNullOrWhiteSpace(emp.Username)) { return View(new LoginFormModel()); } else { return Login(new LoginFormModel() { Username = emp.Email, Password = emp.Password }); } } } } } } } } } return View(new LoginFormModel()); }