Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getUserPrincipal.

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("users/me")
@GET/*from  ww  w  .  j a v a2 s. c  om*/
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getUser(@Context HttpServletRequest request) throws GoogleUserInfoException {
    String googleUserId = request.getUserPrincipal().getName();
    Users user = this.dao.getUserByGoogleId(googleUserId);
    String accessToken = (String) request.getAttribute("accessToken");
    GoogleUserInfo gui = this.dao.getGoogleUserInfo("Bearer " + accessToken);
    //       user.setRefreshToken(null);
    //       GenericEntity<CombinedUser> entity = new GenericEntity<CombinedUser>(new CombinedUser(gui, user)){};
    ////       throw new RuntimeException(entity);
    //       gui.setEmail(null);
    //       gui.setFamilyName(null);
    //       gui.setGender(null);
    //       gui.setGivenName(null);
    //       gui.setLink(null);
    //       gui.setLocale(null);
    //       gui.setName(null);
    //       gui.setPicture(null);

    //       return Response.ok().entity(user).build();
    return Response.ok().entity(new CombinedUser(gui, user)).build();
    //       String accessToken = (String)request.getAttribute("accessToken");
    //       GoogleUserInfo gui = dao.getGoogleUserInfo("Bearer", accessToken);
    //        GenericEntity<GoogleUserInfo> entity = new GenericEntity<GoogleUserInfo>(gui){};
    //        throw new RuntimeException(gui.toString());
    //        return Response.ok().entity(gui).build();// there is an error here
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("stockNumbers/{id}")
@DELETE//from w w w .  j a v  a  2 s.co  m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
public Response deleteStockNumber(@Context HttpServletRequest request,
        @DefaultValue("0") @PathParam("id") Integer id) {
    String googleUserId = request.getUserPrincipal().getName();
    if (!this.dao.userHasRightsToStockNumberId(id, googleUserId))
        return Response.status(400)
                .entity(new ErrorMessage("You do not have rights to alter this stock number")).build();

    if (id != 0)
        return Response.ok().entity(this.dao.deleteStockNumberById(id)).build();
    return Response.status(400).entity(new ErrorMessage("You must specify a valid id to delete")).build();
}

From source file:it.volaconnoi.servlet.BookingServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w  ww.  ja va2  s. c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userPath = request.getServletPath();

    session = request.getSession(true);

    if (userPath.equals("/confirm")) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String name = request.getParameter("name");
        String surname = request.getParameter("surname");
        String address = request.getParameter("address");
        String city = request.getParameter("city");
        String zip_code = request.getParameter("zip_code");
        String country = request.getParameter("country");
        String mobilenumber_code = request.getParameter("mobilenumber_code");
        String mobilenumber = request.getParameter("mobilenumber");
        String passengers = request.getParameter("passengers");
        String luggages = request.getParameter("luggages");

        Route route = (Route) session.getAttribute("route");

        if (request.getUserPrincipal() == null) //se l'utente non  loggato crealo ed inseriscilo nella sessione
        {
            UserCredential user = new UserCredential();

            user.setUsername(username);
            user.setPassword(utilBean.hashPassword(password));
            user.setEmail(email);
            user.setName(name);
            user.setSurname(surname);
            user.setAddress(address);
            user.setCity(city);
            user.setZip_code(zip_code);
            user.setCountry(country);
            user.setFidelity_points(0);

            user.setPhoneNumbers(new LinkedList<PhoneNumber>());

            user.getPhoneNumbers().add(new PhoneNumber("Mobile", mobilenumber_code, mobilenumber));

            user.setReservationsList(new LinkedList<Reservation>());

            session.setAttribute("user", user);
        }

        session.setAttribute("passengers", Integer.parseInt(passengers));
        session.setAttribute("luggages", Integer.parseInt(luggages));

        session.setAttribute("price", (double) (route.getPrice() * Integer.parseInt(passengers)
                + Integer.parseInt(luggages) * PricerBeanInterface.TAX));

        request.getRequestDispatcher("/WEB-INF/view/booking/confirm.jsp").forward(request, response);
    }

    if (userPath.equals("/commit")) {
        String id_committed_reservation;
        String points = null;

        if (StringUtils.isNotEmpty(request.getParameter("points"))) {
            points = request.getParameter("points");
        } else {
            points = "0";
        }

        double final_price = pricerBean.calculateDiscountPrice((Double) session.getAttribute("price"),
                Integer.parseInt(points));

        id_committed_reservation = bookingBean.purchase((Route) session.getAttribute("route"),
                (UserCredential) session.getAttribute("user"), (Integer) session.getAttribute("passengers"),
                (Integer) session.getAttribute("luggages"), final_price, Integer.parseInt(points));

        if (StringUtils.isNotEmpty(id_committed_reservation)) {
            request.setAttribute("id_reservation", id_committed_reservation);

            session.removeAttribute("user");
            session.removeAttribute("route");
            session.removeAttribute("passengers");
            session.removeAttribute("luggages");
            session.removeAttribute("price");

            request.getRequestDispatcher("/WEB-INF/view/booking/success.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("/WEB-INF/view/booking/error.jsp").forward(request, response);
        }
    }
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("dealerships/{dealershipId}") // works 10/13
@GET/*from www.  j  av a2  s  . c  om*/
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) // working 10/3/13
public Response getAllDealerships(@Context HttpServletRequest request,
        @DefaultValue("0") @PathParam("dealershipId") Integer dealershipId) {
    String googleUserId = request.getUserPrincipal().getName();
    if (dealershipId == 0)
        return Response.status(400).entity(new ErrorMessage("You must specify a dealership id")).build();

    int userType = this.dao.getUserByGoogleId(googleUserId).getType();
    if (userType > 2)
        return Response.ok(this.dao.getDealershipById(dealershipId)).build();

    return Response.status(401)
            .entity(new ErrorMessage("You dont have rights to this, need a userType > 2, you have " + userType))
            .build();
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("stockNumbers/{id}")
@GET//from ww w .  j  av a2 s . c  o  m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getStockNumberById(@Context HttpServletRequest request,
        @DefaultValue("0") @PathParam("id") Integer id) throws NoResultInResultSet {
    String googleUserId = request.getUserPrincipal().getName();
    if (!this.dao.userHasRightsToStockNumberId(id, googleUserId))
        return Response.status(400)
                .entity(new ErrorMessage("You do not have rights to alter this stock number")).build();

    return Response.ok().entity(this.dao.getStockNumberById(id)).build();
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("users") // works 2-6-14
@GET//from  ww w  .  ja  va2s .  c  om
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getAllUsers(@Context HttpServletRequest request,
        @DefaultValue("0") @QueryParam("dealershipId") Integer dealershipId) {
    String googleUserId = request.getUserPrincipal().getName();
    if (dealershipId != 0) {
        GenericEntity<List<Users>> entity = new GenericEntity<List<Users>>(
                this.dao.getUsersForDealershipId(dealershipId)) {
        };
        return Response.ok(entity).build();
    }
    Users user = this.dao.getUserByGoogleId(googleUserId);
    if (user.getType() > 1) {
        GenericEntity<List<Users>> entity = new GenericEntity<List<Users>>(this.dao.getAllUsers()) {
        };
        return Response.ok(entity).build();
    }
    throw new RuntimeException(
            "invalid user type, your type must be more than 1 to get all users, you are: " + user.toString());
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("dealerships") // works 10/13
@GET/*from www.ja  va2 s  .co m*/
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) // working 10/3/13
public Response getAllDealerships(@Context HttpServletRequest request,
        @DefaultValue("") @QueryParam("dealershipCode") String dealershipCode) {
    String googleUserId = request.getUserPrincipal().getName();
    if (dealershipCode.length() != 0)
        return Response.ok(this.dao.getDealershipWithDealershipCode(dealershipCode)).build();

    int userType = this.dao.getUserByGoogleId(googleUserId).getType();
    if (userType > 2) {
        GenericEntity<List<Dealerships>> entity = new GenericEntity<List<Dealerships>>(
                this.dao.getAllDealerships()) {
        };
        return Response.ok(entity).build();
    }
    return Response.status(401)
            .entity(new ErrorMessage("You dont have rights to this, need a userType > 2, you have " + userType))
            .build();
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (bypassAuth((HttpServletRequest) request)) {
        chain.doFilter(request, response);
        return;/*from   ww  w .j  ava  2 s .c  o  m*/
    }

    String tokenPage = getRequestedPage(request);
    if (tokenPage.equals(SWITCH_USER_PAGE)) {
        boolean result = switchUser(request, response, chain);
        if (result) {
            return;
        }
    }

    if (request instanceof NuxeoSecuredRequestWrapper) {
        log.debug("ReEntering Nuxeo Authentication Filter ... exiting directly");
        chain.doFilter(request, response);
        return;
    } else if (service.canBypassRequest(request)) {
        log.debug("ReEntering Nuxeo Authentication Filter after URL rewrite ... exiting directly");
        chain.doFilter(request, response);
        return;
    } else {
        log.debug("Entering Nuxeo Authentication Filter");
    }

    String targetPageURL = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Principal principal = httpRequest.getUserPrincipal();

    NuxeoAuthenticationPropagator.CleanupCallback propagatedAuthCb = null;

    try {
        if (principal == null) {
            log.debug("Principal not found inside Request via getUserPrincipal");
            // need to authenticate !

            // retrieve user & password
            CachableUserIdentificationInfo cachableUserIdent;
            if (avoidReauthenticate) {
                log.debug("Try getting authentication from cache");
                cachableUserIdent = retrieveIdentityFromCache(httpRequest);
            } else {
                log.debug("Principal cache is NOT activated");
            }

            if (cachableUserIdent != null && cachableUserIdent.getUserInfo() != null
                    && service.needResetLogin(request)) {
                HttpSession session = httpRequest.getSession(false);
                if (session != null) {
                    session.removeAttribute(USERIDENT_KEY);
                }
                // first propagate the login because invalidation may
                // require
                // an authenticated session
                propagatedAuthCb = service.propagateUserIdentificationInformation(cachableUserIdent);
                // invalidate Session !
                try {
                    service.invalidateSession(request);
                } finally {
                    if (propagatedAuthCb != null) {
                        propagatedAuthCb.cleanup();
                        propagatedAuthCb = null;
                    }
                }
                // TODO perform logout?
                cachableUserIdent = null;
            }

            // identity found in cache
            if (cachableUserIdent != null && cachableUserIdent.getUserInfo() != null) {
                log.debug("userIdent found in cache, get the Principal from it without reloggin");

                NuxeoHttpSessionMonitor.instance().updateEntry(httpRequest);

                principal = cachableUserIdent.getPrincipal();
                log.debug("Principal = " + principal.getName());
                propagatedAuthCb = service.propagateUserIdentificationInformation(cachableUserIdent);

                String requestedPage = getRequestedPage(httpRequest);
                if (LOGOUT_PAGE.equals(requestedPage)) {
                    boolean redirected = handleLogout(request, response, cachableUserIdent);
                    cachableUserIdent = null;
                    principal = null;
                    if (redirected && httpRequest.getParameter(FORM_SUBMITTED_MARKER) == null) {
                        return;
                    }
                } else if (LOGIN_PAGE.equals(requestedPage)) {
                    if (handleLogin(httpRequest, httpResponse)) {
                        return;
                    }
                } else {
                    targetPageURL = getSavedRequestedURL(httpRequest, httpResponse);
                }
            }

            // identity not found in cache or reseted by logout
            if (cachableUserIdent == null || cachableUserIdent.getUserInfo() == null) {
                UserIdentificationInfo userIdent = handleRetrieveIdentity(httpRequest, httpResponse);
                if (userIdent != null && userIdent.containsValidIdentity()
                        && userIdent.getUserName().equals(getAnonymousId())) {
                    String forceAuth = httpRequest.getParameter(FORCE_ANONYMOUS_LOGIN);
                    if (forceAuth != null && forceAuth.equals("true")) {
                        userIdent = null;
                    }
                }
                if ((userIdent == null || !userIdent.containsValidIdentity()) && !bypassAuth(httpRequest)) {
                    boolean res = handleLoginPrompt(httpRequest, httpResponse);
                    if (res) {
                        return;
                    }
                } else {
                    // restore saved Starting page
                    targetPageURL = getSavedRequestedURL(httpRequest, httpResponse);
                }
                if (userIdent != null && userIdent.containsValidIdentity()) {
                    // do the authentication
                    cachableUserIdent = new CachableUserIdentificationInfo(userIdent);
                    principal = doAuthenticate(cachableUserIdent, httpRequest);
                    if (principal != null && principal != DIRECTORY_ERROR_PRINCIPAL) {
                        // Do the propagation too ????
                        propagatedAuthCb = service.propagateUserIdentificationInformation(cachableUserIdent);
                        // setPrincipalToSession(httpRequest, principal);
                        // check if the current authenticator is a
                        // LoginResponseHandler
                        NuxeoAuthenticationPlugin plugin = getAuthenticator(cachableUserIdent);
                        if (plugin instanceof LoginResponseHandler) {
                            // call the extended error handler
                            if (((LoginResponseHandler) plugin).onSuccess((HttpServletRequest) request,
                                    (HttpServletResponse) response)) {
                                return;
                            }
                        }
                    } else {
                        // first check if the current authenticator is a
                        // LoginResponseHandler
                        NuxeoAuthenticationPlugin plugin = getAuthenticator(cachableUserIdent);
                        if (plugin instanceof LoginResponseHandler) {
                            // call the extended error handler
                            if (((LoginResponseHandler) plugin).onError((HttpServletRequest) request,
                                    (HttpServletResponse) response)) {
                                return;
                            }
                        } else {
                            // use the old method
                            String err = principal == DIRECTORY_ERROR_PRINCIPAL ? ERROR_CONNECTION_FAILED
                                    : ERROR_AUTHENTICATION_FAILED;
                            httpRequest.setAttribute(LOGIN_ERROR, err);
                            boolean res = handleLoginPrompt(httpRequest, httpResponse);
                            if (res) {
                                return;
                            }
                        }
                    }

                }
            }
        }

        if (principal != null) {
            if (targetPageURL != null && targetPageURL.length() > 0) {
                // forward to target page
                String baseURL = service.getBaseURL(request);

                // httpRequest.getRequestDispatcher(targetPageURL).forward(new
                // NuxeoSecuredRequestWrapper(httpRequest, principal),
                // response);
                if (XMLHTTP_REQUEST_TYPE.equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
                    // httpResponse.setStatus(200);
                    return;
                } else {
                    httpResponse.sendRedirect(baseURL + targetPageURL);
                    return;
                }

            } else {
                // simply continue request
                chain.doFilter(new NuxeoSecuredRequestWrapper(httpRequest, principal), response);
            }
        } else {
            chain.doFilter(request, response);
        }
    } finally {
        if (propagatedAuthCb != null) {
            propagatedAuthCb.cleanup();
        }
    }
    if (!avoidReauthenticate) {
        // destroy login context
        log.debug("Log out");
        LoginContext lc = (LoginContext) httpRequest.getAttribute("LoginContext");
        if (lc != null) {
            try {
                lc.logout();
            } catch (LoginException e) {
                log.error(e, e);
            }
        }
    }
    log.debug("Exit Nuxeo Authentication filter");
}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

@RequestMapping(value = "/claimDatasets", method = RequestMethod.POST, params = { "claim" })
public String claimDatasets(Model model, HttpServletRequest request, HttpServletResponse response,
        @RequestParam(required = false) String[] ids, @RequestParam String facilityName)
        throws IOException, QueueFileException, InterruptedException {
    GenericPrincipal principal = (GenericPrincipal) request.getUserPrincipal();
    if (principal == null) {
        LOG.error("No principal ... can't proceed");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }/*from  w  w w.  j  a  va2 s. c o m*/
    model.addAttribute("returnTo", inferReturnTo(request));
    if (ids == null) {
        model.addAttribute("facilityName", facilityName);
        model.addAttribute("datasets", getQueueManager().getSnapshot(Slice.HELD, facilityName, true));
        model.addAttribute("message", "Check the checkboxes for the " + "Datasets you want to claim");
        return "claimDatasets";
    }
    if (!principal.hasRole("ROLE_ACLS_USER")) {
        model.addAttribute("message", "You must be logged in using " + "ACLS credentials to claim files");
        return "failed";
    }
    String userName = principal.getName();
    try {
        int nosChanged = getQueueManager().changeUser(ids, userName, false);
        model.addAttribute("message", verbiage(nosChanged, "dataset", "datasets", "claimed"));
        return "ok";
    } catch (NumberFormatException ex) {
        LOG.debug("Rejected request with bad entry id(s)");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

private void populateHeaders(HttpServletRequest request, MessageBuilder<?> builder) {
    Enumeration<?> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            Enumeration<?> headerEnum = request.getHeaders(headerName);
            if (headerEnum != null) {
                List<Object> headers = new ArrayList<Object>();
                while (headerEnum.hasMoreElements()) {
                    headers.add(headerEnum.nextElement());
                }/*  w w  w  .j av  a 2 s  .  c  o m*/
                if (headers.size() == 1) {
                    builder.setHeader(headerName, headers.get(0));
                } else if (headers.size() > 1) {
                    builder.setHeader(headerName, headers);
                }
            }
        }
    }
    builder.setHeader(HttpHeaders.REQUEST_URL, request.getRequestURL().toString());
    builder.setHeader(HttpHeaders.REQUEST_METHOD, request.getMethod());
    builder.setHeader(HttpHeaders.USER_PRINCIPAL, request.getUserPrincipal());
}