UserService extends Service { @ApiOperation(value = "Create a new user", notes = "Create a new user in the system. There are two ways to create a user: through a regular registration workflow " + "and by system/admin. In the former case, auth token is sent to user's mailbox, while system/admin can create a user directly " + "with predefined name and password", response = UserDescriptor.class) @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 missing 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(); } @Inject  UserService(UserDao userDao,
                       UserProfileDao profileDao,
                       PreferenceDao preferenceDao,
                       TokenValidator tokenValidator); @ApiOperation(value = "Create a new user", notes = "Create a new user in the system. There are two ways to create a user: through a regular registration workflow " + "and by system/admin. In the former case, auth token is sent to user's mailbox, while system/admin can create a user directly " + "with predefined name and password", response = UserDescriptor.class) @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 missing request parameters"), @ApiResponse(code = 500, message = "Internal Server Error")}) @POST @Path("/create") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @GenerateLink(rel = LINK_REL_CREATE_USER) 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); @ApiOperation(value = "Get current user", notes = "Get user currently logged in the system", response = UserDescriptor.class, position = 2) @ApiResponses({@ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal Server Error")}) @GET @GenerateLink(rel = LINK_REL_GET_CURRENT_USER) @RolesAllowed({"user", "temp_user"}) @Produces(APPLICATION_JSON) UserDescriptor getCurrent(@Context SecurityContext context); @ApiOperation(value = "Update password", notes = "Update current password") @ApiResponses({@ApiResponse(code = 204, message = "OK"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 403, message = "Invalid password"), @ApiResponse(code = 500, message = "Internal Server Error")}) @POST @Path("/password") @GenerateLink(rel = LINK_REL_UPDATE_PASSWORD) @RolesAllowed("user") @Consumes(APPLICATION_FORM_URLENCODED) void updatePassword(@ApiParam(value = "New password", required = true)
                               @FormParam("password")
                               String password); @ApiOperation(value = "Get user by ID", notes = "Get user by its ID in the system. Roles allowed: system/admin, system/manager.", response = UserDescriptor.class) @ApiResponses({@ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal Server Error")}) @GET @Path("/{id}") @GenerateLink(rel = LINK_REL_GET_USER_BY_ID) @RolesAllowed({"user", "system/admin", "system/manager"}) @Produces(APPLICATION_JSON) UserDescriptor getById(@ApiParam(value = "User ID") @PathParam("id") String id,
                                  @Context SecurityContext context); @ApiOperation(value = "Get user by email", notes = "Get user by registration email. Roles allowed: system/admin, system/manager.", response = UserDescriptor.class) @ApiResponses({@ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "Missed parameter email"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal Server Error")}) @GET @Path("/find") @GenerateLink(rel = LINK_REL_GET_USER_BY_EMAIL) @RolesAllowed({"user", "system/admin", "system/manager"}) @Produces(APPLICATION_JSON) UserDescriptor getByEmail(@ApiParam(value = "User email", required = true) @QueryParam("email") @Required String email,
                                     @Context SecurityContext context); @ApiOperation(value = "Delete user", notes = "Delete a user from the system. Roles allowed: system/admin") @ApiResponses({@ApiResponse(code = 204, message = "Deleted"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 409, message = "Impossible to remove user"), @ApiResponse(code = 500, message = "Internal Server Error")}) @DELETE @Path("/{id}") @GenerateLink(rel = LINK_REL_REMOVE_USER_BY_ID) @RolesAllowed("system/admin") void remove(@ApiParam(value = "User ID")
                       @PathParam("id") String id); @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) @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 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);  }
@Test public void shouldBeAbleToCreateNewUser() throws Exception { final String userEmail = "test@email.com"; final String token = "test_token"; when(tokenValidator.validateToken(token)).thenReturn(userEmail); final ContainerResponse response = makeRequest(HttpMethod.POST, SERVICE_PATH + "/create?token=" + token, null); assertEquals(response.getStatus(), CREATED.getStatusCode()); final UserDescriptor user = (UserDescriptor) response.getEntity(); assertEquals(user.getEmail(), userEmail); assertEquals(user.getPassword(), "<none>"); verify(userDao).create(any(User.class)); verify(profileDao).create(any(Profile.class)); }
@Test public void shouldBeAbleToCreateNewUserForSystemAdmin() throws Exception { final NewUser newUser = DtoFactory.getInstance() .createDto(NewUser.class) .withName("test") .withPassword("password123"); when(securityContext.isUserInRole("system/admin")).thenReturn(true); final ContainerResponse response = makeRequest(HttpMethod.POST, SERVICE_PATH + "/create", newUser); assertEquals(response.getStatus(), CREATED.getStatusCode()); final UserDescriptor descriptor = (UserDescriptor)response.getEntity(); assertEquals(descriptor.getName(), newUser.getName()); assertEquals(descriptor.getPassword(), "<none>"); verify(userDao).create(any(User.class)); verify(profileDao).create(any(Profile.class)); }
@Test public void shouldThrowForbiddenExceptionWhenCreatingUserWithInvalidPassword() throws Exception { final NewUser newUser = DtoFactory.getInstance() .createDto(NewUser.class) .withName("test") .withPassword("password"); when(securityContext.isUserInRole("system/admin")).thenReturn(true); final ContainerResponse response = makeRequest(HttpMethod.POST, SERVICE_PATH + "/create", newUser); assertEquals(response.getStatus(), FORBIDDEN.getStatusCode()); verify(userDao, never()).create(any(User.class)); verify(profileDao, never()).create(any(Profile.class)); }
@Test public void shouldGeneratedPasswordWhenCreatingUserAndItIsMissing() throws Exception { final NewUser newUser = DtoFactory.getInstance() .createDto(NewUser.class) .withName("test"); when(securityContext.isUserInRole("system/admin")).thenReturn(true); final ContainerResponse response = makeRequest(HttpMethod.POST, SERVICE_PATH + "/create", newUser); final UserDescriptor descriptor = (UserDescriptor)response.getEntity(); assertEquals(descriptor.getName(), newUser.getName()); assertEquals(descriptor.getPassword(), "<none>"); verify(userDao).create(any(User.class)); verify(profileDao).create(any(Profile.class)); }
@Test public void shouldThrowUnauthorizedExceptionWhenCreatingUserBasedOnTokenAndItIsNull() throws Exception { final ContainerResponse response = makeRequest(HttpMethod.POST, SERVICE_PATH + "/create", null); assertEquals(response.getStatus(), UNAUTHORIZED.getStatusCode()); verify(userDao, never()).create(any(User.class)); verify(profileDao, never()).create(any(Profile.class)); }
@Test public void shouldThrowForbiddenExceptionWhenCreatingUserBasedOnEntityWhichIsNull() throws Exception { when(securityContext.isUserInRole("system/admin")).thenReturn(true); final ContainerResponse response = makeRequest(HttpMethod.POST, SERVICE_PATH + "/create", null); assertEquals(response.getStatus(), FORBIDDEN.getStatusCode()); verify(userDao, never()).create(any(User.class)); verify(profileDao, never()).create(any(Profile.class)); }
@Test public void shouldThrowForbiddenExceptionWhenCreatingUserBasedOnEntityWhichContainsNullEmail() throws Exception { final NewUser newUser = DtoFactory.getInstance().createDto(NewUser.class); when(securityContext.isUserInRole("system/admin")).thenReturn(true); final ContainerResponse response = makeRequest(HttpMethod.POST, SERVICE_PATH + "/create", newUser); assertEquals(response.getStatus(), FORBIDDEN.getStatusCode()); verify(userDao, never()).create(any(User.class)); verify(profileDao, never()).create(any(Profile.class)); }