@GET public String userInfo() { if (securityContext == null) { throw new NotAuthorizedException("Acesso não autorizado"); } String name = securityContext.getUserPrincipal().getName(); if (securityContext.isUserInRole("admin")) { return "Você é um administrador: " + name; } if (securityContext.isUserInRole("user")) { return "Você é um usuário: " + name; } return "Nenhum dos dois"; }
@POST() @Path("New") public Response New( String siteInfo, @Context HttpServletResponse servletResponse, @Context SecurityContext context) { if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } Response response; try { Gson gson = new Gson(); String json = siteInfo.split("=")[1]; Site site = gson.fromJson(json, Site.class); SitesController.getInstance().NewSite(site); response = Response.status(200).entity(GeoRedConstants.SITE_SUCCESSFULY_ADDED).build(); } catch (Exception e) { response = Response.status(500).entity(e.getMessage()).build(); } return response; }
// crear comentario. recibe un Comment. @POST() @Path("Comments/New") public Response CommentsNew( String commentInfo, @Context HttpServletResponse servletResponse, @Context SecurityContext context) { // si no es un usuario registrado, devolver error 500 de acceso denegado if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } // crear comentario try { Gson gson = new Gson(); commentInfo = commentInfo.split("=")[1]; Comment comment = gson.fromJson(commentInfo, Comment.class); SitesController.getInstance().newComment(comment); return Response.status(200).entity(GeoRedConstants.COMMENT_SUCCESSFULY_ADDED).build(); } // si salta una excepción, devolver error catch (Exception ex) { return Response.status(500).entity(ex.getMessage()).build(); } }
// obtener datos de una visita. // recibe un String con el id, y devuelve un Site. @GET() @Produces("text/plain") @Path("GetById") public Response GetById( @QueryParam("siteId") String siteId, @Context HttpServletResponse servletResponse, @Context SecurityContext context) { if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } // obtener visita try { Gson gson = new Gson(); Site site = SitesController.getInstance().getById(siteId); return Response.status(200).entity(gson.toJson(site)).build(); } // si salta una excepción, devolver error catch (Exception ex) { return Response.status(500).entity(ex.getMessage()).build(); } }
@PUT @Path("/{id}/password") @PermitAll public Response updatePassword(@PathParam("id") final Long id, final String body) { logger.debug("Updating the password for user {}", id); if (!securityContext.isUserInRole(Roles.ADMINISTRATOR.name())) { if (!isLoggedUser(id)) { return Response.status(HttpCode.FORBIDDEN.getCode()).build(); } } HttpCode httpCode = HttpCode.OK; OperationResult result; try { userService.updatePassword(id, getPasswordFromJson(body)); result = OperationResult.success(); } catch (UserNotFoundException e) { httpCode = HttpCode.NOT_FOUND; logger.error("No user found for the given id", e); result = getOperationResultNotFound(RESOURCE_MESSAGE); } logger.debug("Returning the operation result after updating user password: {}", result); return Response.status(httpCode.getCode()) .entity(OperationResultJsonWriter.toJson(result)) .build(); }
private boolean checkRoles(String[] rolesAllowed) { for (String role : rolesAllowed) { if (securityContext.isUserInRole(role)) { return true; } } return false; }
public User securityCheck(SecurityContext sec, Roles role) { if (sec == null) { throw new NullPointerException(); } if (!sec.isUserInRole(role.name())) { throw new WebApplicationException(forbiddenResponse(role, sec)); } return (User) sec.getUserPrincipal(); }
/** * Allow to check if current user has a given role or not. status <b>200</b> and {@link * UserInRoleDescriptor} is returned by indicating if role is granted or not * * @param role role to search (like admin or manager) * @param scope the optional scope like system, workspace, account.(default scope is system) * @param scopeId an optional scopeID used by the scope like the workspace ID if scope is * workspace. * @return {UserInRoleDescriptor} which indicates if role is granted or not * @throws org.eclipse.che.api.core.ForbiddenException with an uknown scope * @throws ServerException when unable to perform the check */ @ApiOperation( value = "Check role for the authenticated user", notes = "Check if user has a role in given scope (default is system) and with an optional scope id. Roles allowed: user, system/admin, system/manager.", response = UserInRoleDescriptor.class, position = 7) @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "Unable to check for the given scope"), @ApiResponse(code = 500, message = "Internal Server Error") }) @GET @Path("/inrole") @GenerateLink(rel = LINK_REL_INROLE) @RolesAllowed({"user", "system/admin", "system/manager"}) @Produces(APPLICATION_JSON) @Beta public UserInRoleDescriptor inRole( @Required @Description("role inside a scope") @QueryParam("role") String role, @DefaultValue("system") @Description("scope of the role (like system, workspace)") @QueryParam("scope") String scope, @DefaultValue("") @Description("id used by the scope, like workspaceId for workspace scope") @QueryParam("scopeId") String scopeId, @Context SecurityContext context) throws NotFoundException, ServerException, ForbiddenException { // handle scope boolean isInRole; if ("system".equals(scope)) { String roleToCheck; if ("user".equals(role) || "temp_user".equals(role)) { roleToCheck = role; } else { roleToCheck = "system/" + role; } // check role isInRole = context.isUserInRole(roleToCheck); } else { throw new ForbiddenException( String.format("Only system scope is handled for now. Provided scope is %s", scope)); } return DtoFactory.getInstance() .createDto(UserInRoleDescriptor.class) .withIsInRole(isInRole) .withRoleName(role) .withScope(scope) .withScopeId(scopeId); }
// obtener sitios, por pagina @GET() @Produces("text/plain") @Path("GetPage") public Response GetPaged( @QueryParam("from") Integer from, @QueryParam("count") Integer count, @Context HttpServletResponse servletResponse, @Context SecurityContext context) { if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } if (count == null) count = 15; if (from == null) from = 0; Gson gson = new Gson(); List<Site> sites = SitesController.getInstance().getSites(from, count); return Response.status(200).entity(gson.toJson(sites)).build(); }
// obtener comentarios del usuario @GET() @Produces("text/plain") @Path("Comments/GetByUser") public Response CommentsGetByUser(@Context SecurityContext context) { if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } // obtener comentarios del usuario try { Gson gson = new Gson(); List<Comment> comments = SitesController.getInstance().getCommentsByUser(); return Response.status(200).entity(gson.toJson(comments)).build(); } // si salta una excepción, devolver error catch (Exception ex) { return Response.status(500).entity(ex.getMessage()).build(); } }
// obtener sitios @GET() @Produces("text/plain") @Path("Get") public Response Get(@Context SecurityContext context) { if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } // obtener sitios try { Gson gson = new Gson(); List<Site> sites = SitesController.getInstance().getSites(); return Response.status(200).entity(gson.toJson(sites)).build(); } // si salta una excepción, devolver error catch (Exception ex) { return Response.status(500).entity(ex.getMessage()).build(); } }
// obtener visitas del usuario, sistema paginado @GET() @Produces("text/plain") @Path("Visits/GetByUserPage") public Response VisitsGetByUserPage( @QueryParam("pageNumber") Integer pageNumber, @Context SecurityContext context) { if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } // obtener visitas del usuario try { Gson gson = new Gson(); List<Visit> visits = SitesController.getInstance().getVisitsByUser(pageNumber); return Response.status(200).entity(gson.toJson(visits)).build(); } // si salta una excepción, devolver error catch (Exception ex) { return Response.status(500).entity(ex.getMessage()).build(); } }
@GET() @Produces("text/plain") @Path("GetByLocation") public Response GetByLocation( @QueryParam("bottomLeftLatitude") Integer bottomLeftLatitude, @QueryParam("bottomLeftLongitude") Integer bottomLeftLongitud, @QueryParam("topRightLatitude") Integer topRightLatitude, @QueryParam("topRightLongitude") Integer topRightLongitude, @Context SecurityContext context) { if (!context.isUserInRole(Roles.REG_USER)) { return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build(); } Gson gson = new Gson(); List<Site> sites = SitesController.getInstance() .getSitesByPosition( bottomLeftLatitude, bottomLeftLongitud, topRightLatitude, topRightLongitude); return Response.status(200).entity(gson.toJson(sites)).build(); }
/** * Creates new user and profile. * * <p>When current user is in 'system/admin' role then {@code newUser} parameter will be used for * user creation, otherwise method uses {@code token} and {@link #tokenValidator}. * * @param token authentication token * @param isTemporary if it is {@code true} creates temporary user * @return entity of created user * @throws UnauthorizedException when token is {@code null} * @throws ConflictException when token is not valid * @throws ServerException when some error occurred while persisting user or user profile * @see UserDescriptor * @see #getCurrent(SecurityContext) * @see #updatePassword(String) * @see #getById(String, SecurityContext) * @see #getByEmail(String, SecurityContext) * @see #remove(String) */ @ApiOperation( value = "Create a new user", notes = "Create a new user in the system", response = UserDescriptor.class, position = 1) @ApiResponses({ @ApiResponse(code = 201, message = "Created"), @ApiResponse(code = 401, message = "Missed token parameter"), @ApiResponse(code = 409, message = "Invalid token"), @ApiResponse(code = 403, message = "Invalid or absent request parameters"), @ApiResponse(code = 500, message = "Internal Server Error") }) @POST @Path("/create") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @GenerateLink(rel = LINK_REL_CREATE_USER) public Response create( @ApiParam(value = "New user") NewUser newUser, @ApiParam(value = "Authentication token") @QueryParam("token") String token, @ApiParam(value = "User type") @QueryParam("temporary") @DefaultValue("false") Boolean isTemporary, @Context SecurityContext context) throws ApiException { final User user = context.isUserInRole("system/admin") ? fromEntity(newUser) : fromToken(token); userDao.create( user.withId(generate("user", ID_LENGTH)) .withPassword(firstNonNull(user.getPassword(), generate("", PASSWORD_LENGTH)))); profileDao.create(new Profile(user.getId())); final Map<String, String> preferences = new HashMap<>(4); preferences.put("temporary", Boolean.toString(isTemporary)); preferences.put("codenvy:created", Long.toString(System.currentTimeMillis())); preferenceDao.setPreferences(user.getId(), preferences); return status(CREATED).entity(toDescriptor(user, context)).build(); }
@PUT @Path("/{id}") @PermitAll public Response update(@PathParam("id") final Long id, final String body) { logger.debug("Updating the user {} with body {}", id, body); if (!securityContext.isUserInRole(Roles.ADMINISTRATOR.name())) { if (!isLoggedUser(id)) { return Response.status(HttpCode.FORBIDDEN.getCode()).build(); } } final User user = userJsonConverter.convertFrom(body); user.setId(id); HttpCode httpCode = HttpCode.OK; OperationResult result; try { userService.update(user); result = OperationResult.success(); } catch (FieldNotValidException e) { httpCode = HttpCode.VALIDATION_ERROR; logger.error("One of the fields of the user is not valid", e); result = getOperationResultInvalidField(RESOURCE_MESSAGE, e); } catch (UserExistException e) { httpCode = HttpCode.VALIDATION_ERROR; logger.error("There is already an user for the given email", e); result = getOperationResultExists(RESOURCE_MESSAGE, "email"); } catch (UserNotFoundException e) { httpCode = HttpCode.NOT_FOUND; logger.error("No user found for the given id", e); result = getOperationResultNotFound(RESOURCE_MESSAGE); } logger.debug("Returning the operation result after updating user: {}", result); return Response.status(httpCode.getCode()) .entity(OperationResultJsonWriter.toJson(result)) .build(); }
@PUT @Path("{id}") @Consumes(MediaType.APPLICATION_JSON) @Transaction public Response put( Dataset requestDataset, @PathParam("id") UUID datasetId, @Context SecurityContext sc) { // override the url in json with the id in the url, in case a // malicious client has changed it requestDataset.setDatasetId(datasetId); /* * Checks that * - user has write authorization for the session * - the session contains this dataset */ Session session = sessionResource.getSessionForWriting(sc, sessionId); Dataset dbDataset = getHibernate().session().get(Dataset.class, datasetId); if (dbDataset == null || dbDataset.getSession().getSessionId() != session.getSessionId()) { throw new NotFoundException("dataset doesn't exist"); } if (!sc.isUserInRole(Role.FILE_BROKER)) { checkFileModification(requestDataset, getHibernate().session()); } if (requestDataset.getFile() == null || requestDataset.getFile().isEmpty()) { // if the client doesn't care about the File, simply keep the db version requestDataset.setFile(dbDataset.getFile()); } // make sure a hostile client doesn't set the session requestDataset.setSession(session); update(requestDataset, getHibernate().session()); return Response.noContent().build(); }
private UserDescriptor toDescriptor(User user, SecurityContext context) { final List<Link> links = new LinkedList<>(); final UriBuilder uriBuilder = getServiceContext().getServiceUriBuilder(); if (context.isUserInRole("user")) { links.add( LinksHelper.createLink( HttpMethod.GET, getServiceContext() .getBaseUriBuilder() .path(UserProfileService.class) .path(UserProfileService.class, "getCurrent") .build() .toString(), null, APPLICATION_JSON, LINK_REL_GET_CURRENT_USER_PROFILE)); links.add( LinksHelper.createLink( HttpMethod.GET, uriBuilder.clone().path(getClass(), "getCurrent").build().toString(), null, APPLICATION_JSON, LINK_REL_GET_CURRENT_USER)); links.add( LinksHelper.createLink( HttpMethod.POST, uriBuilder.clone().path(getClass(), "updatePassword").build().toString(), APPLICATION_FORM_URLENCODED, null, LINK_REL_UPDATE_PASSWORD)); } if (context.isUserInRole("system/admin") || context.isUserInRole("system/manager")) { links.add( LinksHelper.createLink( HttpMethod.GET, uriBuilder.clone().path(getClass(), "getById").build(user.getId()).toString(), null, APPLICATION_JSON, LINK_REL_GET_USER_BY_ID)); links.add( LinksHelper.createLink( HttpMethod.GET, getServiceContext() .getBaseUriBuilder() .path(UserProfileService.class) .path(UserProfileService.class, "getById") .build(user.getId()) .toString(), null, APPLICATION_JSON, LINK_REL_GET_USER_PROFILE_BY_ID)); if (user.getEmail() != null) { links.add( LinksHelper.createLink( HttpMethod.GET, uriBuilder .clone() .path(getClass(), "getByEmail") .queryParam("email", user.getEmail()) .build() .toString(), null, APPLICATION_JSON, LINK_REL_GET_USER_BY_EMAIL)); } } if (context.isUserInRole("system/admin")) { links.add( LinksHelper.createLink( HttpMethod.DELETE, uriBuilder.clone().path(getClass(), "remove").build(user.getId()).toString(), null, null, LINK_REL_REMOVE_USER_BY_ID)); } return DtoFactory.getInstance() .createDto(UserDescriptor.class) .withId(user.getId()) .withEmail(user.getEmail()) .withName(user.getName()) .withAliases(user.getAliases()) .withPassword("<none>") .withLinks(links); }