private User authenticate(ContainerRequest request) {
// Extract authentication credentials
String authentication = request.getHeaderValue(ContainerRequest.AUTHORIZATION);
if (authentication == null) {
throw new MappableContainerException
(new AuthenticationException("Authentication credentials are required\r\n", REALM));
}
if (!authentication.startsWith("Basic ")) {
throw new MappableContainerException
(new AuthenticationException("Only HTTP Basic authentication is supported\r\n", REALM));
}
authentication = authentication.substring("Basic ".length());
String[] values = new String(Base64.base64Decode(authentication)).split(":");
if (values.length < 2) {
throw new MappableContainerException
(new AuthenticationException("Invalid syntax for username and password\r\n", REALM));
}
String username = values[0];
String password = values[1];
if ((username == null) || (password == null)) {
throw new MappableContainerException
(new AuthenticationException("Missing username or password\r\n", REALM));
}
// Validate the extracted credentials
User user = null;
synchronized (Database.users) {
user = Database.users.get(username);
if (user == null) {
throw new MappableContainerException(new AuthenticationException("Invalid username or password\r\n", REALM));
} else if (!password.trim().equals(user.getPassword().trim())) {
throw new MappableContainerException(new AuthenticationException("Invalid username or password\r\n", REALM));
}
}
// Return the validated user
return user;