SOQL injection skip

Fixed login() — parameterized query (escaped for Blogger)

public Optional<User> login(String userName, String password) {
    // get connection as before
    try (Connection connection = DatabaseConnection.connect()) {
        // compute hashed password if your system stores/compares hashes in DB
        String hashedPassword = PasswordUtils.hashPassword(password);

        // Parameterized query (no string concatenation) - prevents SQL injection
        String sql = "SELECT id, username, first_name, last_name, admin, email, location "
                   + "FROM users WHERE username = ? AND password = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, userName);
            stmt.setString(2, hashedPassword);

            try (ResultSet rs = stmt.executeQuery()) {
                if (!rs.next()) {
                    return Optional.empty();
                }

                User user = new User(
                    rs.getInt("id"),
                    rs.getString("username"),
                    rs.getString("first_name"),
                    rs.getString("last_name"),
                    null, // placeholder for any field you don't want to expose
                    rs.getInt("admin"),
                    rs.getString("email"),
                    rs.getString("location")
                );

                this.deleteResetTokens(user.getId());
                return Optional.of(user);
            }
        }
    } catch (SQLException e) {
        // handle/log safely (do not log password or hashedPassword)
        return Optional.empty();
    }
}

Tip: This replaces the vulnerable concatenated SQL. If you instead store salted hashes (bcrypt/argon2), prefer fetching by username only and verifying the password in Java (so the raw password or hash is never passed into SQL).

SOQL injection skip SOQL injection skip Reviewed by dasfrogpractice on 09:53 Rating: 5

No comments:

Theme images by mariusFM77. Powered by Blogger.
Youtube Channel Image
Dasfrog Subscribe To watch more Salesforce Training
Subscribe