public async Task login_user_with_correct_data_should_return_302_status_code() { var request = new LogInUser { Email = _existingUser.Email, Password = _existingUser.Password }; var payload = GetPayload(request); var response = await _client.PostAsync($"users/login", payload); response.StatusCode.ShouldBeEquivalentTo(HttpStatusCode.Found); }
public LoginResponse LogIn(LogInUser logInUser) { string haslo; if (logInUser.Password.Length < 64) { haslo = GetHash(logInUser.Password); } else { haslo = logInUser.Password; } Uzytkownicy user; using (PP_testEntities context = new PP_testEntities()) { user = (from u in context.Uzytkownicies where u.email == logInUser.Email && u.haslo == haslo select u).FirstOrDefault(); } if (user == null) { return new LoginResponse() { Result = "Failed", Reason = "Bad email or password" } } ; var time = DateTime.Now; string str = time.ToString("yyyyMMddHHmmssfffffff") + logInUser.Email + logInUser.UserAgent; MD5 md5 = MD5.Create(); byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } var token = sBuilder.ToString(); sessions.Add(token, logInUser.Email); return(new LoginResponse() { Token = token, Result = "OK" }); }
public HttpResponseMessage Register(UserDTO newUser) { if (!ModelState.IsValid) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest)); } newUser.Salt = newUser.Salt.GetHashCode().ToString(); if (!_userService.CreateUser(newUser)) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest)); } LogInUser a = new LogInUser() { Email = newUser.EmailAddress, Salt = newUser.Salt }; return(Login(a)); }
public async Task <bool> IsValid(LogInUser command) { try { var isValid = false; var user = await _context.Users.FirstOrDefaultAsync(x => x.Login == command.Login); if (_dataHashManager.VerifyPasswordHash(command.Password, user.PasswordHash, user.Salt) == true) { isValid = true; } return(isValid); } catch (Exception) { return(false); } }
public void Execute(object parameter) { Log.Info("Employee started viewing projects."); if (Resources.Count != 0) { Resources.Clear(); } LogInUser logInUser = ClientDialogViewModel.Instance.LogInUser(); Log.Debug("proxy poziv - GetEmployee"); Employee emp = ClientProxy.Instance.GetEmployee(logInUser.Username, logInUser.Password); Log.Info("Successfully returned employee."); Log.Debug("proxy poziv - GetHcIdForUser"); int hiringCompanyId = ClientProxy.Instance.GetHcIdForUser(logInUser.Username); Log.Info("Successfully returned hiring company id."); Log.Debug("proxy poziv - GetOutsourcingCompanyProjects"); bool ret = ClientProxy.Instance.GetOutsourcingCompanyProjects(hiringCompanyId); Log.Info("Successfully done."); Log.Debug("proxy poziv - GetProjects"); List <Project> projects = ClientProxy.Instance.GetProjects(hiringCompanyId); Log.Info("Successfully returned list of projects."); foreach (Project p in projects) { Resources.Add(p); } ClientDialogViewModel.Instance.PrResources(Resources); ClientDialogViewModel.Instance.ShowShowProjectsView(); }
public IActionResult Logging(LogInUser userSubmission) { if (ModelState.IsValid) { // If inital ModelState is valid, query for a user with provided email var userInDb = dbContext.Users.FirstOrDefault(u => u.Email == userSubmission.LoginEmail); // If no user exists with provided email if (userInDb == null) { // Add an error to ModelState and return to View! ModelState.AddModelError("LoginEmail", "Invalid Email/Password"); return(View("Index")); } // Initialize hasher object var hasher = new PasswordHasher <LogInUser>(); // verify provided password against hash stored in db var result = hasher.VerifyHashedPassword(userSubmission, userInDb.Password, userSubmission.LoginPassword); // result can be compared to 0 for failure if (result == 0) { // handle failure (this should be similar to how "existing email" is handled) return(View("Index")); } User currentUser = dbContext.Users .FirstOrDefault(user => user.Email == userSubmission.LoginEmail); HttpContext.Session.SetInt32("id", currentUser.UserId); int?id = HttpContext.Session.GetInt32("id"); return(RedirectToAction("Dashboard")); } else { return(View("Index")); } }
public IHttpActionResult LogIn([FromBody] LogInUser user) { try { if (logInService.ValidateLogIn(LogInUser.ToEntity(user))) { Guid token = sessionHandler.GetToken(LogInUser.ToEntity(user)); GetSession session = GetSession.ToModel(sessionHandler.GetSessionByUser(LogInUser.ToEntity(user))); User registeredUser = userService.GetByEmail(LogInUser.ToEntity(user).Email); loggingService.AddLogForLogin(registeredUser.UserName); return(Ok(session)); } } catch (MissingUserException e) { return(BadRequest(e.Message)); } return(BadRequest()); }
public void LogIn(LogInUser logInUser) { var result = AsyncHelpers.RunSync(() => _logInStrategy.LogIn(logInUser.Username, logInUser.Password)); switch (result.Result) { case LoginResultType.LoginOk: HttpContext.Current.Session[LogInStatusSessionValueName] = true; HttpContext.Current.Session[LoggedUserSessionValueName] = logInUser.Username; HttpContext.Current.Session[TokenSessionValueName] = result.Token; break; case LoginResultType.LoginFailed: throw new Exception("Wrong username or password."); case LoginResultType.ConnectionError: throw new Exception("There are some problms now. Please try later."); default: throw new ArgumentOutOfRangeException(); } }
public async Task <object> LogInUser(LogInUser loginUser) { var userToLogin = await authRepo.Login(loginUser.UserName.ToLower(), loginUser.Password); if (userToLogin == null) { throw new Exception(); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userToLogin.Id.ToString()), new Claim(ClaimTypes.Name, userToLogin.UserName) }; var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var user = mapper.Map <DetailedUser>(userToLogin); return(new { token = tokenHandler.WriteToken(token), user }); }
/// <summary> /// , 19 August 2019, To get token for api authentication /// </summary> /// <param name="logInUser"></param> /// <returns></returns> private string GenerateJSONWebToken(LogInUser logInUser) { var key = _config["Jwt:Key"]; var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, logInUser.Id.ToString()), new Claim(JwtRegisteredClaimNames.FamilyName, logInUser.LastName), new Claim(JwtRegisteredClaimNames.GivenName, logInUser.FirstName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()) }; var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Audience"], claims, expires: DateTime.Now.AddMinutes(Convert.ToInt32(_config["Jwt:Minutes"])), signingCredentials: credentials); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public ActionResult LogIn(LogInUser logInUser) { if (ModelState.IsValid) { using (var db = new DbContext()) { try { ResourceManager.LoggedUser = db.Users.Where(u => u.Login.Equals(logInUser.Login) && u.Password.Equals(logInUser.Password)).First(); } catch (Exception e) { try { int UserID = db.Users.Where(u => u.Login.Equals(logInUser.Login)).First().UserID; db.FailedLogins.Add(new FailedLogin { Message = "Niepoprawne dane logowania: Użytkownik o loginie -> \"" + logInUser.Login + "\"", UserID = UserID, DateLogin = DateTime.Now }); db.SaveChanges(); } catch (Exception ex) {} // tu brak takiego loginu więc nic nie odnotowujemy ViewBag.Error = ResourceManager.getElementTextInLanguage(99, 1); return(View(logInUser)); } } return(RedirectToAction("Home", "Home")); } ViewBag.Error = ResourceManager.getElementTextInLanguage(100, 1);//"Niepoprawne dane - upewnij się, że uzupełniłeś wszyskie pola!"; return(View(logInUser)); }
public async Task <IActionResult> Login([FromBody] LogInUser request) { if (request == null) { return(BadRequest()); } if (await _userService.LoginAsync(request.Email, request.Password)) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, request.Email) }; var userIdentity = new ClaimsIdentity(claims, "login"); ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity); await HttpContext.Authentication.SignInAsync("CookieAuthentication", principal); return(StatusCode(302)); } return(BadRequest()); }
public void Execute(object parameter) { Log.Info("Employee saved new project definition."); Project project = new Project(); project.Name = CreateProjectViewModel.Instance.NewProjectDefinition().Name; project.Description = CreateProjectViewModel.Instance.NewProjectDefinition().Description; project.StartDate = CreateProjectViewModel.Instance.NewProjectDefinition().StartDate; project.EndDate = CreateProjectViewModel.Instance.NewProjectDefinition().EndDate; LogInUser logInUser = ClientDialogViewModel.Instance.LogInUser(); Log.Debug("proxy poziv - GetEmployee "); Employee productOwner = ClientProxy.Instance.GetEmployee(logInUser.Username, logInUser.Password); Log.Info("Successfully returned employee."); project.ProductOwner = productOwner; string username = ClientDialogViewModel.Instance.LogInUser().Username; Log.Debug("proxy poziv - GetHcIdForUser "); int hiringCompanyId = ClientProxy.Instance.GetHcIdForUser(username); Log.Info("Successfully returned hiring company id."); Log.Debug("proxy poziv - GetHiringCompany "); HiringCompany hc = ClientProxy.Instance.GetHiringCompany(hiringCompanyId); Log.Info("Successfully returned hiring company."); project.HiringCompany = hc; Log.Debug("proxy poziv - AddProjectDefinition "); ClientProxy.Instance.AddProjectDefinition(project); Log.Info("Successfully added project definition."); }
void IClientDialogViewModel.LogInUser(LogInUser logInUser) { LogInUser = logInUser; }
private object Execute(IEventPublisher eventPublisher, IUserIdentitiesRepository userIdentitiesRepository, LogInUser command) { var userIdentity = userIdentitiesRepository.GetUserIdentity(command.UserId); var sessionId = userIdentity.LogIn(eventPublisher); return(Negotiate.WithStatusCode(HttpStatusCode.Created).WithModel(new { Id = sessionId, Url = "/api/identity/sessions/" + Uri.EscapeUriString(sessionId.ToString()) })); }
public async static Task <bool> UpdateUserAccount(AccountUser user, Tokens tokens, LogInUser loginUser, User userUpdate) { UpdateUserObject(user, tokens, loginUser, userUpdate); var result = await Db.AccountUserRepository.Update(user); return(result > 0); }
public User Login(LogInUser inUser) { return(Database.User.QueryToTable.FirstOrDefault(x => x.EmailAddress == inUser.Email && x.Salt == inUser.Salt)); }
public LoginResponse LogIn(LogInUser logInUser) { return(authRepository.LogIn(logInUser)); }
public void SetupTest() { this.logInUserUnderTest = new LogInUser(); }