package protocol;
import general.XssHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import domain.Role;
import domain.User;
/**
* This class represent a query for user register
* @author Yury Michurin
*
*/
public class UserRegisterQuery extends Query {
private static final long serialVersionUID = -8807046708617583816L;
private String username;
private String password;
private String fullname;
public UserRegisterQuery() {} // required for Gson
@Override
protected Response internalExecute(HttpServletRequest request, Session databaseSession) {
Response response = null;
User user = null;
HttpSession httpSession = request.getSession();
if( null != httpSession.getAttribute("currentUser") ) {
return new Response(ResponseStatus.FAIL, "You are already logged-in");
}
try {
// wow, how unnecessary is to store roles in the database...
Criteria userRoleCriteria = databaseSession.createCriteria(Role.class).add(Restrictions.eq("description", "User"));
Role userRole = (Role) userRoleCriteria.uniqueResult();
if (userRole == null) {
return new Response(ResponseStatus.FAIL, "User role does not exist, database failure.");
}
this.username = XssHandler.escape(this.username);
this.fullname = XssHandler.escape(this.fullname);
user = new User();
user.setRole(userRole);
user.setFullname(fullname);
user.setPassword(password);
user.setUsername(username);
Transaction transaction = databaseSession.beginTransaction();
try {
databaseSession.save(user);
transaction.commit();
// All was ok
response = new Response(ResponseStatus.OK);
// "LogIn" the user to the session
httpSession.setAttribute("currentUser", user);
} catch(Exception transEx) {
transaction.rollback();
response = new Response(ResponseStatus.FAIL, transEx.toString());
}
} catch (Exception ex) {
// if there was an error, it'll be set here.
response = new Response(ResponseStatus.FAIL, ex.toString());
}
return response;
}
}