Unique Email Addresses

In the Registering a User challenge, you updated the RegisterAsync() 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 RegisterAsync() method, it had been hardcoded to throw a new ValidationException if the email address is anything other than graphacademy@neo4j.com.

c#
Neoflix/Services/AuthService.cs
public async Task<Dictionary<string, object>> RegisterAsync(string email, string plainPassword, string name)
{
    var rounds = Config.UnpackPasswordConfig();
    var encrypted = BCryptNet.HashPassword(plainPassword, rounds);
    // TODO: Handle Unique constraints in the database
    if (email != "graphacademy@neo4j.com")
        throw new ValidationException($"An account already exists with the email address", email);
    
    // TODO: Save user
    var exampleUser = new Dictionary<string, object>
    {
        ["identity"] = 1,
        ["properties"] = new Dictionary<string, object>
        {
            ["userId"] = 1,
            ["email"] = "graphacademy@neo4j.com",
            ["name"] = "Graph Academy"
        }
    };

    var safeProperties = SafeProperties(exampleUser["properties"] as Dictionary<string, object>);
    safeProperties.Add("token", JwtHelper.CreateToken(GetUserClaims(safeProperties)));

    return safeProperties;
}

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.

c#
Try/Catch/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.

cypher
CREATE CONSTRAINT UserEmailUnique
IF NOT EXISTS
FOR (user:User)
REQUIRE user.email IS UNIQUE;

Add a Try/Catch Block

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:

  1. Try to create a User with the supplied email, encrypted password and name.

  2. Catch an error when it is thrown, using the Code() method to check and turn a Neo.ClientError.Schema.ConstraintValidationFailed error into a ValidationException.

  3. The session is auto-closed because we allocated it in the try-with-resources block.

Your code should look like this:

c#
try
{
    await using var session = _driver.AsyncSession();

    var user = await session.ExecuteWriteAsync(async tx =>
    {
        var query = @"
        CREATE (u:User {
            userId: randomUuid(),
            email: $email,
            password: $encrypted,
            name: $name
        })
        RETURN u { .userId, .name, .email } as u";
        var cursor = await tx.RunAsync(query, new {email, encrypted, name});

        var record = await cursor.SingleAsync();
        // Extract safe properties from the user node (`u`) in the first row
        return record["u"].As<Dictionary<string, object>>();
    });
   
    var safeProperties = SafeProperties(user);
    safeProperties.Add("token", JwtHelper.CreateToken(GetUserClaims(safeProperties)));

    return safeProperties;
}
catch (ClientException exception) when (exception.Code == "Neo.ClientError.Schema.ConstraintValidationFailed")
{
    throw new ValidationException(exception.Message, email);
}

Update the RegisterAsync() 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 RegisterAsync() method.
c#
public async Task<Dictionary<string, object>> RegisterAsync(string email, string plainPassword, string name)
{
    var rounds = Config.UnpackPasswordConfig();
    var encrypted = BCryptNet.HashPassword(plainPassword, rounds);

    try
    {
        await using var session = _driver.AsyncSession();

        var user = await session.ExecuteWriteAsync(async tx =>
        {
            var query = @"
            CREATE (u:User {
                userId: randomUuid(),
                email: $email,
                password: $encrypted,
                name: $name
            })
            RETURN u { .userId, .name, .email } as u";
            var cursor = await tx.RunAsync(query, new {email, encrypted, name});

            var record = await cursor.SingleAsync();
            // Extract safe properties from the user node (`u`) in the first row
            return record["u"].As<Dictionary<string, object>>();
        });
       
        var safeProperties = SafeProperties(user);
        safeProperties.Add("token", JwtHelper.CreateToken(GetUserClaims(safeProperties)));

        return safeProperties;
    }
    catch (ClientException exception) when (exception.Code == "Neo.ClientError.Schema.ConstraintValidationFailed")
    {
        throw new ValidationException(exception.Message, email);
    }
}

Testing

To test that this functionality has been correctly implemented, run the following code in a new terminal session:

sh
Running the test
dotnet test --logger "console;verbosity=detailed" --filter "Neoflix.Challenges._04_HandleConstraintErrors"

The test file is located at Neoflix.Challenges/04_HandleConstraintErrors.cs.

Are you stuck? Click here for help

If you get stuck, you can see a working solution by checking out the 04-handling-constraint-errors branch by running:

sh
Check out the 04-handling-constraint-errors branch
git checkout 04-handling-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:

cypher
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 RegisterAsync() 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 AuthenticateAsync() method to find our user in the database.