User Login Getting User Info

DSE Version: 6.7

Intro

Exercises

Slides

Resources

In this unit we will create the second of the two methods necessary to allow user login in your KillrVideo app!

No write up.

Exercise: User Login

In this exercise, you will:

  • Complete database access layer code (for the user) in a sandbox

  • Integrate the code from the sandbox into the KillrVideo web app so that login works

In the previous exercise, we built code in the data access layer that retrieved the user credentials. However, this was not sufficient to get the login functionality fully operational. We also need to write the data access layer code that retrieves the user information. We will follow the same development pattern of creating the code first in a sandbox, and then moving the working code into the web app. Once we complete the work in this exercise, you will be able to login to your web app!

Steps

1) Refresh your ScratchPad.java. In the previous exercise we saw that we need to implement the getUserById() method. We want to build and test this method in the scratchpad project. The first step is to copy the fresh code that follows into your ScratchPad.java file (scratchpad/src/main/java/com.datastax.academy.cloud.demo/ScratchPad.java):

package com.datastax.academy.cloud.demo;

import java.io.File;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.datastax.oss.driver.api.core.cql.BatchStatement;
import com.datastax.oss.driver.api.core.cql.BoundStatement;
import com.datastax.oss.driver.api.core.cql.DefaultBatchType;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.cql.SimpleStatementBuilder;
import com.datastax.dse.driver.api.core.DseSession;
import com.datastax.oss.driver.api.core.DefaultConsistencyLevel;
import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ScratchPad {
  static final Logger LOGGER = LoggerFactory.getLogger(ScratchPad.class);

  public static User getUserById(DseSession session, 
    UUID userid) throws Exception {
    LOGGER.debug("------Start getUserById------");
    return null;
  }

  public static void main(String[] args) {
    LOGGER.info("Starting main()...");
    try {
      SessionManagement.initSession();
      DseSession session = SessionManagement.getSession();
    
      //-----------------------------------------------------------------------------
      // TBD: Be sure to replace the UUID in the next line with one from your users table
      //-----------------------------------------------------------------------------
      User user = getUserById(session, UUID.fromString("db2523a7-81a6-4629-97aa-96456e583ed1"));
      LOGGER.info("email = " + user.getEmail());
      LOGGER.info("first name = " + user.getFirstname());
      LOGGER.info("last name = " + user.getLastname());
      LOGGER.info("created date = " + user.getCreatedAt());
    }
    catch (Exception e) { e.printStackTrace(); }
    finally { SessionManagement.closeSession(); }
    System.exit(0);
  }
}

In this version of ScratchPad.java, notice we copied the getUserById() method stub from UserAccess.java. We also set up some test code in main() which calls getUserById() and displays the results.

2) Change the UUID. In our main() test code, we included a userid value from our (Steve + Jamie's) database for you (db2523a7-81a6-4629-97aa-96456e583ed1). This is not going to work in your case. Replace the userid UUID value with a value from your own database.

Not sure how to retrieve a valid userid from your database? Click here.
Launch cqlsh with the following (remember the password is KVPassword):
cqlsh --username KVUser --cqlshrc /projects/creds/cqlshrc

Use the following CQL to retrieve the userid values from your database:

SELECT firstname, lastname, userid FROM killrvideo.users;

3) Run the test. Try the test by running scratchpad. Of course the test fails because the getUserById() method stub returns null and we try to dereference that null pointer when we attempt to log its field values in main().

4) Write the code. Now you can build the getUserById() method in ScratchPad.java.  This method retrieves a User from the users table using the ID. If you think you know how to do this, go ahead and give it a shot - remember your helpful cheat sheet. But if you think you might like some help, use the hint below to see a method outline. Remember, you can also refer back to the code you wrote for the previous exercise, in UserAccess.java.

Need to see the method outline? Click here.
  public static User getUserById(DseSession session, 
    UUID userid) throws Exception {
    LOGGER.debug("------Start getUserById------");

    // Create a string to SELECT the user from users based on parameterized userid
    // Create the SimpleStatement that combines the command with the userid
    // Execute the query string and get the result set
    // Get the row from the result set
    // Extract all the values from the row and create a User object
    // Return the User object    	
  }
Maybe the method outline wasn't enough help? Click here for the full method.
  public static User getUserById(DseSession session, 
    UUID userid) throws Exception {
    LOGGER.debug("------Start getUserById------");

    // Create a string to SELECT the user from users based on parameterized userid
	String command = "SELECT * FROM killrvideo.users WHERE userid = ?";
    // Create the SimpleStatement that combines the command with the userid
    SimpleStatement statement = SimpleStatement.newInstance(command, userid);
    // Execute the query string and get the result set
    ResultSet meResultSet = session.execute(statement);
    // Get the row from the result set
    Row meRow = meResultSet.one();
    	
    // Extract all the values from the row and create a User object
    String firstname = meRow.getString("firstname");
    String lastname = meRow.getString("lastname");
    String email = meRow.getString("email");
    Instant createdAt = meRow.getInstant("created_date");
    User user = new User(userid, firstname, lastname, email, createdAt);
   	
    // Return the User object    	
    return user;
  }
Need all the code for ScratchPad.java? Click here (but remember, you will need to supply the correct UUID in main()).
package com.datastax.academy.cloud.demo;

import java.io.File;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.datastax.oss.driver.api.core.cql.BatchStatement;
import com.datastax.oss.driver.api.core.cql.BoundStatement;
import com.datastax.oss.driver.api.core.cql.DefaultBatchType;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.cql.SimpleStatementBuilder;
import com.datastax.dse.driver.api.core.DseSession;
import com.datastax.oss.driver.api.core.DefaultConsistencyLevel;
import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ScratchPad {
  static final Logger LOGGER = LoggerFactory.getLogger(ScratchPad.class);

  public static User getUserById(DseSession session, 
    UUID userid) throws Exception {
    LOGGER.debug("------Start getUserById------");

    // Create a string to SELECT the user from users based on parameterized userid
	String command = "SELECT * FROM killrvideo.users WHERE userid = ?";
    // Create the SimpleStatement that combines the command with the userid
    SimpleStatement statement = SimpleStatement.newInstance(command, userid);
    // Execute the query string and get the result set
    ResultSet meResultSet = session.execute(statement);
    // Get the row from the result set
    Row meRow = meResultSet.one();
    	
    // Extract all the values from the row and create a User object
    String firstname = meRow.getString("firstname");
    String lastname = meRow.getString("lastname");
    String email = meRow.getString("email");
    Instant createdAt = meRow.getInstant("created_date");
    User user = new User(userid, firstname, lastname, email, createdAt);
   	
    // Return the User object    	
    return user;
  }

  public static void main(String[] args) {
    LOGGER.info("Starting main()...");
    try {
      SessionManagement.initSession();
      DseSession session = SessionManagement.getSession();
    
      //-----------------------------------------------------------------------------
      // TBD: Be sure to replace the UUID in the next line with one from your users table
      //-----------------------------------------------------------------------------
      User user = getUserById(session, UUID.fromString("e44187ef-bdfd-43ca-9702-5931146001c8"));
      LOGGER.info("email = " + user.getEmail());
      LOGGER.info("first name = " + user.getFirstname());
      LOGGER.info("last name = " + user.getLastname());
      LOGGER.info("created date = " + user.getCreatedAt());
    }
    catch (Exception e) { e.printStackTrace(); }
    finally { SessionManagement.closeSession(); }
    System.exit(0);
  }
}

5) Rerun the test. Now that you have added the code to getUserById(), try running the test again. If you have implemented the method correctly, you should see output like the following:

6) Move the getUserById() method to production. Once you have getUserById() working in the scratchpad project, copy the method over to the UserAccess class in the killrvideo project (killrvideo/src/main/java/killrvideo/dataLayer/UserAccess.java) - replacing the method stub with the full method. Be sure to keep the code you wrote in the previous exercise for the getAuthenticatedIdByEmailPassword() method.

Did you get stuck and need to see the final source for UserAccess.java? Click here.
package killrvideo.dataLayer;

import java.io.File;
import java.util.UUID;
import java.time.Instant;

import com.datastax.oss.driver.api.core.cql.BatchStatement;
import com.datastax.oss.driver.api.core.cql.BoundStatement;
import com.datastax.oss.driver.api.core.cql.DefaultBatchType;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.cql.SimpleStatementBuilder;
import com.datastax.dse.driver.api.core.DseSession;
import com.datastax.oss.driver.api.core.DefaultConsistencyLevel;
import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import killrvideo.entity.User;

public class UserAccess {

  private static final Logger LOGGER = LoggerFactory.getLogger(UserAccess.class);
  
  public static boolean createNewUser(DseSession session, 
    String password, User user) throws Exception {
    LOGGER.debug("------Start createNewUser------");
    return false;
  }

  public static UUID getAuthenticatedIdByEmailPassword(DseSession session,
    String email, String password) throws Exception {
    LOGGER.debug("------Start getAuthenticatedIdByEmailPassword------");

    //-----------------------------------------------------------------------------
	// Create a string to SELECT the user from user_credentials based on email
	// TBD: Create the SELECT command string that selects from user_credentials:
    //-----------------------------------------------------------------------------
    String command = "SELECT * FROM killrvideo.user_credentials WHERE email = ?";
    // Create the SimpleStatement that combines the command with the email:
    SimpleStatement statement = SimpleStatement.newInstance(command, email);
	// Execute the statement and get the result set
	ResultSet meResultSet = session.execute(statement);
	// Get the row from the result set
	Row meRow = meResultSet.one();
	// Create a UUID for the returned user ID and initialize it to null
	UUID userId = null;
	// If the row exists,
	if (meRow != null) {
		// Get the password value from the row
		String passwordFromDB = meRow.getString("password");
		// If the password value from the row equals password parameter,
		if (password.equals(passwordFromDB)) {
			// Set the returned user ID to the row’s user ID
			userId = meRow.getUuid("userid");
		}
	}

	// Return the user ID
	return userId;
  }

  public static User getUserById(DseSession session, 
    UUID userid) throws Exception {
    LOGGER.debug("------Start getUserById------");

    // Create a string to SELECT the user from users based on parameterized userid
	String command = "SELECT * FROM killrvideo.users WHERE userid = ?";
    // Create the SimpleStatement that combines the command with the userid
    SimpleStatement statement = SimpleStatement.newInstance(command, userid);
    // Execute the query string and get the result set
    ResultSet meResultSet = session.execute(statement);
    // Get the row from the result set
    Row meRow = meResultSet.one();
    	
    // Extract all the values from the row and create a User object
    String firstname = meRow.getString("firstname");
    String lastname = meRow.getString("lastname");
    String email = meRow.getString("email");
    Instant createdAt = meRow.getInstant("created_date");
    User user = new User(userid, firstname, lastname, email, createdAt);
   	
    // Return the User object    	
    return user;
  }
}

7) Bounce the server. Now, bounce the server again and try to login with valid credentials.

If it works correctly, you will see something like the following with your first and last name in the top-right corner:

Be sure to sign out of the website before continuing.

Congrats! You have implemented the first step of the KillrVideo application! 

END OF EXERCISE

No FAQs.

Retrieving user information: define a method to retrieve user information for logging in to your KillrVideo instance.

Comments are closed.