public async Task <IActionResult> SignIn(SignInForm loginForm) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Profile")); } if (!ModelState.IsValid) { TempData["Result"] = "Error"; return(RedirectToAction("SignIn")); } var result = await _signInManager.PasswordSignInAsync(loginForm.Username, loginForm.Password, loginForm.Remember, true); if (result.Succeeded) { return(RedirectToAction("Index", "Profile")); } TempData["Result"] = "Error"; return(RedirectToAction("SignIn")); }
public MasterMainMenu(SignInForm parentForm, User user) { this.user = user; InitializeComponent(); this.parentSignInForm = parentForm; parentSignInForm.Hide(); }
public virtual ActionResult Post(SignInForm model) { if (model == null) return HttpNotFound(); // sync the model email address with cookie or temp data model.EmailAddress = HttpContext.SigningEmailAddressCookie(false) ?? TempData.SigningEmailAddress(); if (!ModelState.IsValid) return View(model); // clear the email from temp data TempData.SigningEmailAddress(null); // reset the invalid password attempt window Session.FailedPasswordAttempts(false); // sign on the user _services.UserSigner.SignOn(model.EmailAddress, model.RememberMe); // flash the success message SetFeedbackMessage(string.Format( SignOnController.SuccessMessageFormat, model.EmailAddress)); // redirect to return url var establishment = _services.QueryProcessor.Execute( new GetEstablishmentByEmailQuery(model.EmailAddress)); var returnUrl = model.ReturnUrl ?? _services.UserSigner.DefaultSignedOnUrl; var skinsUrl = Url.Action(MVC.Common.Skins.Change(establishment.WebsiteUrl, returnUrl)); return Redirect(skinsUrl); }
public virtual ActionResult Get(string returnUrl) { // return a sign-in form var model = new SignInForm(HttpContext, TempData, returnUrl); return(View(model)); }
public static object Response(SignInForm form, HashSalt hashSalt) { var identity = GetIdentity(form, hashSalt); if (identity == null) { return(null); } var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; return(response); }
public ActionResult SignIn(SignInForm form) { var user = (ApplicationUser)Session["User"]; if (user != null) { return(RedirectToAction("Home", "Home")); } if (!ModelState.IsValid) { return(View("SignIn", form)); } var dbUser = db.ApplicationUsers.SingleOrDefault(u => u.Username == form.Username && u.Password == form.Password); if (dbUser == null) { ModelState.AddModelError("", "Invalid credentials."); return(View("SignIn", form)); } var loginUser = new ApplicationUser(); //loginUser.GetLoginData(dbUser); //Session["User"] = loginUser; Session["User"] = dbUser; return(RedirectToAction("Home", "Home")); }
private void btnLogout_Click(object sender, EventArgs e) { this.Hide(); SignInForm signinForm = new SignInForm(); signinForm.Show(); }
public IActionResult SignIn(SignInForm form, [FromQuery] string returnUrl = null) { return(Form( form, () => returnUrl != null ? (IActionResult)Redirect(returnUrl) : this.RedirectToAction <EmployeeController>(x => x.List()), () => View(form))); }
public JsonResult SignIn(SignInForm form) { if (ModelState.IsValid) { contentManager.Application.SignIn(form.UserName, form.Password); return(JsonNet(new { success = true })); } return(JsonNet(new { success = false, message = "Validation Error" })); }
public async Task <IActionResult> SignInAsync([FromBody] SignInForm signInForm) { if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(signInForm.Email); if (!await _userManager.CheckPasswordAsync(user, signInForm.Password)) { return(BadRequest(new { errorMessage = "Username Or password is not correct." })); } Microsoft.AspNetCore.Identity.SignInResult result = null; result = await _signInManager.PasswordSignInAsync(user.UserName, signInForm.Password, signInForm.RememberMe, lockoutOnFailure : false); if (result.Succeeded) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_config["IdentitySetting:Secret"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)); // Write token to http only cookie Response.Cookies.Append( "access_token", token, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = true } ); return(Ok(new { token, user })); } if (result.IsLockedOut) { return(BadRequest(new { errorMessage = "User account is locked." })); } if (result.IsNotAllowed) { return(BadRequest(new { errorMessage = "User account is not allowed." })); } } return(BadRequest(new { errorMessage = "Please contact system administrator." })); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var context = new StorageContext(); var view = new SignInForm(context); Application.Run(view); }
public virtual async Task <IActionResult> SignIn(SignInForm form) { var authorizationRequest = await this.ResolveAndValidateAsync(form); if (form.Cancel) { // ReSharper disable InvertIf if (authorizationRequest != null) { await this.Facade.Interaction.DenyAuthorizationAsync(authorizationRequest, AuthorizationError.AccessDenied); if (authorizationRequest.IsNativeClient()) { return(await this.Redirect(form.ReturnUrl, this.Facade.IdentityServer.CurrentValue.Redirection.SecondsBeforeRedirect)); } } // ReSharper restore InvertIf return(this.Redirect(form.ReturnUrl)); } if (this.ModelState.IsValid) { var signInResult = await this.Facade.Identity.SignInAsync(form.Password, form.Persistent, form.UserName); if (signInResult.Succeeded) { var user = await this.Facade.Identity.GetUserAsync(form.UserName); if (user == null) { throw new InvalidOperationException($"The user \"{form.UserName}\" does not exist."); } await this.Facade.Events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId : authorizationRequest?.Client.ClientId)); if (authorizationRequest != null && authorizationRequest.IsNativeClient()) { return(await this.Redirect(form.ReturnUrl, this.Facade.IdentityServer.CurrentValue.Redirection.SecondsBeforeRedirect)); } return(this.Redirect(form.ReturnUrl)); } this.Logger.LogDebugIfEnabled($"Sign-in for user \"{form.UserName}\" failed. Result: {signInResult}"); await this.Facade.Events.RaiseAsync(new UserLoginFailureEvent(form.UserName, "invalid credentials", clientId : authorizationRequest?.Client.ClientId)); this.ModelState.AddModelError(string.Empty, this.Localizer.GetString("errors/invalid-username-or-password")); } var model = await this.CreateSignInViewModelAsync(form); return(await Task.FromResult(this.View(model))); }
static void Main(string[] args) { string culture = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Wammer\WinStation", "Culture", null); if (culture == null) { CultureManager.ApplicationUICulture = CultureInfo.CurrentCulture; } else { CultureManager.ApplicationUICulture = new CultureInfo(culture); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form form = null; if (args.Length == 1 && args[0].Equals("--dropbox")) { form = new DropboxForm(); } else { if (SystemTrayHelper.IsAlreadyResistered()) { SystemTrayHelper.StartSystemTrayProgram(); return; } form = new SignInForm(); // force window to have focus // please refer http://stackoverflow.com/questions/278237/keep-window-on-top-and-steal-focus-in-winforms uint foreThread = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero); uint appThread = GetCurrentThreadId(); const uint SW_SHOW = 5; if (foreThread != appThread) { AttachThreadInput(foreThread, appThread, true); BringWindowToTop(form.Handle); ShowWindow(form.Handle, SW_SHOW); AttachThreadInput(foreThread, appThread, false); } else { BringWindowToTop(form.Handle); ShowWindow(form.Handle, SW_SHOW); } form.Activate(); } Application.Run(form); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SignInForm frmSignIn = new SignInForm(); if (frmSignIn.ShowDialog() == DialogResult.Yes) { //If the sign-in completed successfully, show the main form //(otherwise, the application will quit because the sign-in failed) Application.Run(new ControlPanelForm()); } }
public IActionResult SignIn(SignInForm signInForm) { logger.Info("Developer Portal: SignIn - Posted"); try { DeveloperAccountDTO account = auth.AuthenticateUser(signInForm); logger.Info("Developer Portal: SignIn - Posted - Successfully Signed In", account.ForLogging()); return(RedirectToAction("AccountHome")); } catch (Exception e) { logger.Info("Developer Portal: SignIn - Posted ERROR", e); return(View()); } }
private System.Windows.Window CreateWindow(CredentialRequestInfo info) { Window window = new Window() { Height = 470, Width = 681, WindowStartupLocation = WindowStartupLocation.CenterOwner, ShowInTaskbar = false, WindowStyle = WindowStyle.ToolWindow, ResizeMode = ResizeMode.NoResize }; var contentDialog = new SignInForm() { EnableCredentialCache = EnableCredentialsCache, CredentialRequestInfo = info }; if (SignInFormStyle != null) { contentDialog.Style = SignInFormStyle; } contentDialog.Completed += (s, e) => { window.Close(); }; contentDialog.Cancelled += (s, e) => { window.Close(); }; contentDialog.CreateCredentialError += (s, e) => { MessageBox.Show("Sign in failed. Check your username and password", e.Message); }; if (info.AuthenticationType == AuthenticationType.NetworkCredential) { contentDialog.MessageText = "Network Credentials required for "; } else if (info.AuthenticationType == AuthenticationType.Token) { contentDialog.MessageText = "ArcGIS Credentials required for "; } window.Content = contentDialog; window.Title = contentDialog.HeaderText; return(window); }
public async Task SignIn(Ui ui, SignInForm form) { if (ui.Context.User.Identity.IsAuthenticated) { // TODO redirect to dashboard return; } form.identityType = form.identityType ?? _identityOptions.CurrentValue.DefaultIdentityType.GetValueOrDefault(IdentityType.Email); string identity; switch (form.identityType) { case IdentityType.Username: identity = form.username; break; case IdentityType.Email: identity = form.email; break; case IdentityType.PhoneNumber: identity = form.phoneNumber; break; default: throw new ArgumentOutOfRangeException(nameof(form.identityType), form.identityType, null); } if (form.email != null && form.password != null) { var operation = await _signInService.SignInAsync(form.identityType.Value, identity, form.password, form.rememberMe); if (operation.Succeeded) { return; } } ui.Component <SignIn>(new SignInModel { IdentityType = form.identityType, Identity = identity, Password = form.password }); }
public DeveloperAccountDTO AuthenticateUser(SignInForm signInForm) { DeveloperAccountDTO account = accountsService.Get(signInForm.Email); if (account == null || string.IsNullOrEmpty(account.Email)) { throw new AccountNotFoundException(); } bool correctPassword = passwordService.VerifyPassword(account.Password, signInForm.Password); if (!correctPassword) { throw new IncorrectPasswordException(); } SetEmailToSession(account.Email); return(account); }
private static ClaimsIdentity GetIdentity(SignInForm form, HashSalt hashSalt) { byte[] byteArr = Encoding.ASCII.GetBytes(hashSalt.salt); string passwordHashed = PasswordManager.PasswordSaveHashing(form.Password, byteArr); if (passwordHashed == hashSalt.hash) { var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, form.Login), new Claim(ClaimsIdentity.DefaultRoleClaimType, form.Role) }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); return(claimsIdentity); } return(null); }
IEnumerator SignIn(SignInForm form) { string postData = JsonUtility.ToJson(form); using (UnityWebRequest www = UnityWebRequest.Put("http://localhost:3000/users/signin", postData)) { www.method = "POST"; www.SetRequestHeader("Content-Type", "application/json"); yield return(www.Send()); loginButton.interactable = true; if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { string cookie = www.GetResponseHeader("set-cookie"); int lastIdx = cookie.IndexOf(';'); string sid = cookie.Substring(0, lastIdx); string resultStr = www.downloadHandler.text; var result = JsonUtility.FromJson <LoginResult>(resultStr); if (result.result == 2) { if (!string.IsNullOrEmpty(sid)) { PlayerPrefs.SetString("sid", sid); } //SceneManager.LoadScene("Game"); SceneManager.LoadScene("TicTacToe"); } Debug.Log(www.downloadHandler.text); } } }
// 로그인 버튼 이벤트 public void OnClickSignInButton() { loginButton.interactable = false; string username = loginUsernameInputField.text; string password = loginPasswordInputField.text; if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return; } // TODO: 서버에 회원가입 정보 전송 SignInForm signinForm = new SignInForm(); signinForm.username = username; signinForm.password = password; StartCoroutine(SignIn(signinForm)); }
public virtual async Task <IActionResult> SignIn(SignInForm form) { if (form == null) { throw new ArgumentNullException(nameof(form)); } form.ReturnUrl = this.ResolveAndValidateReturnUrl(form.ReturnUrl); if (form.Cancel) { return(this.Redirect(form.ReturnUrl)); } if (this.ModelState.IsValid) { if (!string.IsNullOrWhiteSpace(form.UserName)) { var nameIdentifier = string.Equals(form.UserName, "alice", StringComparison.OrdinalIgnoreCase) ? 2 : string.Equals(form.UserName, "bob", StringComparison.OrdinalIgnoreCase) ? 3 : 4; var claims = new List <Claim> { new(ClaimTypes.Name, form.UserName), new(ClaimTypes.NameIdentifier, nameIdentifier.ToString(CultureInfo.InvariantCulture)) }; var authenticationProperties = new AuthenticationProperties(); var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Fake")); await this.HttpContext.SignInAsync(AuthenticationSchemes.Cookie, principal, authenticationProperties); return(this.Redirect(form.ReturnUrl)); } this.ModelState.AddModelError(nameof(SignInForm.UserName), "Invalid user-name."); } var model = await this.CreateSignInViewModelAsync(form); return(await Task.FromResult(this.View(model))); }
private void SetLoginAndPasswordUsingSignInForm() { bool success = false; SignInForm signInForm = new SignInForm(); while (success == false) { try { signInForm.ShowDialog(); User = signInForm.User; User = authorizationManager.SignIn(User); success = true; } catch (UserIsNullException ex) { success = false; signInForm.ShowInvalidLoginMessage(); } } }
public async Task <IActionResult> SignIn([FromBody] SignInForm form) { try { using (var client = new HttpClient()) { var response = await client.GetAsync($"https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={form.GoogleToken}"); var content = await response.Content.ReadAsStringAsync(); var googleUser = JsonConvert.DeserializeObject <GoogleUser>(content); var user = await _userService.SignInAsync(googleUser.email); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("SymmetricSecurityKey"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new UserDto { Id = user.Id, Email = user.Email, Token = tokenString })); } } catch (Exception e) { throw; } }
public IActionResult Token(SignInForm form) { if (String.IsNullOrWhiteSpace(form.Login) || String.IsNullOrWhiteSpace(form.Password)) { return(BadRequest("All fields are required")); } var manager = _context.HashSalts.FromSqlInterpolated($"SELECT hash, salt FROM Managers WHERE Managers.email = {form.Login}").ToList(); if (manager.Count == 0) { return(BadRequest(new { errorText = "Invalid username" })); } var response = AuthenticationManager.Response(form, manager.First()); if (response == null) { return(BadRequest(new { errorText = "Invalid password" })); } return(Ok(response)); }
public virtual async Task <IActionResult> SignIn([FromBody] SignInForm signInForm, CancellationToken cancellationToken = default(CancellationToken)) { var userFromDatabase = await userManager.FindByEmailAsync(signInForm.Email); if (userFromDatabase == null) { return(BadRequest(new ResponseMessage { Title = $"خطا در احراز هویت", Descripton = $"ایمیل یا رمز عبور اشتباه است" })); } var isPasswordValid = await userManager.CheckPasswordAsync(userFromDatabase, signInForm.Password); if (!isPasswordValid) { return(BadRequest(new ResponseMessage { Title = $"خطا در احراز هویت", Descripton = $"ایمیل یا رمز عبور اشتباه است" })); } var result = await signInManager.ClaimsFactory.CreateAsync(userFromDatabase); var claimList = new List <Claim>(result.Claims); var generatedToken = tokenFactory.GenerateToken(claimList); var userToken = new UserToken() { UserId = userFromDatabase.Id, RefreshToken = generatedToken.RefreshToken, Expiration = generatedToken.AccessTokenExpirationTime }; await tokenService.SaveRefreshTokenAsync(userToken, cancellationToken); return(Created(string.Empty, generatedToken)); }
public virtual ActionResult Post(SignInForm model) { if (model == null) { return(HttpNotFound()); } // sync the model email address with cookie or temp data model.EmailAddress = HttpContext.SigningEmailAddressCookie(false) ?? TempData.SigningEmailAddress(); if (!ModelState.IsValid) { return(View(model)); } // clear the email from temp data TempData.SigningEmailAddress(null); // reset the invalid password attempt window Session.FailedPasswordAttempts(false); // sign on the user _services.UserSigner.SignOn(model.EmailAddress, model.RememberMe); // flash the success message SetFeedbackMessage(string.Format( SignOnController.SuccessMessageFormat, model.EmailAddress)); // redirect to return url var establishment = _services.QueryProcessor.Execute( new GetEstablishmentByEmailQuery(model.EmailAddress)); var returnUrl = model.ReturnUrl ?? _services.UserSigner.DefaultSignedOnUrl; var skinsUrl = Url.Action(MVC.Common.Skins.Change(establishment.WebsiteUrl, returnUrl)); return(Redirect(skinsUrl)); }
public async Task <IActionResult> SignIn([FromBody] SignInForm form) { LogBeginOfRequest(); if (VerifyRequestLimit()) { LogEndOfRequest($"Failed request Ip: {GetRequestIp()} reached limit", 429); return(StatusCode(429, "Reached request limit. Come back after few minutes")); } if (!ModelState.IsValid) { LogEndOfRequest("Failed Bad Request", 400); return(BadRequest(ModelState)); } try { await services.SignIn.HandleAsync(new SignInCommand( form.Login, form.Password, form.Name, form.Surname, form.Email, hashHandler, credentialsRestriction )); LogEndOfRequest($"Success created user {form}", 200); return(Ok()); } catch (Exception e) { LogEndOfRequest("Failed " + e.Message, 400); return(BadRequest(e.Message)); } }
public IActionResult SignIn([FromBody] SignInForm form) { try { var user = _context.Users.Include(u => u.Room).FirstOrDefault(u => u.Email == form.Email); if (user == null || user.Password != form.Password) { return(BadRequest(Errors.EmailOrPassInc)); } Identity id = new Identity { UserId = user.UserId, Name = user.Name, Guest = null }; return(Ok(new { jwt = Helper.GetToken(JsonSerializer.Serialize(id)), userId = id.UserId, userGuid = id.Guest, name = user.Name, room = user.Room == null ? null : new { name = user.Room.Name, description = user.Room.Description, country = user.Room.Country, password = user.Room.Password, limit = user.Room.Limit } })); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex)); } }
public virtual JsonResult ValidatePassword( [CustomizeValidator(Properties = SignInForm.PasswordPropertyName)] SignInForm model) { // form is valid unless email address is eligible return(ValidateRemote(SignInForm.PasswordPropertyName)); }
protected internal virtual async Task <SignInViewModel> CreateSignInViewModelAsync(SignInForm form) { if (form == null) { throw new ArgumentNullException(nameof(form)); } var model = await this.CreateSignInViewModelAsync(form.ReturnUrl); model.Form = form; return(model); }
public virtual ActionResult Get(string returnUrl) { // return a sign-in form var model = new SignInForm(HttpContext, TempData, returnUrl); return View(model); }