private boolean handleDelete( HttpServletRequest request, HttpServletResponse response, String pathString) throws GitAPIException, CoreException, IOException, ServletException { IPath path = pathString == null ? Path.EMPTY : new Path(pathString); // expected path format is /file/{workspaceId}/{projectId}[/{directoryPath}] if (path.segment(0).equals("file") && path.segmentCount() > 2) { // $NON-NLS-1$ // make sure a clone is addressed WebProject webProject = GitUtils.projectFromPath(path); if (webProject != null && isAccessAllowed(request.getRemoteUser(), webProject)) { File gitDir = GitUtils.getGitDirs(path, Traverse.CURRENT).values().iterator().next(); Repository repo = new FileRepository(gitDir); repo.close(); FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY); if (path.segmentCount() == 3) return statusHandler.handleRequest( request, response, removeProject(request.getRemoteUser(), webProject)); return true; } String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } String msg = NLS.bind("Invalid delete request {0}", pathString); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); }
public ReturnStatus login(String Auth, HttpServletRequest req, HttpSession session) { System.out.println("login"); String[] result = decodeToken(Auth); System.out.println("login, result = " + result[0]); if (result[0].equals("OK")) { System.out.println("login : "******" / password = "******"user", req.getRemoteUser()); } catch (ServletException e) { System.out.println("login ServletException"); return new ReturnStatus(false, "login ServletException" + e.getMessage()); } System.out.println("Login OK, remoteuser = "******"login, RequestedSessionId = " + req.getRequestedSessionId()); System.out.println("Login OK"); return new ReturnStatus(true, getroles(result[1])); } else { System.out.println("user niet gevonden (null)"); return new ReturnStatus(false, "user niet gevonden (null)"); } } else { System.out.println("invalid"); return new ReturnStatus(false, result[1]); } }
@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response action( @Context HttpServletRequest httpRequest, @FormParam("csrfToken") String csrfToken, @FormParam("key") @DefaultValue("") String key, @FormParam("name") @DefaultValue("") String name, @FormParam("description") @DefaultValue("") String description, @FormParam("rollback") @DefaultValue("") String rollback, @FormParam("version") @DefaultValue("") String version, @FormParam("upgrade") @DefaultValue("") String upgrade, @FormParam("repository") @DefaultValue("") String repository, @FormParam("email") @DefaultValue("") String email, @FormParam("autoRelease") @DefaultValue("false") boolean autoRelease, @FormParam("action") @DefaultValue("") String action) { return shiroRequestHelper.csrfCall( csrfToken, "releases/action", (csrfToken1) -> { if (action.startsWith("export")) { String export = pluginRegion.doExport( new ReleasesPluginRegionInput( key, name, description, rollback, version, upgrade, repository, email, autoRelease, "export"), httpRequest.getRemoteUser()); return Response.ok(export, MediaType.APPLICATION_OCTET_STREAM_TYPE); } else { String rendered = soyService.renderPlugin( httpRequest.getRemoteUser(), csrfToken1, pluginRegion, new ReleasesPluginRegionInput( key, name, description, rollback, version, upgrade, repository, email, autoRelease, action)); return Response.ok(rendered, MediaType.TEXT_HTML); } }); }
@ModelAttribute @RequestMapping(method = RequestMethod.GET) protected User showForm(HttpServletRequest request, HttpServletResponse response) throws Exception { // If not an administrator, make sure user is not trying to add or edit another user if (!request.isUserInRole(Constants.ADMIN_ROLE) && !isFormSubmission(request)) { if (isAdd(request) || request.getParameter("id") != null) { response.sendError(HttpServletResponse.SC_FORBIDDEN); log.warn( "User '" + request.getRemoteUser() + "' is trying to edit user with id '" + request.getParameter("id") + "'"); throw new AccessDeniedException("You do not have permission to modify other users."); } } if (!isFormSubmission(request)) { String userId = request.getParameter("id"); // if user logged in with remember me, display a warning that they can't change passwords log.debug("checking for remember me login..."); AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); SecurityContext ctx = SecurityContextHolder.getContext(); if (ctx.getAuthentication() != null) { Authentication auth = ctx.getAuthentication(); if (resolver.isRememberMe(auth)) { request.getSession().setAttribute("cookieLogin", "true"); // add warning message saveMessage(request, getText("userProfile.cookieLogin", request.getLocale())); } } User user; if (userId == null && !isAdd(request)) { user = getUserManager().getUserByUsername(request.getRemoteUser()); } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) { user = getUserManager().getUser(userId); } else { user = new User(); user.addRole(new Role(Constants.USER_ROLE)); } user.setConfirmPassword(user.getPassword()); return user; } else { // populate user object from database, so all fields don't need to be hidden fields in form return getUserManager().getUser(request.getParameter("id")); } }
public void login() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); try { if (StringUtils.isBlank(request.getRemoteUser())) { // request.logout(); request.login(this.username, this.password); } else if (!request.getRemoteUser().equals(this.username)) { request.logout(); request.login(this.username, this.password); } if (originalURL != null && originalURL.indexOf("service.jsf?") > 0) { externalContext.redirect(originalURL); } else { if (UserDAO.isProvider(this.username)) { String recentServiceId = serviceDAO.getProviderRecentServiceId(this.username); if (recentServiceId == null) externalContext.redirect( externalContext.getRequestContextPath() + "/provider/providerappointment.jsf"); else externalContext.redirect( externalContext.getRequestContextPath() + "/provider/serviceappointment.jsf?serviceId=" + recentServiceId); } else { String recentServiceId = serviceDAO.getUserRecentServiceId(this.username); if (recentServiceId == null) externalContext.redirect( externalContext.getRequestContextPath() + "/user/userappointment.jsf"); else externalContext.redirect( externalContext.getRequestContextPath() + "/user/appointment.jsf?serviceId=" + recentServiceId); } } } catch (Exception e) { // log.error(e.getCause(), e); WebUtil.addMessage( new FacesMessage( FacesMessage.SEVERITY_INFO, WebUtil.getMessage("login.failed.header"), WebUtil.getMessage("login.failed.message"))); // context.addMessage(null, new FacesMessage("Login failed.")); } }
/** * Approval node of transportation fee apply * * @param request HttpServletRequest * @param form ActionForm * @return String Return forward url */ public String transfeeCheck(HttpServletRequest request, ActionForm form) { String forward = "resultMessage"; try { Long userid = ((CommonSearch) SpringContextUtil.getBean("commonSearch")) .findUserIdByUserName(request.getRemoteUser()); // TransfeeApplyBo wabo = new TransfeeApplyBo(); switch (transfeeApplyBo.transfeeCheck((WorkFlowCheckForm) form, userid)) { case 1: request.setAttribute("tag", "1"); request.setAttribute("businessFlag", "transfeeCheck"); break; case -2: request.setAttribute("tag", "-1"); // 流程不存在或已经被处理 request.setAttribute("businessFlag", "Check12"); break; case -1: request.setAttribute("tag", "-1"); request.setAttribute("businessFlag", "transfeeCheck"); break; } } catch (Exception e) { e.printStackTrace(); } return forward; }
protected boolean isCacheableRequest(HttpServletRequest request) { String portletId = ParamUtil.getString(request, "p_p_id"); if (Validator.isNotNull(portletId)) { return false; } if ((_pattern == _PATTERN_FRIENDLY) || (_pattern == _PATTERN_LAYOUT)) { long userId = PortalUtil.getUserId(request); String remoteUser = request.getRemoteUser(); if ((userId > 0) || Validator.isNotNull(remoteUser)) { return false; } } if (_pattern == _PATTERN_LAYOUT) { String plid = ParamUtil.getString(request, "p_l_id"); if (Validator.isNull(plid)) { return false; } } return true; }
/** * Obtiene la lista de los registros de Book. * * @return Colección de objetos de TranslatorDTO cada uno con sus respectivos Review * @generated */ @GET public List<TranslatorDTO> getTranslators() { String accountHref = req.getRemoteUser(); if (accountHref == null) return new ArrayList<TranslatorDTO>(); Account account = getClient().getResource(accountHref, Account.class); for (Group gr : account.getGroups()) { switch (gr.getHref()) { case ADMIN_HREF: if (page != null && maxRecords != null) { this.response.setIntHeader("X-Total-Count", translatorLogic.countTranslators()); return TranslatorConverter.listEntity2DTO( translatorLogic.getTranslators(page, maxRecords)); } return TranslatorConverter.listEntity2DTO(translatorLogic.getTranslators()); case TRANSLATOR_GROUP_HREF: Integer id = (int) account.getCustomData().get("translatorId"); List<TranslatorDTO> list = new ArrayList(); list.add( TranslatorConverter.fullEntity2DTO(translatorLogic.getTranslator(id.longValue()))); return list; default: return new ArrayList<TranslatorDTO>(); } } // Nothing? return new ArrayList<TranslatorDTO>(); }
/** * Does the user sending the HttpServletRequest have the administrator ACLs? If it isn't the case, * response will be modified to send an error to the user. * * @param servletContext * @param request * @param response used to send the error response if user does not have admin access. * @return true if admin-authorized, false otherwise * @throws IOException */ static boolean hasAdministratorAccess( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException { Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE); // If there is no authorization, anybody has administrator access. if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) { return true; } String remoteUser = request.getRemoteUser(); if (remoteUser == null) { response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthenticated users are not " + "authorized to access this page."); return false; } if (servletContext.getAttribute(ADMINS_ACL) != null && !userHasAdministratorAccess(servletContext, remoteUser)) { response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "User " + remoteUser + " is unauthorized to access this page."); return false; } return true; }
private static WebUser getWebUser(HttpServletRequest req) { String remoteUser = req.getRemoteUser(); if (remoteUser != null) { return WebUser.fromUserId(remoteUser); } return null; }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Low Level SecServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Low Level Security at " + request.getContextPath() + "</h1>"); out.println("<br>"); out.println("AuthType:[" + request.getAuthType() + "]"); out.println("<br>"); out.println("RemoteUser:[" + request.getRemoteUser() + "]"); out.println("<br>"); if (request.getUserPrincipal() != null) { out.println("UserPrincipal.Name:[" + request.getUserPrincipal().getName() + "]"); } else { out.println("no principal"); } out.println("</hr>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } }
/* * (non-Javadoc) * @see * org.fcrepo.server.security.xacml.pep.rest.filters.RESTFilter#handleRequest(javax.servlet * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public RequestCtx handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { RequestCtx req = null; Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>(); Map<URI, AttributeValue> resAttr; try { resAttr = ResourceAttributes.getRepositoryResources(); actions.put(Constants.ACTION.ID.getURI(), Constants.ACTION.GET_NEXT_PID.getStringAttribute()); actions.put(Constants.ACTION.API.getURI(), Constants.ACTION.APIM.getStringAttribute()); req = getContextHandler() .buildRequest(getSubjects(request), actions, resAttr, getEnvironment(request)); LogUtil.statLog( request.getRemoteUser(), Constants.ACTION.GET_NEXT_PID.uri, Constants.FEDORA_REPOSITORY_PID.uri, null); } catch (Exception e) { logger.error(e.getMessage(), e); CXFUtility.getFault(e); } return req; }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("EvalExpr: Unexpected post request" + request.getRemoteUser()); out.close(); }
private ModelAndView deleteGroupInternal( HttpServletRequest request, HttpServletResponse response, UserGroupDAO userGroupRequest) { if (notNull(userGroupRequest.getPid())) { userGroupRequest.setType(Constants.DELETE_GROUP); userGroupRequest.setAdminName(request.getRemoteUser()); UserGroupDAO userGroupResponse = uiWebService.userGroupOperation(userGroupRequest); userGroupRequest.setMessage(chooseMessage(request, userGroupResponse)); } else { userGroupRequest.setMessage(""); userGroupRequest.setPid(""); } userGroupRequest.setType(Constants.GET_GROUPS); UserGroupDAO userGroupResponse = uiWebService.userGroupOperation(userGroupRequest); userGroupRequest.getGroups().clear(); userGroupRequest.getGroups().addAll(userGroupResponse.getGroups()); return new ModelAndView("deletegroup", "userGroupDAO", userGroupRequest); }
/** {@inheritDoc} */ @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8")); ThreadCategory.setPrefix(MapsConstants.LOG4J_CATEGORY); log = ThreadCategory.getInstance(this.getClass()); try { String user = request.getRemoteUser(); if (log.isDebugEnabled()) log.debug("MapStartUp for user:"******"Error in map's startup", e); bw.write(ResponseAssembler.getMapErrorResponse(MapsConstants.MAPS_STARTUP_ACTION)); } finally { bw.close(); } return null; }
/** * GET an URL on the Google Apps apis as the current user. * * @param googlePath The google API path to get, not including the "www.googleapis.com" * @return The Google API server's response. */ @GET @Path("/{googlepath:.*}") @Produces({MediaType.APPLICATION_JSON}) public Response get( @PathParam(value = "googlepath") String googlePath, @Context HttpServletRequest request) { String userID = request.getRemoteUser(); if (userID == null) { throw new UnauthorizedException("Google proxy is not supported for anonymous users"); } Credential credential = getCredential(userID); try { return doMethod( HttpMethod.GET, RestUtils.convertToEntity(request, credential.getAccessToken()), RestUtils.pathPlusQueryString(googlePath, request)); } catch (HttpClientErrorException error4xx) { if (error4xx.getStatusCode().value() == HttpResponseCodes.SC_UNAUTHORIZED) { oAuth2Dao.delete(userID, GoogleCredentialStore.GOOGLE_APP_ID); } return ServerResponse.ok() .status(error4xx.getStatusCode().value()) .entity(error4xx.getMessage()) .build(); } }
protected void executeLogic( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountFB fb = (AccountFB) form; UserAccount account = (UserAccount) getEnvironment().getEntityFactory().create("gallery-useraccount"); PropertyUtils.copyProperties(account, fb); getEnvironment().getEntityStorageFactory().getStorage("gallery-useraccount").store(account); if (account.getStylesheet() != null && account.getStylesheet().length() > 0) { request.getSession().setAttribute("stylesheetPB", account.getStylesheet()); } else { request.getSession().removeAttribute("stylesheetPB"); } if (account.getUsername().equals(request.getRemoteUser())) { boolean useEnglish = !request .getLocale() .getLanguage() .equals(getEnvironment().getConfigurableResources().getParameter("nativelanguage")); String title = account.getTitle(); if (useEnglish && StringUtil.asNull(account.getTitleEnglish()) != null) { title = account.getTitleEnglish(); } request.getSession().setAttribute("titlePB", title); } }
@Test public void testDoFilterForClientBackwardsCompatibility() throws Exception { Filter filter = new FalconAuthenticationFilter(); final String userName = System.getProperty("user.name"); final String httpAuthType = StartupProperties.get().getProperty("falcon.http.authentication.type", "simple"); try { System.setProperty("user.name", ""); StartupProperties.get() .setProperty( "falcon.http.authentication.type", "org.apache.falcon.security.RemoteUserInHeaderBasedAuthenticationHandler"); synchronized (StartupProperties.get()) { filter.init(mockConfig); } Mockito.when(mockRequest.getMethod()).thenReturn("POST"); Mockito.when(mockRequest.getQueryString()).thenReturn(""); Mockito.when(mockRequest.getRemoteUser()).thenReturn(null); Mockito.when(mockRequest.getHeader("Remote-User")).thenReturn("remote-user"); filter.doFilter(mockRequest, mockResponse, mockChain); Assert.assertEquals(CurrentUser.getUser(), "remote-user"); } finally { System.setProperty("user.name", userName); StartupProperties.get().setProperty("falcon.http.authentication.type", httpAuthType); } }
/** * This method implements the HTTP <code>GET</code> method of the present deployment carrying * entity resource. It facilitates the retrieval of all deployments either attached to the present * entity or one of its subentities. It expects the method to be addressed via the following URL * pattern <code>/{Entity}/Deployment/all/{code}</code>. <code>{Entity}</code> is the name of the * deployment carrying entity class, <code>{code}</code> is the code of the entity. * * @return a 500 code in case of an internal problem, a 404 code if the deployment carrying entity * resource could not be found, a 200 code otherwise. The body of the response contains the * XML representation of the retrieved entity codes. * <p>The form is * <blockquote> * <list xmlns="http://www.mercatis.com/lighthouse3"> <code>AAA</code> * <location>BBB</location> </list> * </blockquote> */ @GET @Path("Deployment/all/{code}") @Produces("application/xml") public Response findAllDeployments( @PathParam("code") String code, @Context HttpServletRequest servletRequest) { if (log.isDebugEnabled()) { log.debug("Retrieving all deployments at " + getEntityDAO().getManagedType().getSimpleName()); } List<Deployment> matches = new LinkedList<Deployment>(); try { Entity entity = getEntityDAO().findByCode(code); if (entity == null) { log.error( "Could not find " + getEntityDAO().getManagedType().getSimpleName() + " with code" + code); return Response.status(Status.NOT_FOUND) .entity("Could not find resource with code " + code) .build(); } if (overridableDenyAccess(servletRequest.getRemoteUser(), getContextRole(CtxOp.FIND), entity)) return Response.status(Status.UNAUTHORIZED).build(); for (Deployment d : entity.getAllDeployments()) { StringBuilder context = formatContext( new StringBuilder("/Deployment/Deployment"), d.getLocation(), d.getDeployedComponent().getCode()); if (LighthouseAuthorizator.allowAccess( getServiceContainer(), servletRequest.getRemoteUser(), "viewDeployment", context)) matches.add(d); } } catch (PersistenceException exception) { log.error( "Persistence exception caught while retrieving deployments for " + getEntityDAO().getManagedType().getSimpleName(), exception); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(exception.toString()).build(); } return Response.status(Status.OK).entity(createXmlListOfDeploymentReferences(matches)).build(); }
protected void _init(PageContext pc, Map<String, String> arguments) { this.pc = pc; // header HttpServletRequest req = pc.getHttpServletRequest(); header = new StringBuffer(); createHeader(header, "context-path", req.getContextPath()); createHeader(header, "remote-user", req.getRemoteUser()); createHeader(header, "remote-addr", req.getRemoteAddr()); createHeader(header, "remote-host", req.getRemoteHost()); createHeader( header, "script-name", StringUtil.emptyIfNull(req.getContextPath()) + StringUtil.emptyIfNull(req.getServletPath())); createHeader(header, "server-name", req.getServerName()); createHeader(header, "protocol", req.getProtocol()); createHeader(header, "server-port", Caster.toString(req.getServerPort())); createHeader( header, "path-info", StringUtil.replace( StringUtil.emptyIfNull(req.getRequestURI()), StringUtil.emptyIfNull(req.getServletPath()), "", true)); // createHeader(header,"path-translated",pc.getBasePageSource().getDisplayPath()); createHeader(header, "query-string", req.getQueryString()); createHeader(header, "unit", unitShortToString(unit)); createHeader(header, "min-time-nano", min + ""); content = new StringBuffer(); // directory String strDirectory = arguments.get("directory"); if (dir == null) { if (StringUtil.isEmpty(strDirectory)) { dir = getTemp(pc); } else { try { dir = ResourceUtil.toResourceNotExisting(pc, strDirectory, false); if (!dir.exists()) { dir.createDirectory(true); } else if (dir.isFile()) { err( pc, "can not create directory [" + dir + "], there is already a file with same name."); } } catch (Throwable t) { err(pc, t); dir = getTemp(pc); } } } file = dir.getRealResource((pc.getId()) + "-" + CreateUUID.call(pc) + ".exl"); file.createNewFile(); start = System.currentTimeMillis(); }
@Test public void testTrackClusterUser() throws Exception { // activate String serverId = getServerId(); Capture<String> serverIdCapture = new Capture<String>(); Capture<ClusterServerImpl> clusterServerCapture = new Capture<ClusterServerImpl>(); expect(serverTrackingCache.list()).andReturn(new ArrayList<Object>()).times(2); expect(serverTrackingCache.put(capture(serverIdCapture), capture(clusterServerCapture))) .andReturn(new Object()); // trackClusterUser HttpServletRequest request = createMock(HttpServletRequest.class); HttpServletResponse response = createMock(HttpServletResponse.class); Cookie cookieA = new Cookie("something", "someValue"); Cookie cookieMatching = new Cookie("SAKAI-TRACKING", serverId + "-trackingValue"); Cookie cookieB = new Cookie("somethingElse", "someOtherValue"); Cookie[] cookies = new Cookie[] {cookieA, cookieMatching, cookieB}; expect(request.getCookies()).andReturn(cookies); expect(request.getRemoteUser()).andReturn("userid"); ClusterServerImpl csImple = new ClusterServerImpl(serverId, 4, "http://sdfsdfs"); expect(serverTrackingCache.get(serverId)).andReturn(csImple).times(2); // nothing in the cache. expect(userTrackingCache.get(serverId + "-trackingValue")).andReturn(null); Capture<String> trackingValueCapture = new Capture<String>(); Capture<ClusterUserImpl> clusterUserCapture = new Capture<ClusterUserImpl>(); expect(userTrackingCache.put(capture(trackingValueCapture), capture(clusterUserCapture))) .andReturn(new Object()); // deactivate serverTrackingCache.remove(serverId); replay(); clusterTrackingServiceImpl.activate(componentContext); clusterTrackingServiceImpl.trackClusterUser(request, response); clusterTrackingServiceImpl.deactivate(componentContext); assertTrue(serverIdCapture.hasCaptured()); assertEquals(serverId, serverIdCapture.getValue()); assertTrue(clusterServerCapture.hasCaptured()); ClusterServerImpl clusterServerImpl = clusterServerCapture.getValue(); assertEquals(serverId, clusterServerImpl.getServerId()); assertTrue(System.currentTimeMillis() >= clusterServerImpl.getLastModified()); // check the user capture assertTrue(trackingValueCapture.hasCaptured()); assertTrue(clusterUserCapture.hasCaptured()); assertEquals(serverId + "-trackingValue", trackingValueCapture.getValue()); ClusterUserImpl clusterUserImpl = clusterUserCapture.getValue(); assertEquals("userid", clusterUserImpl.getUser()); assertEquals(serverId, clusterUserImpl.getServerId()); assertTrue(System.currentTimeMillis() >= clusterUserImpl.getLastModified()); verify(); }
public Integer findUserName() throws Exception { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); String username = request.getRemoteUser(); Users u = this.userList.findByUsername(username); int userId = u.getId(); return userId; }
@Test public void testTrackClusterNewUser() throws Exception { // activate String serverId = getServerId(); Capture<String> serverIdCapture = new Capture<String>(); Capture<ClusterServerImpl> clusterServerCapture = new Capture<ClusterServerImpl>(); expect(serverTrackingCache.list()).andReturn(new ArrayList<Object>()).times(2); expect(serverTrackingCache.put(capture(serverIdCapture), capture(clusterServerCapture))) .andReturn(new Object()); // trackClusterUser HttpServletRequest request = createMock(HttpServletRequest.class); HttpServletResponse response = createMock(HttpServletResponse.class); Cookie cookieA = new Cookie("something", "someValue"); Cookie cookieB = new Cookie("somethingElse", "someOtherValue"); Cookie[] cookies = new Cookie[] {cookieA, cookieB}; expect(request.getCookies()).andReturn(cookies); expect(request.getRemoteUser()).andReturn("userid"); expect(response.isCommitted()).andReturn(false); Capture<Cookie> captureCookie = new Capture<Cookie>(); response.addCookie(capture(captureCookie)); expectLastCall(); response.addHeader("Cache-Control", "no-cache=\"set-cookie\" "); expectLastCall(); response.addDateHeader("Expires", 0); expectLastCall(); // deactivate serverTrackingCache.remove(serverId); replay(); clusterTrackingServiceImpl.activate(componentContext); clusterTrackingServiceImpl.trackClusterUser(request, response); clusterTrackingServiceImpl.deactivate(componentContext); assertTrue(serverIdCapture.hasCaptured()); assertEquals(serverId, serverIdCapture.getValue()); assertTrue(clusterServerCapture.hasCaptured()); ClusterServerImpl clusterServerImpl = clusterServerCapture.getValue(); assertEquals(serverId, clusterServerImpl.getServerId()); assertTrue(System.currentTimeMillis() >= clusterServerImpl.getLastModified()); // check the cookie assertTrue(captureCookie.hasCaptured()); Cookie cookie = captureCookie.getValue(); assertEquals("SAKAI-TRACKING", cookie.getName()); assertEquals("/", cookie.getPath()); assertEquals(-1, cookie.getMaxAge()); assertNotNull(cookie.getValue()); assertTrue(cookie.getValue().startsWith(serverId)); verify(); }
/** * Read user id. * * @param session HttpSession * @return String */ public String readUserIdentifier(HttpServletRequest request) { HttpSession session = request.getSession(); Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); String userInSession = assertion.getPrincipal().getName(); String user = (String) request.getRemoteUser(); logger.debug("CAS user in HttpServletRequest:" + user); logger.debug("CAS user in HttpSession:" + userInSession); return user != null ? user : userInSession; }
private SolrQuery buildSolrQuery(HttpServletRequest req) { SolrQuery query = new SolrQuery(); query.setParam(CommonParams.WT, "json"); // $NON-NLS-1$ query.setParam(CommonParams.FL, FIELD_NAMES); String queryString = getEncodedParameter(req, CommonParams.Q); if (queryString == null) return null; if (queryString.length() > 0) { String processedQuery = ""; // $NON-NLS-1$ // divide into search terms delimited by space or plus ('+') character List<String> terms = new ArrayList<String>(Arrays.asList(queryString.split("[\\s\\+]+"))); // $NON-NLS-1$ while (!terms.isEmpty()) { String term = terms.remove(0); if (term.length() == 0) continue; if (isSearchField(term)) { if (term.startsWith("NameLower:")) { // $NON-NLS-1$ // solr does not lowercase queries containing wildcards // https://issues.apache.org/jira/browse/SOLR-219 processedQuery += "NameLower:" + term.substring(10).toLowerCase(); // $NON-NLS-1$ } else if (term.startsWith("Location:")) { // $NON-NLS-1${ // all other field searches are case sensitive processedQuery += "Location:" + term.substring(9 + req.getContextPath().length()); } else { // all other field searches are case sensitive processedQuery += term; } } else { // decode the term string now try { term = URLDecoder.decode(term, "UTF-8"); } catch (UnsupportedEncodingException e) { // try with encoded term } boolean isPhrase = term.charAt(0) == '"'; // solr does not lowercase queries containing wildcards // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=359766 String processedTerm = ClientUtils.escapeQueryChars(term.toLowerCase()); // add leading and trailing wildcards to match word segments if (!isPhrase) { if (processedTerm.charAt(0) != '*') processedTerm = '*' + processedTerm; if (processedTerm.charAt(processedTerm.length() - 1) != '*') processedTerm += '*'; } processedQuery += processedTerm; } processedQuery += " AND "; // $NON-NLS-1$ } queryString = processedQuery; } queryString += ProtocolConstants.KEY_USER_NAME + ':' + ClientUtils.escapeQueryChars(req.getRemoteUser()); query.setQuery(queryString); // other common fields setField(req, query, CommonParams.ROWS); setField(req, query, CommonParams.START); setField(req, query, CommonParams.SORT); return query; }
public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1, Object handler) throws Exception { if (request.getRequestURI().endsWith("products/add") && request.getMethod().equals("POST")) { user = request.getRemoteUser(); productId = request.getParameterValues("productId")[0]; } return true; }
/** GET /authenticate -> check if the user is authenticated, and return its login. */ @RequestMapping( value = "/authenticate", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public String isAuthenticated(HttpServletRequest request) { log.debug("REST request to check if the current user is authenticated"); return request.getRemoteUser(); }
/** Remove the current user's stored API key for google. */ @POST @Path("gappsOAuthEnabled") public void disableOAuth( @Context HttpServletRequest request, @FormParam(Params.METHOD) String method) { String uid = request.getRemoteUser(); if (uid != null && method != null && method.equalsIgnoreCase("delete")) { oAuth2Dao.delete(uid, GoogleCredentialStore.GOOGLE_APP_ID); } }
private HttpServletRequest getMockRequest(String remoteUser, String user, String doAs) { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getParameter(UserParam.NAME)).thenReturn(user); if (doAs != null) { when(request.getParameter(DoAsParam.NAME)).thenReturn(doAs); } when(request.getRemoteUser()).thenReturn(remoteUser); return request; }
/** * From user profile * * @param model * @param request * @param response * @param locale * @return * @throws Exception */ @PreAuthorize("hasRole('AUTH')") @RequestMapping(value = "/admin/users/displayUser.html", method = RequestMethod.GET) public String displayUserEdit( Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { String userName = request.getRemoteUser(); User user = userService.getByUserName(userName); return displayUser(user, model, request, response, locale); }