Package com.arrgsocal.servlets

Source Code of com.arrgsocal.servlets.RegisterServlet

package com.arrgsocal.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.arrgsocal.entities.ArrgError;
import com.arrgsocal.entities.Group;
import com.arrgsocal.entities.User;
import com.arrgsocal.managers.GroupManager;
import com.arrgsocal.managers.UserManager;

/**
* Servlet implementation class RegisterServlet
*/
@WebServlet(description = "For registering a user", urlPatterns = { "/register" })
public class RegisterServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  private static final String USERNAME_REGEX = "[a-zA-Z0-9]{6,20}";
  private static final String PASSWORD_REGEX = "([!,\\w\\.\\?]){8,20}";

  @EJB
  UserManager userManager;
  @EJB
  GroupManager groupManager;

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request,
        response);
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    try {
      String username = request.getParameter("username");
      String password = request.getParameter("password");
      String passConf = request.getParameter("confirm");
      boolean fail = false;
      List<ArrgError> errors = null;

      // Make sure all fields are filled in
      if (username == null || username.isEmpty()) {
        if (errors == null) {
          errors = new ArrayList<ArrgError>();
        }

        ArrgError error = new ArrgError();
        error.setMessage("Username is required");
        errors.add(error);
        fail = true;
      }

      // Check the username against the regex
      if (!username.matches(USERNAME_REGEX)) {
        if (errors == null) {
          errors = new ArrayList<ArrgError>();
        }

        ArrgError error = new ArrgError();
        error.setMessage("Username isn't valid. It must be between 6 and 20 characters and consist of only a-z and 0-9");
        errors.add(error);
        fail = true;
      }

      if (password == null || password.isEmpty()) {
        if (errors == null) {
          errors = new ArrayList<ArrgError>();
        }

        ArrgError error = new ArrgError();
        error.setMessage("Password is required");
        errors.add(error);
        fail = true;
      }

      if (!password.matches(PASSWORD_REGEX)) {
        if (errors == null) {
          errors = new ArrayList<ArrgError>();
        }

        ArrgError error = new ArrgError();
        error.setMessage("Password isn't valid. Must be 8-20 of the following characters: a-z 0-9 , ! ? .");
        errors.add(error);
        fail = true;
      }

      if (passConf == null || !passConf.equals(password)) {
        if (errors == null) {
          errors = new ArrayList<ArrgError>();
        }

        ArrgError error = new ArrgError();
        error.setMessage("Password and confirmation don't match");
        errors.add(error);
        fail = true;
      }

      // Send back if there were any errors
      if (fail) {
        request.setAttribute("errors", errors);
        System.out
            .println("[[DEBUG]] Errors occured, going back to JSP");
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(
            request, response);
        return;
      }

      // Check for duplicate registration
      List<User> users = userManager.getUsers();
      for (User u : users) {
        System.out.println("[[DEBUG]] Checking " + username
            + " against " + u.getName());
        if (u.getName().equals(username)) {
          if (errors == null) {
            errors = new ArrayList<ArrgError>();
          }
          ArrgError error = new ArrgError();
          error.setMessage("An account already exists with that username");
          errors.add(error);
          request.setAttribute("duplicate", true);
          System.out
              .println("[[DEBUG]] Duplicate user, going back to JSP");
          request.getRequestDispatcher("/registerPage.jsp").forward(
              request, response);
          return;
        }
      }

      // Create the user
      User u = new User();
      u.setName(username);
      u.setClearPassword(password);

      // And the user to the "users" group, create if needed
      List<Group> groups = groupManager.getGroups();
      if (groups == null || groups.isEmpty() || groups.size() == 0) {
        Group userGroup = new Group();
        userGroup.setName("users");
        userManager.create(u, userGroup);
      } else {
        for (Group g : groups) {
          if (g.getName().equals("users")) {
            userManager.createWithExistingGroup(u, g);
          }
        }
      }

      // Get/Create the session as needed
      HttpSession session = request.getSession(false);
      if (session != null) {
        request.logout();
        session.invalidate();
        session = request.getSession(true);
      } else {
        session = request.getSession(true);
      }

      // Log the user in and send them to their control panel
      request.login(username, password);
      session.setAttribute("currentUser", u);
      response.sendRedirect(response.encodeRedirectURL("me"));
    } catch (ServletException e) {
      List<ArrgError> errors = new ArrayList<>();
      ArrgError error = new ArrgError();
      error.setMessage("Couldn't log you in, please try again");
      errors.add(error);
      request.setAttribute("errors", errors);
      request.getSession().invalidate();
      request.getRequestDispatcher("login").forward(request, response);
    }
  }
}
TOP

Related Classes of com.arrgsocal.servlets.RegisterServlet

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.