//Add administrator to the database private async Task CreateAdmin(Admin admin) { try { //Encrypt password string hash = encryption.Encrypt(admin.Password); admin.Password = hash; _context.Admins.Add(admin); await _context.SaveChangesAsync(); } catch (Exception ex) { Debug.WriteLine(ex); } }
//Add user to the database private async Task CreateUser(User user) { try { //Encrypt password string hash = encryption.Encrypt(user.Password); user.Password = hash; _context.Users.Add(user); await _context.SaveChangesAsync(); } catch (Exception ex) { Debug.WriteLine(ex); } }
public async Task <ServiceResponse <UserDto> > Handle(UpdateUserCommand request, CancellationToken cancellationToken) { var dbUser = await _userRepository.GetByIdAsync(request.Id); if (dbUser is null) { throw new ApiException("User not faund"); } dbUser.Password = PasswordEncrypter.Encrypt(request.Password); dbUser.Email = request.Email; dbUser.FirstName = request.FirstName; dbUser.IsActive = request.IsActive; dbUser.LastName = request.LastName; //_mapper.Map(request, dbUser); await _userRepository.UpdateAsync(dbUser); return(new ServiceResponse <UserDto>() { Value = _mapper.Map <UserDto>(dbUser) }); }
public IActionResult Login([FromBody] LoginCredentials credentials) { var errors = credentials.Validate(); if (errors.Any()) { return(BadRequest(errors)); } var encryptedPassword = PasswordEncrypter.Encrypt(credentials.Password); var user = Context.Users.SingleOrDefault(x => x.Email.Equals(credentials.Email) && x.Password.Equals(encryptedPassword)); if (user == null) { return(Unauthorized()); } var longLivedToken = TokenStore.GiveToken(DateTime.Now.AddSeconds(LongLivedTokenTimeInSeconds), SecurityKeyBuilder, GetClaims(user)); var shortLivedToken = TokenStore.GiveToken(DateTime.Now.AddSeconds(ShortLivedTokenTimeInSeconds), SecurityKeyBuilder, GetClaims(user)); return(Ok(new LoginResponse { LongLivedToken = longLivedToken, ShortLivedToken = shortLivedToken, IsAdmin = user.Role.Equals(Role.ADMIN) })); }
public async Task <ServiceResponse <UserLoginDto> > Handle(LoginCommand request, CancellationToken cancellationToken) { var encryptedPassword = PasswordEncrypter.Encrypt(request.Password); var dbUser = await _userRepository.TableNoTracking.FirstOrDefaultAsync(r => r.Email == request.Email && r.Password == encryptedPassword, cancellationToken); if (dbUser is null) { throw new ApiException("User not found or given information is wrong"); } if (!dbUser.IsActive) { throw new ApiException("User state is Passive!"); } var user = _mapper.Map <UserDto>(dbUser); UserLoginDto userLogin = _JWTGenerator.CreateToken(dbUser); userLogin.User = user; return(new ServiceResponse <UserLoginDto>() { Value = userLogin }); }
public async Task <IActionResult> ResetPassword([FromBody] RecoveryCredential credential) { var errors = credential.Validate(); var user = await Context.Users.FindAsync(credential.Id); if (user == null) { errors.Add("El usuario en el token no existe"); } if (errors.Any()) { return(BadRequest(errors)); } var keyBuilder = new PasswordRecoveryKeyBuilder(user); var jwtDecodeErrors = TokenStore.IsTokenValid(credential.Token, keyBuilder); if (jwtDecodeErrors.Count > 0) { return(BadRequest(jwtDecodeErrors)); } user.Password = PasswordEncrypter.Encrypt(credential.Password); Context.Users.Update(user); await Context.SaveChangesAsync(); return(Ok()); }
public async Task <bool> RegisterUserAsync(RegistrationUser regUser) { Thread.Sleep(2000); var users = await _storage.GetAllAsync(); var dbUser = users.FirstOrDefault(user => user.Login == regUser.Login); if (dbUser != null) { throw new Exception("User already exists"); } if (String.IsNullOrWhiteSpace(regUser.Login) || String.IsNullOrWhiteSpace(regUser.Password) || String.IsNullOrWhiteSpace(regUser.LastName)) { throw new ArgumentException("Login, Password or Last Name is Empty"); } ////encrypt pswd // PasswordEncrypter.CreateEncryptionKey(); string encryptedPswd = PasswordEncrypter.Encrypt(regUser.Password); dbUser = new DBUser(regUser.LastName + regUser.FirstName, regUser.LastName, regUser.Email, regUser.Login, encryptedPswd); await _storage.AddOrUpdateAsync(dbUser); return(true); }
public async Task <IActionResult> Post([FromBody] UserDto dto) { var errors = dto.Validate(); if (Context.Users.Any(x => x.Email.Equals(dto.Email))) { errors.Add("Email ya está siendo usado"); } if (dto.Email != null && !IsEmailValid(dto.Email)) { errors.Add("Email no es válido"); } if (errors.Count > 0) { return(BadRequest(errors)); } var user = Mapper.Map <User>(dto); user.Password = PasswordEncrypter.Encrypt(dto.Password); await Context.Users.AddAsync(user); await Context.SaveChangesAsync(); var userWithoutPassword = Mapper.Map <UserDtoWithoutPassword>(user); return(Ok(userWithoutPassword)); }
public async Task <ServiceResponse <UserDto> > Handle(CreateUserCommand request, CancellationToken cancellationToken) { var user = _mapper.Map <Domain.Entities.Users>(request); if (user is null) { throw new ApiException("user not mapping"); } var dbUser = await _userRepository.TableNoTracking.FirstOrDefaultAsync(r => r.Email == request.Email, cancellationToken); if (dbUser != null) { throw new ApiException("User already exists"); } user.IsActive = true; user.Password = PasswordEncrypter.Encrypt(user.Password); await _userRepository.InsertAsync(user); return(new ServiceResponse <UserDto>() { Value = _mapper.Map <UserDto>(user) }); }
public void UpdatePassword(string oldPassword, string newPassword, Action onWrongPassword, Action onPasswordUpdated) { Action wrongPassword = onWrongPassword; Action passwordUpdated = onPasswordUpdated; if (PasswordEncrypter.Encrypt(oldPassword) != _authorizedUser.Password) { wrongPassword?.Invoke(); } else { _authorizedUser.Password = PasswordEncrypter.Encrypt(newPassword); SaveRepository(); passwordUpdated?.Invoke(); } }
public virtual void Authorization(string email, string password, Action wrongEmail, Action wrongPassword, Action authorized) { Action WrongEmail = wrongEmail; Action WrongPassword = wrongPassword; Action Authorized = authorized; var curUser = Users.SingleOrDefault(u => u.Email == email); if (curUser == null) { WrongEmail?.Invoke(); } else if (curUser.Password != PasswordEncrypter.Encrypt(password)) { WrongPassword?.Invoke(); } else { _authorizedUser = curUser; Authorized?.Invoke(); } }
//Create new login for debtor private async Task CreateLogin(Debtor debtor) { try { User user = new User(); user.Debtor = debtor; user.Email = debtor.Email; user.Password = debtor.FirstName + "_" + DateTime.Now.ToString("ddMMHH"); //Encrypt password string hash = encryption.Encrypt(user.Password); user.Password = hash; _context.Users.Add(user); await _context.SaveChangesAsync(); //Send email with username and password AuthMessageSender email = new AuthMessageSender(_settings); await email.SendLoginEmailAsync(user.Email, encryption.Decrypt(user.Password)); } catch (Exception ex) { Debug.WriteLine(ex); } }
public GeneralMapping() { AllowNullDestinationValues = true; AllowNullCollections = true; CreateMap <Supplier, SupplierDto>() .ReverseMap(); CreateMap <Supplier, CreateSupplierCommand>().ReverseMap(); CreateMap <Supplier, UpdateSupplierCommand>().ReverseMap(); CreateMap <Users, UserDto>(); CreateMap <UserDto, Users>() .ForMember(x => x.Password, y => y.MapFrom(z => PasswordEncrypter.Encrypt(z.Password))) ; CreateMap <Users, CreateUserCommand>().ReverseMap(); CreateMap <Users, UpdateUserCommand>().ReverseMap(); CreateMap <Order, OrderDto>() .ForMember(x => x.SupplierName, y => y.MapFrom(z => z.Supplier.Name)) .ForMember(x => x.CreatedUserFullName, y => y.MapFrom(z => z.CreatedUser.FirstName + " " + z.CreatedUser.LastName)); CreateMap <OrderDto, Order>(); CreateMap <Order, CreateOrderCommand>().ReverseMap(); CreateMap <Order, UpdateOrderCommand>().ReverseMap(); CreateMap <OrderItem, OrderItemDto>() .ForMember(x => x.CreatedUserFullName, y => y.MapFrom(z => z.CreatedUser.FirstName + " " + z.CreatedUser.LastName)) .ForMember(x => x.OrderName, y => y.MapFrom(z => z.Order.Name ?? "")); CreateMap <OrderItemDto, OrderItem>(); CreateMap <OrderItem, CreateOrderItemCommand>().ReverseMap(); CreateMap <OrderItem, UpdateOrderItemCommand>().ReverseMap(); }
public override void Authorization(string email, string password, Action wrongEmail, Action wrongPassword, Action authorized) { Action WrongEmail = wrongEmail; Action WrongPassword = wrongPassword; Action Authorized = authorized; var curUser = _context.Users.Include("Preferences").SingleOrDefault(u => u.Email == email); if (curUser == null) { WrongEmail?.Invoke(); } else if (curUser.Password != PasswordEncrypter.Encrypt(password)) { WrongPassword?.Invoke(); } else { _stations = _context.Stations.ToList(); _authorizedUser = curUser; _routes = _context.Routes.Include("Stations").ToList(); Authorized?.Invoke(); } }
//public UserRegistrationDelegate UserRegistered; private void Button_Submit_Click(object sender, RoutedEventArgs e) { emptySurnameMessage.Visibility = System.Windows.Visibility.Collapsed; emptyEmailMessage.Visibility = System.Windows.Visibility.Collapsed; emptyNameMessage.Visibility = System.Windows.Visibility.Collapsed; emptyPasswordMessage.Visibility = System.Windows.Visibility.Collapsed; invalidPasswordMessage.Visibility = System.Windows.Visibility.Collapsed; bool emptyName = string.IsNullOrEmpty(textBoxName.Text.Trim()); bool emptySurname = string.IsNullOrEmpty(textBoxSurname.Text.Trim()); bool emptyEmail = string.IsNullOrEmpty(textBoxEmail.Text.Trim()); bool emptyPassword = string.IsNullOrEmpty(passwordBoxPassword.Password.Trim()); if (emptyEmail || emptyEmail || emptyPassword || emptySurname) { if (emptySurname) { emptySurnameMessage.Visibility = System.Windows.Visibility.Visible; } if (emptyPassword) { emptyPasswordMessage.Visibility = System.Windows.Visibility.Visible; } if (emptyName) { emptyNameMessage.Visibility = System.Windows.Visibility.Visible; } if (emptyEmail) { emptyEmailMessage.Visibility = System.Windows.Visibility.Visible; } } else if (passwordBoxPassword.Password.Length < 7) { invalidPasswordMessage.Visibility = System.Windows.Visibility.Visible; } else { if (!_repo.RegisterUser(textBoxName.Text, textBoxSurname.Text, textBoxEmail.Text, PasswordEncrypter.Encrypt(passwordBoxPassword.Password), OnUserRegistered)) { existingEmailMessage.Visibility = System.Windows.Visibility.Visible; } } }
public void TestHashEncoding(string expectedHashCode, string stringToHashCode) { var c = PasswordEncrypter.Encrypt(stringToHashCode); Assert.AreEqual(expectedHashCode, c); }