In the Registering a User challenge, you updated the register()
method in the AuthService
to create a new User node in the database.
There is still something to be done in the registration process.
Currently, it is still possible to use the same email address twice, we should guard against that.
This functionality could be handled by checking the database before running the CREATE
Cypher statement, but this could still cause problems if the database is manually updated elsewhere.
Instead, you can pass the responsibility of handling the duplicate user error to the database by creating a Unique Constraint on the :User
label, asserting that the email
property must be unique.
To pass this challenge, you will need to:
Handling Constraint Errors
If we take a look at register()
method, it had been hardcoded to throw a new RuntimeException
if the email address is anything other than graphacademy@neo4j.com
from the fixture in users.json
.
public Map<String,Object> register(String email, String plainPassword, String name) {
var encrypted = AuthUtils.encryptPassword(plainPassword);
// TODO: Handle Unique constraints in the database
var foundUser = users.stream().filter(u -> u.get("email").equals(email)).findAny();
if (foundUser.isPresent()) {
throw new RuntimeException("An account already exists with the email address");
}
// TODO: Save user in database
var user = Map.<String,Object>of("email",email, "name",name,
"userId", String.valueOf(email.hashCode()), "password", encrypted);
users.add(user);
String sub = (String) user.get("userId");
String token = AuthUtils.sign(sub,userToClaims(user), jwtSecret);
return userWithToken(user, token);
}
The code we added had no explicit error handling.
Any errors will be sent back up the stack and will result in a 500 Bad Request
error.
Instead, this error should be caught and reformatted in such a way that the server would return a 422 Unprocessable Entity
error.
This way, the error can be better handled by the UI.
To do this, you will need to rearrange the code into try
/catch
blocks.
If we take a look at a generic try
/catch
, it can be broken down into three parts; try
, catch
, and an optional finally
.
try (/* allocate resources */) {
// Attempt the code inside the block
}
catch (Exception e) {
// If anything goes wrong in the try block,
// deal with the error here
}
finally {
// Run this statement regardless of whether an error
// is thrown or not
}
When a user tries to register with an email address that has already been taken, the database will throw an Neo.ClientError.Schema.ConstraintViolation
error.
Instead of this being treated as an internal server error, it should instead be treated as a 422 Unprocessable Entity
.
This will allow the front end to render an appropriate error page.
Completing the Challenge
To complete this challenge, you will first create a new constraint in your Sandbox database and modify the code to add a try/catch block
Create a Unique Constraint
In order to ensure that a property and label combination is unique, you run a CREATE CONSTRAINT
query.
In this case, we need to ensure that the email
property is unique across all nodes with a :User
label.
Click the Run in Sandbox button to create the constraint on your Sandbox.
CREATE CONSTRAINT UserEmailUnique
IF NOT EXISTS
FOR (user:User)
REQUIRE user.email IS UNIQUE;
Add a Try/Catch Block
First add the imports for neoflix.ValidationException
and org.neo4j.driver.exceptions.ClientException
.
Our app treats ValidationException
as an indicator that an expectation was not met and will return an HTTP-422 error.
In the method, we should:
-
Try to create a User with the supplied email, encrypted password and name.
-
Catch an error when it is thrown, using the
code()
method to check and turn aNeo.ClientError.Schema.ConstraintValidationFailed
error into aValidationException
. -
The session is auto-closed because we allocated it in the try-with-resources block.
Your code should look like this:
} catch (ClientException e) {
// Handle unique constraints in the database
if (e.code().equals("Neo.ClientError.Schema.ConstraintValidationFailed")) {
throw new ValidationException("An account already exists with the email address", Map.of("email","Email address already taken"));
}
throw e;
}
Update the register()
method to reflect the changes above, then scroll to Testing to verify that the code works as expected.
Working Solution
Click here to reveal the fully-implemented register()
method.
public Map<String,Object> register(String email, String plainPassword, String name) {
var encrypted = AuthUtils.encryptPassword(plainPassword);
// Open a new Session
try (var session = this.driver.session()) {
var user = session.executeWrite(tx -> {
String statement = """
CREATE (u:User {
userId: randomUuid(),
email: $email,
password: $encrypted,
name: $name
})
RETURN u { .userId, .name, .email } as u""";
var res = tx.run(statement, Values.parameters("email", email, "encrypted", encrypted, "name", name));
// Extract safe properties from the user node (`u`) in the first row
return res.single().get("u").asMap();
});
String sub = (String)user.get("userId");
String token = AuthUtils.sign(sub,userToClaims(user), jwtSecret);
return userWithToken(user, token);
} catch (ClientException e) {
// Handle unique constraints in the database
if (e.code().equals("Neo.ClientError.Schema.ConstraintValidationFailed")) {
throw new ValidationException("An account already exists with the email address", Map.of("email","Email address already taken"));
}
throw e;
}
}
Testing
To test that this functionality has been correctly implemented, run the following code in a new terminal session:
mvn test -Dtest=neoflix._04_ConstraintErrorTest#checkConstraintWithDuplicateUser
The test file is located at src/test/java/neoflix/_04_ConstraintErrorTest.java
.
Are you stuck? Click here for help
If you get stuck, you can see a working solution by checking out the 04-handle-constraint-errors
branch by running:
git checkout 04-handle-constraint-errors
You may have to commit or stash your changes before checking out this branch. You can also click here to expand the Support pane.
Verifying the Test
If you have completed the steps in this challenge, a Unique Constraint will have been added to the database.
Click the Check Database button below to verify the constraint has been correctly created.
Hint
Try running the Cypher statement at Create a Unique Constraint and then click Check Database again.
Solution
If you haven’t already done so, run the following statement to create the constraint:
CREATE CONSTRAINT UserEmailUnique
IF NOT EXISTS
FOR (user:User)
REQUIRE user.email IS UNIQUE
The unit test then attempts to create a user twice with a random email address, with the test passing if the ValidationException
error is thrown by the AuthService
.
Once you have run this statement, click Try again…* to complete the challenge.
Lesson Summary
In this Challenge, you have modified the register()
function to catch specific errors thrown by the database.
If you wanted to go further, you could use a Regular Expression to extract more specific information about the ConstraintValidationFailed
error.
Now that a user is able to successfully register, in the next Challenge, you will update the authenticate()
method to find our user in the database.