public UserController(GetUsers getFets, AuthenticateUser authenticateUser, UpdateDeviceId updateDeviceId, AddUser addUser) { _getUsers = getFets; _authenticateUser = authenticateUser; _updateDeviceId = updateDeviceId; _addUser = addUser; }
public void Invoke_EmptyUser_ReturnsNull() { // prepare var domain = new DataAccess.Models.Domain { Name = "Test Domain" }; var mockedUserRepository = new Mock <IUserRepository>(); var findByResult = new List <DataAccess.Models.Domain> { domain }; var mockedDomainRepository = new Mock <IDomainRepository>(); mockedDomainRepository.Setup(r => r.FindBy(It.IsAny <Expression <Func <DataAccess.Models.Domain, bool> > >())) .Returns(findByResult.AsQueryable); var action = new AuthenticateUser(mockedUserRepository.Object, mockedDomainRepository.Object); // action var user = action.Invoke("*****@*****.**", "test", "123"); // check Assert.Null(user); mockedDomainRepository.Verify(r => r.FindBy(It.IsAny <Expression <Func <DataAccess.Models.Domain, bool> > >()), Times.Once); mockedUserRepository.Verify(r => r.FindBy(It.IsAny <Expression <Func <DataAccess.Models.User, bool> > >()), Times.Once); }
public async Task DeleteAsync_EntityNotExist_ReturnFalse() { // Arrange var authenticateUser = new AuthenticateUser <int>() { Name = "codedesignplus", IdUser = new Random().Next(0, int.MaxValue), IsAuthenticated = true, IsApplication = false, }; var builder = new DbContextOptionsBuilder <CodeDesignPlusContextInMemory>(); var options = builder.UseInMemoryDatabase(nameof(OperationBaseTest)).Options; var context = new CodeDesignPlusContextInMemory(options); var repository = new PermissionRepository(authenticateUser, context); // Act var success = await repository.DeleteAsync(new Random().Next(1, int.MaxValue)); // Assert Assert.False(success); }
public ActionResult Authenticate([FromBody] AuthenticateUser apiUser) { try { if (apiUser == null || string.IsNullOrEmpty(apiUser.Username) || string.IsNullOrEmpty(apiUser.Password)) { return(BadRequest("Missing values")); } var appUser = _users.SingleOrDefault(x => x.UserName == apiUser.Username && x.Password == apiUser.Password); if (appUser == null) { return(Ok("Wrong user or password")); } _auth.CreateToken(appUser); return(Ok(appUser)); } catch (Exception ex) { string error = ex.ToString(); //_logger.LogError(ex.ToString()); return(StatusCode(StatusCodes.Status500InternalServerError, "Error retriving trigger paths from database")); } }
public IHttpActionResult PostAuthenticateUser(AuthenticateUser authenticateUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.AuthenticateUsers.Add(authenticateUser); try { db.SaveChanges(); } catch (DbUpdateException) { if (AuthenticateUserExists(authenticateUser.Id)) { return(Conflict()); } else { throw; } } return(CreatedAtRoute("DefaultApi", new { id = authenticateUser.Id }, authenticateUser)); }
public async void USER_AUTHENTICATE_SUCCESSFULLY(string userEmail) { // Arrange var userDetails = new Mock <IGetUserLoginAuthenticate>(); AuthenticateUser getUserDetails = new AuthenticateUser(userDetails.Object); UserLoginRequestMessages userInfo = new UserLoginRequestMessages(); UserLoginRequestDTO userInformation = new UserLoginRequestDTO(); userInfo.UserEmail = userEmail; userInformation.UserEmail = userEmail; var UserResponse = new UserInformation(); UserResponse.FirstName = "CJay2"; UserResponse.LastName = "BJay1"; UserResponse.PhoneNumber = "2222222222"; UserResponse.UserEmail = userEmail; UserResponse.UserStatus = "FullAccess"; UserResponse.UserType = "Acitved"; userDetails.Setup(user => user.GetUserAuthenticate(userInformation)).ReturnsAsync(UserResponse); // Act var actualUser = await getUserDetails.AuthenticateUserAsync(userInfo); // Assert Assert.Equal(UserResponse.UserEmail, actualUser.UserEmail); //Assert.Equal(UserResponse.FirstName, actualUser.FirstName); //Assert.Equal(UserResponse.LastName, actualUser.LastName); //Assert.Equal(UserResponse.PhoneNumber, actualUser.PhoneNumber); //Assert.Equal(UserResponse.UserStatus, actualUser.UserStatus); //Assert.Equal(UserResponse.UserType, actualUser.UserType); }
public IActionResult Authenticate([FromBody] AuthenticateUser model) { var user = _db.User.AuthenticateByUserNameAndPassword(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Email or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("17f48405-05c1-4a26-a801-ad6a21e62d84"); 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.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { Id = user.Id, Token = tokenString })); }
public IActionResult Authenticate([FromBody] AuthenticateUser model) { var user = _userService.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.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.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info and authentication token return(Ok(new { Id = user.Id, Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Token = tokenString })); }
public async Task <IActionResult> Register([FromBody] AuthenticateUser userParam) { if (userParam == null || userParam.Password == null || userParam.UserName == null) { return(BadRequest(new { message = "Incomplete registration object" })); } string passwordSalt = generateRandomString(); if (_context.User.FirstOrDefault(u => u.UserName == userParam.UserName) != null) { return(BadRequest("A user with this username already exists")); } User user = new User() { UserName = userParam.UserName, PasswordHash = Encoding.Default.GetString(hash(userParam.Password + passwordSalt)), PasswordSalt = passwordSalt }; _context.User.Add(user); await _context.SaveChangesAsync(); var userDTO = new AuthenticateUser() { ID = user.id, UserName = user.UserName, Token = generateToken(_appSettings.Secret, user) }; return(Ok(userDTO)); }
public async Task <IActionResult> Post( [FromBody] AuthenticateUser command, [FromServices] IJwtService tokenService) { if (command == null) { return(UnprocessableEntity()); } //TODO implementar busca de usuário por email User user = await _userRepository.FindAsNoTrackingAsync(x => x.Email == command.Email); //User user = await _userRepository.FindFromLoginAsync(command.Email, command.Password); var result = new AuthenticatedUserResult(); result.SessionUser = new SessionUser( id: user.Id, email: user.Email, name: user.Name, profile: user.UserProfile ); tokenService.Generate(result.SessionUser.Identity, ref result); return(Ok(result)); }
public IHttpActionResult Authentication(AuthenticateUser loginUser) { var user = userService.Authenticate(loginUser.UserName, loginUser.UserPwd); if (user == null) { return(Unauthorized()); } //var tokenHandler = new JwtSecurityTokenHandler(); //var key = Encoding.ASCII.GetBytes("123"); //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.CreateToken(tokenDescriptor); //var tokenString = tokenHandler.WriteToken(token); //// return basic user info (without password) and token to store client side ////return Ok(new ////{ //// Id = user.Id, //// Username = user.Username, //// FirstName = user.FirstName, //// LastName = user.LastName, //// Token = tokenString ////}); return(Ok(user)); }
public override async Task <SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout) { if (UserManager == null) { return(SignInStatus.Failure); } var message = new AuthenticateUser(userName, password); try { var result = await _authenticateRequest.Request(message); if (!result.Authenticated) { return(SignInStatus.Failure); } var user = new ApplicationUser(result.User) { ServiceTicket = result.Ticket }; await SignInAsync(user, isPersistent, false); return(SignInStatus.Success); } catch (Exception e) { Log.Error("An error occurred while authentication", e); return(SignInStatus.Failure); } }
public async Task <IActionResult> Login(AuthenticateUser userModel) { var user = await _userManager.FindByEmailAsync(userModel.UserName); if (user == null) { return(BadRequest()); } if (!await _userManager.IsEmailConfirmedAsync(user)) { return(BadRequest()); } var result = await _userManager.CheckPasswordAsync(user, userModel.Password); if (!result) { return(BadRequest()); } var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); var token = await _tokenFactory.Create(user, roles); return(Created("JWT", token)); }
public async Task <dynamic> AuthenticateAsync([FromBody] AuthenticateUser model) { try { var user = await _userAuthenticate.AuthenticateAsync(model); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var token = TokenService.GenerateToken(user); return(Ok(new { user = user, token = token })); } catch (ArgumentException arg) { return(BadRequest(arg.Message)); } catch (Exception e) { return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public ActionResult LogIn(AuthenticateUser userInfo) { AuthenticateUser User = db.authenticateUser.Where(x => x.Email == userInfo.Email && x.password == userInfo.password).FirstOrDefault(); if (User != null) { if (User.UserLevel == "Level1") { Session["Admin_Name"] = User.UserName.ToString(); Session["Admin_ID"] = User.ID.ToString(); Session["Admin_Email"] = User.Email.ToString(); return(RedirectToAction("Index", "Admin")); } else if (User.UserLevel == "Level2") { Session["User_Name"] = User.UserName.ToString(); Session["User_ID"] = User.ID.ToString(); Session["User_Email"] = User.Email.ToString(); return(RedirectToAction("Index", "User")); } else { return(RedirectToAction("LogIn", "User")); } } ModelState.AddModelError("", "LogIn failed. Please Input valid Email or password."); return(View()); }
public void isValidUser_UserNotExists_returnFalse() { var userExisting = new User("User", "Dante", "Castillo", "Password", "mail", new Rol("Rol Prueba", "Rol Prueba") { Nivel = 1 }); int nivel = 1; var repositoryRead = Mock.Of <IUserRepositoryReadOnly>(); var cryptoService = getCryptoService(); userExisting.Password = cryptoService.getEncryptedText(userExisting.Password); userExisting.UserKey = cryptoService.getKey(); var repository = Mock.Of <IUserRepositoryReadOnly>(); var userToValidate = new User("User", "Dante", "Castillo", "Password", "mail", new Rol("Rol Prueba", "Rol Prueba")); var authenticateUser = new AuthenticateUser(repository, (x) => new UserKeyRecovery(x), generator => new DefaultHmacProvider(generator), (generator, func) => new CryptoService(generator, func)); var respuesta = authenticateUser.isValidUser(userToValidate, nivel); Assert.IsFalse(respuesta); }
/// <summary> /// Initializes a new instance of the <see cref="TeamOvertimesDialog" /> class. /// </summary> /// <param name="response">LoginResponse object.</param> /// <param name="authenticationService">AuthenticationService object.</param> /// <param name="hoursWorkedActivity">HoursWorkedActivity object.</param> /// <param name="hyperFindActivity">HyperFindActivity object.</param> /// <param name="jobAssignment">JobAssignmentActivity object.</param> /// <param name="authenticateUser">AuthenticateUser object.</param> /// <param name="teamOvertimesCard">CarouselTeamOvertimes object.</param> /// <param name="azureTableStorageHelper">AzureTableStorageHelper object.</param> /// <param name="dateRangeCard">AdaptiveDateRange object.</param> /// <param name="adaptiveTeamOvertimesCard">TeamOvertimesCard object.</param> /// <param name="upcomingShiftsActivity">UpcomingShiftsActivity object.</param> public TeamOvertimesDialog( LoginResponse response, IAuthenticationService authenticationService, IHoursWorkedActivity hoursWorkedActivity, IHyperFindActivity hyperFindActivity, IJobAssignmentActivity jobAssignment, AuthenticateUser authenticateUser, CarouselTeamOvertimes teamOvertimesCard, IAzureTableStorageHelper azureTableStorageHelper, AdaptiveDateRange dateRangeCard, TeamOvertimesCard adaptiveTeamOvertimesCard, IUpcomingShiftsActivity upcomingShiftsActivity) { this.response = response; this.authenticationService = authenticationService; this.hoursWorkedActivity = hoursWorkedActivity; this.hyperFindActivity = hyperFindActivity; this.authenticateUser = authenticateUser; this.jobAssignment = jobAssignment; this.teamOvertimesCard = teamOvertimesCard; this.azureTableStorageHelper = azureTableStorageHelper; this.dateRangeCard = dateRangeCard; this.adaptiveTeamOvertimesCard = adaptiveTeamOvertimesCard; this.upcomingShiftsActivity = upcomingShiftsActivity; }
public IHttpActionResult PutAuthenticateUser(string id, AuthenticateUser authenticateUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != authenticateUser.Id) { return(BadRequest()); } db.Entry(authenticateUser).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!AuthenticateUserExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <User> Authenticate(AuthenticateUser query) { var user = await GetUser(query.UserName); ValidatePassword(user, query.Password); return(user); }
public bool Post(AuthenticateUser request) { var password = OneTimePasswordRepository.GetOneTimePassword(request.UserId); if (password != null && password == request.Password) { OneTimePasswordRepository.DeleteOneTimePassword(request.UserId); } return password != null && password == request.Password; }
private ApplicationUser FindByUsernameOrEmail(AuthenticateUser userCredentials) { var user = _context.Users.FirstOrDefault(user => user.UserName == userCredentials.Username); if (user == null) { return(_context.Users.FirstOrDefault(user => user.Email == userCredentials.Username)); } return(user); }
public async Task <ActionResult <AuthenticateResponse> > Login(AuthenticateUser userCredentials) { var result = _userService.Authenticate(userCredentials); if (result != null) { return(Ok(result)); } return(Unauthorized()); }
public async Task UpdateAsync_UpdateEntity_ReturnTrue() { // Arrange var permission = new Permission() { Name = "Create - Permissions", Description = "Can create to permissions", Controller = "Permission", Action = "Post", State = true }; var authenticateUser = new AuthenticateUser <int>() { Name = "codedesignplus", IdUser = new Random().Next(0, int.MaxValue), IsAuthenticated = true, IsApplication = false, }; var builder = new DbContextOptionsBuilder <CodeDesignPlusContextInMemory>(); var options = builder.UseInMemoryDatabase(nameof(OperationBaseTest)).Options; var context = new CodeDesignPlusContextInMemory(options); var repository = new PermissionRepository(authenticateUser, context); var id = await repository.CreateAsync(permission); // Act var entityUpdate = new Permission() { Name = "Update - Permissions", Description = "Can update to permissions", Controller = "Permission", Action = "Put", State = false }; var success = await repository.UpdateAsync(id, entityUpdate); // Assert var entity = await repository.GetEntity <Permission>().FindAsync(id); Assert.True(success); Assert.Equal(id, entity.Id); Assert.Equal("Update - Permissions", entity.Name); Assert.Equal("Can update to permissions", entity.Description); Assert.Equal("Permission", entity.Controller); Assert.Equal("Put", entity.Action); Assert.False(entity.State); Assert.Equal(authenticateUser.IdUser, entity.IdUserCreator); Assert.Equal(permission.DateCreated, entity.DateCreated); }
public IHttpActionResult GetAuthenticateUser(string id) { AuthenticateUser authenticateUser = db.AuthenticateUsers.Find(id); if (authenticateUser == null) { return(NotFound()); } return(Ok(authenticateUser)); }
public async Task RetrieveAsyncAuthorizedGuestTest() { AuthenticateUser objAuthenticateUser = new AuthenticateUser(); objAuthenticateUser.AuthenticateUserAccount = new AuthenticateUserAccount(); objAuthenticateUser.AuthenticateUserAccount.AccountStatus = "Active"; objAuthenticateUser.AuthenticateUserAccount.AccountType = "Guest"; this.authenticateUserData.Setup(mockItem => mockItem.GetAsync(It.IsNotNull<UserAccount>())).Returns(Task.FromResult(objAuthenticateUser)); var authenticateUserDetails = await this.authenticateUserManager.GetAsync(new UserAccount()); Assert.IsNull(authenticateUserDetails); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticateUser model) { var user = await _userService.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Invalid Username of Password" })); } return(Ok(user)); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticateUser command) { var response = await _mediator.Send(command); if (response.HasMessages) { return(BadRequest(response.Messages)); } return(Ok(response.Value)); }
public async Task <IActionResult> Login([FromBody] AuthenticateUser model) { _logger.LogInformation( "----- recieving request Login : {model} : Data ({data})", model.GetGenericTypeName(), model.GetObjectAsJson()); var jwttoken = await _accountService.LoginAsync(model); return(Ok(jwttoken)); }
/// <summary> /// Initializes a new instance of the <see cref="RootDialog" /> class. /// </summary> /// <param name="dialogFactory">DialogFactory object.</param> /// <param name="authenticateUser">AuthenticateUser object.</param> /// <param name="carousel">CarouselHelp object.</param> /// <param name="welcomeCard">WelcomeCard object.</param> public RootDialog( IDialogFactory dialogFactory, AuthenticateUser authenticateUser, CarouselHelp carousel, WelcomeCard welcomeCard) { this.dialogFactory = dialogFactory; this.authenticateUser = authenticateUser; this.carousel = carousel; this.welcomeCard = welcomeCard; }
public IActionResult Authenticate([FromBody] AuthenticateUser user) { var authenticatedUser = _service.Authenticate(user); if (authenticatedUser == null) { return(Unauthorized()); } return(Ok(_service.GenerateToken(authenticatedUser, _appSettings))); }
public string ProcessAuthenticate(string userid, string password) { try { AuthenticateUser userObject = new AuthenticateUser(); return(userObject.Authenticate(userid, password)); } catch { throw; } }
public void Execute_NullAuthenticateUserShouldReturnErrorMessageInResult() { //arrange var tokenManager = new Mock <ITokenManager>(); var authenticateUser = new AuthenticateUser(tokenManager.Object); //act var result = authenticateUser.Execute(new LoginModel()); //assert Assert.Equal("Login failed. Please try again.", result.Message); }
public override int Run(string[] remainingArguments) { InitialiseClient(); AuthenticateUser request = new AuthenticateUser { UserId = remainingArguments[0], Password = remainingArguments[1], }; var response = client.Post<bool>(request); Console.WriteLine("User authentication {0}.", response ? "successful" : "failed"); return 0; }
public async Task RetrieveAsyncTest() { var userAccount = new UserAccount { Password = "******", UserId = "12345" }; var authenticateUser = new AuthenticateUser { AuthenticateUserAccount = new AuthenticateUserAccount { AccountStatus = "2", AccountType = "3", AddedDate = DateTime.Now }, UserUId = "12345" }; this.authenticateUserRepository.Setup(mockItem => mockItem.RetrieveAuthenticateUser(It.IsAny<UserAccount>())).Returns(Task.FromResult(authenticateUser)); var result = await this.authenticateUserData.GetAsync(userAccount); Assert.IsNotNull(result); }
public async Task RetrieveAsyncAuthorizedCrewTest() { AuthenticateUser objAuthenticateUser = new AuthenticateUser(); objAuthenticateUser.UserUId = "484516"; objAuthenticateUser.AuthenticateUserAccount = new AuthenticateUserAccount(); objAuthenticateUser.AuthenticateUserAccount.AccountStatus = "Active"; objAuthenticateUser.AuthenticateUserAccount.AccountType = "Crew"; this.authenticateUserData.Setup(mockItem => mockItem.GetAsync(It.IsNotNull<UserAccount>())).Returns(Task.FromResult(objAuthenticateUser)); this.crewData.Setup(mockItem => mockItem.RetrieveUserByUserAccountId(It.IsNotNull<string>())).Returns((string userUId) => RetrieveCrewmember(userUId)); var authenticateUserDetails = await this.authenticateUserManager.GetAsync(new UserAccount()); Assert.IsNotNull(authenticateUserDetails); }