public async Task AddAsync(WebSite webSite) { webSite.Login.Password = _passwordEncryptor.Encrypt(webSite.Login.Password); _webSiteManagerData.WebSiteRepository.Add(webSite); await _webSiteManagerData.SaveChangesAsync(); }
public UserAccountModule(IDispatcherFactory dispatcherFactory, IPasswordEncryptor passwordEncryptor) { Post["/register"] = _ => { var req = this.Bind<NewUserRequest>(); var command = new CreateUser(req.Email, passwordEncryptor.Encrypt(req.Password), req.Name, req.PhoneNumber); dispatcherFactory.Create(this.UserSession(), command) .Dispatch(this.UserSession(), command); return null; }; Post["/password/requestReset"] = _ => { var req = this.Bind<ResetPasswordRequest>(); var command = new CreatePasswordResetToken(req.Email); dispatcherFactory.Create(this.UserSession(), command) .Dispatch(this.UserSession(), command ); return null; }; Put["/password/reset/{token}"] = p => { var newPasswordRequest = this.Bind<NewPasswordRequest>(); var token = Guid.Parse((string)p.token); var command = new ResetPassword(token, passwordEncryptor.Encrypt(newPasswordRequest.Password)); dispatcherFactory.Create(this.UserSession(), command) .Dispatch(this.UserSession(), command); return null; }; }
public async Task <int> Handle(CreateUserCommand request, CancellationToken cancellationToken) { if (await _dbContext.Users.AnyAsync(s => s.Email == request.Email)) { throw new MonumentsManagerAppException(ExceptionType.UserAlreadyExists, $"User with email {request.Email} already exists"); } if (!await _emailSender.TrySendWelcomeMailAsync(request.Email)) { throw new MonumentsManagerAppException(ExceptionType.CannotSendEmail, $"Cannot send welcome mail to {request.Email}"); } var entity = new UserEntity() { Password = _passwordEncryptor.Encrypt(request.Password), Email = request.Email, JobTitle = request.JobTitle, LastLoggedIn = DateTime.UtcNow }; var result = await _dbContext.AddAsync(entity, cancellationToken); await _dbContext.SaveChangesAsync(); return(result.Entity.Id); }
public UserAccountModule(ICommandDispatcher commandDispatcher, IPasswordEncryptor passwordEncryptor) { Post["/register"] = _ => { var req = this.Bind<NewUserRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreateUser(req.Email, passwordEncryptor.Encrypt(req.Password), req.Name, req.PhoneNumber)); return null; }; Post["/password/requestReset"] = _ => { var req = this.Bind<ResetPasswordRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreatePasswordResetToken(req.Email) ); return null; }; Put["/password/reset/{token}"] = _ => { return null; }; }
public LoginModule( IReadOnlyRepository readOnlyRepository, IPasswordEncryptor passwordEncryptor, IUserSessionFactory userSessionFactory) { Post["/login"] = r => { var loginInfo = this.Bind<LoginRequest>(); EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password); try { var user = readOnlyRepository.First<User>( x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password); if (!user.Activated) return new Response().WithStatusCode(HttpStatusCode.Forbidden); var userSession = userSessionFactory.Create(user); return new SuccessfulLoginResponse<Guid>(userSession.Id, userSession.Expires); } catch (ItemNotFoundException<User> ex) { return new Response().WithStatusCode(HttpStatusCode.Unauthorized); } }; }
public LoginModule(IPasswordEncryptor passwordEncryptor, IReadOnlyRepository readOnlyRepository, IUserSessionFactory userSessionFactory) { Post["/login"] = _ => { var loginInfo = this.Bind<LoginRequest>(); if (loginInfo.Email == null) throw new UserInputPropertyMissingException("Email"); if (loginInfo.Password == null) throw new UserInputPropertyMissingException("Password"); EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password); try { var user = readOnlyRepository.First<User>( x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password); UserLoginSession userLoginSession = userSessionFactory.Create(user); return new SuccessfulLoginResponse<Guid>(userLoginSession.Id, user.Id, user.Name, userLoginSession.Expires); } catch (ItemNotFoundException<User>) { throw new UnauthorizedAccessException(); } }; }
public NewUserModule(IPasswordEncryptor passwordEncryptor, ICommandDispatcher commandDispatcher, IReadOnlyRepository readOnlyRepository) { Post["/user/facebook"] = r => { var newUserRequest = this.Bind<NewUserRequest>(); CheckForExistingFacebookUser(readOnlyRepository, newUserRequest); DispatchCommand(commandDispatcher, newUserRequest); return new Response().WithStatusCode(HttpStatusCode.OK); }; Post["/user"] = r => { var newUserRequest = this.Bind<NewUserRequest>(); CheckForExistingUser(readOnlyRepository, newUserRequest); commandDispatcher.Dispatch(this.VisitorSession(), new NewUserCommand { Email = newUserRequest.Email, EncryptedPassword = passwordEncryptor. Encrypt( newUserRequest. Password) }); return new Response().WithStatusCode(HttpStatusCode.OK); }; }
public async Task <Unit> Handle(UpdateUserCommand request, CancellationToken cancellationToken) { var entity = await _dbContext.Users.FindAsync(request.Id); if (entity is null) { throw new MonumentsManagerAppException(ExceptionType.EntityNotFound, $"Entity of type UserEntity with id {request.Id} does not exists"); } entity.JobTitle = request.JobTitle; entity.FirstName = request.FirstName; entity.LastName = request.LastName; if (!string.IsNullOrEmpty(request.Password)) { entity.Password = _passwordEncryptor.Encrypt(request.Password); var userContext = await _dbContext.Users.FindAsync(_applicationContext.UserId); await _emailSender.SendPasswordHasBeenChangedByAdministrator(entity.Email, userContext.Email); } _dbContext.Users.Update(entity); await _dbContext.SaveChangesAsync(); return(Unit.Value); }
public async Task <TokenResponse> CreateAnAccount(UserCredential userCredential) { if (userCredential == null) { throw new ArgumentNullException(nameof(userCredential)); } if (!IsValidPassword(userCredential.UserPassword)) { throw new ValidationException(_stringLocalizer["PasswordIsNotValid"]); } if (!IsValidUserName(userCredential.Login)) { throw new ValidationException(_stringLocalizer["LoginIsNotValid"]); } var newUser = new UserDto { Login = userCredential.Login, CountryId = default }; var user = await _userService.CreateAsync(newUser); if (user != null) { var hashedPassword = _passwordEncryptor.Encrypt(userCredential.UserPassword); var _ = await _authService.CreateUserAuthenticationAsync(user.Id, hashedPassword, false, userCredential.FcmToken, userCredential.Os); } var claimIdentity = _authService.GetIdentity(user); var pathToDirectory = Path.Combine(_appEnvironment.WebRootPath, "Photos", "Users", $"{user.Login}"); if (!Directory.Exists(pathToDirectory)) { Directory.CreateDirectory(pathToDirectory); } var jwtToken = _authService.GetJwtToken(claimIdentity); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwtToken); return(new TokenResponse { Token = encodedJwt, Login = user.Login }); }
/// <inheritdoc /> public async Task <User> AddAsync(User user) { var userDto = _mapper.Map <UserDto>(user); userDto.Password = _passwordEncryptor.Encrypt(user); var addedUser = await _usersRepository.AddAsync(userDto); var result = _mapper.Map <User>(addedUser); return(result); }
static void DispatchCommand(IPasswordEncryptor passwordEncryptor, ICommandDispatcher commandDispatcher, NewUserRequest newUserRequest) { commandDispatcher.Dispatch(new NewUserCommand { Email = newUserRequest.Email, EncryptedPassword = passwordEncryptor.Encrypt( newUserRequest.Password), AgreementVersion = newUserRequest.AgreementVersion }); }
public AuthenticationModule( IDatabase database, IPasswordEncryptor passwordEncryptor ) { Get[Route.Login] = o => View[Route.Login, new LoginRequest()]; Post[Route.Login] = o => { var request = this.Bind<LoginRequest>(); try { // TODO: Use validation attributes, or call Validate on LoginRequest if ( string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password) ) { throw new Exception("Username and password are required"); } var user = database.GetUserByName( request.UserName ); if ( null == user ) { throw new Exception( LoginFailureMessage ); } var credentials = database.GetUserCredentialsByUserId( user.Id ); if ( passwordEncryptor.Encrypt(request.Password) != credentials.EncryptedPassword ) { throw new Exception( LoginFailureMessage ); } var expiry = DateTime.MaxValue; return this.LoginAndRedirect( credentials.AuthId, expiry, Route.Home ); } catch ( Exception exception ) { this.AddUserMessage(exception.Message); return View[Route.Login, request]; } }; Get[Route.Logout] = o => { // this.AddUserMessage("You have been logged out"); return this.LogoutAndRedirect( Route.Login ); }; }
public async Task <Unit> Handle(ChangePasswordByRecoveryKeyCommand request, CancellationToken cancellationToken) { var decryptedRecoveryKey = _stringEncoder.Decrypt(request.RecoveryKey); var encrytedUserDto = JsonConvert.DeserializeObject <EncryptedUserDto>(decryptedRecoveryKey); var userEntity = await _dbContext.Users.FindAsync(encrytedUserDto.Id); if (userEntity is null || userEntity.Password != encrytedUserDto.Password) { throw new MonumentsManagerAppException(ExceptionType.RecoveryKeyValidationFailed, $"Recovery key is invalid for user with id {userEntity.Id}"); } userEntity.Password = _passwordEncryptor.Encrypt(request.Password); await _dbContext.SaveChangesAsync(); return(Unit.Value); }
public async Task <CreateUserResponse> Handle(CreateUserCommand request, CancellationToken cancellationToken) { await _validator.ValidateAndThrowAsync(request, cancellationToken); var salt = Guid.NewGuid().ToString(); var hashedPassword = _passwordEncryptor.Encrypt(request.Password, salt); var user = new User { Id = Guid.NewGuid(), Username = request.Username, Password = hashedPassword, Roles = new [] { "user" }, Salt = salt, }; _collection.Insert(user); return(new CreateUserResponse()); }
public async Task <UserDto> Handle(AuthenticateUserCommand request, CancellationToken cancellationToken) { var encryptedPassword = _passwordEncryptor.Encrypt(request.Password); var user = await _dbContext.Users .FirstOrDefaultAsync(s => s.Email == request.Email && s.Password == encryptedPassword); if (user is null) { return(null); } user.LastLoggedIn = DateTime.UtcNow; await _dbContext.SaveChangesAsync(); return(new UserDto() { Id = user.Id, JobTitle = user.JobTitle, Role = user.Role.ConvertTo <UserRoleDto>(), Email = user.Email }); }
public UserAccountModule(IUserAbilityRepository abilityReadRepo, ICommandDispatcher commandDispatcher, IPasswordEncryptor passwordEncryptor, IMapper mapper, IUserSessionFactory userSessionFactory) { Post["/register", true] = async(a, ct) => { var req = this.Bind <NewUserRequest>(); IEnumerable <UserAbility> abilities = mapper.Map <IEnumerable <UserAbilityRequest>, IEnumerable <UserAbility> >(req.Abilities); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new CreateEmailLoginUser(req.Email, passwordEncryptor.Encrypt(req.Password), req.Name, req.PhoneNumber, abilities)); return(null); }; Post["/register/facebook", true] = async(a, ct) => { var req = this.Bind <FacebookRegisterRequest>(); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new CreateFacebookLoginUser(req.id, req.email, req.first_name, req.last_name, req.link, req.name, req.url_image)); return(null); }; Post["/register/google", true] = async(a, ct) => { var req = this.Bind <GoogleRegisterRequest>(); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new CreateGoogleLoginUser(req.id, req.email, req.name.givenName, req.name.familyName, req.url, req.displayName, req.image.url)); return(null); }; Post["/password/requestReset", true] = async(a, ct) => { var req = this.Bind <ResetPasswordRequest>(); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new StartPasswordResetProcess(req.Email)); return(null); }; Put["/password/reset/{token}", true] = async(a, ct) => { var newPasswordRequest = this.Bind <NewPasswordRequest>(); Guid token = Guid.Parse((string)a.token); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new ResetPassword(token, passwordEncryptor.Encrypt(newPasswordRequest.Password))); return(null); }; Post["/user/abilites", true] = async(a, ct) => { var requestAbilites = this.Bind <UserAbilitiesRequest>(); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new AddAbilitiesToUser(requestAbilites.UserId, requestAbilites.Abilities.Select(x => x.Id))); return(null); }; Get["/abilities", true] = async(_, c) => { IEnumerable <UserAbility> abilites = await abilityReadRepo.GetAll(); IEnumerable <UserAbilityRequest> mappedAbilites = mapper .Map <IEnumerable <UserAbility>, IEnumerable <UserAbilityRequest> >( abilites); return(mappedAbilites); }; }
public UserAccountModule(IReadOnlyRepository readOnlyRepository,ICommandDispatcher commandDispatcher, IPasswordEncryptor passwordEncryptor, IMappingEngine mappingEngine) { Post["/register"] = _ => { var req = this.Bind<NewUserRequest>(); var abilities = mappingEngine.Map<IEnumerable<UserAbilityRequest>, IEnumerable<UserAbility>>(req.Abilities); commandDispatcher.Dispatch(this.UserSession(), new CreateEmailLoginUser(req.Email, passwordEncryptor.Encrypt(req.Password), req.Name, req.PhoneNumber, abilities)); return null; }; Post["/register/facebook"] = _ => { var req = this.Bind<FacebookRegisterRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreateFacebookLoginUser(req.id,req.email, req.first_name, req.last_name,req.link,req.name,req.url_image)); return null; }; Post["/register/google"] = _ => { var req = this.Bind<GoogleRegisterRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreateGoogleLoginUser(req.id,req.email,req.name.givenName,req.name.familyName,req.url,req.displayName,req.image.url)); return null; }; Post["/password/requestReset"] = _ => { var req = this.Bind<ResetPasswordRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreatePasswordResetToken(req.Email) ); return null; }; Put["/password/reset/{token}"] = p => { var newPasswordRequest = this.Bind<NewPasswordRequest>(); var token = Guid.Parse((string)p.token); commandDispatcher.Dispatch(this.UserSession(), new ResetPassword(token, passwordEncryptor.Encrypt(newPasswordRequest.Password))); return null; }; Post["/user/abilites"] = p => { var requestAbilites = this.Bind<UserAbilitiesRequest>(); commandDispatcher.Dispatch(this.UserSession(), new AddAbilitiesToUser(requestAbilites.UserId, requestAbilites.Abilities.Select(x => x.Id))); return null; }; Get["/abilities"] = _ => { var abilites = readOnlyRepository.GetAll<UserAbility>(); var mappedAbilites = mappingEngine.Map<IEnumerable<UserAbility>, IEnumerable<UserAbilityRequest>>(abilites); return mappedAbilites; }; }
public virtual string Encrypt(string password) { var prefix = PrefixHandler.GeneratePrefix(DefaultPasswordEncryptor.HashAlgorithmName()); return(prefix + DefaultPasswordEncryptor.Encrypt(password)); }
public UserAccountModule(IReadOnlyRepository readOnlyRepository, ICommandDispatcher commandDispatcher, IPasswordEncryptor passwordEncryptor, IMappingEngine mappingEngine) { Post["/register"] = _ => { var req = this.Bind <NewUserRequest>(); var abilities = mappingEngine.Map <IEnumerable <UserAbilityRequest>, IEnumerable <UserAbility> >(req.Abilities); commandDispatcher.Dispatch(this.UserSession(), new CreateEmailLoginUser(req.Email, passwordEncryptor.Encrypt(req.Password), req.Name, req.PhoneNumber, abilities)); return(null); }; Post["/register/facebook"] = _ => { var req = this.Bind <FacebookRegisterRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreateFacebookLoginUser(req.id, req.email, req.first_name, req.last_name, req.link, req.name, req.url_image)); return(null); }; Post["/register/google"] = _ => { var req = this.Bind <GoogleRegisterRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreateGoogleLoginUser(req.id, req.email, req.name.givenName, req.name.familyName, req.url, req.displayName, req.image.url)); return(null); }; Post["/password/requestReset"] = _ => { var req = this.Bind <ResetPasswordRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreatePasswordResetToken(req.Email)); return(null); }; Put["/password/reset/{token}"] = p => { var newPasswordRequest = this.Bind <NewPasswordRequest>(); var token = Guid.Parse((string)p.token); commandDispatcher.Dispatch(this.UserSession(), new ResetPassword(token, passwordEncryptor.Encrypt(newPasswordRequest.Password))); return(null); }; Post["/user/abilites"] = p => { var requestAbilites = this.Bind <UserAbilitiesRequest>(); commandDispatcher.Dispatch(this.UserSession(), new AddAbilitiesToUser(requestAbilites.UserId, requestAbilites.Abilities.Select(x => x.Id))); return(null); }; Get["/abilities"] = _ => { var abilites = readOnlyRepository.GetAll <UserAbility>(); var mappedAbilites = mappingEngine.Map <IEnumerable <UserAbility>, IEnumerable <UserAbilityRequest> >(abilites); return(mappedAbilites); }; Get["/testStatePattern"] = _ => { var traficLight = new Domain.DesignPattern.StatePattern.TraficLight(); var process = traficLight.StartTheTraficLight(); return(process); }; Get["/testNullObjectPattern"] = _ => { var dog = new Domain.DesignPattern.NullObjectPattern.Dog(); var dougSound = "Dog Sound: " + dog.MakeSound() + ", "; var unknown = Domain.DesignPattern.NullObjectPattern.Animal.Null; var noAnimalSound = "No Animal Sound: " + unknown.MakeSound(); return(dougSound + noAnimalSound); }; Get["/testObserverPattern"] = _ => { var observable = new Domain.DesignPattern.ObserverPattern.Observable(); var observer = new Domain.DesignPattern.ObserverPattern.Observer(); observable.SomethingHappened += observer.HandleEvent; var observerValue = observable.DoSomething(); return(observerValue); }; Get["/testBridgePattern/{currentSource}"] = _ => { var currentSource = (string)_.currentSource; var myCustomTv = new Domain.DesignPattern.BridgePattern.MyCustomTv(); switch (currentSource) { case "1": myCustomTv.VideoSource = new Domain.DesignPattern.BridgePattern.LocalCableTv(); break; case "2": myCustomTv.VideoSource = new Domain.DesignPattern.BridgePattern.CableColorTv(); break; case "3": myCustomTv.VideoSource = new Domain.DesignPattern.BridgePattern.TigoService(); break; } var tvGuide = myCustomTv.ShowTvGuide(); var playVideo = myCustomTv.ShowTvGuide(); return(tvGuide + " / " + playVideo); }; }
public LoginModule( IReadOnlyRepository readOnlyRepository, IUserSessionFactory userSessionFactory, IPasswordEncryptor passwordEncryptor) { Post["/login/facebook"] = r => { var loginInfo = this.Bind<FacebookLoginRequest>(); try { var user = readOnlyRepository.First<User>(x => x.FacebookId == loginInfo.FacebookId); //if (!user.Verified) return new Response().WithStatusCode(HttpStatusCode.Forbidden); UserSession userSession = userSessionFactory.Create(user); return new SuccessfulLoginResponse<Guid>(userSession.Id, userSession.Expires); } catch (ItemNotFoundException<User> ex) { return new Response().WithStatusCode(HttpStatusCode.Unauthorized); } }; Post["/login"] = r => { var loginInfo = this.Bind<BasicLoginRequest>(); if (loginInfo.Email == null) throw new UserInputPropertyMissingException("Email"); if (loginInfo.Password == null) throw new UserInputPropertyMissingException("Password"); EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password); try { var user = readOnlyRepository.First<User>( x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password); //if (!user.Activated) throw new ForbiddenRequestException(); UserSession userSession = userSessionFactory.Create(user); return new SuccessfulLoginResponse<Guid>(userSession.Id, userSession.Expires); } catch (ItemNotFoundException<User>) { throw new UnauthorizedAccessException(); } }; Post["/logout"] = r => { var loginInfo = this.Bind<FacebookLoginRequest>(); try { var session = readOnlyRepository.First<UserSession>(x => x.User.FacebookId == loginInfo.FacebookId); userSessionFactory.Delete(session.Id); return new Response().WithStatusCode(HttpStatusCode.OK); } catch (ItemNotFoundException<UserSession> ex) { return new Response().WithStatusCode(HttpStatusCode.Unauthorized); } }; }
public UserAccountModule(IReadOnlyRepository readOnlyRepository, ICommandDispatcher commandDispatcher, IPasswordEncryptor passwordEncryptor, IMappingEngine mappingEngine) { Post["/register"] = _ => { var req = this.Bind <NewUserRequest>(); var abilities = mappingEngine.Map <IEnumerable <UserAbilityRequest>, IEnumerable <UserAbility> >(req.Abilities); commandDispatcher.Dispatch(this.UserSession(), new CreateEmailLoginUser(req.Email, passwordEncryptor.Encrypt(req.Password), req.Name, req.PhoneNumber, abilities)); return(null); }; Post["/register/facebook"] = _ => { var req = this.Bind <FacebookRegisterRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreateFacebookLoginUser(req.id, req.email, req.first_name, req.last_name, req.link, req.name, req.url_image)); return(null); }; Post["/register/google"] = _ => { var req = this.Bind <GoogleRegisterRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreateGoogleLoginUser(req.id, req.email, req.name.givenName, req.name.familyName, req.url, req.displayName, req.image.url)); return(null); }; Post["/password/requestReset"] = _ => { var req = this.Bind <ResetPasswordRequest>(); commandDispatcher.Dispatch(this.UserSession(), new CreatePasswordResetToken(req.Email)); return(null); }; Put["/password/reset/{token}"] = p => { var newPasswordRequest = this.Bind <NewPasswordRequest>(); var token = Guid.Parse((string)p.token); commandDispatcher.Dispatch(this.UserSession(), new ResetPassword(token, passwordEncryptor.Encrypt(newPasswordRequest.Password))); return(null); }; Post["/user/abilites"] = p => { var requestAbilites = this.Bind <UserAbilitiesRequest>(); commandDispatcher.Dispatch(this.UserSession(), new AddAbilitiesToUser(requestAbilites.UserId, requestAbilites.Abilities.Select(x => x.Id))); return(null); }; Get["/abilities"] = _ => { var abilites = readOnlyRepository.GetAll <UserAbility>(); var mappedAbilites = mappingEngine.Map <IEnumerable <UserAbility>, IEnumerable <UserAbilityRequest> >(abilites); return(mappedAbilites); }; }
public LoginModule(IPasswordEncryptor passwordEncryptor, IReadOnlyRepository readOnlyRepository, IUserSessionFactory userSessionFactory, IMenuProvider menuProvider) { Post["/login"] = _ => { var loginInfo = this.Bind <LoginRequest>(); if (loginInfo.Email == null) { throw new UserInputPropertyMissingException("Email"); } if (loginInfo.Password == null) { throw new UserInputPropertyMissingException("Password"); } EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password); try { var user = readOnlyRepository.First <UserEmailLogin>( x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password); if (!user.IsActive) { throw new DisableUserAccountException(); } UserLoginSession userLoginSession = userSessionFactory.Create(user); return(new SuccessfulLoginResponse <Guid>(userLoginSession.Id, user.Name, userLoginSession.Expires, menuProvider.getFeatures(userLoginSession.GetClaimsAsArray()))); } catch (ItemNotFoundException <UserEmailLogin> ) { throw new UnauthorizedAccessException("Invalid email address or password. Please try again."); } catch (DisableUserAccountException) { throw new UnauthorizedAccessException("Your account has been disabled. Please contact your administrator for help."); } }; Post["/login/facebook"] = _ => { var loginInfo = this.Bind <LoginSocialRequest>(); if (loginInfo.Email == null) { throw new UserInputPropertyMissingException("Email"); } if (loginInfo.Id == null) { throw new UserInputPropertyMissingException("Social Id"); } try { var user = readOnlyRepository.First <UserFacebookLogin>( x => x.Email == loginInfo.Email && x.FacebookId == loginInfo.Id); if (!user.IsActive) { throw new DisableUserAccountException(); } UserLoginSession userLoginSession = userSessionFactory.Create(user); return(new SuccessfulLoginResponse <Guid>(userLoginSession.Id, user.Name, userLoginSession.Expires, menuProvider.getFeatures(userLoginSession.GetClaimsAsArray()))); } catch (ItemNotFoundException <UserEmailLogin> ) { throw new UnauthorizedAccessException("Invalid facebook user, you need to register first."); } catch (DisableUserAccountException) { throw new UnauthorizedAccessException("Your account has been disabled. Please contact your administrator for help."); } }; Get["/roles"] = _ => { this.RequiresAuthentication(); return(Response.AsJson(menuProvider.getAllFeatures())); }; Post["/login/google"] = _ => { var loginInfo = this.Bind <LoginSocialRequest>(); if (loginInfo.Email == null) { throw new UserInputPropertyMissingException("Email"); } if (loginInfo.Id == null) { throw new UserInputPropertyMissingException("Social Id"); } try { var user = readOnlyRepository.First <UserGoogleLogin>( x => x.Email == loginInfo.Email && x.GoogleId == loginInfo.Id); if (!user.IsActive) { throw new DisableUserAccountException(); } UserLoginSession userLoginSession = userSessionFactory.Create(user); return(new SuccessfulLoginResponse <Guid>(userLoginSession.Id, user.Name, userLoginSession.Expires, menuProvider.getFeatures(userLoginSession.GetClaimsAsArray()))); } catch (ItemNotFoundException <UserEmailLogin> ) { throw new UnauthorizedAccessException("Invalid google user, you need to register first."); } catch (DisableUserAccountException) { throw new UnauthorizedAccessException("Your account has been disabled. Please contact your administrator for help."); } }; }
public UserProfileModule( IDatabase database, IPasswordEncryptor passwordEncryptor ) : base(database) { this.passwordEncryptor = passwordEncryptor; this.RequiresAuthentication(); Get[Route.UserProfile] = o => { return View[Route.UserProfile]; }; Get[Route.ChangePassword] = o => { return View[Route.ChangePassword]; }; Post[Route.ChangePassword] = o => { var request = this.Bind<ChangePasswordRequest>(); var user = this.CurrentUser; try { var userCredentials = database.GetUserCredentialsByUserId( user.Id ); if ( string.IsNullOrWhiteSpace( request.CurrentPassword ) ) { throw new Exception( "Incorrect password" ); } if ( passwordEncryptor.Encrypt( request.CurrentPassword ) != userCredentials.EncryptedPassword ) { throw new Exception( "Incorrect password" ); } if ( request.NewPassword1 != request.NewPassword2 ) { throw new Exception( "Passwords don't match" ); } var result = PasswordValidator.Validate( request.NewPassword1 ); if ( !result.IsValid ) { throw new Exception( string.Join( ", ", result.ValidationErrors ) ); } userCredentials.EncryptedPassword = passwordEncryptor.Encrypt( request.NewPassword1 ); database.UpdateUserCredentials( userCredentials ); } catch ( Exception ex ) { this.AddUserMessage( ex.Message ); return View[Route.ChangePassword]; } this.AddUserMessage( "Your password has been changed" ); return View[Route.UserProfile]; }; Get[Route.SelectGames] = o => { var model = new SelectGamesViewModel(); var availableGames = database.GetGames(); var gamesPlayedByUser = database.GetGamesPlayedByUser( ((UserIdentity)Context.CurrentUser).UserId ); foreach ( var availableGame in availableGames ) { model.SelectableGames.Add( new Selectable<Game> { Item = availableGame, IsSelected = gamesPlayedByUser.Any( game => game.Id == availableGame.Id ) } ); } return View[Route.SelectGames, model]; }; Post[Route.SelectGames] = o => { var request = this.Bind<SelectGamesRequest>(); database.SetGamesPlayedByUser(((UserIdentity)Context.CurrentUser).UserId, request.GameIds); return Response.AsRedirect( Route.Home ); }; }