public User createUser(SecurityContext sec, User user) {
   User existingUser = getUser(((User) sec.getUserPrincipal()).getId());
   if (existingUser == null) { // User never registed
     return db.createUser(user, ((User) sec.getUserPrincipal()));
   } else if (existingUser.getEmail().equals(user.getEmail())) { // Email exists
     throw new DuplicateKeyException("");
   }
   return existingUser;
 }
  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();
  }
 @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";
 }
 private Response forbiddenResponse(Roles search, SecurityContext sec) {
   return Response.status(Response.Status.FORBIDDEN)
       .entity(
           Errors.createPlain(
               format("%s is unavailable to %s ", search, sec.getUserPrincipal().getName())))
       .build();
 }
Example #5
0
  // 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();
    }
  }
Example #6
0
 @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @Produces(GrouptalkMediaType.GROUPTALK_AUTH_TOKEN)
 public Response createJoinGroup(
     @FormParam("userid") String userid,
     @FormParam("groupid") String groupid,
     @Context UriInfo uriInfo)
     throws URISyntaxException {
   if (userid == null || groupid == null)
     throw new BadRequestException("all parameters are mandatory");
   JoinGroupDAO joinGroupDAO = new JoinGroupDAOImpl();
   JoinGroup joinGroup = null;
   AuthToken authenticationToken = null;
   try {
     joinGroup =
         joinGroupDAO.createJoinGroup(securityContext.getUserPrincipal().getName(), groupid);
   } catch (SQLException e) {
     throw new InternalServerErrorException();
   }
   URI uri = new URI(uriInfo.getAbsolutePath().toString() + "/" + joinGroup.getUserid());
   return Response.created(uri)
       .type(GrouptalkMediaType.GROUPTALK_InterestGroups)
       .entity(joinGroup)
       .build();
 }
Example #7
0
  @RolesAllowed(Roles.OWNER)
  @DELETE
  @Path("/{stream_name}")
  @ApiOperation(value = "Delete a stream.", notes = "TBD")
  @ApiResponses(value = {@ApiResponse(code = 500, message = "Internal Server Error")})
  public ResponseMsg doDeleteStream(
      @PathParam("stream_name") String streamName,
      @QueryParam("start_time") String startTime,
      @QueryParam("end_time") String endTime)
      throws JsonProcessingException {

    String ownerName = securityContext.getUserPrincipal().getName();
    StreamDatabaseDriver db = null;
    try {
      db = DatabaseConnector.getStreamDatabase();
      db.deleteStream(ownerName, streamName, startTime, endTime);
    } catch (ClassNotFoundException | IOException | NamingException | SQLException e) {
      throw WebExceptionBuilder.buildInternalServerError(e);
    } catch (IllegalArgumentException e) {
      throw WebExceptionBuilder.buildBadRequest(e);
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
    return new ResponseMsg("Succefully deleted stream (" + streamName + ").");
  }
Example #8
0
 @PUT
 @Produces(MediaType.APPLICATION_JSON)
 public EbolaChart getUserName(@Context SecurityContext securityContext, EbolaData data) {
   if (securityContext.getUserPrincipal() == null) {
     throw new EbolaAuthenticationException("login body method");
   }
   EbolaChart chart = new EbolaChart();
   chart.addRangeItem(1, 0, 10);
   chart.addRangeItem(2, 2, 13);
   chart.addRangeItem(3, 5, 18);
   chart.addRangeItem(4, 17, 29);
   chart.addRangeItem(5, 18, 35);
   chart.addRangeItem(6, 23, 45);
   chart.addRangeItem(7, 28, 53);
   chart.addRangeItem(8, 35, 68);
   chart.addRangeItem(9, 45, 100);
   chart.addRangeItem(10, 50, 123);
   chart.addAverageItem(1, 5);
   chart.addAverageItem(2, 8);
   chart.addAverageItem(3, 10);
   chart.addAverageItem(4, 15);
   chart.addAverageItem(5, 20);
   chart.addAverageItem(6, 30);
   chart.addAverageItem(7, 33);
   chart.addAverageItem(8, 55);
   chart.addAverageItem(9, 60);
   chart.addAverageItem(10, 70);
   return chart;
 }
Example #9
0
  // 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();
    }
  }
  /**
   * Get the {@link ActivityStream} for the currently authorized user formatted as a JSON document.
   *
   * @param security Security context of the request
   * @param page Page of the {@link ActivityStream} to fetch
   * @param size Number of activities to include in the {@Link ActivityStream}
   * @return {@link ActivityStream} of the logged in user
   */
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @ApiOperation(
      value = "Get the activity stream of the current user",
      notes = "Get the activity stream of the currently logged-in user",
      response = ActivityStream.class)
  @ApiResponses(
      value = {@ApiResponse(code = 200, message = "Activity stream found for the current user")})
  public ActivityStream getJson(
      @Context SecurityContext security,
      @ApiParam(value = "The page number to retrieve.", defaultValue = "1", required = false)
          @QueryParam("page")
          Integer page,
      @ApiParam(
              value = "Number of activities to retrieve per page.",
              defaultValue = "25",
              required = false)
          @QueryParam("size")
          Integer size) {
    authCheck(security);
    String username = security.getUserPrincipal().getName();
    int start = DEFAULT_START;

    if (size == null) {
      size = DEFAULT_SIZE;
    }

    if (page != null) {
      start = page * size;
    }

    return activityStreamFacade.getActivityStream(username, start, size);
  }
Example #11
0
  @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;
  }
Example #12
0
  @RolesAllowed({Roles.OWNER, Roles.CONSUMER})
  @GET
  @ApiOperation(value = "Get list of streams", notes = "TBD")
  @ApiResponses(value = {@ApiResponse(code = 500, message = "Internal Server Error")})
  public List<Stream> doGetAllStreams(
      @ApiParam(
              name = "stream_owner",
              value = "If null, get currently authenticated user's streams.")
          @QueryParam("stream_owner")
          String streamOwner)
      throws JsonProcessingException {

    if (streamOwner == null) {
      streamOwner = securityContext.getUserPrincipal().getName();
    }

    List<Stream> streams = null;
    StreamDatabaseDriver db = null;
    try {
      db = DatabaseConnector.getStreamDatabase();
      streams = db.getStreamList(streamOwner);
    } catch (SQLException | ClassNotFoundException | IOException | NamingException e) {
      throw WebExceptionBuilder.buildInternalServerError(e);
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
    return streams;
  }
Example #13
0
  @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();
  }
Example #14
0
 @RolesAllowed(Roles.OWNER)
 @POST
 @Consumes(MediaType.APPLICATION_JSON)
 @ApiOperation(value = "Create a new stream", notes = "TBD")
 @ApiResponses(value = {@ApiResponse(code = 500, message = "Internal Server Error")})
 public ResponseMsg doPostNewStream(@Valid Stream stream) throws JsonProcessingException {
   StreamDatabaseDriver db = null;
   String ownerName = securityContext.getUserPrincipal().getName();
   stream.setOwner(ownerName);
   try {
     db = DatabaseConnector.getStreamDatabase();
     db.createStream(stream);
   } catch (IOException | NamingException | SQLException | ClassNotFoundException e) {
     throw WebExceptionBuilder.buildInternalServerError(e);
   } catch (IllegalArgumentException e) {
     throw WebExceptionBuilder.buildBadRequest(e);
   } finally {
     if (db != null) {
       try {
         db.close();
       } catch (SQLException e) {
         e.printStackTrace();
       }
     }
   }
   return new ResponseMsg("Successfully created a new stream: " + stream.name);
 }
Example #15
0
 @PUT
 @Produces("application/json")
 @Path("/changePassword")
 public String changePassword(String passwordInfo)
     throws PreexistingEntityException, NonexistentEntityException {
   String user = securityContext.getUserPrincipal().getName();
   return jsonAssembler.editPassword(passwordInfo, user);
 }
 /**
  * Make sure the specified project has been loaded and is available for use. Checks logged user
  * too. Also the loaded project is placed in the activeProject variable
  *
  * @param projectName
  * @return
  * @throws StorageException, WebApplicationException/unauthorized
  * @throws ProjectDoesNotExist
  */
 void assertProjectAvailable(String projectName) throws StorageException, ProjectDoesNotExist {
   if (!FsProjectStorage.projectExists(projectName, workspaceStorage))
     throw new ProjectDoesNotExist("Project " + projectName + " does not exist");
   ProjectState project = FsProjectStorage.loadProject(projectName, workspaceStorage);
   if (project.getHeader().getOwner() != null) {
     // needs further checking
     if (securityContext.getUserPrincipal() != null) {
       String loggedUser = securityContext.getUserPrincipal().getName();
       if (loggedUser.equals(project.getHeader().getOwner())) {
         this.activeProject = project;
         return;
       }
     }
     throw new WebApplicationException(Response.Status.UNAUTHORIZED);
   }
   activeProject = project;
 }
 private boolean checkRoles(String[] rolesAllowed) {
   for (String role : rolesAllowed) {
     if (securityContext.isUserInRole(role)) {
       return true;
     }
   }
   return false;
 }
Example #18
0
 @PUT
 @Produces("application/json")
 @Path("/edit")
 public String editUser(String userToEdit)
     throws PreexistingEntityException, NonexistentEntityException {
   String user = securityContext.getUserPrincipal().getName();
   return jsonAssembler.editUser(userToEdit, user);
 }
 private void checkSecurityContextEnd(
     ContainerRequestContext rc, MultivaluedMap<String, String> requestParams) {
   String codeParam = requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
   SecurityContext sc = rc.getSecurityContext();
   if (sc == null || sc.getUserPrincipal() == null) {
     if (codeParam == null
         && requestParams.containsKey(OAuthConstants.ERROR_KEY)
         && !faultAccessDeniedResponses) {
       if (!applicationCanHandleAccessDenied) {
         String error = requestParams.getFirst(OAuthConstants.ERROR_KEY);
         rc.abortWith(Response.ok(new AccessDeniedResponse(error)).build());
       }
     } else {
       throw ExceptionUtils.toNotAuthorizedException(null, null);
     }
   }
 }
Example #20
0
 private String getUserId(SecurityContext sc, UriInfo uriInfo) {
   try {
     return sc.getUserPrincipal().getName();
   } catch (NullPointerException e) {
     return getViewerId(uriInfo);
   } catch (Exception e) {
     return null;
   }
 }
Example #21
0
 @Path("myStudyPoints/{classId}")
 @GET
 @Produces("application/json")
 public Response studypointsForStudentClass(@PathParam("classId") String classId) {
   String user = securityContext.getUserPrincipal().getName();
   return Response.status(200)
       .header("Access-Control-Allow-Origin", "*")
       .entity(jsonAssembler.getStudyPointsForCurrentUser(classId, user))
       .build();
 }
Example #22
0
 private boolean isLoggedUser(final Long id) {
   try {
     final User loggerUser = userService.find(securityContext.getUserPrincipal().getName());
     if (loggerUser.getId().equals(id)) {
       return true;
     }
   } catch (final UserNotFoundException e) {
   }
   return false;
 }
Example #23
0
 @DELETE
 public void logout() {
   String userid = securityContext.getUserPrincipal().getName();
   AuthTokenDAO authTokenDAO = new AuthTokenDAOImpl();
   try {
     authTokenDAO.deleteToken(userid);
   } catch (SQLException e) {
     throw new InternalServerErrorException();
   }
 }
Example #24
0
 @Path("login")
 @POST
 public String login(
     @FormParam("userName") String username,
     @FormParam("password") String password,
     @Context SecurityContext securityContext) {
   System.out.println(securityContext.isSecure());
   System.out.println(securityContext.getUserPrincipal());
   try {
     String token = new MobileLoginDAO().loginCheckDAO(username, encodePassword(password));
     if (token.equals("false")) {
       return "false";
     } else {
       return token;
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
     return "false";
   }
 }
Example #25
0
  /**
   * 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);
  }
Example #26
0
 @GET
 @Path("/{id}")
 @Produces({MediaType.APPLICATION_JSON})
 @OAuth20
 @AllowedScopes(scopes = {"test1", "test2"})
 public SampleEntity getEntity(
     @WebParam(name = "id") String id, @Context SecurityContext securityContext) {
   IOAuthPrincipal principal = (IOAuthPrincipal) securityContext.getUserPrincipal();
   String username = principal.getUser().getName();
   String clientId = principal.getClientId();
   return new SampleEntity(id, username, clientId);
 }
Example #27
0
  @RolesAllowed(Roles.OWNER)
  @POST
  @Path("/{stream_name}")
  @Consumes(MediaType.APPLICATION_JSON)
  @ApiOperation(value = "Add a new tuple to the stream.", notes = "TBD")
  @ApiResponses(value = {@ApiResponse(code = 500, message = "Interval Server Error")})
  public ResponseMsg doPostStream(
      @PathParam("stream_name") String streamName,
      @ApiParam(
              name = "str_tuple",
              value =
                  "<pre>Usage:\n"
                      + "[ timestamp, 1st_channel, 2nd_channel, 3rd_channel, .. ]\n"
                      + "\n"
                      + "  e.g., [ \"2013-01-01 09:20:12.12345\", 12.4, 1.2, 5.5 ]\n"
                      + "  e.g., [ null, 12.4, 1.2, 5.5 ]\n"
                      + "\n"
                      + "Or,\n"
                      + "{ \"timestamp\": timestamp\n"
                      + "  \"tuple\": [ 1st_channel, 2nd_channel, 3rd_channel, .. ] }\n"
                      + "\n"
                      + "  e.g., { \"timestamp\": \"2013-01-01 09:20:12.12345\"\n"
                      + "          \"tuple\": [ 12.4, 1.2, 5.5 ] }\n"
                      + "  e.g., { \"timestamp\": null\n"
                      + "          \"tuple\": [ 12.4, 1.2, 5.5 ] }\n"
                      + "\n"
                      + "If timestamp is null, current server time will be used.</pre>")
          String strTuple)
      throws JsonProcessingException {

    String ownerName = securityContext.getUserPrincipal().getName();
    StreamDatabaseDriver db = null;
    try {
      db = DatabaseConnector.getStreamDatabase();
      db.addTuple(ownerName, streamName, strTuple);
    } catch (ClassNotFoundException | IOException | NamingException | SQLException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildInternalServerError(e);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildBadRequest(e);
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
    return new ResponseMsg("Successfully added the tuple.");
  }
 @Path("/{id}")
 @DELETE
 public void deleteUser(@PathParam("id") String id) {
   String userid = securityContext.getUserPrincipal().getName();
   if (!userid.equals(id)) throw new ForbiddenException("operation not allowed");
   UserDAO userDAO = new UserDAOImpl();
   try {
     if (!userDAO.deleteUser(id))
       throw new NotFoundException("User with id = " + id + " doesn't exist");
   } catch (SQLException e) {
     throw new InternalServerErrorException();
   }
 }
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response findAllByUser(@Context SecurityContext sc, @Context HttpServletRequest req) {
    User user = userBean.getUserByEmail(sc.getUserPrincipal().getName());
    List<Activity> activityDetails = activityBean.getAllActivityByUser(user);
    GenericEntity<List<Activity>> projectActivities =
        new GenericEntity<List<Activity>>(activityDetails) {};

    return noCacheResponse
        .getNoCacheResponseBuilder(Response.Status.OK)
        .entity(projectActivities)
        .build();
  }
Example #30
0
  @Path("/events/{eventName}/my-schedule")
  @GET
  public Response getMySchedule(
      @Context final SecurityContext securityContext,
      @PathParam("eventName") final String eventName) {
    String name = securityContext.getUserPrincipal().getName();

    if (name == null) {
      throw new WebApplicationException(Status.UNAUTHORIZED);
    }

    return getScheduleForUser(securityContext, eventName, name);
  }