package protocol;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import domain.User;
/**
* This class represent a query for login a user to the system
* @author Yury Michurin
*
*/
public class UserLoginQuery extends Query {
private static final long serialVersionUID = -8372020796782406526L;
private String username;
private String password;
/**
* Checks if some user is already logged-in to the system,
* if not - login the user.
*/
@Override
protected Response internalExecute(HttpServletRequest request, Session databaseSession) {
Response response = null;
User user = null;
HttpSession httpSession = request.getSession();
// Checks if some user is already logged-in to the system
if( null != httpSession.getAttribute("currentUser") ) {
return new Response(ResponseStatus.FAIL, "You are already logged-in");
}
try {
user = (User) databaseSession.createCriteria(User.class).add(Restrictions.eq("username", this.username)).uniqueResult();
if (null != user && user.getUsername().equals(this.username) && user.getPassword().equals(this.password)) { // user exists and password match
// "LogIn" the user to the session
httpSession.setAttribute("currentUser", user);
response = new Response(ResponseStatus.OK);
} else { // user does not exists
response = new Response(ResponseStatus.FAIL, "Bad user password combination!");
}
} catch (HibernateException ex) {
// if there was an error, it'll be set here.
response = new Response(ResponseStatus.FAIL, ex.toString());
}
// return the response
return response;
}
}