/// <summary> /// Asynchronicznie zmienia hasło użytkownika. /// </summary> /// <param name="context">Kontekst bazy danych</param> /// <param name="username">Nazwa uzytkownika</param> /// <param name="model">Obiekt z hasłami uzytkownika</param> /// <returns>String z ewentualną przyczyną błędu (pusty, jeśli wszystko przebiegło pomyślnie).</returns> public async Task <string> ChangePasswordAsync(IAccommodationContext context, string username, ChangePasswordViewModel model) { try { IUserAuthenticationService authenticationService = new UserAuthenticationService(); var identity = await authenticationService.AuthenticateUserAsync(context, username, model.OldPassword); if (identity == null) { return("Nieprawidłowe hasło dla użytkownika " + username); } IRegisterUser register = new UserRegister(); User newUser = register.GetNewUser(username, model.NewPassword); User user = context.Users.FirstOrDefault(u => u.Username.Equals(username)); if (user == null) { return("Błąd! Nie odnaleziono użytkownika"); } user.HashedPassword = newUser.HashedPassword; user.Salt = newUser.Salt; context.SaveChanges(); return(string.Empty); } catch (Exception) { return("Błąd!"); } }
public AccountControllerTest() { var dataContext = TestHelpers.GetDataContext(); AutoMapperConfig.Initialize(); var mapper = AutoMapperConfig.GetMapper(); var options = Options.Create(new LocalizationOptions()); // you should not need any params here if using a StringLocalizer<T> var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance); var defaultHttpContext = new DefaultHttpContext(); // TestHelpers.GetTestHttpContext(); //Mock IHttpContextAccessor var mockHttpContextAccessor = new Mock <IHttpContextAccessor>(); mockHttpContextAccessor.Setup(m => m.HttpContext).Returns(defaultHttpContext); var httpContextAccessor = mockHttpContextAccessor.Object; IUserService userService = new UserService(dataContext, mapper); ILocalizationService <UserResource> localizerService = new LocalizationService <UserResource>(factory); IUserAuthenticationService authenticationService = new UserAuthenticationService(httpContextAccessor); // var httpContext = new DefaultHttpContext(); var tempData = new TempDataDictionary(defaultHttpContext, Mock.Of <ITempDataProvider>()); _accountController = new AccountController(userService, localizerService, authenticationService) { TempData = tempData }; }
public void SetUp() { _userInput = new User { Username = "******" }; _userOutput = new User { ID = 1, Username = "******", PasswordHash = new byte[1], PasswordSalt = new byte[1] }; _mockRepo = new Mock <IAuthRepository>(); _mockRepo.Setup(c => c.Register( It.Is <User>(c => c.Username == _userInput.Username), _password)) .Returns(Task.FromResult(_userOutput)); _mockRepo.Setup(c => c.Register( It.Is <User>(c => c.Username != _userInput.Username), It.Is <string>(c => !c.Contains(_password)))) .Returns(Task.FromResult <User>(null)); _mockRepo.Setup(c => c.UserExists(_usernameThatDoesExist.ToLower())).Returns(Task.FromResult(true)); _mockRepo.Setup(c => c.UserExists(_usernameThatDoesntExist.ToLower())).Returns(Task.FromResult(false)); _config = new Mock <IConfiguration>(); _authService = new UserAuthenticationService(_mockRepo.Object, _config.Object); }
public void UserGeneratedKeysQueryClosedOrdersFailTest_TestsIfTheAuthenticationFailsDueToExpirationDate_VerifiesThroughTheReturnedValue() { ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; UserAuthenticationService userAuthenticationService = new UserAuthenticationService(userRepository, securityKeysRepository, persistenceRepository); string nounce = userAuthenticationService.GenerateNonce(); string apiKey = "123456789"; string uri = "www.blancrock.com/orders/cancelorder"; string secretKey = "1234567"; string username = "******"; // Provide the permission List <SecurityKeysPermission> permissionslist = new List <SecurityKeysPermission>(); permissionslist.Add(new SecurityKeysPermission(apiKey, new Permission(PermissionsConstant.Query_Closed_Orders, "Query Closed Orders"), true)); // Here we provide the expiration date for the current moment, which will expire instantly SecurityKeysPair securityKeysPair = new SecurityKeysPair("1", apiKey, secretKey, 1, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, false, permissionslist); securityKeysPair.EnableExpirationDate = true; persistenceRepository.SaveUpdate(securityKeysPair); // Create a user and store it in database, this is the user for whom we have created the key User user = new User("*****@*****.**", username, "abc", "Pakistan", TimeZone.CurrentTimeZone, "", ""); persistenceRepository.SaveUpdate(user); string response = String.Format("{0}:{1}:{2}", apiKey, uri, secretKey).ToMD5Hash(); userAuthenticationService.Authenticate(new AuthenticateCommand("Rtg65s345", nounce, apiKey, uri, response, "1")); }
public void SystemGeneratedKeysSuccessfulTest_TestsIfTheAuthenticationIsSuccessful_VerifiesThroughTheReturnedValue() { ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; UserAuthenticationService userAuthenticationService = new UserAuthenticationService(userRepository, securityKeysRepository, persistenceRepository); string nounce = userAuthenticationService.GenerateNonce(); string apiKey = "123456789"; string uri = "www.blancrock.com/orders/cancelorder"; string secretKey = "1234567"; string username = "******"; // Create a user and store it in database, this is the user for whom we have created the key User user = new User("*****@*****.**", username, "abc", "Pakistan", TimeZone.CurrentTimeZone, "", ""); persistenceRepository.SaveUpdate(user); User userByUserName = userRepository.GetUserByUserName(username); // Create System generated Keys and store in repo. SecurityKeysPair securityKeysPair = new SecurityKeysPair(apiKey, secretKey, "1", userByUserName.Id, true); persistenceRepository.SaveUpdate(securityKeysPair); string response = String.Format("{0}:{1}:{2}", apiKey, uri, secretKey).ToMD5Hash(); bool authenticate = userAuthenticationService.Authenticate(new AuthenticateCommand("Rtg65s345", nounce, apiKey, uri, response, "1")); Assert.IsTrue(authenticate); }
public void Login_UserFoundHasUnknownRole_ReturnsFailedResult() { var mockDal = Substitute.For <IUserDal>(); var mockPatientUserDal = Substitute.For <IPatientUserDal>(); var mockLogger = Substitute.For <ILogger <UserAuthenticationService> >(); var mockCryptoSvc = Substitute.For <ICryptographyService>(); var user = new User() { Id = 1, Username = "******", JobDescription = new JobDescription() { Description = "General Practitioner", Role = UserRole.Unknown }, State = AccountState.Active, PasswordHash = new byte[8], PasswordSalt = new byte[8], }; mockDal.GetUserAsync("username").Returns(user); var svc = new UserAuthenticationService(mockDal, mockLogger, mockCryptoSvc, mockPatientUserDal); var result = svc.Login("username", "rightPassword").GetAwaiter().GetResult(); Assert.That(result, Is.Not.Null); Assert.That(result.ResultStatus, Is.EqualTo(ServiceResultStatusCode.Failed)); Assert.That(result.Message, Does.Contain("Account login failed. Account role is unknown")); }
public void Login_UserFoundButPasswordIncorrect_ReturnsFailedResult() { var mockDal = Substitute.For <IUserDal>(); var mockPatientUserDal = Substitute.For <IPatientUserDal>(); var mockLogger = Substitute.For <ILogger <UserAuthenticationService> >(); var mockCryptoSvc = Substitute.For <ICryptographyService>(); var mockUser = new User() { Username = "******", State = AccountState.Active, JobDescription = new JobDescription() { Role = UserRole.MedicalPractitioner, Description = "GP" } }; mockDal.GetUserAsync("username").Returns(mockUser); mockCryptoSvc.VerifyPasswordHash(Arg.Any <byte[]>(), Arg.Any <byte[]>(), "wrongPassword").Returns(false); var svc = new UserAuthenticationService(mockDal, mockLogger, mockCryptoSvc, mockPatientUserDal); var result = svc.Login("username", "wrongPassword").GetAwaiter().GetResult(); Assert.That(result, Is.Not.Null); Assert.That(result.ResultStatus, Is.EqualTo(ServiceResultStatusCode.Failed)); Assert.That(result.Message, Does.Contain("Account login failed. Username or password not recognised.")); }
public async Task <object> SignOutAsync( [FromServices] UserAuthenticationService userAuthenticationService) { var currentUser = User.Identity as AuthenticatedUser; await userAuthenticationService.RevokeTokenAsync(currentUser.Token); return(JResponse.OK()); }
public void AuthenticationPasswordFailed() { string username = "******"; string password = "******"; var auth = new UserAuthenticationService(); var identity = auth.AuthenticateUser <MockContext>(username, password); Assert.IsNull(identity); }
public void AuthenticationFailedWithNonExistingUser() { string username = "******"; string password = "******"; var auth = new UserAuthenticationService(); var identity = auth.AuthenticateUser <MockContext>(username, password); Assert.IsNull(identity); }
public void AuthenticationWithEmptyLogin() { string username = string.Empty; string password = string.Empty; var auth = new UserAuthenticationService(); var identity = auth.AuthenticateUser <MockContext>(username, password); Assert.IsNull(identity); }
public IHttpActionResult GetUserIdentity(UserCredentialDto dto) { string username = dto.Username; string password = dto.Password; IUserAuthenticationService service = new UserAuthenticationService(); var user = service.AuthenticateUser <AccommodationContext>(username, password); return(Ok(user)); }
public async Task <IActionResult> Authentication(CancellationToken cancellationToken, [FromForm] AuthenticationBinding binding, [FromServices] UserAuthenticationService authenticationService) { const string passwordGrantType = "password"; const string refreshTokenGrantType = "refresh_token"; if (string.IsNullOrEmpty(binding.GrantType)) { return(BadRequest(new ErrorView(ErrorCode.InvalidRequest, "Field 'grant_type' is required"))); } switch (binding.GrantType) { case passwordGrantType: try { if (string.IsNullOrEmpty(binding.Username)) { return(BadRequest(new ErrorView(ErrorCode.InvalidRequest, $"Field 'username' is required for '{passwordGrantType}' grant type"))); } if (string.IsNullOrEmpty(binding.Password)) { BadRequest(new ErrorView(ErrorCode.InvalidRequest, $"Field 'password' is required for '{passwordGrantType}' grant type")); } var token = await authenticationService.AuthenticationByPassword(binding.Username, binding.Password, cancellationToken); return(Ok(new TokenView(token.AccessToken, token.ExpiresIn, token.RefreshToken))); } catch (InvalidCredentialsException) { return(BadRequest(new ErrorView(ErrorCode.UnauthorizedClient, "Invalid username or password"))); } case refreshTokenGrantType: try { if (string.IsNullOrEmpty(binding.RefreshToken)) { return(BadRequest(new ErrorView(ErrorCode.InvalidRequest, "Field 'refresh_token' is required for '{refreshTokenGrantType}' grant type"))); } var token = await authenticationService.AuthenticationByRefreshToken(binding.RefreshToken, cancellationToken); return(Ok(new TokenView(token.AccessToken, token.ExpiresIn, token.RefreshToken))); } catch (InvalidCredentialsException) { return(BadRequest(new ErrorView(ErrorCode.InvalidGrant, "Invalid refresh token"))); } default: return(BadRequest(new ErrorView(ErrorCode.UnsupportedGrantType, $"The authorization grant type '{binding.GrantType}' is not supported. Supported authorization grant types: '{passwordGrantType}', '{refreshTokenGrantType}'"))); } }
public ApiAuthenticationHandler( IOptionsMonitor <ApiAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, UserAuthenticationService userAuthenticationService) : base(options, logger, encoder, clock) { _userAuthenticationService = userAuthenticationService; }
public AccountController( RecipeReviewsContext context, IHostingEnvironment hostingEnv, UserAuthenticationService authService, FileUploadService uploadService) { _accountService = new AccountService(context); _hostingEnv = hostingEnv; _authService = authService; _fileUploadService = uploadService; }
public async Task AuthenticateAdminUserAsync() { string username = "******"; string password = "******"; var auth = new UserAuthenticationService(); var identity = await auth.AuthenticateUserAsync <MockContext>(username, password); Assert.IsFalse(identity is AnonymousIdentity); Assert.IsNotNull(identity); Assert.AreEqual(identity.Username, "admin"); }
public void AuthenticateBakalamUser() { string username = "******"; string password = "******"; var auth = new UserAuthenticationService(); var identity = auth.AuthenticateUser <MockContext>(username, password); Assert.IsFalse(identity is AnonymousIdentity); Assert.IsNotNull(identity); Assert.AreEqual(identity.Username, "bakalam"); }
/// <summary> /// 用户登录 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns>int = 用户ID ,string=用户姓名</returns> public Tuple <int, string> Login(string username, string password) { UserDescriptor user = new UserAuthenticationService().Authenticate(username, password); if (user == null) { return(null); } return(new Tuple <int, string>(user.Id, user.Name)); }
public void Login_PasswordIsEmpty_ThrowsArgumentNullException() { var mockDal = Substitute.For <IUserDal>(); var mockPatientUserDal = Substitute.For <IPatientUserDal>(); var mockLogger = Substitute.For <ILogger <UserAuthenticationService> >(); var mockCryptoSvc = Substitute.For <ICryptographyService>(); var svc = new UserAuthenticationService(mockDal, mockLogger, mockCryptoSvc, mockPatientUserDal); var e = Assert.ThrowsAsync <ArgumentNullException>(() => svc.Login("username", string.Empty)); Assert.That(e.Message, Does.Contain("password")); }
public ActionResult Ingresar(LoginWrapper model) { if (ModelState.IsValid) { UserAuthenticationService usuarioService = model.Profesor ? (UserAuthenticationService) new ProfesorService() : (UserAuthenticationService) new AlumnoService(); UsuarioWrapper usuarioWrapper = usuarioService.GetUsuarioByLogin(model); if (usuarioWrapper != null) { var cacheWrapper = new CacheWrapper { IdUsuario = usuarioWrapper.IdUsuario, Username = usuarioWrapper.Username, Nombre = usuarioWrapper.Nombre, IdPerfil = Convert.ToInt32(usuarioWrapper.PerfilUsuario), }; string loginJson = new JavaScriptSerializer().Serialize(cacheWrapper); var ticket = new FormsAuthenticationTicket(1, usuarioWrapper.IdUsuario.ToString(), DateTime.Now, DateTime.Now.AddDays(2), true, loginJson, FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); FormsAuthentication.SetAuthCookie(loginJson, false); System.Web.HttpContext.Current.Session.Timeout = 2500; UserCache.IdUsuario = usuarioWrapper.IdUsuario; UserCache.Username = usuarioWrapper.Username; UserCache.IdPerfil = Convert.ToInt32(usuarioWrapper.PerfilUsuario); if (!string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } return(model.Profesor ? RedirectToAction("HomeProfesores", "Profesores") : RedirectToAction("HomeAlumnos", "Alumnos")); } ModelState.AddModelError("", ""); } return(View(model)); }
public void AuthenticateUser_WrongCredentialsPassed_ReturnsNull() { var email = "*****@*****.**"; var password = "******"; var userRepositoryMock = new Mock <IUserRepository>(); userRepositoryMock.Setup(x => x.GetUserByCredentials(It.IsAny <string>(), It.IsAny <string>())).Returns((UserEntity)null); var authenticationService = new UserAuthenticationService(userRepositoryMock.Object, _mapper); var result = authenticationService.AuthenticateUser(email, password); Assert.Null(result); }
public UserServiceTests() { _userRepository = Substitute.For <IUserRepository>(); _hasher = new Hasher(); _salter = new Salter(); _options = Substitute.For <IOptions <Secrets> >(); _secrets = new Secrets { SuperStrongPassword = "******" }; _options.Value.Returns(_secrets); _userAuthService = new UserAuthenticationService(_userRepository, _hasher, _salter, _options); }
public void AuthenticateUser_CorrectCredentialsPassed_GeneratesToken() { var email = "*****@*****.**"; var password = "******"; var userRepositoryMock = new Mock <IUserRepository>(); userRepositoryMock.Setup(x => x.GetUserByCredentials(It.IsAny <string>(), It.IsAny <string>())).Returns(new UserEntity()); var authenticationService = new UserAuthenticationService(userRepositoryMock.Object, _mapper); var result = authenticationService.AuthenticateUser(email, password); Assert.NotNull(result); Assert.IsType <User>(result); Assert.NotNull(result.Token); }
public void Login_UserNotFound_ReturnsFailedResult() { var mockDal = Substitute.For <IUserDal>(); var mockPatientUserDal = Substitute.For <IPatientUserDal>(); var mockLogger = Substitute.For <ILogger <UserAuthenticationService> >(); var mockCryptoSvc = Substitute.For <ICryptographyService>(); mockDal.GetUserAsync("username").Returns((User)null); var svc = new UserAuthenticationService(mockDal, mockLogger, mockCryptoSvc, mockPatientUserDal); var result = svc.Login("username", "password").GetAwaiter().GetResult(); Assert.That(result, Is.Not.Null); Assert.That(result.ResultStatus, Is.EqualTo(ServiceResultStatusCode.NotFound)); Assert.That(result.Message, Does.Contain("User not found. \"Username\"=username")); }
public async Task <object> SignInAsync( [FromServices] UserAuthenticationService userAuthenticationService, [FromBody] SignInRequest body) { var(user, authToken) = await userAuthenticationService.AuthenticateAsync(body.Username, body.Password); if (authToken == null) { var result = JResponse.Error("Invalid username or password."); return(StatusCode(StatusCodes.Status401Unauthorized, result)); } return(new { status = JStatus.OK, token = authToken.Token, user = GetProfileInfo(user) }); }
public UnitOfWork(RestProContext context) { _context = context; Users = new UserRepository(_context); WorkCycles = new WorkCycleRepository(_context); UserAuthenticationService = new UserAuthenticationService(new UserRepository(_context)); Suppliers = new SupplierRepository(_context); Statuses = new StatusRepository(_context); PurchaseOrders = new PurchaseOrderRepository(_context); RawMaterials = new RawMaterialsRepository(_context); RawMaterialCategories = new RawMaterialCategoryRepository(_context); Locations = new LocationRepository(_context); InventorySettings = new InventorySettingsRepository(_context); WorkCycleStatuses = new WorkCycleStatusRepository(_context); PurchaseOrderTransactions = new PurchaseOrderTransactionRepository(_context); WorkCycleTransactions = new WorkCycleTransactionRepository(_context); WorkCyclesLines = new WorkCycleLineRepository(_context); Inventory = new InventoryRepository(_context); InventoryTransactionRepository = new InventoryTransactionsRepository(_context); }
public void UserGeneratedKeysCancelOrderSuccessfulTest_TestsIfTheAuthenticationIsSuccessful_VerifiesThroughTheReturnedValue() { ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; UserAuthenticationService userAuthenticationService = new UserAuthenticationService(userRepository, securityKeysRepository, persistenceRepository); string nounce = userAuthenticationService.GenerateNonce(); string apiKey = "123456789"; string uri = "www.blancrock.com/orders/cancelorder"; string secretKey = "1234567"; string username = "******"; List <SecurityKeysPermission> permissionslist = new List <SecurityKeysPermission>(); permissionslist.Add(new SecurityKeysPermission(apiKey, new Permission(PermissionsConstant.Cancel_Order, "Query Cancel Orders"), true)); // Create System generated Keys and store in repo //SecurityKeysPairFactory.UserGeneratedSecurityPair(username, "1", apiKey, secretKey, true, "", // false, DateTime.Now, false, DateTime.Now, permissionslist, securityKeysRepository); // Create a user and store it in database, this is the user for whom we have created the key User user = new User("*****@*****.**", username, "abc", "Pakistan", TimeZone.CurrentTimeZone, "", ""); user.AutoLogout = new TimeSpan(0, 0, 10, 0); persistenceRepository.SaveUpdate(user); // Get the user from the database, to confirm the user.Id generated by the database User userByUserName = userRepository.GetUserByUserName(username); SecurityKeysPair securityKeysPair = new SecurityKeysPair("1", apiKey, secretKey, userByUserName.Id, DateTime.Now.AddHours(2), DateTime.Now, DateTime.Now, DateTime.Now, false, permissionslist); securityKeysPair.EnableExpirationDate = true; persistenceRepository.SaveUpdate(securityKeysPair); string response = String.Format("{0}:{1}:{2}", apiKey, uri, secretKey).ToMD5Hash(); bool authenticate = userAuthenticationService.Authenticate(new AuthenticateCommand("Rtg65s345", nounce, apiKey, uri, response, "1")); Assert.IsTrue(authenticate); }
public UserAuthenticationServiceTest() { _authenticationConfiguration = new AuthenticationConfiguration { Audience = "AUDIENCE", Issuer = "ISSUER", TokenSecret = "GENERATETOKENSECRET", TokenLifetimeInSeconds = 1800 }; var authenticationConfigurationMock = new Mock <IOptionsSnapshot <AuthenticationConfiguration> >(); authenticationConfigurationMock.Setup(x => x.Value).Returns(_authenticationConfiguration); _userPasswordServiceMock = new Mock <IUserPasswordService>(); _target = new UserAuthenticationService( authenticationConfigurationMock.Object, _userPasswordServiceMock.Object ); }
public async Task TestForUserAuthenticationinServiceLayer() { ServiceLayer.DataContract.User user = new ServiceLayer.DataContract.User() { Email = "dverma", Password = "******" }; User Buser = new User() { Email = "dverma", Password = "******" }; Mock <IUserAuthenticationManager> manager = new Mock <IUserAuthenticationManager>(); manager.Setup(x => x.AuthenticateUser(It.IsAny <User>())).Returns(true); UserAuthenticationService service = new UserAuthenticationService(manager.Object); var expectedOutput = service.AuthenticateUser(user); Assert.IsTrue(expectedOutput); }
public void TestForChangePassword() { ServiceLayer.DataContract.User user = new ServiceLayer.DataContract.User() { Email = "dverma", Password = "******" }; User Buser = new User() { Email = "dverma", Password = "******" }; Mock <IUserAuthenticationManager> manager = new Mock <IUserAuthenticationManager>(); manager.Setup(x => x.ChangePassword(Buser, "abcdefgh")).Returns(true); UserAuthenticationService service = new UserAuthenticationService(manager.Object); var expectedOutput = service.ChangePassword(user, "abcdefgh"); Assert.IsTrue(expectedOutput); }