Skip to content
Snippets Groups Projects

Course initial

Files

@@ -9,7 +9,9 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import nl.tudelft.ewi.auta.core.response.exception.DuplicateUserException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
@@ -48,8 +50,13 @@ public class DatabaseConnection implements AutoCloseable {
* Creates a new user.
* @param user the user
* @throws SQLException if the SQL goes wrong
* @throws DuplicateUserException if the user already exists
*/
public void register(final User user) throws SQLException {
final var username = user.getUsername();
if (this.hasUser(username)) {
throw new DuplicateUserException("User with username " + username + " already exists");
}
try (var userStatement = this.connection.prepareStatement(
"INSERT INTO users (username, password, enabled) values (?, ?, ?)"
); var authStatement = this.connection.prepareStatement(
@@ -112,7 +119,7 @@ public class DatabaseConnection implements AutoCloseable {
* @return the user
* @throws SQLException if the SQL goes wrong
*/
public User getUser(final String username) throws SQLException {
public Optional<User> getUser(final String username) throws SQLException {
try (var userStatement = this.connection.prepareStatement(
"SELECT users.password, users.enabled, authorities.authority "
+ " FROM users "
@@ -122,15 +129,17 @@ public class DatabaseConnection implements AutoCloseable {
)) {
userStatement.setString(1, username);
try (var userRes = userStatement.executeQuery()) {
if (!userRes.next()) {
return Optional.empty();
}
final var password = userRes.getString("password");
final var enabled = userRes.getBoolean("enabled");
final var authorities = new HashSet<GrantedAuthority>();
while (userRes.next()) {
do {
authorities.add(new SimpleGrantedAuthority(userRes.getString("authority")));
}
return new User(username, password, enabled, true, true, true, authorities);
} while (userRes.next());
return Optional.of(new User(username, password, enabled, true, true, true,
authorities));
}
}
}
Loading