List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal
public java.security.Principal getUserPrincipal();
java.security.Principal
object containing the name of the current authenticated user. From source file:edu.emory.cci.aiw.cvrg.eureka.services.resource.UserResource.java
/** * Changes a user's password.//from w w w .ja v a 2s .c om * * @param request the incoming servlet request * @param passwordChangeRequest the request to use to make the password * change * * @throws HttpStatusException Thrown when a password cannot be properly * hashed, or the passwords are mismatched. */ @RolesAllowed({ "researcher", "admin" }) @Path("/passwordchange") @POST public void changePassword(@Context HttpServletRequest request, PasswordChangeRequest passwordChangeRequest) { String username = request.getUserPrincipal().getName(); LocalUserEntity user = this.localUserDao.getByName(username); if (user == null) { LOGGER.error("User " + username + " not found"); throw new HttpStatusException(Response.Status.NOT_FOUND); } else this.localUserDao.refresh(user); String newPassword = passwordChangeRequest.getNewPassword(); String oldPasswordHash; String newPasswordHash; try { oldPasswordHash = StringUtil.md5(passwordChangeRequest.getOldPassword()); newPasswordHash = StringUtil.md5(newPassword); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); throw new HttpStatusException(Response.Status.INTERNAL_SERVER_ERROR, e); } if (user.getPassword().equals(oldPasswordHash)) { user.setPassword(newPasswordHash); user.setPasswordExpiration(this.getExpirationDate()); if (this.properties.getI2b2URL() != null) { this.i2b2Client.changePassword(user.getEmail(), newPassword); } this.localUserDao.update(user); try { this.emailSender.sendPasswordChangeMessage(user); } catch (EmailException ee) { LOGGER.error(ee.getMessage(), ee); } } else { throw new HttpStatusException(Response.Status.BAD_REQUEST, "Error while changing password. Old password is incorrect."); } }
From source file:com.onehippo.gogreen.login.HstConcurrentLoginFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; // NOSONAR: req can always be cast to an HTTP servlet request HttpSession session = request.getSession(false); if (session != null) { String username = (request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null); if (!StringUtils.isBlank(username)) { String usernameInSession = (String) session.getAttribute(USERNAME_ATTR); if (!username.equals(usernameInSession)) { registerUserSession(request, username); } else if (!isMySessionStillValid(session, username)) { log.debug(// w w w. j a v a2 s . c o m "HstConcurrentLoginFilter found another session had been logged in by {}. This session is to be invalidated.", username); session.invalidate(); } } } chain.doFilter(req, res); }
From source file:org.apache.directory.fortress.web.FortressWebBasePage.java
public FortressWebBasePage() { // Build the title bar string. StringBuilder titlebuf = new StringBuilder(); titlebuf.append("Fortress Web Administration"); String szContextId = Config.getInstance().getProperty(GlobalIds.CONTEXT_ID_PROPERTY); // append the tenantId if set if (StringUtils.isNotEmpty(szContextId) && !szContextId.equalsIgnoreCase(org.apache.directory.fortress.core.GlobalIds.HOME)) { titlebuf.append(" : "); titlebuf.append(szContextId);// www . ja va 2s. com } // add it to title bar of page add(new Label(org.apache.directory.fortress.web.common.GlobalIds.TITLE_BAR, titlebuf.toString())); SecureBookmarkablePageLink usersLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.USERS_PAGE, UserPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_USERS); add(usersLink); PageParameters parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.RBAC_TYPE ); SecureBookmarkablePageLink rolesLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.ROLES_PAGE, RolePage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_ROLES); add(rolesLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.ADMIN_TYPE ); SecureBookmarkablePageLink admrolesLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.ADMROLES_PAGE, RoleAdminPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_ADMINROLES); add(admrolesLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.RBAC_TYPE ); SecureBookmarkablePageLink objectsLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.POBJS_PAGE, ObjectPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_PERMOBJS); add(objectsLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.ADMIN_TYPE ); SecureBookmarkablePageLink admobjsLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.ADMPOBJS_PAGE, ObjectAdminPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_ADMINOBJS); add(admobjsLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.RBAC_TYPE ); SecureBookmarkablePageLink permsLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.PERMS_PAGE, PermPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_PERMS); add(permsLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.ADMIN_TYPE ); SecureBookmarkablePageLink admpermsLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.ADMPERMS_PAGE, PermAdminPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_ADMINPERMS); add(admpermsLink); SecureBookmarkablePageLink policiesLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.PWPOLICIES_PAGE, PwPolicyPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_POLICIES); add(policiesLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.SSD ); SecureBookmarkablePageLink ssdsLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.SSDS_PAGE, SdStaticPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_SSDS); add(ssdsLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.DSD ); SecureBookmarkablePageLink dsdsLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.DSDS_PAGE, SdDynamicPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_DSDS); add(dsdsLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.USEROUS ); SecureBookmarkablePageLink userouLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.USEROUS_PAGE, OuUserPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_USEROUS); add(userouLink); parameters = new PageParameters(); //parameters.set( GlobalIds.PAGE_TYPE, "PERMOUS" ); SecureBookmarkablePageLink permouLink = new SecureBookmarkablePageLink( org.apache.directory.fortress.web.common.GlobalIds.PERMOUS_PAGE, OuPermPage.class, parameters, org.apache.directory.fortress.web.common.GlobalIds.ROLE_PERMOUS); add(permouLink); add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.GROUP_PAGE, GroupPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_GROUPS)); add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.AUDIT_BINDS_PAGE, AuditBindPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_AUDIT_BINDS)); add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.AUDIT_AUTHZS_PAGE, AuditAuthzPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_AUDIT_AUTHZS)); add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.AUDIT_MODS_PAGE, AuditModPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_AUDIT_MODS)); add(new Label("footer", "Copyright (c) 2003-2016, The Apache Software Foundation. All Rights Reserved.")); final Link actionLink = new Link("logout") { /** Default serialVersionUID */ private static final long serialVersionUID = 1L; @Override public void onClick() { setResponsePage(LogoutPage.class); } }; add(actionLink); HttpServletRequest servletReq = (HttpServletRequest) getRequest().getContainerRequest(); // RBAC Security Processing: Principal principal = servletReq.getUserPrincipal(); // Is this a Java EE secured page && has the User successfully authenticated already? boolean isSecured = principal != null; if (isSecured && !isLoggedIn()) { // Here the principal was created by fortress realm and is a serialized instance of {@link Session}. String szPrincipal = principal.toString(); Session session = null; String szIsJetty = System .getProperty(org.apache.directory.fortress.web.common.GlobalIds.IS_JETTY_SERVER); boolean isJetty = false; if (StringUtils.isNotEmpty(szIsJetty)) { if (szIsJetty.equalsIgnoreCase("true")) { isJetty = true; } } if (!isJetty) { try { // Deserialize the principal string into a fortress session: session = j2eePolicyMgr.deserialize(szPrincipal); } catch (SecurityException se) { // Can't recover.... throw new RuntimeException(se); } } // If this is null, it means this app cannot share an rbac session with container and must now (re)create session here: if (session == null) { session = SecUtils.createSession(accessMgr, principal.getName()); } // Now load the fortress session into the Wicket session and let wicket hold onto that for us. Also retreive the arbac perms from server and cache those too. synchronized ((WicketSession) WicketSession.get()) { SecUtils.loadPermissionsIntoSession(delAccessMgr, session); } } }
From source file:org.nuxeo.ecm.platform.web.common.exceptionhandling.NuxeoSecurityExceptionHandler.java
@Override public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t) throws IOException, ServletException { Throwable unwrappedException = unwrapException(t); if (!ExceptionHelper.isSecurityError(unwrappedException)) { super.handleException(request, response, t); return;/*from w ww . ja v a 2 s .com*/ } Principal principal = request.getUserPrincipal(); if (principal instanceof NuxeoPrincipal) { NuxeoPrincipal nuxeoPrincipal = (NuxeoPrincipal) principal; if (nuxeoPrincipal.isAnonymous()) { // redirect to login than to requested page if (handleAnonymousException(request, response)) { return; } } } // go back to default handler super.handleException(request, response, t); }
From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java
private String getUsername(HttpServletRequest request) { String username = request.getRemoteUser(); if (username == null) { Principal principal = request.getUserPrincipal(); if (principal != null) { username = principal.getName(); }// w w w . j ava 2 s . co m } return username; }
From source file:org.apache.axis2.jaxws.context.WebServiceContextImpl.java
public Principal getUserPrincipal() { // Note that the MessageContext might not be set up yet, or it // may have been released because the lifetime of the WebServiceContext is completed. if (log.isDebugEnabled()) { if (soapMessageContext == null) { log.debug("The MessageContext is not available"); }/*w w w. j ava2 s . c om*/ } if (soapMessageContext != null) { HttpServletRequest request = (HttpServletRequest) soapMessageContext .get(MessageContext.SERVLET_REQUEST); if (request != null) { if (log.isDebugEnabled()) { log.debug("Access to the user Principal was requested."); } return request.getUserPrincipal(); } else { if (log.isDebugEnabled()) { log.debug("No HttpServletRequest object was found, so no Principal can be found."); } } } return null; }
From source file:org.opendaylight.controller.web.DaylightWeb.java
@RequestMapping(value = "web.json") @ResponseBody// ww w . j a v a2s .c om public Map<String, Map<String, Object>> bundles(HttpServletRequest request) { Object[] instances = ServiceHelper.getGlobalInstances(IDaylightWeb.class, this, null); Map<String, Map<String, Object>> bundles = new HashMap<String, Map<String, Object>>(); Map<String, Object> entry; IDaylightWeb bundle; String username = request.getUserPrincipal().getName(); IUserManager userManger = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); for (Object instance : instances) { bundle = (IDaylightWeb) instance; if (userManger != null && bundle.isAuthorized(userManger.getUserLevel(username))) { entry = new HashMap<String, Object>(); entry.put("name", bundle.getWebName()); entry.put("order", bundle.getWebOrder()); bundles.put(bundle.getWebId(), entry); } } return bundles; }
From source file:org.rti.zcore.dar.struts.action.HomeAction.java
/** * Build the ZEPRS home page, incorporating the search interface/results * if it's a report-only user, send to reports * otherwise, send to permissions page.//from w w w . ja va2s. c o m * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return Action to forward to * @throws Exception if an input/output error or servlet exception occurs */ protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Principal user = request.getUserPrincipal(); String username = user.getName(); Integer maxRows = 0; Integer offset = 0; Integer prevRows = 0; Integer nextRows = 0; Connection conn = null; try { conn = DatabaseUtils.getZEPRSConnection(username); if (request.isUserInRole("VIEW_INDIVIDUAL_PATIENT_RECORDS") || request.isUserInRole("CREATE_NEW_PATIENTS_AND_SEARCH")) { String searchStringRequest = request.getParameter("search_string"); String firstSurname = request.getParameter("first_surname"); // used in a-z search String labour = request.getParameter("labour"); // used in a-z search String searchType = "keyword"; String searchString = ""; if (searchStringRequest == null) { searchString = ""; } else { searchString = searchStringRequest.trim().toLowerCase(); } if (firstSurname != null && !firstSurname.equals("")) { searchType = "firstSurname"; searchString = firstSurname; request.setAttribute("firstSurname", firstSurname); } request.setAttribute("searchString", searchString); String patientSiteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString(); request.setAttribute("patientSiteId", patientSiteId); String site = request.getParameter("site"); request.setAttribute("site", site); if (site != null) { if (site.equals("")) { site = patientSiteId; } } if (request.getParameter("maxRows") != null) { maxRows = Integer.decode(request.getParameter("maxRows")); } else if (request.getAttribute("maxRows") != null) { maxRows = Integer.decode(request.getAttribute("maxRows").toString()); } else { maxRows = 20; } if (request.getParameter("offset") != null) { offset = Integer.decode(request.getParameter("offset")); } else if (request.getAttribute("offset") != null) { offset = Integer.decode(request.getAttribute("offset").toString()); } if (request.getParameter("prevRows") != null) { prevRows = Integer.decode(request.getParameter("prevRows")); offset = prevRows; } else if (request.getAttribute("prevRows") != null) { prevRows = Integer.decode(request.getAttribute("prevRows").toString()); offset = prevRows; } if (request.getParameter("nextRows") != null) { nextRows = Integer.decode(request.getParameter("nextRows")); } else if (request.getAttribute("nextRows") != null) { nextRows = Integer.decode(request.getAttribute("nextRows").toString()); } if (site == null) { site = patientSiteId; } List results = null; results = PatientSearchDAO.getResults(conn, site, searchString, offset, maxRows, searchType, 0, username); request.setAttribute("results", results); request.setAttribute("maxRows", maxRows); nextRows = offset + maxRows; if (results.size() < maxRows) { if (offset == 0) { request.setAttribute("noNavigationWidget", "1"); } } else { request.setAttribute("offset", nextRows); } if (offset - maxRows >= 0) { prevRows = offset - maxRows; request.setAttribute("prevRows", prevRows); } request.setAttribute("nextRows", nextRows); SessionUtil.getInstance(session).setSessionPatient(null); List sites = null; sites = DynaSiteObjects.getClinics();// request.setAttribute("sites", sites); if (SessionUtil.getInstance(request.getSession()).isClientConfigured()) { String sitename = SessionUtil.getInstance(session).getClientSettings().getSite().getName(); request.setAttribute("sitename", sitename); } else { request.setAttribute("sitename", "Configure PC: "); } String fullname = null; try { fullname = SessionUtil.getInstance(session).getFullname(); } catch (SessionUtil.AttributeNotFoundException e) { // ok } //List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn); //List<Task> stockAlertList = PatientRecordUtils.getStockAlerts(); List<Task> stockAlertList = null; if (DynaSiteObjects.getStatusMap().get("stockAlertList") != null) { stockAlertList = (List<Task>) DynaSiteObjects.getStatusMap().get("stockAlertList"); } request.setAttribute("activeProblems", stockAlertList); request.setAttribute("fullname", fullname); if (conn != null && !conn.isClosed()) { conn.close(); conn = null; } return mapping.findForward("success"); } else if (request.isUserInRole("VIEW_SELECTED_REPORTS_AND_VIEW_STATISTICAL_SUMMARIES")) { if (conn != null && !conn.isClosed()) { conn.close(); conn = null; } return mapping.findForward("reports"); } else if (request.isUserInRole("CREATE_MEDICAL_STAFF_IDS_AND_PASSWORDS_FOR_MEDICAL_STAFF")) { if (conn != null && !conn.isClosed()) { conn.close(); conn = null; } // Create user accounts ActionForward fwd = mapping.findForward("admin/records/list"); String path = fwd.getPath(); path += "?formId="; path += "170"; return new ActionForward(path); } } catch (ServletException e) { log.error(e); request.setAttribute("exception", "There is an error generating the Search Results for the Home page. Please stand by - the system may be undergoing maintenance."); return mapping.findForward("error"); } finally { if (conn != null && !conn.isClosed()) { conn.close(); conn = null; } } return mapping.findForward("noPermissions"); }
From source file:com.linuxbox.enkive.web.search.DeleteSearchWebScript.java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { String searchIds = ""; ArrayList<String> failedDeletedSearches = new ArrayList<String>(); searchIds = WebScriptUtils.cleanGetParameter(req, "searchids"); WorkspaceService workspaceService = getWorkspaceService(); Workspace workspace;//from ww w. ja v a2s . c o m try { workspace = workspaceService.getActiveWorkspace(req.getUserPrincipal().getName()); for (String searchId : searchIds.split(",")) { if (!searchId.isEmpty()) { try { workspace.deleteSearchResult(searchIds); SearchResult result = workspace.getSearchResultBuilder().getSearchResult(searchId); result.deleteSearchResult(); if (LOGGER.isDebugEnabled()) LOGGER.debug("deleted search at id " + searchId); } catch (WorkspaceException e) { failedDeletedSearches.add(searchId); } } } workspace.saveWorkspace(); if (!failedDeletedSearches.isEmpty()) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res); throw new IOException("Could not delete searches with UUIDs " + failedDeletedSearches.toString()); } } catch (WorkspaceException e1) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res); throw new IOException("Could not update workspace to remove searches"); } }
From source file:org.eurekaclinical.user.service.resource.UserResource.java
/** * Put an updated user to the system. Unless the user has the admin role, * s/he may only update their own user info. * * @param req in request/*from w w w.j a va 2 s . c o m*/ * @param inUser Object containing all the information about the user to * add. * @param inId in Id * @return A "Created" response with a link to the user page if successful. */ @RolesAllowed({ "researcher", "admin" }) @Path("/{id}") @PUT public Response putUser(@Context HttpServletRequest req, User inUser, @PathParam("id") Long inId) { String username = req.getUserPrincipal().getName(); if (!req.isUserInRole("admin") && !username.equals(inUser.getUsername())) { throw new HttpStatusException(Response.Status.FORBIDDEN); } LOGGER.debug("Received updated user: {}", inUser); Response response; UserEntity currentUser = this.userDao.retrieve(inId); User me = getMe(req); boolean activation = (!currentUser.isActive()) && (inUser.isActive()); if (this.validateUpdatedUser(currentUser, inUser, me)) { currentUser.setFirstName(inUser.getFirstName()); currentUser.setLastName(inUser.getLastName()); currentUser.setEmail(inUser.getEmail()); currentUser.setOrganization(inUser.getOrganization()); currentUser.setTitle(inUser.getTitle()); currentUser.setDepartment(inUser.getDepartment()); currentUser.setFullName(inUser.getFullName()); List<RoleEntity> updatedRoles = this.roleIdsToRoles(inUser.getRoles()); currentUser.setRoles(updatedRoles); currentUser.setActive(inUser.isActive()); currentUser.setLastLogin(inUser.getLastLogin()); LOGGER.debug("Saving updated user: {}", currentUser.getEmail()); this.userDao.update(currentUser); if (activation) { try { this.emailSender.sendActivationMessage(currentUser); } catch (EmailException ee) { LOGGER.error(ee.getMessage(), ee); } } response = Response.ok().entity(currentUser).build(); } else { response = Response.notModified(this.validationError).build(); } return response; }