/// <summary> /// Método para criar/registar um utilizador na base de dados /// </summary> /// <param name="model">Modelo do utilizador com os dados</param> /// <returns>Utilizador caso seja adicionado com sucesso, /// senão retorna NULL</returns> public User Create(User model) { try { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO dbo.[User] (Email, Password, PasswordSalt, FirstName, LastName, Localization)" + "VALUES (@Email, @Pass, @Salt, @Fname, @Lname, @Local); SELECT @@Identity"; cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = model.Email; var password = PasswordEncrypt.Encrypt(model.Password); cmd.Parameters.Add("@Pass", SqlDbType.NVarChar).Value = password.Item2; cmd.Parameters.Add("@Salt", SqlDbType.NVarChar).Value = password.Item1; cmd.Parameters.Add("@Fname", SqlDbType.NVarChar).Value = model.FirstName; cmd.Parameters.Add("@Lname", SqlDbType.NVarChar).Value = model.LastName; cmd.Parameters.Add("@Local", SqlDbType.NVarChar).Value = model.Localization; model.Id = int.Parse(cmd.ExecuteScalar().ToString()); } return(model); } catch (Exception ex) { throw new Exception(ex.Message); } }
public void Test1() { const int DataN = 100; const int PassN = 80; var data = new byte[DataN]; for (var i = 0; i < DataN; i++) { data[i] = (byte)i; } var pass = new string[PassN]; var sb = new StringBuilder(); for (var i = 0; i < PassN; i++) { pass[i] = sb.ToString(); sb.Append((char)('!' + i)); } for (var i = 0; i < DataN; i++) { var dataSpan = data.AsSpan(0, i); for (var j = 0; j < PassN; j++) { var encrypted = PasswordEncrypt.Encrypt(dataSpan, pass[j]); PasswordEncrypt.TryDecrypt(encrypted, pass[j], out var decrypted).IsTrue(); dataSpan.SequenceEqual(decrypted.Span).IsTrue(); } } }
public async Task <GenericCommandResult> Handle(NewUsuarioCommand request, CancellationToken cancellationToken) { var usuario = await _usuarioRepository.Get(request.Login); if (usuario != null) { return(GenericCommandResult.Failure(new List <string> { ErrorMessages.UserAlreadyExists })); } var validator = new NewUsuarioCommandValidator(); var results = validator.Validate(request); if (!results.IsValid) { return(GenericCommandResult.Failure(results.Errors)); } var passEncrypt = PasswordEncrypt.Encrypt(request.Senha); var enderecos = request.Enderecos.Select(s => new Endereco(s.Rua, s.Numero, s.Complemento, s.Bairro, s.Cep, s.Cidade, s.Estado)).ToList(); var Usuario = new Usuario(request.Nome, request.Login, passEncrypt, request.DDD, request.Telefone, enderecos); await _usuarioRepository.Create(Usuario); return(GenericCommandResult.Success()); }
public async Task <GenericCommandResult> Handle(AutenticarUsuarioCommand request, CancellationToken cancellationToken) { var validator = new AutenticarUsuarioCommandValidator(); var results = validator.Validate(request); if (!results.IsValid) { return(GenericCommandResult.Failure(results.Errors)); } var usuario = await _usuarioRepository.Get(request.Login, PasswordEncrypt.Encrypt(request.Senha)); if (usuario is null) { return(GenericCommandResult.Failure(new List <string> { ErrorMessages.WrongUser })); } var retorno = new UsuarioModel { Login = usuario.EmailLogin, Nome = usuario.Nome, Token = Token.GenerateNewToken(usuario.EmailLogin) }; return(GenericCommandResult.Success(retorno)); }
public void UpdateProfile(UserEntity user) { SqlConnection sqlConnection = dbConnection.GetDbConnection(); SqlCommand command = commandInstance.GetSqlCommand(); bool newPassword = false; UserEntity oldUser = null; try { bool hasUserEmptyFields = ValidateNullOrEmptyFields(user); if (user == null) { throw new PersonalizedException("El usuario no puede ser nulo o vacío"); } else if (hasUserEmptyFields) { throw new PersonalizedException("No puedes dejar campos vacíos"); } else if (string.IsNullOrEmpty(user.Password)) { oldUser = GetUserById(user.UserId); newPassword = false; } sqlConnection.Open(); command.Connection = sqlConnection; command.CommandText = "UpdateUser"; command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.Clear(); command.Parameters.Add(new SqlParameter("@UserId", user.UserId)); command.Parameters.Add(new SqlParameter("@FirstName", user.FirstName)); command.Parameters.Add(new SqlParameter("@LastName", user.LastName)); command.Parameters.Add(new SqlParameter("@CellPhone", user.CellPhone)); command.Parameters.Add(new SqlParameter("@Genre", user.Genre)); command.Parameters.Add(new SqlParameter("@Email", user.Email)); if (newPassword) { command.Parameters.Add(new SqlParameter("@Password", PasswordEncrypt.Encrypt(user.Password))); } else { command.Parameters.Add(new SqlParameter("@Password", oldUser.Password)); } command.Parameters.Add(new SqlParameter("@LastModificationDate", DateTime.Today)); command.Parameters.Add(new SqlParameter("@Active", user.Active)); command.ExecuteNonQuery(); DBConnection.CloseConnection(sqlConnection); } catch (Exception exception) { throw new PersonalizedException(exception.Message); } finally { DBConnection.CloseConnection(sqlConnection); } }
public void CreateUser(UserEntity user) { SqlConnection sqlConnection = dbConnection.GetDbConnection(); SqlCommand command = commandInstance.GetSqlCommand(); try { bool hasUserEmptyFields = ValidateNullOrEmptyFields(user); bool isUserNameExists = ValidateIfUserNameExists(user.UserName); if (user == null) { throw new PersonalizedException("El usuario no puede ser nulo"); } else if (hasUserEmptyFields) { throw new PersonalizedException("No puedes dejar campos vacíos"); } else if (isUserNameExists) { throw new PersonalizedException("El nombre de usuario ya existe, intente con uno nuevo"); } else { sqlConnection.Open(); command.Connection = sqlConnection; command.CommandText = "CreateUser"; command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.Clear(); command.Parameters.Add(new SqlParameter("@FirstName", user.FirstName)); command.Parameters.Add(new SqlParameter("@LastName", user.LastName)); command.Parameters.Add(new SqlParameter("@CellPhone", user.CellPhone)); command.Parameters.Add(new SqlParameter("@Genre", user.Genre)); command.Parameters.Add(new SqlParameter("@Email", user.Email)); command.Parameters.Add(new SqlParameter("@UserName", user.UserName)); command.Parameters.Add(new SqlParameter("@Password", PasswordEncrypt.Encrypt(user.Password))); command.Parameters.Add(new SqlParameter("@CreationDate", DateTime.Today)); command.Parameters.Add(new SqlParameter("@LastModificationDate", DateTime.Today)); command.Parameters.Add(new SqlParameter("@Active", true)); command.ExecuteNonQuery(); DBConnection.CloseConnection(sqlConnection); } } catch (Exception exception) { throw new PersonalizedException(exception.Message); } finally { DBConnection.CloseConnection(sqlConnection); } }
public UserEntity SignIn(string UserName, string Password) { SqlConnection sqlConnection = dbConnection.GetDbConnection(); SqlCommand command = commandInstance.GetSqlCommand(); UserEntity user = new UserEntity(); try { if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) { throw new PersonalizedException("Debes ingresar un nombre de usuario y una contraseña"); } else { sqlConnection.Open(); command.Connection = sqlConnection; command.CommandText = "GetUserByUserNameAndPassword"; command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.Clear(); command.Parameters.Add(new SqlParameter("@UserName", UserName)); command.Parameters.Add(new SqlParameter("@Password", PasswordEncrypt.Encrypt(Password))); sqlDataReader = command.ExecuteReader(); while (sqlDataReader.Read()) { user = new UserEntity { UserId = sqlDataReader.GetInt32(0), UserName = sqlDataReader.GetString(6), Active = sqlDataReader.GetBoolean(10) }; } sqlDataReader.Close(); DBConnection.CloseConnection(sqlConnection); if (user == null) { throw new PersonalizedException("Nombre de usuario o contraseña incorrecta"); } return(user); } } catch (Exception exception) { throw new PersonalizedException(exception.Message); } finally { DBConnection.CloseConnection(sqlConnection); } }
/// <summary> /// Método para recuperar a password /// </summary> /// <param name="newPass">Nova Password</param> /// <param name="email">Email do user que vai alterar a password</param> /// <returns>Retorna bool</returns> public bool RecoverPassword(RecoverPasswordModel newPass, string email) { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "UPDATE dbo.[User] SET Password = @pass, PasswordSalt = @salt " + "WHERE Email = @email"; cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = email; var password = PasswordEncrypt.Encrypt(newPass.Password); cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = password.Item2; cmd.Parameters.Add("@salt", SqlDbType.NVarChar).Value = password.Item1; newPass.Password = password.Item2; cmd.ExecuteNonQuery(); } return(true); }
/// <summary> /// Método que atualiza a password /// de um determindado utilizador /// </summary> /// <param name="newPass">Nova palavra-passe</param> /// <param name="id">Id do utilizador que pretende alterar /// a sua palavra-passe</param> /// <returns> /// True caso a password seja atualizada com sucesso /// False caso contrário /// </returns> public bool UpdatePassword(UserUpdatePassword newPass, int?id) { User user = FindById((int)id); if (user == null) { throw new Exception("O utilizador não existe!"); } if (PasswordEncrypt.VerifyHash(newPass.ActualPassword, user.Password, user.PasswordSalt)) { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "UPDATE dbo.[User] " + "SET Password = @pass, PasswordSalt = @salt " + "WHERE Id = @id"; cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; var password = PasswordEncrypt.Encrypt(newPass.NewPassword); cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = password.Item2; cmd.Parameters.Add("@salt", SqlDbType.NVarChar).Value = password.Item1; if (cmd.ExecuteNonQuery() == 0) { return(false); } } return(true); } else { throw new Exception("A password antiga é inválida!"); } }
// Sets an encrypted password. public void SetPassword(string password) { this.password = PasswordEncrypt.Encrypt(password, "password"); }