2

I'm trying to create a user object with ALL of the users fields after a user logs in so that I may retrieve any given attributes from the user's class. Here's the User class.

public class User  {

private String username;
private String password;
private String f_name;
private String l_name;
private String email;
private String dob;
private int user_id;

public User(){}

public User(String username, String password)
{
    this.username = username;
    this.password = password;
}

public User(String username, String password, String f_name, String l_name, String email, String dob, int user_id)
{
    this.f_name = f_name;
    this.l_name = l_name;
    this.username = username;
    this.password = password;
    this.email = email;
    this.dob = dob;
    this.user_id = user_id;
}

I have getters and setters for all of the fields. All users fields are also stored in an Oracle database.

In my Java Servlet, I have the following code to create a User object and set the session attributes:

HttpSession session = request.getSession();

String username = request.getParameter("username").toString();
String password = request.getParameter("password").toString();

User user1 = new User(username, password);

session.setAttribute("username", username);
session.setAttribute("password", password);

How can I create a user object with ALL of the user's fields based on only the username and password?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
user2297666
  • 321
  • 2
  • 6
  • 20
  • 3
    You already answered your own question: *How can I create a user object based on only the username and password?* using `User user1 = new User(username, password);`. Also, **do not store password in session**. – Luiggi Mendoza Jul 03 '13 at 14:30
  • You already created it: `User user1 = new User(username, password);` Or I'm misuderstanding you.. – Maroun Jul 03 '13 at 14:31
  • I'm trying to create an object which contains ALL of the fields, based on the username and password – user2297666 Jul 03 '13 at 14:31
  • @LuiggiMendoza Not to mention in the database. – Bill the Lizard Jul 03 '13 at 14:31
  • @user2297666 you should have a class that holds the business logic for login using the `User` object reference and the `username` and `password` fields. If the user is authenticated and validated, then it should return a **new** `User` object reference that contains all the data: `f_name`, `l_name`, `email`... and the `username` except the `password` and **this should be the object that you should save as session attribute**. – Luiggi Mendoza Jul 03 '13 at 14:34
  • Not sure, where these values are...are these values stored in the database...which you need to retrieve...or are these values provided by the user, just like the username and password? – IndianNoob Jul 03 '13 at 14:43
  • That's exactly what I'm trying to do, I just don't know how to do it – user2297666 Jul 03 '13 at 14:43
  • The values are stored in the database, I need to retrieve them so that I can set them into my session – user2297666 Jul 03 '13 at 14:44

3 Answers3

5

You should have:

  • A class that holds the business logic for login using the User object reference and the username and password fields.
  • If the user is authenticated and validated, then it should return a new User object reference that contains all the data: f_name, l_name, email... and the username except the password. This should be the object that you should save as session attribute.
  • If the user has give wrong credentials, then you should show an error message.

A basic code example:

public class YourServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String username = request.getParameter("username").toString();
        String password = request.getParameter("password").toString();
        User user = new User(username, password);
        UserBL userBL = new UserBL();
        user = userBL.validateUser(user);
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
        } else {
            request.setAttribute("errorMessage", "User is not valid.");
        }
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}

public class UserBL {
    String hashPassword(String password) {
        //method to hash the password for security purposes
        //for simplicity, just returning the same String
        return password;
    }

    public User validateUser(User user) {
        UserDAO userDao = new UserDAO();
        //password should not be stored in plainText
        //so let's hash it
        String password = hashPassword(user.getPassword());
        return userDao.getUserFromCredentials(user.getUsername(), password);
    }
}

public class UserDAO {
    public User getUserFromCredentials(String username, String password) {
        //probably a query
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;
        try {
            con = ... //retrieve your database connection
            //pretty basic query example, yours should be more secure
            pstmt = con.prepareStatement("SELECT f_name, l_name, email, ... FROM users"
                + " WHERE username = ? AND password = ?");
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                user = new User(rs.getString("f_name"), rs.getString("l_name"),
                    rs.getString("email"), ...);
            }
        } catch (Exception e) {
            //handle the exception
            e.printStacktrace();
        } finally {
            //close the resources
            try {
                rs.close();
                pstmt.close();
                con.close();
            } catch (SQLException e) {
                //handle the exception
                e.printStacktrace();
            }
        }
        return user;
    }
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • What does BL stand for in UserBL? – user2297666 Jul 03 '13 at 15:06
  • 1
    @user2297666 BL = Business Logic. DAO = Data Access Object. You can change the names of the classes as you please. – Luiggi Mendoza Jul 03 '13 at 15:08
  • What if we add password hash? For example using BCrypt (so we do not need to provide salt explicitly, just hash). Do I need to provide User class with password field and store there plain text password or with passHash and store there hash? Maybe I need to have them both in User class? – Sabine Jan 23 '17 at 14:48
  • 1
    @Sabine you store the password hashed. When you go check against database, before sending the raw password, you hash it in the service layer (or any other layer on top of this dao). Let me update this example in the code. – Luiggi Mendoza Jan 23 '17 at 14:51
  • Ok, so now I see. I keep hash in DB and plain text password in User object. Thank you. – Sabine Jan 23 '17 at 15:04
0

Just write f_name = ""; or something simular for all fields in the constructor. It will create all those fields as empty strings.

Chenab
  • 93
  • 8
0

This is typically the way database-backed username/password authentication works:

  1. Get the username and password from the user.
  2. Use the username as a key to load the user records from the database.
  3. Compare the given password to the stored password. Or better, hash the given password and compare to a stored DB hash, since storing passwords in cleartext in the DB is NOT recommended.
  4. If given password (hash) is equal to stored password (hash), allow user to continue onward.
lreeder
  • 12,047
  • 2
  • 56
  • 65