public async Task <ApiResult <User> > GoogleLogin(LoginCredential loginCredential) { try { var stopwatch = Stopwatch.StartNew(); _logger.LogInformation("Google login"); var result = await _userService.GoogleLogin(loginCredential); _logger.LogInformation("Google login complete"); stopwatch.Stop(); result.ExecutionTime = stopwatch.Elapsed.TotalMilliseconds; _logger.LogInformation($"Execution time: {result.ExecutionTime}ms"); return(result); } catch (Exception ex) { _logger.LogInformation($"Google login error: {ex}"); return(new ApiResult <User> { Result = null, ApiCode = ApiCode.UnknownError, ErrorMessage = ex.ToString() }); } }
public ActionResult Authorize(LoginCredential credentials) { using (EmployeeDBEntities_Login db = new EmployeeDBEntities_Login()) { try { var userDetails = db.LoginCredentials .FirstOrDefault(x => x.UserName == credentials.UserName && x.Password == credentials.Password); if (userDetails == null) { credentials.LoginErrorMessage = "Wrong username or password."; return(View("Index", credentials)); } } catch (Exception ex) { credentials.LoginErrorMessage = "Unable to find credentials."; Console.WriteLine(ex); return(View("Index", credentials)); } Session["userId"] = credentials.UserId; Session["userName"] = credentials.UserName; return(RedirectToAction("Index", "Home")); } }
public IHttpActionResult LoginWithLoginCredentials([FromBody] LoginCredentialLoginForm request) { var _loginType = request._loginType; string _password = request._password; string _username = request._username; LoginCredential LoginCredential = null; var _contextIncluded = _context.LoginCredentials .Include("User") .Include("User.UserCommunicationPreferences") .Include("User.UserFarms") .Include("User.UserFarms.Farm"); if (_loginType == "Email") { LoginCredential = _contextIncluded. Where(x => x.Password.Equals(_password) && x.User.UserEmail == _username).FirstOrDefault(); } else if (_loginType == "PhoneNumber") { LoginCredential = _contextIncluded. Where(x => x.Password.Equals(_password) && x.User.UserPhoneNumber == _username).FirstOrDefault(); } if (LoginCredential == null) { return(Content(HttpStatusCode.Unauthorized, new { code = ErrorCode.INVALID_CREDENTIALS })); } return(Ok(AutoMapper.Mapper.Map <LoginCredentialDTO>(LoginCredential))); }
private async Task LoginAsync() { using (Busy.GetTicket()) { FailureMessage = ""; var credential = new LoginCredential(Username, Password, null); // Clear username and password fields Username = null; Password = null; try { await _authenticationService.LoginAsync(credential); if (_globalCache != null) { try { await _globalCache.LoadAsync(); } catch (Exception e) { throw new Exception("Failed to load global entity cache. Try again!", e); } } } catch (Exception e) { FailureMessage = e.Message; } } }
public async Task <IActionResult> Login([FromBody] LoginCredential c) { string token = null; /* * using (var reader = new StreamReader(Request.Body)) * { * try * { * var body = await reader.ReadToEndAsync(); // reader.ReadToEnd(); * } * catch (Exception e) * { * } * * // Do something else * } */ if (c.Uname != null && c.Upassword != null) { var admin = await _context.Administrator.FirstOrDefaultAsync( a => a.Uname == c.Uname && a.Upassword == c.Upassword); if (admin != null) { var adminRole = await _context.AdminRole.FirstOrDefaultAsync(a => a.AdminLevel.ToString() == admin.AdminLevel.ToString()); token = JwtHelper.GenrateJwtTokenForLibraryAdmin(admin.AdminId.ToString(), System.Convert.ToString(adminRole), _config["Jwt:Key"]); return(Ok(new { token })); } } return(BadRequest(new { message = "Username or password is incorrect." })); }
private UserAccount Authenticate(LoginCredential login) { var hashPassword = EncryptPassword(login.ClientSecret); var client = _dbContext.UserAccounts.FirstOrDefault (c => c.UserName == login.ClientId && c.HashedPassword == hashPassword); return(client); }
public async Task <User> AuthenticateUser(LoginCredential login) { Entities.User efUser = await _unitOfWork.Users.GetUserInformation(login.UserName, login.Password); User user = _mapper.Map <Entities.User, User>(efUser); return(user); }
public ActionResult Login(LoginCredential l) { if (!Membership.ValidateUser(l.UserName, l.Password)) { return(Redirect("/Account/Index?l=false")); } else { WebSecurity.Login(l.UserName, l.Password); return(RedirectToAction("Home", "Account")); } }
public bool IsUserValid(LoginCredential userLoginCredentials) { var userCredentials = _context.UserCredentials.FirstOrDefault(x => x.UserID.Equals(userLoginCredentials.UserID)); if (userCredentials != null) { if (userCredentials.Password.Equals(userLoginCredentials.Password)) { return(true); } } return(false); }
//public async void Edit_Address() //{ // try // { // App.Current.Properties["Action"] = "Edit"; // HttpClient client = new HttpClient(); // client.BaseAddress = new Uri(GlobalData.gblApiAdress); // client.DefaultRequestHeaders.Accept.Add( // new MediaTypeWithQualityHeaderValue("application/json")); // client.Timeout = new TimeSpan(500000000000); // HttpResponseMessage response = client.GetAsync("api/CompanyAPI/ShowData/").Result; // //response = client.GetAsync("api/DeliveryAddressAPI/EditDelivery/?id=" + selectDelivery.DELIVERY_ID + "").Result; // if (response.StatusCode.ToString() == "OK") // { // data = JsonConvert.DeserializeObject<DeliveryAddressModel[]>(await response.Content.ReadAsStringAsync()); // if (data.Length > 0) // { // for (int i = 0; i < data.Length; i++) // { // DELIVERY_CODE = data[i].DELIVERY_CODE; // DELIVERY_COMPANY_NAME = data[i].DELIVERY_COMPANY_NAME; // ADDRESS = data[i].ADDRESS; // COUNTRY = data[i].COUNTRY; // CONTACTS = data[i].CONTACTS; // TELEPHONE = data[i].TELEPHONE; // POSTCODE = data[i].POSTCODE; // EC_COUNTRY = data[i].EC_COUNTRY; // SAME_STATEMENT = data[i].SAME_STATEMENT; // //DELIVERY_CODE = data[i].DELIVERY_CODE; // TELEPHONE = data[i].TELEPHONE; // FAX = data[i].FAX; // DELIVERY_MODE = data[i].DELIVERY_CODE; // DELIVERY_TIME = data[i].DELIVERY_CODE; // } // App.Current.Properties["CatagoryEdit"] = selectDelivery; // //selectDelivery = App.Current.Properties["CatagoryEdit"] as DeliveryAddressModel; // } // } // } // catch (Exception ex) // { // throw; // } //} public async void LoginCredential_Click() { try { Cancel_Company(); LoginCredential _LC = new LoginCredential(); _LC.ShowDialog(); //Cancel_Company(); } catch { } }
public async Task <IActionResult> LoginAsync([FromBody] LoginCredential loginCredential) { var signInResult = await _signinManager.PasswordSignInAsync(loginCredential.Username, loginCredential.Password, false, false); if (signInResult.Succeeded) { var user = await _userManager.FindByNameAsync(loginCredential.Username); return(Ok(new { access_token = _jwtTokenService.GenerateToken(user) })); } return(Forbid()); }
public virtual void SetLoginCredentials(LoginCredential loginCredentials) { DomElement signInPageContainer = BodyContainer.GetElementWaitByCSS(SignInSectionContainer.locator); DomElement loginContainer = signInPageContainer.GetElementWaitByCSS(LoginContainer.locator); DomElement emailField = loginContainer.GetElementWaitByCSS(EmailInput.locator); DomElement passwordField = loginContainer.GetElementWaitByCSS(PasswordInput.locator); emailField.webElement.SendKeys(loginCredentials.User); passwordField.webElement.SendKeys(loginCredentials.Password); //TODO: //use a selenium wait to replace this Sleep System.Threading.Thread.Sleep(1900); }
public void StartLogin_withValidCredential_willAllowLogin() { mockMainView.Setup(view => view.ShowErrorMessage(It.IsAny <string>())).Verifiable(); mockMainView.Setup(view => view.OnLoginSuccess()).Verifiable(); var loginCredential = new LoginCredential { UserName = "******", Password = "******" }; _MainPresenter.StartLogin(loginCredential); mockMainView.Verify(view => view.ShowErrorMessage(It.IsAny <string>()), Times.Never()); mockMainView.Verify(view => view.OnLoginSuccess(), Times.Once()); }
public void StartLogin_withInvalidPassword_willShowErrorMessage() { mockMainView.Setup(view => view.ShowErrorMessage("Invalid password")).Verifiable(); mockMainView.Setup(view => view.OnLoginSuccess()).Verifiable(); var loginCredential = new LoginCredential { UserName = "******", Password = "******" }; _MainPresenter.StartLogin(loginCredential); mockMainView.Verify(view => view.ShowErrorMessage("Invalid password"), Times.Once()); mockMainView.Verify(view => view.OnLoginSuccess(), Times.Never()); }
public IActionResult LoginWithToken([FromBody] LoginCredential login) { IActionResult response = Unauthorized(); if (login != null) { var user = Authenticate(login); if (user != null) { var tokenString = BuildToken(user); response = Ok(new { Token = tokenString }); } } return(response); }
public void StartLogin(LoginCredential loginCredential) { if (!loginCredential.IsValidUserName()) { _View.ShowErrorMessage("Invalid username"); return; } if (!loginCredential.IsValidPassword()) { _View.ShowErrorMessage("Invalid password"); return; } _View.OnLoginSuccess(); }
public static Tuple <User, LoginCredential> MapToEntity(this UserRegistrationInfo userInfo) { var user = new User() { Name = userInfo.Name, DateOfBirth = userInfo.DateOfBirth, EmailID = userInfo.EmailID, }; var userCredentials = new LoginCredential() { UserID = userInfo.EmailID, Password = userInfo.Password }; return(new Tuple <User, LoginCredential>(user, userCredentials)); }
public IActionResult CreateToken(LoginCredential login) { IActionResult response = Unauthorized(); if (login != null) { var user = AuthenticateUser(login); if (user != null) { string token = BuildToken(user); response = Ok(new { Token = token }); } } return(response); }
public StatusEnum.ChangePasswordStatus ChangePassword(LoginCredential credential, SecUser secUser = null) { StatusEnum.ChangePasswordStatus status = StatusEnum.ChangePasswordStatus.InvalidOldPassword; try { _user = secUser ?? GetUserByEmail(credential.Email.ToLower()); if (_user != null) { _isPIN = credential.IsPIN; _isOldPIN = credential.IsOldPIN; status = ValidatePasswordForChange(credential); } return(status); } catch (Exception) { throw; } }
private User AuthenticateUser(LoginCredential login) { var user = _dbContext.User.Where(x => x.UserName == login.UserName).FirstOrDefault(); var hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: login.Password, salt: System.Convert.FromBase64String(user.SaltKey), prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); if (hashedPassword.Equals(user.HashPassword)) { return(user); } return(null); }
public IHttpActionResult RegisterLoginCredentials(LoginCredentialsRegisterForm _loginFormData) { LoginCredential loginCredential = null; try { var loginCredentialData = _loginFormData.LoginCredential; var userData = _loginFormData.User; userData.UserType = _loginFormData.UserType; userData.IsActive = "1"; if (_loginFormData.RegisterType == "UserPhoneNumber") { if (_context.Users.Any(x => x.UserPhoneNumber == loginCredentialData.UserLoginID)) { return(Content(HttpStatusCode.Unauthorized, new { code = ErrorCode.USER_ALREADY_REGISTER })); } userData.UserPhoneNumber = loginCredentialData.UserLoginID; } if (_loginFormData.RegisterType == "UserEmail") { userData.UserEmail = loginCredentialData.UserLoginID; } var createdUser = _context.Users.Add(userData); loginCredentialData.UserID = createdUser.UserID; loginCredentialData.UserSecurityRole = _context.UserSecurityRoles.Find(loginCredentialData.UserRoleID); loginCredential = _context.LoginCredentials.Add(loginCredentialData); _context.SaveChanges(); } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, new { code = ErrorCode.OTHER, exception = ex })); } return(Ok(AutoMapper.Mapper.Map <LoginCredentialDTO>(loginCredential))); }
public StatusEnum.ChangePasswordStatus ValidatePasswordForChange(LoginCredential credential) { StatusEnum.ChangePasswordStatus status = StatusEnum.ChangePasswordStatus.Success; if (!_user.IsActive) { status = StatusEnum.ChangePasswordStatus.AccountDeactivated; return(status); } status = _isOldPIN != true?ValidatePrimaryPasswordForChange(credential.OldPassword) : ValidatePINPasswordForChange(credential.OldPIN); if (status != StatusEnum.ChangePasswordStatus.Success) { status = StatusEnum.ChangePasswordStatus.InvalidOldPassword; return(status); } return(status); }
public void CanLoadCredential() { var vm = new LoginWndVm(_clientFactory, _credentialPersist) { UserName = "", Password = "" }; var expectedCredential = new LoginCredential() { UserName = "******", Password = "******" }; _credentialPersist.Load().Returns(expectedCredential); vm.LoadCredential(); _credentialPersist.Received(1).Load(); Assert.That(vm.UserName, Is.EqualTo(expectedCredential.UserName)); Assert.That(vm.Password, Is.EqualTo(expectedCredential.Password)); }
public void GivenAnEmptyCredential_ShouldntBePopulated() { var vm = new LoginWndVm(_clientFactory, _credentialPersist) { UserName = "", Password = "" }; var expectedCredential = new LoginCredential() { UserName = "", Password = "" }; _credentialPersist.Load().Returns(expectedCredential); vm.LoadCredential(); _credentialPersist.Received(1).Load(); Assert.IsEmpty(vm.UserName); Assert.IsEmpty(vm.Password); }
public async Task <IActionResult> Login([Bind("Username, Password")] LoginCredential user) { if (ModelState.IsValid) { TablesController table = new TablesController(); if (table.GetUser(user.Username, user.Password)) { table.UpdateLastLogin(user.Username, user.Password); return(RedirectToAction("Index", "Dishes")); } else { ViewBag.isValid = false; } } return(View()); }
public async Task <ApiResult <User> > Login(LoginCredential loginCredential) { if (loginCredential == null || string.IsNullOrEmpty(loginCredential.Email) || string.IsNullOrEmpty(loginCredential.Password)) { return(new ApiResult <User> { ApiCode = ApiCode.BadCredential, Result = null }); } var user = await _unitOfWork.UserRepository.FindUserByEmail(loginCredential.Email); if (user == null) { return(new ApiResult <User> { ApiCode = ApiCode.BadCredential, Result = null }); } var hashedPassword = HashPassword(loginCredential.Password); if (hashedPassword != user.Password) { return(new ApiResult <User> { ApiCode = ApiCode.BadCredential, Result = null }); } user.Token = GenerateToken(user); return(new ApiResult <User> { Result = user, ApiCode = ApiCode.Success }); }
public UserActivityReason ValidatePassword(LoginCredential credentials, UserActivityReason activityReason) { UserActivityReason activityReasonNew = new UserActivityReason(); if (activityReason != null) { activityReasonNew = activityReason; } if (!_user.IsActive) { activityReasonNew.Message = UserAccountNotification.AccountDeactiveOrExpirePass; activityReasonNew.ReturnFlag = false; return(activityReasonNew); } activityReasonNew = credentials.IsPIN != true?ValidatePrimaryPassword(credentials.Password.Trim(), activityReasonNew) : ValidatePINPassword(credentials.PIN, activityReasonNew); _secUserRepository.Update(_user); _secUserRepository.SaveChanges(); return(activityReasonNew); }
public async Task <IActionResult> Login([FromBody] LoginCredential c) { string token = null; if (c.Uname != null && c.Upassword != null) { var admin = await _context.Administrator.FirstOrDefaultAsync( a => string.Equals(a.Uname, c.Uname) && a.Upassword == CryptoHelper.Hash(c.Upassword)); if (admin != null) { var adminRole = await _context.AdminRole.FirstOrDefaultAsync(a => a.AdminLevel.ToString() == admin.AdminLevel.ToString()); token = JwtHelper.GenrateJwtTokenForLibraryAdmin(admin.AdminId.ToString(), System.Convert.ToString(adminRole.AdminRole1), _config["Jwt:Key"]); return(Ok(new { token })); } } return(BadRequest(new { message = "Username or password is incorrect." })); }
//[Route("GetToken")] public IActionResult GetToken([FromBody] LoginCredential credentials) { var utente = _context.Utente.FirstOrDefault(acc => acc.Username == credentials.Email && acc.Password == credentials.Password); var identity = User.Identity as ClaimsIdentity; LoginHelper lh = new LoginHelper(); if (utente == null) { return(NotFound("")); } var token = lh.CreateTokenForIdentity(identity); utente.Token = token; List <UtenteRuolo> utenteRuolo = _context.UtenteRuolo.Where(x => x.IdUtente == utente.IdUtente).ToList(); foreach (UtenteRuolo ur in utenteRuolo) { Ruolo ruolo = _context.Ruolo.Where(x => x.IdRuolo == ur.IdRuolo).FirstOrDefault(); ur.IdRuoloNavigation = ruolo; utente.UtenteRuolo.Add(ur); } //foreach (UtenteRuolo ur in utenteRuolo) //{ // var ruolo = await _context.Ruolo.FindAsync(ur.IdRuolo); // ur.IdRuoloNavigation = ruolo; // u.UtenteRuolo.Add(ur); //} return(Ok(utente)); }
public async Task SignIn([FromBody] LoginCredential credential) { var identityUser = await _userManager.FindByNameAsync(credential.Username); var result = _userManager.PasswordHasher.VerifyHashedPassword(identityUser, identityUser.PasswordHash, credential.Password); if (result != PasswordVerificationResult.Success) { throw new InvalidOperationException("Wrong Password"); } var claims = new List <Claim> { new Claim(ClaimTypes.Name, "Jiuchenm"), new Claim(ClaimTypes.Role, identityUser.IsAdmin ? AdminRoleRequirement.AdminRoleName : AdminRoleRequirement.NormalRoleName), }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); }