diff --git a/src/main/java/com/appirio/tech/core/service/identity/IdentityApplication.java b/src/main/java/com/appirio/tech/core/service/identity/IdentityApplication.java index 6745af0..3a127d0 100644 --- a/src/main/java/com/appirio/tech/core/service/identity/IdentityApplication.java +++ b/src/main/java/com/appirio/tech/core/service/identity/IdentityApplication.java @@ -250,8 +250,6 @@ public void run(IdentityConfiguration configuration, Environment environment) th GroupResource groupResource = new GroupResource(groupDao, groupInformixDao); environment.jersey().register(groupResource); environment.jersey().register(groupDao); - // TODO: temporary fix. - userResource.setGroupDAO(groupDao); // Resources::authorizations AuthDataStore authDataStore = configuration.getAuthStore().createAuthDataStore(); diff --git a/src/main/java/com/appirio/tech/core/service/identity/resource/GroupResource.java b/src/main/java/com/appirio/tech/core/service/identity/resource/GroupResource.java index dee9f3d..d31e194 100644 --- a/src/main/java/com/appirio/tech/core/service/identity/resource/GroupResource.java +++ b/src/main/java/com/appirio/tech/core/service/identity/resource/GroupResource.java @@ -98,11 +98,6 @@ public class GroupResource implements GetResource, DDLResource { */ private static final String[] writeScopes = {"write:groups", "all:groups"}; - /** - * Represents the admin roles - */ - private static final String[] adminRoles = {"administrator"}; - /** * Represents the DAO For Group */ @@ -139,7 +134,7 @@ public ApiResponse createObject( @Context HttpServletRequest request) { logger.info("createObject()"); - checkAccess(authUser, writeScopes, adminRoles); + Utils.checkAccess(authUser, writeScopes, Utils.AdminRoles); Group group = validateGroup(postRequest); @@ -185,7 +180,7 @@ public ApiResponse createSecurityGroup( logger.info("createSecurityGroup()"); - checkAccess(authUser, writeScopes, adminRoles); + Utils.checkAccess(authUser, writeScopes, Utils.AdminRoles); if (postRequest == null) { throw new APIRuntimeException(SC_BAD_REQUEST, String.format(MSG_TEMPLATE_MANDATORY, "Group")); @@ -392,7 +387,7 @@ public ApiResponse updateObject( @Context HttpServletRequest request) { logger.info("updateObject()"); - checkAccess(authUser, writeScopes, adminRoles); + Utils.checkAccess(authUser, writeScopes, Utils.AdminRoles); Group group = validateGroup(putRequest); @@ -447,7 +442,7 @@ public ApiResponse deleteObject( @Context HttpServletRequest request) { logger.info(String.format("deleteObject(%s)", groupId)); - checkAccess(authUser, writeScopes, adminRoles); + Utils.checkAccess(authUser, writeScopes, Utils.AdminRoles); Group group = getExistingGroup(new TCID(groupId)); @@ -511,7 +506,7 @@ public ApiResponse getObject( logger.info(String.format("getObject(%s)", groupId)); Group group = getExistingGroup(groupId); - validateAdminRoleOrPrivateGroupMembership(authUser, group, readScopes, adminRoles); + validateAdminRoleOrPrivateGroupMembership(authUser, group, readScopes, Utils.AdminRoles); return ApiResponseFactory.createFieldSelectorResponse(group, selector); } @@ -636,7 +631,7 @@ public ApiResponse getMembers( // Check group exists Group group = getExistingGroup(groupId); - validateAdminRoleOrPrivateGroupMembership(authUser, group, readScopes, adminRoles); + validateAdminRoleOrPrivateGroupMembership(authUser, group, readScopes, Utils.AdminRoles); try { List memberships = groupDao.findMembershipsByGroup(Utils.toLongValue(groupId)); @@ -669,10 +664,10 @@ public ApiResponse getObjects( logger.info(String.format("getObjects(%s, %s)", memberId, membershipType)); - checkAccess(authUser, readScopes, null); + Utils.checkAccess(authUser, readScopes, null); // for admin and machine token - if (authUser.isMachine() || hasAdminRole(authUser)) { + if (authUser.isMachine() || Utils.hasAdminRole(authUser)) { if (memberId==null && Utils.isEmpty(membershipType)) { return ApiResponseFactory.createFieldSelectorResponse(groupDao.findAllGroups(), null); } @@ -709,7 +704,7 @@ public ApiResponse addMember( logger.info("addMember()"); - checkAccess(authUser, writeScopes, null); + Utils.checkAccess(authUser, writeScopes, null); validateMembership(postRequest); @@ -722,7 +717,7 @@ public ApiResponse addMember( Group group = getExistingGroup(groupId); // only admins or self registering users are allowed (if the group allows self register) - if(!authUser.isMachine() && !hasAdminRole(authUser) && !(group.getSelfRegister() && membership.getMemberId().toString().equals(authUser.getUserId().getId()))) { + if(!authUser.isMachine() && !Utils.hasAdminRole(authUser) && !(group.getSelfRegister() && membership.getMemberId().toString().equals(authUser.getUserId().getId()))) { throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); } @@ -759,7 +754,7 @@ public ApiResponse removeMember( logger.info(String.format("removeMember(%s, %s)", groupId, membershipId)); - checkAccess(authUser, writeScopes, null); + Utils.checkAccess(authUser, writeScopes, null); long id = Utils.toLongValue(membershipId); GroupMembership membership = groupDao.findMembership(id); @@ -770,7 +765,7 @@ public ApiResponse removeMember( } // only admins or self registering users are allowed (if the group allows self register) - if(!authUser.isMachine() && !hasAdminRole(authUser) && !(group.getSelfRegister() && membership.getMemberId().toString().equals(authUser.getUserId().getId()))) { + if(!authUser.isMachine() && !Utils.hasAdminRole(authUser) && !(group.getSelfRegister() && membership.getMemberId().toString().equals(authUser.getUserId().getId()))) { throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); } @@ -812,46 +807,4 @@ private void validateAdminRoleOrPrivateGroupMembership(AuthUser authUser, Group } throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); } - - private void checkAccess(AuthUser authUser, String[] allowedScopes, String[] allowedRoles) { - if (authUser == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, String.format(MSG_TEMPLATE_MANDATORY, "Authentication user")); - } - - if (authUser.isMachine()) { - if (allowedScopes == null || allowedScopes.length == 0) { - return; - } - - for (String allowedScope : allowedScopes) { - if (authUser.getScope().contains(allowedScope)) { - return; - } - } - } else { - if (allowedRoles == null || allowedRoles.length == 0) { - return; - } - - for (String role : allowedRoles) { - if (authUser.getRoles() != null && authUser.getRoles().contains(role)) { - return; - } - } - } - - throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); - } - - private boolean hasAdminRole(AuthUser authUser) { - if (authUser.getRoles() != null) { - for (String role : adminRoles) { - if (authUser.getRoles().contains(role)) { - return true; - } - } - } - - return false; - } } diff --git a/src/main/java/com/appirio/tech/core/service/identity/resource/UserResource.java b/src/main/java/com/appirio/tech/core/service/identity/resource/UserResource.java index 58acf4e..9bbdd08 100644 --- a/src/main/java/com/appirio/tech/core/service/identity/resource/UserResource.java +++ b/src/main/java/com/appirio/tech/core/service/identity/resource/UserResource.java @@ -8,10 +8,7 @@ import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -30,7 +27,6 @@ import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; -import org.joda.time.DateTime; import com.appirio.eventsbus.api.client.EventProducer; import com.appirio.tech.core.api.v3.TCID; @@ -48,7 +44,6 @@ import com.appirio.tech.core.auth.AuthUser; import com.appirio.tech.core.service.identity.clients.EventBusServiceClient; import com.appirio.tech.core.service.identity.clients.EventMessage; -import com.appirio.tech.core.service.identity.dao.GroupDAO; import com.appirio.tech.core.service.identity.dao.RoleDAO; import com.appirio.tech.core.service.identity.dao.SSOUserDAO; import com.appirio.tech.core.service.identity.dao.UserDAO; @@ -56,7 +51,6 @@ import com.appirio.tech.core.service.identity.representation.Country; import com.appirio.tech.core.service.identity.representation.Credential; import com.appirio.tech.core.service.identity.representation.Email; -import com.appirio.tech.core.service.identity.representation.GroupMembership; import com.appirio.tech.core.service.identity.representation.ProviderType; import com.appirio.tech.core.service.identity.representation.Role; import com.appirio.tech.core.service.identity.representation.User; @@ -96,7 +90,27 @@ public class UserResource implements GetResource, DDLResource { // TODO: switch to slf4j directly (this delegates to it) - it's more efficient private static final Logger logger = Logger.getLogger(UserResource.class); - + + /** + * Represents the create scopes for machine token validation. + */ + public static final String[] ReadScopes = {"read:user_profiles", "all:user_profiles"}; + + /** + * Represents the create scopes for machine token validation. + */ + public static final String[] CreateScopes = {"create:user_profiles", "all:user_profiles"}; + + /** + * Represents the delete scopes for machine token validation. + */ + public static final String[] DeleteScopes = {"delete:user_profiles", "all:user_profiles"}; + + /** + * Represents the update scopes for machine token validation. + */ + public static final String[] UpdateScopes = {"update:user_profiles", "all:user_profiles"}; + private int resetTokenExpirySeconds = 30 * 60; //30min private int resendActivationCodeExpirySeconds = 30 * 60; //30min @@ -108,24 +122,19 @@ public class UserResource implements GetResource, DDLResource { protected UserDAO userDao; private final RoleDAO roleDao; - - // TODO: temporary fix - private GroupDAO groupDao; - public void setGroupDAO(GroupDAO groupDao) { this.groupDao = groupDao; } protected CacheService cacheService; private Auth0Client auth0; - private EventProducer eventProducer; + private final EventProducer eventProducer; private ObjectMapper objectMapper = new ObjectMapper(); private Long defaultUserRoleId; private String secret; - - + /** * The event bus service client field used to send the event */ @@ -160,6 +169,24 @@ protected void setObjectMapper(ObjectMapper objectMapper) { public void setAuth0Client(Auth0Client auth0) { this.auth0 = auth0; } + + private static void checkAccessAndUserProfile(AuthUser authUser, long userId, UserProfile profile, String[] allowedScopes) { + Utils.checkAccess(authUser, allowedScopes, Utils.AdminRoles); + + if (userId <= 0) { + throw new APIRuntimeException(SC_BAD_REQUEST, "userId should be positive:" + userId); + } + + if (profile == null) { + throw new APIRuntimeException(SC_BAD_REQUEST, "profile must be specified."); + } + if (profile.getProvider() == null) { + throw new APIRuntimeException(SC_BAD_REQUEST, "profile must have provider."); + } + if (profile.getUserId() == null) { + throw new APIRuntimeException(SC_BAD_REQUEST, "profile must have sso user id."); + } + } /** * Create sso user login @@ -167,7 +194,7 @@ public void setAuth0Client(Auth0Client auth0) { * @param authUser the authUser to use * @param userId the userId to use * @param postRequest the postRequest to use - * @throws Exception if any error occurs + * @throws APIRuntimeException if any error occurs * @return the ApiResponse result */ @POST @@ -175,24 +202,11 @@ public void setAuth0Client(Auth0Client auth0) { @Path("/{userId}/SSOUserLogin") public ApiResponse createSSOUserLogin(@Auth AuthUser authUser, @PathParam("userId") long userId, - @Valid PostPutRequest postRequest) throws Exception { - if(!hasAdminRole(authUser)) { - throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); - } - if (userId <= 0) { - throw new APIRuntimeException(SC_BAD_REQUEST, "userId should be positive:" + userId); - } - + @Valid PostPutRequest postRequest) { UserProfile profile = postRequest.getParam(); - if (profile == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, "profile must be specified."); - } - if (profile.getProvider() == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, "profile must have provider."); - } - if (profile.getUserId() == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, "profile must have sso user id."); - } + + checkAccessAndUserProfile(authUser, userId, profile, CreateScopes); + try { SSOUserDAO ssoUserDao = this.userDao.createSSOUserDAO(); Long providerId = ssoUserDao.getSSOProviderIdByName(profile.getProvider()); @@ -222,7 +236,7 @@ public ApiResponse createSSOUserLogin(@Auth AuthUser authUser, * @param authUser the authUser to use * @param userId the userId to use * @param postRequest the postRequest to use - * @throws Exception if any error occurs + * @throws APIRuntimeException if any error occurs * @return the ApiResponse result */ @PUT @@ -230,24 +244,10 @@ public ApiResponse createSSOUserLogin(@Auth AuthUser authUser, @Path("/{userId}/SSOUserLogin") public ApiResponse updateSSOUserLogin(@Auth AuthUser authUser, @PathParam("userId") long userId, - @Valid PostPutRequest postRequest) throws Exception { - if(!hasAdminRole(authUser)) { - throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); - } - if (userId <= 0) { - throw new APIRuntimeException(SC_BAD_REQUEST, "userId should be positive:" + userId); - } - + @Valid PostPutRequest postRequest) { UserProfile profile = postRequest.getParam(); - if (profile == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, "profile must be specified."); - } - if (profile.getProvider() == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, "profile must have provider."); - } - if (profile.getUserId() == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, "profile must have sso user id."); - } + checkAccessAndUserProfile(authUser, userId, profile, UpdateScopes); + try { SSOUserDAO ssoUserDao = this.userDao.createSSOUserDAO(); Long providerId = ssoUserDao.getSSOProviderIdByName(profile.getProvider()); @@ -275,17 +275,15 @@ public ApiResponse updateSSOUserLogin(@Auth AuthUser authUser, * * @param authUser the authUser to use * @param userId the userId to use - * @throws Exception if any error occurs + * @throws APIRuntimeException if any error occurs * @return the ApiResponse result */ @DELETE @Timed @Path("/{userId}/SSOUserLogin") public ApiResponse deleteSSOUserLogin(@Auth AuthUser authUser, - @PathParam("userId") long userId, @QueryParam("provider") String provider, @QueryParam("providerId") Long providerId) throws Exception { - if(!hasAdminRole(authUser)) { - throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); - } + @PathParam("userId") long userId, @QueryParam("provider") String provider, @QueryParam("providerId") Long providerId) { + Utils.checkAccess(authUser, DeleteScopes, Utils.AdminRoles); if (userId <= 0) { throw new APIRuntimeException(SC_BAD_REQUEST, "userId should be positive:" + userId); } @@ -333,22 +331,20 @@ public ApiResponse deleteSSOUserLogin(@Auth AuthUser authUser, * * @param authUser the authUser to use * @param userId the userId to use - * @throws Exception if any error occurs + * @throws APIRuntimeException if any error occurs * @return the ApiResponse result */ @GET @Timed @Path("/{userId}/SSOUserLogins") public ApiResponse getSSOUserLoginsByUserId(@Auth AuthUser authUser, - @PathParam("userId") long userId) throws Exception { - if(!hasAdminRole(authUser)) { - throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); - } + @PathParam("userId") long userId) { + Utils.checkAccess(authUser, ReadScopes, Utils.AdminRoles); if (userId <= 0) { throw new APIRuntimeException(SC_BAD_REQUEST, "userId should be positive:" + userId); } - List profiles = null; + List profiles; try { SSOUserDAO ssoUserDao = this.userDao.createSSOUserDAO(); profiles = ssoUserDao.findProfilesByUserId(userId); @@ -367,13 +363,9 @@ public ApiResponse getSSOUserLoginsByUserId(@Auth AuthUser authUser, public ApiResponse getObjects( @Auth AuthUser authUser, @APIQueryParam(repClass = User.class) QueryParameter query, - @Context HttpServletRequest request) throws Exception { - + @Context HttpServletRequest request) { logger.info("getObjects"); - - if(!hasAdminRole(authUser) && (authUser.getScope() == null || !authUser.getScope().contains("read:user_profiles"))) { - throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); - } + Utils.checkAccess(authUser, ReadScopes, Utils.AdminRoles); try { List users = userDao.findUsers( @@ -387,7 +379,7 @@ public ApiResponse getObjects( /** * Get user object * @param authUser the authUser to use - * @param recordId the recordId to use + * @param resourceId the recordId to use * @param selector the selector to use * @param request the request to use * @throws Exception if any error occurs @@ -399,19 +391,12 @@ public ApiResponse getObjects( @Timed public ApiResponse getObject( @Auth AuthUser authUser, - @PathParam("resourceId") TCID recordId, + @PathParam("resourceId") TCID resourceId, @APIFieldParam(repClass = User.class) FieldSelector selector, @Context HttpServletRequest request) throws Exception { - if (recordId == null) { - throw new APIRuntimeException(SC_BAD_REQUEST, "resourceId is required."); - } - - // checking ID - checkResourceId(recordId); - // checking permission - checkAdminPermission(authUser, recordId); + validateResourceIdAndCheckPermission(authUser, resourceId, ReadScopes); - User user = this.userDao.populateById(selector, recordId); + User user = this.userDao.populateById(selector, resourceId); if (user == null) { throw new APIRuntimeException(SC_NOT_FOUND, MSG_TEMPLATE_USER_NOT_FOUND); } @@ -423,29 +408,15 @@ public ApiResponse getObject( public ApiResponse createObject( AuthUser authUser, @Valid PostPutRequest postRequest, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { throw new APIRuntimeException(HttpServletResponse.SC_NOT_IMPLEMENTED); } - - void addToGroupById(User user, long groupId) { - GroupMembership membership = new GroupMembership(); - membership.setMemberId(Utils.toLongValue(user.getId())); - membership.setMembershipType("user"); - membership.setGroupId(groupId); - membership.setCreatedBy(user.getId()); - membership.setCreatedAt(DateTime.now()); - try { - groupDao.addMembership(membership); - } catch(Exception e) { - logger.error(String.format("Failed to add user %s(%s) to group %s.", user.getId(), user.getHandle(), groupId), e); - } - } @POST @Timed public ApiResponse createObject( @Valid PostPutRequest postRequest, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info("createObject"); @@ -510,7 +481,7 @@ public ApiResponse createObject( // registration mail with activation code for inactive user if(!user.isActive()) { String redirectUrl = postRequest.getOptionString("afterActivationURL"); - logger.debug(String.format("sending registeration mail to: %s (%s)", user.getEmail(), user.getHandle())); + logger.debug(String.format("sending registration mail to: %s (%s)", user.getEmail(), user.getHandle())); // publish event. notifyActivation(user, redirectUrl); } else { @@ -536,10 +507,8 @@ public ApiResponse updateObject( logger.info(String.format("updateObject userId: %s", resourceId)); TCID id = new TCID(resourceId); - // checking ID - checkResourceId(id); - // checking permission - checkAdminPermission(authUser, id); + + validateResourceIdAndCheckPermission(authUser, id, UpdateScopes); // checking param checkParam(patchRequest); @@ -617,7 +586,7 @@ public ApiResponse updateObject( public ApiResponse deleteObject( @Auth AuthUser authUser, @PathParam("resourceId") String resourceId, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { //TODO: throw new APIRuntimeException(SC_NOT_IMPLEMENTED); } @@ -629,15 +598,12 @@ public ApiResponse createUserProfile( @Auth AuthUser authUser, @PathParam("resourceId") String resourceId, @Valid PostPutRequest postRequest, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("createUserProfile(%s)", resourceId)); TCID id = new TCID(resourceId); - // checking ID - checkResourceId(id); - // checking permission - checkAdminPermission(authUser, id); + validateResourceIdAndCheckPermission(authUser, id, CreateScopes); // checking param checkParam(postRequest); @@ -655,7 +621,7 @@ public ApiResponse createUserProfile( // to handle fake social account, adding below check before verifiying from auth0 if(profile.getContext()==null) { - profile.setContext(new HashMap()); + profile.setContext(new HashMap<>()); } profile.getContext().put("socialUserExist", ""); @@ -685,7 +651,7 @@ protected void setAccessToken(UserProfile profile) { try { String accessToken = auth0.getIdProviderAccessToken(auth0UserId); if(profile.getContext()==null) { - profile.setContext(new HashMap()); + profile.setContext(new HashMap<>()); } if(accessToken!=null) { profile.getContext().put("accessToken", accessToken); @@ -703,8 +669,7 @@ public ApiResponse deleteUserProfile( @Auth AuthUser authUser, @PathParam("resourceId") String resourceId, @PathParam("provider") String provider, - @Context HttpServletRequest request) throws Exception { - + @Context HttpServletRequest request) { logger.info(String.format("deleteUserProfile(%s, %s)", resourceId, provider)); if(resourceId==null) @@ -713,10 +678,7 @@ public ApiResponse deleteUserProfile( throw new APIRuntimeException(SC_BAD_REQUEST, String.format(Constants.MSG_TEMPLATE_MANDATORY, "provider")); TCID id = new TCID(resourceId); - // checking ID - checkResourceId(id); - // checking permission - checkAdminPermission(authUser, id); + validateResourceIdAndCheckPermission(authUser, id, DeleteScopes); ProviderType providerType = ProviderType.getByName(provider); if(providerType==null) @@ -741,11 +703,11 @@ else if(providerType.isEnterprise) { /** * API to authenticate users with email and password. * This is supposed to be called from Auth0 custom connection. - * @param email - * @param password - * @param request - * @return - * @throws Exception + * @param handleOrEmail the handle or email string + * @param password the password + * @param request the request + * @return the login + * @throws APIRuntimeException if any error occurs */ @POST @Path("/login") @@ -754,7 +716,7 @@ else if(providerType.isEnterprise) { public ApiResponse login( @FormParam("handleOrEmail") String handleOrEmail, @FormParam("password") String password, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("login(%s, [PASSWORD])", handleOrEmail)); if(Utils.isEmpty(handleOrEmail)) @@ -783,7 +745,7 @@ public ApiResponse login( @Timed public ApiResponse activateUser( @QueryParam("code") String code, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("activateUser(%s)", code)); @@ -827,7 +789,7 @@ public ApiResponse activateUser( public ApiResponse sendActivationCode( @PathParam("resourceId") String resourceId, @Valid PostPutRequest postRequest, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("sendActivationCode(%s)", resourceId)); @@ -861,7 +823,7 @@ public ApiResponse sendActivationCode( // registration mail with activation code for inactive user String redirectUrl = postRequest.getOptionString("afterActivationURL"); - logger.debug(String.format("sending registeration mail to: %s (%s)", user.getEmail(), user.getHandle())); + logger.debug(String.format("sending registration mail to: %s (%s)", user.getEmail(), user.getHandle())); // publish event notifyActivation(user, redirectUrl); @@ -875,15 +837,12 @@ public ApiResponse updateHandle( @Auth AuthUser authUser, @PathParam("resourceId") String resourceId, @Valid PostPutRequest patchRequest, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("updateHandle(%s)", resourceId)); TCID id = new TCID(resourceId); - // checking ID - checkResourceId(id); - // checking permission - checkAdminPermission(authUser, id); + validateResourceIdAndCheckPermission(authUser, id, UpdateScopes); // checking param checkParam(patchRequest); @@ -924,15 +883,12 @@ public ApiResponse updatePrimaryEmail( @Auth AuthUser authUser, @PathParam("resourceId") String resourceId, @Valid PostPutRequest patchRequest, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("updatePrimaryEmail(%s)", resourceId)); TCID id = new TCID(resourceId); - // checking ID - checkResourceId(id); - // checking permission - checkAdminPermission(authUser, id); + validateResourceIdAndCheckPermission(authUser, id, UpdateScopes); // checking param checkParam(patchRequest); @@ -974,9 +930,9 @@ public ApiResponse updatePrimaryEmail( * A bearer token is needed in Authorization header, which is created by getOneTimeToken(). * @param resourceId User ID * @param email New email address - * @param request - * @return - * @throws Exception + * @param request the http request + * @return the api response + * @throws APIRuntimeException any error occurs */ @POST @Path("/{resourceId}/email/{email}") @@ -984,13 +940,14 @@ public ApiResponse updatePrimaryEmail( public ApiResponse updateEmailWithOneTimeToken( @PathParam("resourceId") String resourceId, @PathParam("email") String email, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("updateEmailWithOneTimeToken(%s)", resourceId)); String token = Utils.extractBearer(request); - if(token==null) + if(token==null) { throw new APIRuntimeException(SC_UNAUTHORIZED, "Valid credentials are required."); + } OneTimeToken onetimeToken; try { @@ -1004,7 +961,7 @@ public ApiResponse updateEmailWithOneTimeToken( if(cache==null) throw new APIRuntimeException(SC_UNAUTHORIZED, "Token is expired."); - PostPutRequest postRequest = new PostPutRequest(); + PostPutRequest postRequest = new PostPutRequest<>(); User user = new User(); user.setId(authUser.getUserId()); user.setEmail(email); @@ -1013,7 +970,9 @@ public ApiResponse updateEmailWithOneTimeToken( try { return updatePrimaryEmail(authUser, resourceId, postRequest, request); } finally { - try { cacheService.delete(getCacheKeyForOneTimeToken(user.getId())); } catch(Exception e){} + try { cacheService.delete(getCacheKeyForOneTimeToken(user.getId())); } catch(Exception e){ + // ignore + } } } @@ -1029,15 +988,12 @@ public ApiResponse updateStatus( @PathParam("resourceId") String resourceId, @Valid PostPutRequest patchRequest, @QueryParam("comment") String comment, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("updateStatus(%s, %s)", resourceId, comment)); TCID id = new TCID(resourceId); - // checking ID - checkResourceId(id); - // checking permission - checkAdminPermission(authUser, id); + validateResourceIdAndCheckPermission(authUser, id, UpdateScopes); // checking param checkParam(patchRequest); @@ -1071,11 +1027,12 @@ public ApiResponse updateStatus( return ApiResponseFactory.createResponse(userInDB); } - - @SuppressWarnings("rawtypes") + + protected void checkParam(PostPutRequest request) { - if(request==null || request.getParam()==null) + if(request==null || request.getParam()==null) { throw new APIRuntimeException(SC_BAD_REQUEST, "The request does not contain param data."); + } } //TODO: should be PATCH? @@ -1084,9 +1041,9 @@ protected void checkParam(PostPutRequest request) { @Timed public ApiResponse resetPassword( @Valid PostPutRequest postRequest, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { - logger.info(String.format("resetPassword")); + logger.info("resetPassword"); // checking param checkParam(postRequest); @@ -1140,7 +1097,7 @@ public ApiResponse resetPassword( public ApiResponse getResetToken( @QueryParam("handle") String handle, @QueryParam("email") String email, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("getResetToken(%s, %s)", handle, email)); @@ -1204,14 +1161,11 @@ public ApiResponse getAchievements( @Auth AuthUser authUser, @PathParam("resourceId") TCID resourceId, @APIQueryParam(repClass = Achievement.class) QueryParameter query, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("getAchievements(%s)", resourceId)); - - // checking ID - checkResourceId(resourceId); - // checking permission - checkAdminPermission(authUser, resourceId); + + validateResourceIdAndCheckPermission(authUser, resourceId, ReadScopes); Long userId = Utils.toLongValue(resourceId); logger.debug(String.format("findUserById(%s)", userId)); @@ -1229,7 +1183,7 @@ public ApiResponse getAchievements( @Timed public ApiResponse validateHandle( @QueryParam("handle") String handle, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("validateHandle(%s)", handle)); if(handle==null || handle.length()==0) @@ -1251,7 +1205,7 @@ public ApiResponse validateHandle( @Timed public ApiResponse validateEmail( @QueryParam("email") String email, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("validateEmail(%s)", email)); @@ -1275,7 +1229,7 @@ public ApiResponse validateEmail( public ApiResponse validateSocial( @QueryParam("socialUserId") String socialUserId, @QueryParam("socialProvider") String socialProvider, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("validateSocial(userId=%s, provider=%s)", socialUserId, socialProvider)); @@ -1303,7 +1257,7 @@ public ApiResponse validateSocial( public ApiResponse getOneTimeToken( @FormParam("userId") String userId, @FormParam("password") String password, - @Context HttpServletRequest request) throws Exception { + @Context HttpServletRequest request) { logger.info(String.format("getOneTimeToken(%s)", userId)); @@ -1340,23 +1294,6 @@ public ApiResponse getOneTimeToken( return ApiResponseFactory.createResponse(token); } - protected Long parseLong(String str) { - try { - return Long.parseLong(str); - } catch(Exception e) { logger.warn("Failed to convert String to Long. value: "+str); } - return null; - } - - protected List getRoleNames(Long userId) { - if(roleDao==null) - return null; // don't throw an error for the case Shiro is disabled. - - List roles = roleDao.getRolesBySubjectId(userId); - if(roles==null) - return new ArrayList(0); - return roles.stream().map(role -> role.getRoleName()).collect(Collectors.toList()); - } - protected String generateOneTimeToken(User user, String domain, Integer expirySeconds) { JWTToken jwt = new JWTToken(); jwt.setHandle(user.getHandle()); @@ -1365,21 +1302,35 @@ protected String generateOneTimeToken(User user, String domain, Integer expirySe jwt.setIssuer(jwt.createIssuerFor(domain)); if(expirySeconds!=null) jwt.setExpirySeconds(expirySeconds); - List roles = new ArrayList(); + List roles = new ArrayList<>(); roles.add("Topcoder User"); jwt.setRoles(roles); return jwt.generateToken(getSecret()); } - protected void checkAdminPermission(AuthUser operator, TCID resourceId) { - if(operator==null) + protected void validateResourceIdAndCheckPermission(AuthUser operator, TCID resourceId, String[] allowedScopes) { + if(operator==null) { throw new IllegalArgumentException("operator should be specified."); - if(resourceId!=null && !resourceId.equals(operator.getUserId()) && !hasAdminRole(operator)) - throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); + } + + // checking ID + checkResourceId(resourceId); + + // check permissions + if (resourceId.equals(operator.getUserId())) { + // update self. + return; + } + + Utils.checkAccess(operator, allowedScopes, Utils.AdminRoles); } protected void checkResourceId(TCID id) { + if (id == null) { + throw new APIRuntimeException(SC_BAD_REQUEST, String.format(Constants.MSG_TEMPLATE_MANDATORY, "resourceId")); + } + if(!Utils.isValid(id)) throw new APIRuntimeException(SC_BAD_REQUEST, Constants.MSG_TEMPLATE_INVALID_ID); } @@ -1406,12 +1357,6 @@ protected String getResetPasswordUrlPrefix(HttpServletRequest request) { String.format(template, "www", domain); } - protected boolean hasAdminRole(AuthUser user) { - if(user==null || user.getRoles()==null) - return false; - return user.getRoles().contains("administrator"); - } - protected String generateResetToken() { return Utils.generateRandomString(ALPHABET_ALPHA_EN+ALPHABET_DIGITS_EN, 6); } @@ -1457,7 +1402,7 @@ protected String validateEmail(String email) { /** * Validates country#code and country#name. * If the country has value on these fields, the method checks they are existing in "country" table. - * @param country + * @param country the country to validate * @return null if country is valid. otherwise error message. */ protected String validateCountry(Country country) { @@ -1664,9 +1609,7 @@ protected void publishEvent(String topic, Object payload) { /** * Fire event * - * @param challengeId the challengeId to use - * @param winnerId the userId to use - * @param userId the user id. + * @param payload the payload */ private void fireEvent(Object payload) { EventMessage msg = EventMessage.getDefault(); diff --git a/src/main/java/com/appirio/tech/core/service/identity/util/Utils.java b/src/main/java/com/appirio/tech/core/service/identity/util/Utils.java index 3f82b5a..84a9af9 100644 --- a/src/main/java/com/appirio/tech/core/service/identity/util/Utils.java +++ b/src/main/java/com/appirio/tech/core/service/identity/util/Utils.java @@ -4,7 +4,7 @@ package com.appirio.tech.core.service.identity.util; import static com.appirio.tech.core.service.identity.util.Constants.*; -import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; +import static javax.servlet.http.HttpServletResponse.*; import java.math.BigInteger; import java.util.ArrayList; @@ -68,7 +68,12 @@ public class Utils { public static final String CONTEXT_KEY_PASSWORD_HASH = "passwordHashKey"; private static final Map applicationContext = new LinkedHashMap(); - + + /** + * Represents the admin roles + */ + public static final String[] AdminRoles = {"administrator"}; + /** * The VALID_ISSUERS field */ @@ -484,12 +489,19 @@ public static boolean checkStringLength(String str, Integer min, Integer max) { * @param user the user. * @return if the user admin role. */ - public static boolean hasAdminRole(AuthUser user) { - if (user == null || user.getRoles() == null) - return false; - return user.getRoles().contains("administrator"); - } - + public static boolean hasAdminRole(AuthUser authUser) { + if (authUser == null || authUser.getRoles() == null) { + return false; + } + + for (String role : AdminRoles) { + if (authUser.getRoles().contains(role)) { + return true; + } + } + + return false; + } public static JWTToken extractJWT(String token, String domain, String secret) { if(token==null) @@ -541,4 +553,34 @@ public static String getFullURL(HttpServletRequest request) { return fullURL; } + + public static void checkAccess(AuthUser authUser, String[] allowedScopes, String[] allowedRoles) { + if (authUser == null) { + throw new APIRuntimeException(SC_BAD_REQUEST, String.format(MSG_TEMPLATE_MANDATORY, "Authentication user")); + } + + if (authUser.isMachine()) { + if (allowedScopes == null || allowedScopes.length == 0) { + return; + } + + for (String allowedScope : allowedScopes) { + if (authUser.getScope().contains(allowedScope)) { + return; + } + } + } else { + if (allowedRoles == null || allowedRoles.length == 0) { + return; + } + + for (String role : allowedRoles) { + if (authUser.getRoles() != null && authUser.getRoles().contains(role)) { + return; + } + } + } + + throw new APIRuntimeException(SC_FORBIDDEN, "Forbidden"); + } } diff --git a/src/test/java/com/appirio/tech/core/service/identity/resource/TestUtils.java b/src/test/java/com/appirio/tech/core/service/identity/resource/TestUtils.java index 87850cc..191832c 100644 --- a/src/test/java/com/appirio/tech/core/service/identity/resource/TestUtils.java +++ b/src/test/java/com/appirio/tech/core/service/identity/resource/TestUtils.java @@ -3,10 +3,12 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; +import java.util.ArrayList; import java.util.Arrays; import com.appirio.tech.core.api.v3.TCID; import com.appirio.tech.core.auth.AuthUser; +import com.appirio.tech.core.service.identity.util.Utils; /** * Util class of helper function for tests. @@ -21,7 +23,7 @@ public class TestUtils { * @return the auth user created. */ public static AuthUser createAdminAuthUserMock(TCID userId) { - return createAuthUserMock(userId, new String[]{"administrator"}); + return createAuthUserMock(userId, Utils.AdminRoles); } /** @@ -47,4 +49,16 @@ public static AuthUser createAuthUserMock(TCID userId, String[] roles) { } return authUser; } + + /** + * Create machine user. + * @param allowedScopes the allowed scopes for the given machine user. + * @return the machine user created. + */ + public static AuthUser createMachineUserMock(String[] allowedScopes) { + AuthUser authUser = spy(new AuthUser()); + doReturn(true).when(authUser).isMachine(); + doReturn(Arrays.asList(allowedScopes)).when(authUser).getScope(); + return authUser; + } } diff --git a/src/test/java/com/appirio/tech/core/service/identity/resource/UserResourceTest.java b/src/test/java/com/appirio/tech/core/service/identity/resource/UserResourceTest.java index e11a298..381e34a 100644 --- a/src/test/java/com/appirio/tech/core/service/identity/resource/UserResourceTest.java +++ b/src/test/java/com/appirio/tech/core/service/identity/resource/UserResourceTest.java @@ -21,6 +21,7 @@ import com.appirio.tech.core.service.identity.dao.UserDAO; import com.appirio.tech.core.service.identity.representation.*; import com.appirio.tech.core.service.identity.resource.UserResource.ValidationResult; +import com.appirio.tech.core.service.identity.util.Constants; import com.appirio.tech.core.service.identity.util.Utils; import com.appirio.tech.core.service.identity.util.auth.Auth0Client; import com.appirio.tech.core.service.identity.util.cache.CacheService; @@ -32,7 +33,6 @@ import org.junit.Before; import org.junit.Test; -import org.mockito.ArgumentMatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -61,9 +61,10 @@ * @version 1.1 * */ +@SuppressWarnings("unchecked") public class UserResourceTest { - private RoleDAO mockRoleDao = mock(RoleDAO.class); + private final RoleDAO mockRoleDao = mock(RoleDAO.class); @Before @SuppressWarnings("serial") @@ -109,7 +110,7 @@ public void testCreateObject_ReferralProgram() throws Exception { } @Test - public void testCreateObject_400WhenUTMSourceIsNotSpecifeidInReferralProgram() throws Exception { + public void testCreateObject_400WhenUTMSourceIsNotSpecifiedInReferralProgram() throws Exception { // data User user = createTestUser(null); user.setUtmCampaign("ReferralProgram"); @@ -149,10 +150,7 @@ public void testCreateSSOUserLogin() throws Exception { PostPutRequest param = (PostPutRequest)mock(PostPutRequest.class); when(param.getParam()).thenReturn(userProfile); - AuthUser authUser = spy(new AuthUser()); - List roles = new ArrayList(); - roles.add("administrator"); - when(authUser.getRoles()).thenReturn(roles); + AuthUser authUser = TestUtils.createAdminAuthUserMock(new TCID(2L)); SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); @@ -171,9 +169,98 @@ public void testCreateSSOUserLogin() throws Exception { assertEquals(SC_OK, (int)result.getStatus()); assertTrue(result.getSuccess()); assertEquals(userProfile, result.getContent()); - } - + + /** + * Test CreateSSOUserLogin + * @throws Exception if any error occurs + */ + @Test + public void testCreateSSOUserLogin_MachineUserWithCreateScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + // Creating mock: PostPutRequest - give mock user + UserProfile userProfile = new UserProfile(); + userProfile.setProvider("provider"); + userProfile.setUserId("userId"); + PostPutRequest param = (PostPutRequest)mock(PostPutRequest.class); + when(param.getParam()).thenReturn(userProfile); + + AuthUser authUser = TestUtils.createMachineUserMock(UserResource.CreateScopes); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + + when(ssoUserDao.checkUserIdAndProviderId(1L, 1L)).thenReturn(0); + when(ssoUserDao.getSSOProviderIdByName(userProfile.getProvider())).thenReturn(1L); + + // Test + ApiResponse resp = testee.createSSOUserLogin(authUser, 1, param); + + // Checking result + assertNotNull(resp); + + Result result = resp.getResult(); + assertNotNull(result); + assertEquals(SC_OK, (int)result.getStatus()); + assertTrue(result.getSuccess()); + assertEquals(userProfile, result.getContent()); + } + + /** + * Test CreateSSOUserLogin + * @throws Exception if any error occurs + */ + @Test + public void testCreateSSOUserLogin_MachineUserWithoutCreateScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + // Creating mock: PostPutRequest - give mock user + UserProfile userProfile = new UserProfile(); + userProfile.setProvider("provider"); + userProfile.setUserId("userId"); + PostPutRequest param = (PostPutRequest)mock(PostPutRequest.class); + when(param.getParam()).thenReturn(userProfile); + + AuthUser authUser = TestUtils.createMachineUserMock(new String[0]); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + + when(ssoUserDao.checkUserIdAndProviderId(1L, 1L)).thenReturn(0); + when(ssoUserDao.getSSOProviderIdByName(userProfile.getProvider())).thenReturn(1L); + + try { + // Test + testee.createSSOUserLogin(authUser, 1, param); + } catch (APIRuntimeException e) { + assertEquals(SC_FORBIDDEN, e.getHttpStatus()); + assertEquals("Forbidden", e.getMessage()); + } + } + /** * Test UpdateSSOUserLogin with update logic * @throws Exception if any error occurs @@ -200,10 +287,7 @@ public void testUpdateSSOUserLogin() throws Exception { PostPutRequest param = (PostPutRequest)mock(PostPutRequest.class); when(param.getParam()).thenReturn(userProfile); - AuthUser authUser = spy(new AuthUser()); - List roles = new ArrayList(); - roles.add("administrator"); - when(authUser.getRoles()).thenReturn(roles); + AuthUser authUser = TestUtils.createAdminAuthUserMock(new TCID(2)); SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); @@ -222,7 +306,95 @@ public void testUpdateSSOUserLogin() throws Exception { assertTrue(result.getSuccess()); assertEquals(userProfile, result.getContent()); } - + + /** + * Test UpdateSSOUserLogin with update logic + * @throws Exception if any error occurs + */ + @Test + public void testUpdateSSOUserLogin_MachineUserWithUpdateScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + // Creating mock: PostPutRequest - give mock user + UserProfile userProfile = new UserProfile(); + userProfile.setProvider("provider"); + userProfile.setUserId("userId"); + PostPutRequest param = (PostPutRequest)mock(PostPutRequest.class); + when(param.getParam()).thenReturn(userProfile); + + AuthUser authUser = TestUtils.createMachineUserMock(UserResource.UpdateScopes); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + when(ssoUserDao.checkUserIdAndProviderId(1L, 1L)).thenReturn(1); + when(ssoUserDao.getSSOProviderIdByName(userProfile.getProvider())).thenReturn(1L); + + // Test + ApiResponse resp = testee.updateSSOUserLogin(authUser, 1, param); + + // Checking result + assertNotNull(resp); + + Result result = resp.getResult(); + assertNotNull(result); + assertEquals(SC_OK, (int)result.getStatus()); + assertTrue(result.getSuccess()); + assertEquals(userProfile, result.getContent()); + } + + /** + * Test UpdateSSOUserLogin with update logic + * @throws Exception if any error occurs + */ + @Test + public void testUpdateSSOUserLogin_MachineUserWithoutUpdateScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + // Creating mock: PostPutRequest - give mock user + UserProfile userProfile = new UserProfile(); + userProfile.setProvider("provider"); + userProfile.setUserId("userId"); + PostPutRequest param = (PostPutRequest)mock(PostPutRequest.class); + when(param.getParam()).thenReturn(userProfile); + + AuthUser authUser = TestUtils.createMachineUserMock(new String[0]); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + when(ssoUserDao.checkUserIdAndProviderId(1L, 1L)).thenReturn(1); + when(ssoUserDao.getSSOProviderIdByName(userProfile.getProvider())).thenReturn(1L); + + // Test + try { + testee.updateSSOUserLogin(authUser, 1, param); + } catch (APIRuntimeException e) { + assertEquals(SC_FORBIDDEN, e.getHttpStatus()); + assertEquals("Forbidden", e.getMessage()); + } + } + /** * Test DeleteSSOUserLogin * @throws Exception if any error occurs @@ -241,12 +413,8 @@ public void testDeleteSSOUserLoginWithProviderId() throws Exception { ObjectMapper objectMapper = mock(ObjectMapper.class); when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); - - - AuthUser authUser = spy(new AuthUser()); - List roles = new ArrayList(); - roles.add("administrator"); - when(authUser.getRoles()).thenReturn(roles); + + AuthUser authUser = TestUtils.createAdminAuthUserMock(new TCID(2L)); SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); @@ -265,7 +433,81 @@ public void testDeleteSSOUserLoginWithProviderId() throws Exception { assertTrue(result.getSuccess()); verify(ssoUserDao).deleteSSOUser(any(Long.class), any(Long.class)); } - + + /** + * Test DeleteSSOUserLogin + * @throws Exception if any error occurs + */ + @Test + public void testDeleteSSOUserLoginWithProviderId_MachineUserWithDeleteScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + AuthUser authUser = TestUtils.createMachineUserMock(UserResource.DeleteScopes); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + when(ssoUserDao.checkUserIdAndProviderId(1L, 1L)).thenReturn(1); + when(ssoUserDao.getSSOProviderIdByName("provider")).thenReturn(1L); + + // Test + ApiResponse resp = testee.deleteSSOUserLogin(authUser, 1, null, 1L); + + // Checking result + assertNotNull(resp); + + Result result = resp.getResult(); + assertNotNull(result); + assertEquals(SC_OK, (int)result.getStatus()); + assertTrue(result.getSuccess()); + verify(ssoUserDao).deleteSSOUser(any(Long.class), any(Long.class)); + } + + /** + * Test DeleteSSOUserLogin + * @throws Exception if any error occurs + */ + @Test + public void testDeleteSSOUserLoginWithProviderId_MachineUserWithoutDeleteScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + AuthUser authUser = TestUtils.createMachineUserMock(new String[0]); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + when(ssoUserDao.checkUserIdAndProviderId(1L, 1L)).thenReturn(1); + when(ssoUserDao.getSSOProviderIdByName("provider")).thenReturn(1L); + + // Test + try { + ApiResponse resp = testee.deleteSSOUserLogin(authUser, 1, null, 1L); + } catch (APIRuntimeException e) { + assertEquals(SC_FORBIDDEN, e.getHttpStatus()); + assertEquals("Forbidden", e.getMessage()); + } + } + /** * Test DeleteSSOUserLogin * @throws Exception if any error occurs @@ -286,10 +528,7 @@ public void testDeleteSSOUserLoginWithProvider() throws Exception { UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); - AuthUser authUser = spy(new AuthUser()); - List roles = new ArrayList(); - roles.add("administrator"); - when(authUser.getRoles()).thenReturn(roles); + AuthUser authUser = TestUtils.createAdminAuthUserMock(new TCID(2L)); SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); @@ -332,13 +571,10 @@ public void testGetSSOUserLoginsByUserId() throws Exception { UserProfile userProfile = new UserProfile(); userProfile.setProvider("provider"); userProfile.setUserId("userId"); - List profiles = new ArrayList(); + List profiles = new ArrayList<>(); profiles.add(userProfile); - AuthUser authUser = spy(new AuthUser()); - List roles = new ArrayList(); - roles.add("administrator"); - when(authUser.getRoles()).thenReturn(roles); + AuthUser authUser = TestUtils.createAdminAuthUserMock(new TCID(2L)); SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); when(ssoUserDao.findProfilesByUserId(1L)).thenReturn(profiles); @@ -357,6 +593,92 @@ public void testGetSSOUserLoginsByUserId() throws Exception { assertEquals(userProfile, ((List) result.getContent()).get(0)); } + /** + * Test getSSOUserLogin with update logic + * @throws Exception if any error occurs + */ + @Test + public void testGetSSOUserLoginsByUserId_MachineUserWithReadScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + // Creating mock: PostPutRequest - give mock user + UserProfile userProfile = new UserProfile(); + userProfile.setProvider("provider"); + userProfile.setUserId("userId"); + List profiles = new ArrayList<>(); + profiles.add(userProfile); + + AuthUser authUser = TestUtils.createMachineUserMock(UserResource.ReadScopes); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(ssoUserDao.findProfilesByUserId(1L)).thenReturn(profiles); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + + // Test + ApiResponse resp = testee.getSSOUserLoginsByUserId(authUser, 1); + + // Checking result + assertNotNull(resp); + + Result result = resp.getResult(); + assertNotNull(result); + assertEquals(SC_OK, (int)result.getStatus()); + assertTrue(result.getSuccess()); + assertEquals(userProfile, ((List) result.getContent()).get(0)); + } + + /** + * Test getSSOUserLogin with update logic + * @throws Exception if any error occurs + */ + @Test + public void testGetSSOUserLoginsByUserId_MachineUserWithoutReadScopes() throws Exception { + User user = createTestUser(null); + user.setUtmCampaign("ReferralProgram"); + + UserDAO userDao = mock(UserDAO.class); + + // Creating mock: Other + CacheService cache = mock(CacheService.class); + EventProducer eventProducer = mock(EventProducer.class); + doNothing().when(eventProducer).publish(anyString(), anyString()); + ObjectMapper objectMapper = mock(ObjectMapper.class); + when(objectMapper.writeValueAsString(anyObject())).thenReturn("payload"); + UserResource testee = spy(new UserResource(userDao, mockRoleDao, cache, eventProducer, null)); + + // Creating mock: PostPutRequest - give mock user + UserProfile userProfile = new UserProfile(); + userProfile.setProvider("provider"); + userProfile.setUserId("userId"); + List profiles = new ArrayList<>(); + profiles.add(userProfile); + + AuthUser authUser = TestUtils.createMachineUserMock(new String[0]); + + SSOUserDAO ssoUserDao = mock(SSOUserDAO.class); + when(ssoUserDao.findProfilesByUserId(1L)).thenReturn(profiles); + when(userDao.createSSOUserDAO()).thenReturn(ssoUserDao); + + // Test + try { + testee.getSSOUserLoginsByUserId(authUser, 1); + } catch (APIRuntimeException e) { + assertEquals(SC_FORBIDDEN, e.getHttpStatus()); + assertEquals("Forbidden", e.getMessage()); + } + } + @SuppressWarnings("unchecked") public void testCreateObject_WithUser(User userdata) throws Exception { @@ -430,7 +752,7 @@ isUserActive? never() : times(1)). @SuppressWarnings("unchecked") @Test - public void testCreateObject_400WhenHandleIsInvalid() throws Exception { + public void testCreateObject_400WhenHandleIsInvalid() { // Creating mock: User - always validated User user = spy(createTestUser(null)); @@ -466,7 +788,7 @@ public void testCreateObject_400WhenHandleIsInvalid() throws Exception { @SuppressWarnings("unchecked") @Test - public void testCreateObject_400WhenHandleIsDuplicated() throws Exception { + public void testCreateObject_400WhenHandleIsDuplicated() { // Creating mock: User - always validated User user = spy(createTestUser(null)); @@ -502,7 +824,7 @@ public void testCreateObject_400WhenHandleIsDuplicated() throws Exception { @SuppressWarnings("unchecked") @Test - public void testCreateObject_400WhenEmailIsAlreadyRegistered() throws Exception { + public void testCreateObject_400WhenEmailIsAlreadyRegistered() { // Creating mock: User - always validated User user = spy(createTestUser(null)); @@ -541,11 +863,11 @@ public void testCreateObject_400WhenEmailIsAlreadyRegistered() throws Exception @SuppressWarnings("unchecked") @Test - public void testCreateObject_400WhenSocialProfileIsAlreadyInUse() throws Exception { + public void testCreateObject_400WhenSocialProfileIsAlreadyInUse() { // data User user = spy(createTestUser(null)); - List profiles = new ArrayList(); + List profiles = new ArrayList<>(); user.setProfiles(profiles); UserProfile profile = new UserProfile(); profiles.add(profile); @@ -589,7 +911,7 @@ public void testCreateObject_400WhenSocialProfileIsAlreadyInUse() throws Excepti @SuppressWarnings("unchecked") @Test - public void testCreateObject_400WhenCountryIsInvalid() throws Exception { + public void testCreateObject_400WhenCountryIsInvalid() { // data User user = spy(createTestUser(null)); @@ -697,7 +1019,7 @@ public void testUpdateObject() throws Exception { // confirm check methods are passed verify(testee).checkResourceId(id); - verify(testee).checkAdminPermission(authUser, id); + verify(testee).validateResourceIdAndCheckPermission(authUser, id, UserResource.UpdateScopes); verify(testee).checkParam(param); } @@ -766,7 +1088,7 @@ public void testUpdateObject_UpdatePassword() throws Exception { // confirm check methods are passed verify(testee).checkResourceId(id); - verify(testee).checkAdminPermission(authUser, id); + verify(testee).validateResourceIdAndCheckPermission(authUser, id, UserResource.UpdateScopes); verify(testee).checkParam(param); } @@ -815,10 +1137,7 @@ public void testUpdateObject_400WhenFirstNameIsInvalid() throws Exception { String msg = "DUMMY-ERROR-FIRST-NAME-IS-TOO-LONG"; doReturn(msg).when(user).validateFirstName(); - testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, new UserVerifyer() { - @Override public void doVerify(User user) { - verify(user).validateFirstName(); - }}); + testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, user1 -> verify(user1).validateFirstName()); } @Test @@ -831,10 +1150,7 @@ public void testUpdateObject_400WhenLastNameIsInvalid() throws Exception { String msg = "DUMMY-ERROR-LAST-NAME-IS-TOO-LONG"; doReturn(msg).when(user).validateLastName(); - testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, new UserVerifyer() { - @Override public void doVerify(User user) { - verify(user).validateLastName(); - }}); + testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, user1 -> verify(user1).validateLastName()); } @Test @@ -849,10 +1165,7 @@ public void testUpdateObject_400WhenPasswordIsInvalid() throws Exception { String msg = "DUMMY-ERROR-PASSWORD-IS-INVALID"; doReturn(msg).when(user).validatePassoword(); - testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, new UserVerifyer() { - @Override public void doVerify(User user) { - verify(user).validatePassoword(); - }}); + testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, user1 -> verify(user1).validatePassoword()); } @Test @@ -868,8 +1181,7 @@ public void testUpdateObject_400WhenNoCurrentPasswordSpecifiedForUpdatingPasswor doReturn(null).when(user).validatePassoword(); String msg = String.format(MSG_TEMPLATE_MANDATORY, "Current password"); - testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, new UserVerifyer() { - @Override public void doVerify(User user) {}}); + testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, user1 -> {}); } @Test @@ -884,13 +1196,10 @@ public void testUpdateObject_400WhenCurrentPasswordIsIncorrectForUpdatingPasswor // mock doReturn(null).when(user).validatePassoword(); - String msg = MSG_TEMPLATE_INVALID_CURRENT_PASSWORD; - testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, msg, new UserVerifyer() { - @Override public void doVerify(User user) {}}); + testUpdateObject_ErrorWhenUserIsInvalid(user, SC_BAD_REQUEST, MSG_TEMPLATE_INVALID_CURRENT_PASSWORD, user1 -> {}); } - - static interface UserVerifyer { void doVerify(User user); } + interface UserVerifyer { void doVerify(User user); } @SuppressWarnings("unchecked") public void testUpdateObject_ErrorWhenUserIsInvalid(User user, int statusCode, String message, UserVerifyer verifyer) throws Exception { @@ -937,7 +1246,7 @@ public void testUpdateObject_ErrorWhenUserIsInvalid(User user, int statusCode, S } @Test - public void testCreateUserProfile() throws Exception { + public void testCreateUserProfile() { // data - input String socialUserId = "DUMMY-SOCIAL-USER-ID"; UserProfile profile = new UserProfile(); @@ -1000,12 +1309,12 @@ public void testCreateUserProfile() throws Exception { // confirm check methods are passed verify(testee).checkResourceId(id); - verify(testee).checkAdminPermission(authUser, id); + verify(testee).validateResourceIdAndCheckPermission(authUser, id, UserResource.CreateScopes); verify(testee).checkParam(param); } @Test - public void testCreateUserProfile_400WhenPayloadIsInvalid() throws Exception { + public void testCreateUserProfile_400WhenPayloadIsInvalid() { // data - input UserProfile profile = new UserProfile(); @@ -1048,7 +1357,7 @@ public void testCreateUserProfile_400WhenPayloadIsInvalid() throws Exception { } @Test - public void testCreateUserProfile_404WhenSpecifiedUserDoesNotExist() throws Exception { + public void testCreateUserProfile_404WhenSpecifiedUserDoesNotExist() { // data - input UserProfile profile = new UserProfile(); @@ -1095,7 +1404,7 @@ public void testCreateUserProfile_404WhenSpecifiedUserDoesNotExist() throws Exce } @Test - public void testDeleteUserProfile() throws Exception { + public void testDeleteUserProfile() { // data - input long userId = 123456L; ProviderType provider = ProviderType.GITHUB; @@ -1106,7 +1415,7 @@ public void testDeleteUserProfile() throws Exception { UserProfile profile = new UserProfile(); profile.setUserId(socialUserId); profile.setProviderType(provider.name); - List profiles = new ArrayList(); + List profiles = new ArrayList<>(); profiles.add(profile); // mock: request/response @@ -1143,11 +1452,11 @@ public void testDeleteUserProfile() throws Exception { // confirm check methods are passed verify(testee).checkResourceId(id); - verify(testee).checkAdminPermission(authUser, id); + verify(testee).validateResourceIdAndCheckPermission(authUser, id, UserResource.DeleteScopes); } @Test - public void testDeleteUserProfile_400WhenUserIdIsNotSpecified() throws Exception { + public void testDeleteUserProfile_400WhenUserIdIsNotSpecified() { // data - input ProviderType provider = ProviderType.GITHUB; assertTrue("Provider should be social", provider.isSocial); @@ -1172,7 +1481,7 @@ public void testDeleteUserProfile_400WhenUserIdIsNotSpecified() throws Exception } @Test - public void testDeleteUserProfile_400WhenProviderIsNotSpecified() throws Exception { + public void testDeleteUserProfile_400WhenProviderIsNotSpecified() { // data - input long userId = 123456L; @@ -1196,7 +1505,7 @@ public void testDeleteUserProfile_400WhenProviderIsNotSpecified() throws Excepti } @Test - public void testDeleteUserProfile_400WhenSpecifiedProviderIsNotSupported() throws Exception { + public void testDeleteUserProfile_400WhenSpecifiedProviderIsNotSupported() { // data - input long userId = 123456L; String provider = "UNSUPPORTED-PROVIDER"; @@ -1226,7 +1535,7 @@ public void testDeleteUserProfile_400WhenSpecifiedProviderIsNotSupported() throw } @Test - public void testDeleteUserProfile_404WhenSpecifiedProfileDoesNotExist() throws Exception { + public void testDeleteUserProfile_404WhenSpecifiedProfileDoesNotExist() { // data - input long userId = 123456L; ProviderType provider = ProviderType.GITHUB; @@ -1315,7 +1624,6 @@ public void testGetObject_400WhenIdIsNull() throws Exception { UserDAO userDao = mock(UserDAO.class); EventProducer eventProducer = mock(EventProducer.class); - // Test try { UserResource testee = new UserResource(userDao, mockRoleDao, null, eventProducer, null); @@ -1394,12 +1702,12 @@ public void testGetObject_403WhenUserDoesNotHavePermission() throws Exception { } @Test - public void testGetObjects() throws Exception { + public void testGetObjects() { // Setup APIApplication.JACKSON_OBJECT_MAPPER = Jackson.newObjectMapper(); // Test data - List users = new ArrayList(); + List users = new ArrayList<>(); users.add(new User()); users.add(new User()); @@ -1440,7 +1748,7 @@ public void testGetObjects() throws Exception { @SuppressWarnings("unchecked") @Test - public void testGetObjects_403WhenUserDoesNotHavePermission() throws Exception { + public void testGetObjects_403WhenUserDoesNotHavePermission() { // mock: Parameters AuthUser authUser = mock(AuthUser.class); @@ -1454,7 +1762,6 @@ public void testGetObjects_403WhenUserDoesNotHavePermission() throws Exception { // Test UserResource testee = spy(new UserResource(userDao, mockRoleDao, null, eventProducer, null)); - doReturn(false).when(testee).hasAdminRole(authUser); // user does not have permission try { testee.getObjects(authUser, queryParam, request); } catch (APIRuntimeException e) { @@ -1462,16 +1769,16 @@ public void testGetObjects_403WhenUserDoesNotHavePermission() throws Exception { } // verify - verify(testee).hasAdminRole(authUser); verify(userDao, never()).findUsers(any(FilterParameter.class), any(List.class), any(LimitQuery.class)); } @SuppressWarnings("unchecked") @Test - public void testGetObjects_400WhenParameterIsInvalid() throws Exception { + public void testGetObjects_400WhenParameterIsInvalid() { // mock: Parameters - AuthUser authUser = mock(AuthUser.class); + TCID userId = new TCID(123456789L); + AuthUser authUser = TestUtils.createAdminAuthUserMock(userId); HttpServletRequest request = mock(HttpServletRequest.class); FieldSelector fields = new FieldSelector(); FilterParameter filter = new FilterParameter(null); @@ -1489,7 +1796,6 @@ public void testGetObjects_400WhenParameterIsInvalid() throws Exception { // Test UserResource testee = spy(new UserResource(userDao, mockRoleDao, null, eventProducer, null)); - doReturn(true).when(testee).hasAdminRole(authUser); // treat as an administrator try { testee.getObjects(authUser, queryParam, request); } catch (APIRuntimeException e) { @@ -1497,7 +1803,6 @@ public void testGetObjects_400WhenParameterIsInvalid() throws Exception { } // verify - verify(testee).hasAdminRole(authUser); verify(userDao).findUsers(any(FilterParameter.class), any(List.class), any(LimitQuery.class)); } @@ -1533,8 +1838,8 @@ public void testActivateUser() throws Exception { assertEquals(SC_OK, (int)apiResult.getStatus()); assertTrue("apiResult#getSuccess() should be true.", apiResult.getSuccess()); assertEquals(user, apiResult.getContent()); - assertEquals("user#isActive() should be true.", true, user.isActive()); - assertEquals("user#isEmailActive() should be true.", true, user.isEmailActive()); + assertTrue("user#isActive() should be true.", user.isActive()); + assertTrue("user#isEmailActive() should be true.", user.isEmailActive()); // verify verify(userDao).findUserById(userId); @@ -1545,7 +1850,7 @@ public void testActivateUser() throws Exception { } @Test - public void testActivateUser_403WhenCodeIsInvalid() throws Exception { + public void testActivateUser_403WhenCodeIsInvalid() { // data User user = createTestUser(123456L); // wrong code @@ -1555,7 +1860,7 @@ public void testActivateUser_403WhenCodeIsInvalid() throws Exception { } @Test - public void testActivateUser_403WhenUserHasBeenActivated() throws Exception { + public void testActivateUser_403WhenUserHasBeenActivated() { // data User user = createTestUser(123456L); @@ -1564,7 +1869,7 @@ public void testActivateUser_403WhenUserHasBeenActivated() throws Exception { testActivateUser_403ErrorCase(user, user.getCredential().getActivationCode()); } - private void testActivateUser_403ErrorCase(User user, String activationCode) throws Exception { + private void testActivateUser_403ErrorCase(User user, String activationCode) { // mock HttpServletRequest request = mock(HttpServletRequest.class); @@ -1747,7 +2052,7 @@ public void testSendActivationCode_400WhenActivationCodeHasAlreadyBeenSent() thr @Test - public void testGetOneTimeToken() throws Exception { + public void testGetOneTimeToken() { long userId = 1234567L; String password = "DUMMY-PASSWORD"; @@ -1794,7 +2099,7 @@ public void testGetOneTimeToken() throws Exception { } @Test - public void testGetOneTimeToken_400WhenUserIdOrPasswordNotSpecified() throws Exception { + public void testGetOneTimeToken_400WhenUserIdOrPasswordNotSpecified() { // testee UserResource testee = new UserResource(null, mockRoleDao, null, null, null); @@ -1814,7 +2119,7 @@ public void testGetOneTimeToken_400WhenUserIdOrPasswordNotSpecified() throws Exc } @Test - public void testGetOneTimeToken_403WhenAuthenticationFailed() throws Exception { + public void testGetOneTimeToken_403WhenAuthenticationFailed() { long userId = 1234567L; String password = "DUMMY-PASSWORD"; @@ -1840,7 +2145,7 @@ public void testGetOneTimeToken_403WhenAuthenticationFailed() throws Exception { } @Test - public void testGetOneTimeToken_400WhenTokenHasBeenIssued() throws Exception { + public void testGetOneTimeToken_400WhenTokenHasBeenIssued() { long userId = 1234567L; String password = "DUMMY-PASSWORD"; @@ -1947,7 +2252,7 @@ public void testUpdateHandle() throws Exception { // confirm check methods are passed verify(testee).checkResourceId(id); - verify(testee).checkAdminPermission(authUser, id); + verify(testee).validateResourceIdAndCheckPermission(authUser, id, UserResource.UpdateScopes); verify(testee).checkParam(param); } @@ -2024,7 +2329,7 @@ public void testUpdateHandle_EventIsNotPublishedWhenHandleIsNotChanged() throws @Test @SuppressWarnings("unchecked") - public void testUpdateHandle_400_WhenHandleIsInvalid() throws Exception { + public void testUpdateHandle_400_WhenHandleIsInvalid() { // data long userId = 123456L; String resourceId = String.valueOf(userId); @@ -2062,7 +2367,7 @@ public void testUpdateHandle_400_WhenHandleIsInvalid() throws Exception { @Test @SuppressWarnings("unchecked") - public void testUpdateHandle_400_WhenHandleIsInvalid2() throws Exception { + public void testUpdateHandle_400_WhenHandleIsInvalid2() { // data long userId = 123456L; String resourceId = String.valueOf(userId); @@ -2105,7 +2410,7 @@ public void testUpdateHandle_400_WhenHandleIsInvalid2() throws Exception { @Test @SuppressWarnings("unchecked") - public void testUpdateHandle_404_WhenUserIsNotFound() throws Exception { + public void testUpdateHandle_404_WhenUserIsNotFound() { // parameter String newHandle = "NEW-HANDLE"; @@ -2216,7 +2521,7 @@ public void testUpdatePrimaryEmail() throws Exception { // confirm check methods are passed verify(testee).checkResourceId(id); - verify(testee).checkAdminPermission(authUser, id); + verify(testee).validateResourceIdAndCheckPermission(authUser, id, UserResource.UpdateScopes); verify(testee).checkParam(param); } @@ -2254,7 +2559,7 @@ public void testUpdatePrimaryEmail_EventIsNotPublishedWhenEmailIsNotChanged() th // testee UserResource testee = spy(new UserResource(userDao, mockRoleDao, null, eventProducer, null)); doNothing().when(testee).checkResourceId(any(TCID.class)); - doNothing().when(testee).checkAdminPermission(any(AuthUser.class), any(TCID.class)); + doNothing().when(testee).validateResourceIdAndCheckPermission(authUser, new TCID(resourceId), UserResource.UpdateScopes); doNothing().when(testee).checkParam(any(PostPutRequest.class)); doReturn(null).when(testee).validateEmail(newEmail); // mock: always valid @@ -2284,9 +2589,8 @@ public void testUpdatePrimaryEmail_EventIsNotPublishedWhenEmailIsNotChanged() th verify(eventProducer, never()).publish(eq("event.user.updated"), anyString()); // confirm check methods are passed - TCID uid = new TCID(userId); - verify(testee).checkResourceId(uid); - verify(testee).checkAdminPermission(authUser, uid); + TCID uid = new TCID(resourceId); + verify(testee).validateResourceIdAndCheckPermission(authUser, uid, UserResource.UpdateScopes); verify(testee).checkParam(param); } @@ -2312,7 +2616,7 @@ public void testUpdatePrimaryEmail_400_WhenEmailIsInvalid() throws Exception { // testee UserResource testee = spy(new UserResource(null, null, null, null, null)); doNothing().when(testee).checkResourceId(any(TCID.class)); - doNothing().when(testee).checkAdminPermission(any(AuthUser.class), any(TCID.class)); + doNothing().when(testee).validateResourceIdAndCheckPermission(authUser, new TCID(resourceId), UserResource.UpdateScopes); doNothing().when(testee).checkParam(any(PostPutRequest.class)); //doReturn(null).when(testee).validateEmail(newEmail); // mock: always valid @@ -2329,15 +2633,14 @@ public void testUpdatePrimaryEmail_400_WhenEmailIsInvalid() throws Exception { verify(param, atLeastOnce()).getParam(); // confirm check methods are passed - TCID uid = new TCID(userId); - verify(testee).checkResourceId(uid); - verify(testee).checkAdminPermission(authUser, uid); + TCID uid = new TCID(resourceId); + verify(testee).validateResourceIdAndCheckPermission(authUser, uid, UserResource.UpdateScopes); verify(testee).checkParam(param); } @Test @SuppressWarnings("unchecked") - public void testUpdatePrimaryEmail_400_WhenEmailIsInvalid2() throws Exception { + public void testUpdatePrimaryEmail_400_WhenEmailIsInvalid2() { // data long userId = 123456L; String resourceId = String.valueOf(userId); @@ -2356,7 +2659,7 @@ public void testUpdatePrimaryEmail_400_WhenEmailIsInvalid2() throws Exception { // testee UserResource testee = spy(new UserResource(null, null, null, null, null)); doNothing().when(testee).checkResourceId(any(TCID.class)); - doNothing().when(testee).checkAdminPermission(any(AuthUser.class), any(TCID.class)); + doNothing().when(testee).validateResourceIdAndCheckPermission(authUser, new TCID(resourceId), UserResource.UpdateScopes); doNothing().when(testee).checkParam(any(PostPutRequest.class)); String error = "ERROR"; doReturn(error).when(testee).validateEmail(newEmail); // mock: invalid @@ -2375,15 +2678,14 @@ public void testUpdatePrimaryEmail_400_WhenEmailIsInvalid2() throws Exception { verify(testee).validateEmail(newEmail); // confirm check methods are passed - TCID uid = new TCID(userId); - verify(testee).checkResourceId(uid); - verify(testee).checkAdminPermission(authUser, uid); + TCID uid = new TCID(resourceId); + verify(testee).validateResourceIdAndCheckPermission(authUser, uid, UserResource.UpdateScopes); verify(testee).checkParam(param); } @Test @SuppressWarnings("unchecked") - public void testUpdatePrimaryEmail_404_WhenUserIsNotFound() throws Exception { + public void testUpdatePrimaryEmail_404_WhenUserIsNotFound() { // data long userId = 123456L; String resourceId = String.valueOf(userId); @@ -2406,7 +2708,7 @@ public void testUpdatePrimaryEmail_404_WhenUserIsNotFound() throws Exception { // testee UserResource testee = spy(new UserResource(userDao, mockRoleDao, null, null, null)); doNothing().when(testee).checkResourceId(any(TCID.class)); - doNothing().when(testee).checkAdminPermission(any(AuthUser.class), any(TCID.class)); + doNothing().when(testee).validateResourceIdAndCheckPermission(authUser, new TCID(resourceId), UserResource.UpdateScopes); doNothing().when(testee).checkParam(any(PostPutRequest.class)); doReturn(null).when(testee).validateEmail(newEmail); // mock: valid @@ -2425,14 +2727,13 @@ public void testUpdatePrimaryEmail_404_WhenUserIsNotFound() throws Exception { verify(testee).validateEmail(newEmail); // confirm check methods are passed - TCID uid = new TCID(userId); - verify(testee).checkResourceId(uid); - verify(testee).checkAdminPermission(authUser, uid); + TCID uid = new TCID(resourceId); + verify(testee).validateResourceIdAndCheckPermission(authUser, uid, UserResource.UpdateScopes); verify(testee).checkParam(param); } @Test - public void testUpdateEmailWithOneTimeToken() throws Exception { + public void testUpdateEmailWithOneTimeToken() { // user long userId = 1234567L; User user = createTestUser(userId); @@ -2487,7 +2788,7 @@ public void testUpdateEmailWithOneTimeToken() throws Exception { } @Test - public void testUpdateEmailWithOneTimeToken_401WhenHeaderIsInvalid() throws Exception { + public void testUpdateEmailWithOneTimeToken_401WhenHeaderIsInvalid() { // user long userId = 1234567L; // email @@ -2526,7 +2827,7 @@ public void testUpdateEmailWithOneTimeToken_401WhenHeaderIsInvalid() throws Exce } @Test - public void testUpdateEmailWithOneTimeToken_401WhenTokenIsInvalid() throws Exception { + public void testUpdateEmailWithOneTimeToken_401WhenTokenIsInvalid() { // user long userId = 1234567L; // email @@ -2559,7 +2860,7 @@ public void testUpdateEmailWithOneTimeToken_401WhenTokenIsInvalid() throws Excep @Test - public void testUpdateEmailWithOneTimeToken_401WhenTokenIsExpiredOrAlreadyInUse() throws Exception { + public void testUpdateEmailWithOneTimeToken_401WhenTokenIsExpiredOrAlreadyInUse() { // user long userId = 1234567L; User user = createTestUser(userId); @@ -2737,7 +3038,7 @@ public void testUpdateStatus(String newStatus, String comment, User user) throws // confirm check methods are passed verify(testee).checkResourceId(id); - verify(testee).checkAdminPermission(authUser, id); + verify(testee).validateResourceIdAndCheckPermission(authUser, id, UserResource.UpdateScopes); verify(testee).checkParam(param); } @@ -2746,14 +3047,13 @@ public void testUpdateStatus(String newStatus, String comment, User user) throws public void testUpdateStatus_EventIsNotPublishedWhenStatusIsNotChanged() throws Exception { // parameter - String newStatus = MemberStatus.INACTIVE_DUPLICATE_ACCOUNT.getValue(); String comment = "DUPLICATE_ACCOUNT"; // data long userId = 123456L; String resourceId = String.valueOf(userId); User user = createTestUser(userId); - newStatus = user.getStatus(); // new status is the same status as old one. + String newStatus = user.getStatus(); // new status is the same status as old one. assertEquals(newStatus, user.getStatus()); // mock: UserDAO @@ -2816,7 +3116,7 @@ public void testUpdateStatus_EventIsNotPublishedWhenStatusIsNotChanged() throws @Test @SuppressWarnings("unchecked") - public void testUpdateStatus_400_WhenStatusIsInvalid() throws Exception { + public void testUpdateStatus_400_WhenStatusIsInvalid() { // parameter String newStatus = "INVALID-STATUS"; @@ -2848,7 +3148,7 @@ public void testUpdateStatus_400_WhenStatusIsInvalid() throws Exception { @Test @SuppressWarnings("unchecked") - public void testUpdateStatus_404_WhenUserIsNotFound() throws Exception { + public void testUpdateStatus_404_WhenUserIsNotFound() { // parameter String newStatus = MemberStatus.INACTIVE_DUPLICATE_ACCOUNT.getValue(); @@ -2881,7 +3181,7 @@ public void testUpdateStatus_404_WhenUserIsNotFound() throws Exception { verify(userDao, never()).updateStatus(any(User.class), anyString()); } - protected void testLogin(String handle, String email, String password) throws Exception { + protected void testLogin(String handle, String email, String password) { // data User user = new User(); user.setHandle(handle); @@ -2933,7 +3233,7 @@ else if(email!=null) { @Test - public void testLoginWithEmail() throws Exception { + public void testLoginWithEmail() { // data String email = "jdoe@example.com"; String password = "PASSWORD"; @@ -2943,7 +3243,7 @@ public void testLoginWithEmail() throws Exception { } @Test - public void testLoginWithHandle() throws Exception { + public void testLoginWithHandle() { // data String handle = "jdoe"; String password = "PASSWORD"; @@ -2953,7 +3253,7 @@ public void testLoginWithHandle() throws Exception { } @Test - public void testLogin_400WhenPasswordIsMissing() throws Exception { + public void testLogin_400WhenPasswordIsMissing() { // mock: UserDAO UserDAO userDao = mock(UserDAO.class); @@ -2976,7 +3276,7 @@ public void testLogin_400WhenPasswordIsMissing() throws Exception { } @Test - public void testLogin_401WhenAuthenticationFailed() throws Exception { + public void testLogin_401WhenAuthenticationFailed() { // data String handle = "jdoe"; String email = "jdoe@example.com"; @@ -3016,7 +3316,7 @@ public void testLogin_401WhenAuthenticationFailed() throws Exception { } @Test - public void testLoginWithEmail_400WhenBothHandleAndEmailAreMissing() throws Exception { + public void testLoginWithEmail_400WhenBothHandleAndEmailAreMissing() { // mock: UserDAO UserDAO userDao = mock(UserDAO.class); @@ -3039,21 +3339,21 @@ public void testLoginWithEmail_400WhenBothHandleAndEmailAreMissing() throws Exce } @Test - public void testGetResetToken_ByHandle() throws Exception { + public void testGetResetToken_ByHandle() { String handle = "jdoe"; testGetResetToken(handle, null, null, null); } @Test - public void testGetResetToken_ByEmail() throws Exception { + public void testGetResetToken_ByEmail() { String email = "jdoe@example.com"; testGetResetToken(null, email, null, null); } @Test - public void testGetResetToken_ForConnect() throws Exception { + public void testGetResetToken_ForConnect() { String handle = "jdoe"; String source = "connect"; @@ -3061,7 +3361,7 @@ public void testGetResetToken_ForConnect() throws Exception { } @Test - public void testGetResetToken_ForUserAssociatedWithSocialAccount() throws Exception { + public void testGetResetToken_ForUserAssociatedWithSocialAccount() { String email = "jdoe@example.com"; String socialUserId = "SOCIAL_USER_ID"; @@ -3069,7 +3369,7 @@ public void testGetResetToken_ForUserAssociatedWithSocialAccount() throws Except testGetResetToken(null, email, socialUserId, null); } - protected void testGetResetToken(String handle, String email, String socialUserId, String source) throws Exception { + protected void testGetResetToken(String handle, String email, String socialUserId, String source) { // data long userId = 123456L; User user = createTestUser(userId); @@ -3087,7 +3387,7 @@ protected void testGetResetToken(String handle, String email, String socialUserI when(userDao.findUserByEmail(email)).thenReturn(user); } if(socialUserId!=null) { - List profiles = new ArrayList(); + List profiles = new ArrayList<>(); UserProfile profile = new UserProfile(); profile.setUserId(socialUserId); profile.setProviderType(ProviderType.FACEBOOK.name); @@ -3132,7 +3432,7 @@ protected void testGetResetToken(String handle, String email, String socialUserI assertNull(profile); // reset token should not be generated for social account. // reset token now should _not_ be in the response due to SPA use of this call (10/13/2017) - assertEquals(null, user.getCredential().getResetToken()); + assertNull(user.getCredential().getResetToken()); } // verify if(user.getHandle()!=null) { @@ -3154,7 +3454,7 @@ protected void testGetResetToken(String handle, String email, String socialUserI @Test - public void testGetResetToken_403ForUserAssociatedWithSSOAccount() throws Exception { + public void testGetResetToken_403ForUserAssociatedWithSSOAccount() { // data: user long userId = 123456L; @@ -3164,7 +3464,7 @@ public void testGetResetToken_403ForUserAssociatedWithSSOAccount() throws Except user.setEmail(email); // data: profile - List profiles = new ArrayList(); + List profiles = new ArrayList<>(); UserProfile profile = new UserProfile(); profile.setUserId(ssoUserId); profile.setProviderType(ProviderType.SAMLP.name); @@ -3203,7 +3503,7 @@ public void testGetResetToken_403ForUserAssociatedWithSSOAccount() throws Except } @Test - public void testGetResetToken_400WhenHandleAndEmailAreNull() throws Exception { + public void testGetResetToken_400WhenHandleAndEmailAreNull() { // mock: UserDAO UserDAO userDao = mock(UserDAO.class); @@ -3231,7 +3531,7 @@ public void testGetResetToken_400WhenHandleAndEmailAreNull() throws Exception { } @Test - public void testGetResetToken_404WhenUserDoesNotExist() throws Exception { + public void testGetResetToken_404WhenUserDoesNotExist() { // data long userId = 123456L; User user = createTestUser(userId); @@ -3264,7 +3564,7 @@ public void testGetResetToken_404WhenUserDoesNotExist() throws Exception { } @Test - public void testGetResetToken_400WhenTokenHasAlreadyBeenIssuedAndNotExpiredYet() throws Exception { + public void testGetResetToken_400WhenTokenHasAlreadyBeenIssuedAndNotExpiredYet() { // data long userId = 123456L; User user = createTestUser(userId); @@ -3299,7 +3599,7 @@ public void testGetResetToken_400WhenTokenHasAlreadyBeenIssuedAndNotExpiredYet() @Test - public void testGetResetPasswordUrlPrefix_Default() throws Exception { + public void testGetResetPasswordUrlPrefix_Default() { // mock HttpServletRequest request = mock(HttpServletRequest.class); @@ -3315,7 +3615,7 @@ public void testGetResetPasswordUrlPrefix_Default() throws Exception { } @Test - public void testGetResetPasswordUrlPrefix_Connect() throws Exception { + public void testGetResetPasswordUrlPrefix_Connect() { // mock String source = "connect"; @@ -3334,7 +3634,7 @@ public void testGetResetPasswordUrlPrefix_Connect() throws Exception { } @Test - public void testGetResetPasswordUrlPrefix_SpecificDomain() throws Exception { + public void testGetResetPasswordUrlPrefix_SpecificDomain() { // mock String domain = "DUMMY-DOMAIN"; HttpServletRequest request = mock(HttpServletRequest.class); @@ -3352,7 +3652,7 @@ public void testGetResetPasswordUrlPrefix_SpecificDomain() throws Exception { } @Test - public void testGetResetPasswordUrlPrefix_SpecificDomain_Connect() throws Exception { + public void testGetResetPasswordUrlPrefix_SpecificDomain_Connect() { // mock String domain = "DUMMY-DOMAIN"; String source = "connect"; @@ -3372,7 +3672,7 @@ public void testGetResetPasswordUrlPrefix_SpecificDomain_Connect() throws Except } @Test - public void testGetResetPasswordUrlPrefix_UrlSpecified() throws Exception { + public void testGetResetPasswordUrlPrefix_UrlSpecified() { // mock String source = "connect"; String prefix = "DUMMY-PREFIX"; @@ -3392,7 +3692,7 @@ public void testGetResetPasswordUrlPrefix_UrlSpecified() throws Exception { @Test - public void testResetPassword_ResetWithEmail() throws Exception { + public void testResetPassword_ResetWithEmail() { // data long userId = 123456L; String resetToken = "ABC123"; @@ -3446,7 +3746,7 @@ public void testResetPassword_ResetWithEmail() throws Exception { } @Test - public void testResetPassword_ResetWithHandle() throws Exception { + public void testResetPassword_ResetWithHandle() { // data long userId = 123456L; String resetToken = "ABC123"; @@ -3498,7 +3798,7 @@ public void testResetPassword_ResetWithHandle() throws Exception { } @Test - public void testResetPassword_400WhenNewPasswordIsInvalid() throws Exception { + public void testResetPassword_400WhenNewPasswordIsInvalid() { // data String resetToken = "ABC123", newPassword = "passowrd"; // weak password User paramUser = createUserForResetPasswordTest("jdoe", resetToken, newPassword); @@ -3509,7 +3809,7 @@ public void testResetPassword_400WhenNewPasswordIsInvalid() throws Exception { } @Test - public void testResetPassword_400WhenTokenIsNotSpecified() throws Exception { + public void testResetPassword_400WhenTokenIsNotSpecified() { // data String newPassword = "passowrd123[]"; User paramUser = createUserForResetPasswordTest("jdoe", null, newPassword); // token is null @@ -3520,7 +3820,7 @@ public void testResetPassword_400WhenTokenIsNotSpecified() throws Exception { } @Test - public void testResetPassword_404WhenUserDoesNotExist() throws Exception { + public void testResetPassword_404WhenUserDoesNotExist() { // data String newPassword = "passowrd123[]", resetToken = "ABC123"; User paramUser = createUserForResetPasswordTest("jdoe", resetToken, newPassword); // token is null @@ -3535,7 +3835,7 @@ public void testResetPassword_404WhenUserDoesNotExist() throws Exception { } @Test - public void testResetPassword_400WhenTokenIsExpired() throws Exception { + public void testResetPassword_400WhenTokenIsExpired() { // data long userId = 123456L; String resetToken = "ABC123"; @@ -3558,7 +3858,7 @@ public void testResetPassword_400WhenTokenIsExpired() throws Exception { } @Test - public void testResetPassword_400WhenTokenIsIncorrect() throws Exception { + public void testResetPassword_400WhenTokenIsIncorrect() { // data long userId = 123456L; String resetToken = "ABC123"; @@ -3582,7 +3882,7 @@ public void testResetPassword_400WhenTokenIsIncorrect() throws Exception { } - private void testResetPassword_ErrorCase(User user, UserDAO userDao, CacheService cacheService, int expectedStatus, String expectedMessage) throws Exception { + private void testResetPassword_ErrorCase(User user, UserDAO userDao, CacheService cacheService, int expectedStatus, String expectedMessage) { // mock: other @SuppressWarnings("unchecked") PostPutRequest postRequest = (PostPutRequest)mock(PostPutRequest.class); @@ -3607,7 +3907,7 @@ private void testResetPassword_ErrorCase(User user, UserDAO userDao, CacheServic } @Test - public void testGetAchievements() throws Exception { + public void testGetAchievements() { // setup APIApplication.JACKSON_OBJECT_MAPPER = Jackson.newObjectMapper(); @@ -3616,7 +3916,7 @@ public void testGetAchievements() throws Exception { User user = createTestUser(uid); int dataSize = 2; - List achievements = new ArrayList(); + List achievements = new ArrayList<>(); for(int i=0; i dbProfiles = new ArrayList(); + List dbProfiles = new ArrayList<>(); UserProfile profileBoundWithUser = new UserProfile(); profileBoundWithUser.setUserId("ANOTHER-SOCIAL-USER-ID"); profileBoundWithUser.setProviderType(ProviderType.GITHUB.name); @@ -4251,7 +4546,7 @@ public void testValidateSocialProfile_WithUser_WhenSpecifiedProviderIsAlreadyBou } @Test - public void testValidateSSOProfile() throws Exception { + public void testValidateSSOProfile() { // data UserProfile profile = new UserProfile(); profile.setUserId("AVAILABLE-SSO-USER-ID"); @@ -4276,7 +4571,7 @@ public void testValidateSSOProfile() throws Exception { @Test - public void testValidateSSOProfile_WhenSSOAccountAlreadyInUse() throws Exception { + public void testValidateSSOProfile_WhenSSOAccountAlreadyInUse() { // data UserProfile profile = new UserProfile(); profile.setUserId("AVAILABLE-SSO-USER-ID"); @@ -4300,7 +4595,7 @@ public void testValidateSSOProfile_WhenSSOAccountAlreadyInUse() throws Exception } @Test - public void testValidateSSOProfile_WhenProfileHasNoUserIdAndEmail() throws Exception { + public void testValidateSSOProfile_WhenProfileHasNoUserIdAndEmail() { // data UserProfile profile = new UserProfile(); profile.setUserId(null); @@ -4325,7 +4620,7 @@ public void testValidateSSOProfile_WhenProfileHasNoUserIdAndEmail() throws Excep } @Test - public void testValidateSSOProfile_WhenProvderIsNotForEnterprise() throws Exception { + public void testValidateSSOProfile_WhenProvderIsNotForEnterprise() { // data UserProfile profile = new UserProfile(); profile.setUserId(null); @@ -4349,7 +4644,7 @@ public void testValidateSSOProfile_WhenProvderIsNotForEnterprise() throws Except } @Test - public void testValidateReferral() throws Exception { + public void testValidateReferral() { String referrer = "HANDLE"; @@ -4369,10 +4664,7 @@ public void testValidateReferral() throws Exception { } @Test - public void testValidateReferral_WhenSourceIsNotSpecified() throws Exception { - - String referrer = null; - + public void testValidateReferral_WhenSourceIsNotSpecified() { // mock UserDAO userDao = mock(UserDAO.class); @@ -4380,7 +4672,7 @@ public void testValidateReferral_WhenSourceIsNotSpecified() throws Exception { UserResource testee = new UserResource(userDao, mockRoleDao, null, null, null); // test - String result = testee.validateReferral(referrer); + String result = testee.validateReferral(null); // verify assertEquals(MSG_TEMPLATE_MISSING_UTMSOURCE, result); @@ -4388,7 +4680,7 @@ public void testValidateReferral_WhenSourceIsNotSpecified() throws Exception { } @Test - public void testValidateReferral_WhenSourceIsNotAnExistingHandle() throws Exception { + public void testValidateReferral_WhenSourceIsNotAnExistingHandle() { String referrer = "HANDLE"; @@ -4408,7 +4700,7 @@ public void testValidateReferral_WhenSourceIsNotAnExistingHandle() throws Except } @Test - public void testValidateCountry() throws Exception { + public void testValidateCountry() { // data Country country = new Country(); @@ -4443,7 +4735,7 @@ public void testValidateCountry() throws Exception { @Test - public void testValidateCountry_InvalidWhenAnyCountryIsNotFoundForInput() throws Exception { + public void testValidateCountry_InvalidWhenAnyCountryIsNotFoundForInput() { // data Country country = new Country(); @@ -4483,7 +4775,7 @@ public void testCheckResourceId() { testee.checkResourceId(null); } catch(APIRuntimeException e) { assertEquals(SC_BAD_REQUEST, e.getHttpStatus()); - assertEquals(MSG_TEMPLATE_INVALID_ID, e.getMessage()); + assertEquals(String.format(Constants.MSG_TEMPLATE_MANDATORY, "resourceId"), e.getMessage()); } } @@ -4500,7 +4792,7 @@ public void testCheckAdminPermission_SuccessWhenResourceIsOperatorItself() { UserResource testee = new UserResource(null, null, null, null, null); - testee.checkAdminPermission(authUser, resourceId); + testee.validateResourceIdAndCheckPermission(authUser, resourceId, null); verify(authUser).getUserId(); } @@ -4511,16 +4803,11 @@ public void testCheckAdminPermission_SuccessWhenOperatorIsAdmin() { TCID operatorId = new TCID(123457L); assertNotEquals(resourceId, operatorId); - AuthUser authUser = spy(new AuthUser()); - doReturn(operatorId).when(authUser).getUserId(); + AuthUser authUser = TestUtils.createAdminAuthUserMock(operatorId); UserResource testee = spy(new UserResource(null, null, null, null, null)); - doReturn(true).when(testee).hasAdminRole(authUser); - - testee.checkAdminPermission(authUser, resourceId); - verify(authUser).getUserId(); - verify(testee).hasAdminRole(authUser); + testee.validateResourceIdAndCheckPermission(authUser, resourceId, null); } @Test @@ -4533,17 +4820,15 @@ public void testCheckAdminPermission_FailWhenOperatorDoesNotHaveAccess() { doReturn(operatorId).when(authUser).getUserId(); UserResource testee = spy(new UserResource(null, null, null, null, null)); - doReturn(false).when(testee).hasAdminRole(authUser); // operator does not have admin access try { - testee.checkAdminPermission(authUser, resourceId); + testee.validateResourceIdAndCheckPermission(authUser, resourceId, null); fail("APIRuntimeException(403) should be thrown in the previous step."); } catch (APIRuntimeException e) { assertEquals(SC_FORBIDDEN, e.getHttpStatus()); } verify(authUser).getUserId(); - verify(testee).hasAdminRole(authUser); } @Test @@ -4587,7 +4872,7 @@ public void testSetAccessToken() throws Exception { String auth0UserId = "DUMMY-AUTH0-USER-ID"; UserProfile profile = new UserProfile(); - profile.setContext(new HashMap()); + profile.setContext(new HashMap<>()); profile.getContext().put("auth0UserId", auth0UserId); // mock @@ -4672,7 +4957,6 @@ public void testSetAccessToken_Null_WhenAuth0CausesException() throws Exception testSetAccessToken_CaseToGetNull(userId, providerType, auth0); } - public void testSetAccessToken_CaseToGetNull(String userId, String providerType, Auth0Client auth0) throws Exception { // data String auth0UserId = providerType + "|" + userId; @@ -4728,7 +5012,7 @@ AuthUser createMockAuthUser(TCID userId) { } AuthUser createMockAdminAuthUser(TCID userId) { - return createMockAuthUser(userId, Arrays.asList(new String[]{"administrator"})); + return createMockAuthUser(userId, Arrays.asList(Utils.AdminRoles)); } AuthUser createMockAuthUser(TCID userId, List roles) {