use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.
the class AbstractAuthenticationResource method connectUserInternal.
protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
// We must also load permissions from repository for configured management or portal role
Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId());
if (!userRoles.isEmpty()) {
userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
// JWT signer
Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
Date issueAt = new Date();
Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
final String token = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setType(BEARER);
tokenEntity.setToken(token);
if (idToken != null) {
tokenEntity.setAccessToken(accessToken);
tokenEntity.setIdToken(idToken);
}
if (state != null && !state.isEmpty()) {
tokenEntity.setState(state);
}
final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
servletResponse.addCookie(bearerCookie);
return Response.ok(tokenEntity).build();
}
use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.
the class AuthoritiesProviderTest method shouldGenerateAuthorities.
@Test
public void shouldGenerateAuthorities() {
final String USER_ID = "userid1";
final RoleEntity portalRole = new RoleEntity();
portalRole.setId("PORTAL_ROLE");
portalRole.setName("PORTAL_ROLE");
portalRole.setScope(RoleScope.ENVIRONMENT);
final RoleEntity mgtRole1 = new RoleEntity();
mgtRole1.setId("MGT_ROLE1");
mgtRole1.setName("MGT_ROLE1");
mgtRole1.setScope(RoleScope.ORGANIZATION);
final RoleEntity mgtRole2 = new RoleEntity();
mgtRole2.setId("MGT_ROLE2");
mgtRole2.setName("MGT_ROLE2");
mgtRole2.setScope(RoleScope.ORGANIZATION);
when(membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, "DEFAULT", MembershipMemberType.USER, USER_ID)).thenReturn(new HashSet<>(asList(portalRole)));
when(membershipService.getRoles(MembershipReferenceType.ORGANIZATION, "DEFAULT", MembershipMemberType.USER, USER_ID)).thenReturn(new HashSet<>(asList(mgtRole1, mgtRole2)));
final Set<GrantedAuthority> grantedAuthorities = cut.retrieveAuthorities(USER_ID);
assertEquals(3, grantedAuthorities.size());
final List<GrantedAuthority> expected = AuthorityUtils.commaSeparatedStringToAuthorityList("ENVIRONMENT:PORTAL_ROLE,ORGANIZATION:MGT_ROLE1,ORGANIZATION:MGT_ROLE2");
assertTrue(grantedAuthorities.containsAll(expected));
}
use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.
the class MembershipCommandHandler method handle.
@Override
public Single<MembershipReply> handle(MembershipCommand command) {
MembershipPayload membershipPayload = command.getPayload();
GraviteeContext.setCurrentOrganization(membershipPayload.getOrganizationId());
try {
RoleScope roleScope;
MembershipReferenceType membershipReferenceType;
try {
roleScope = RoleScope.valueOf(membershipPayload.getReferenceType());
membershipReferenceType = MembershipReferenceType.valueOf(membershipPayload.getReferenceType());
} catch (Exception e) {
logger.error("Invalid referenceType [{}].", membershipPayload.getReferenceType());
return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
}
final UserEntity userEntity = userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false);
final RoleEntity roleEntity = findRole(roleScope, membershipPayload.getRole());
final MembershipService.MembershipReference membershipReference = new MembershipService.MembershipReference(membershipReferenceType, membershipPayload.getReferenceId());
final MembershipService.MembershipMember membershipMember = new MembershipService.MembershipMember(userEntity.getId(), null, MembershipMemberType.USER);
final MembershipService.MembershipRole membershipRole = new MembershipService.MembershipRole(roleEntity.getScope(), roleEntity.getName());
membershipService.updateRolesToMemberOnReference(membershipReference, membershipMember, Collections.singletonList(membershipRole), COCKPIT_SOURCE, false);
logger.info("Role [{}] assigned on {} [{}] for user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), userEntity.getId(), membershipPayload.getOrganizationId());
return Single.just(new MembershipReply(command.getId(), CommandStatus.SUCCEEDED));
} catch (Exception e) {
logger.error("Error occurred when trying to assign role [{}] on {} [{}] for cockpit user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), membershipPayload.getUserId(), membershipPayload.getOrganizationId(), e);
return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
} finally {
GraviteeContext.cleanContext();
}
}
use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.
the class MembershipService_GetMemberPermissionsTest method shouldGetPermissionsIfMemberOfApi.
@Test
public void shouldGetPermissionsIfMemberOfApi() throws Exception {
ApiEntity api = mock(ApiEntity.class);
doReturn(API_ID).when(api).getId();
doReturn(Collections.emptySet()).when(api).getGroups();
doReturn(api).when(apiService).findById(API_ID);
Membership membership = mock(Membership.class);
doReturn("API_" + ROLENAME).when(membership).getRoleId();
doReturn(new HashSet<>(asList(membership))).when(membershipRepository).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
UserEntity userEntity = mock(UserEntity.class);
doReturn(userEntity).when(userService).findById(USERNAME);
RoleEntity roleEntity = mock(RoleEntity.class);
Map<String, char[]> rolePerms = new HashMap<>();
rolePerms.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.UPDATE.getId(), RolePermissionAction.CREATE.getId() });
doReturn(rolePerms).when(roleEntity).getPermissions();
doReturn(roleEntity).when(roleService).findById("API_" + ROLENAME);
Map<String, char[]> permissions = membershipService.getUserMemberPermissions(api, USERNAME);
assertNotNull(permissions);
assertPermissions(rolePerms, permissions);
verify(membershipRepository, times(1)).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
verify(membershipRepository, never()).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.GROUP, GROUP_ID1);
verify(apiService, times(1)).findById(API_ID);
verify(userService, times(1)).findById(USERNAME);
verify(roleService, times(1)).findById("API_" + ROLENAME);
}
use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.
the class MembershipService_GetMemberPermissionsTest method shouldGetMergedPermissionsIfMemberOfApiAndApiGroup.
@Test
public void shouldGetMergedPermissionsIfMemberOfApiAndApiGroup() throws Exception {
ApiEntity api = mock(ApiEntity.class);
doReturn(API_ID).when(api).getId();
doReturn(Collections.singleton(GROUP_ID1)).when(api).getGroups();
doReturn(api).when(apiService).findById(API_ID);
Membership membershipUser = mock(Membership.class);
doReturn("API_" + ROLENAME).when(membershipUser).getRoleId();
doReturn(new HashSet<>(asList(membershipUser))).when(membershipRepository).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
Membership membershipGroup = mock(Membership.class);
doReturn("API_" + ROLENAME2).when(membershipGroup).getRoleId();
doReturn(new HashSet<>(asList(membershipGroup))).when(membershipRepository).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.GROUP, GROUP_ID1);
UserEntity userEntity = mock(UserEntity.class);
doReturn(userEntity).when(userService).findById(USERNAME);
RoleEntity roleEntity = mock(RoleEntity.class);
Map<String, char[]> rolePerms = new HashMap<>();
rolePerms.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.UPDATE.getId(), RolePermissionAction.CREATE.getId() });
doReturn(rolePerms).when(roleEntity).getPermissions();
doReturn(roleEntity).when(roleService).findById("API_" + ROLENAME);
RoleEntity roleEntity2 = mock(RoleEntity.class);
Map<String, char[]> rolePerms2 = new HashMap<>();
rolePerms2.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.READ.getId(), RolePermissionAction.DELETE.getId() });
rolePerms2.put(ApiPermission.PLAN.getName(), new char[] { RolePermissionAction.READ.getId() });
doReturn(rolePerms2).when(roleEntity2).getPermissions();
doReturn(RoleScope.API).when(roleEntity2).getScope();
doReturn(roleEntity2).when(roleService).findById("API_" + ROLENAME2);
Map<String, char[]> permissions = membershipService.getUserMemberPermissions(api, USERNAME);
assertNotNull(permissions);
Map<String, char[]> expectedPermissions = new HashMap<>();
expectedPermissions.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.CREATE.getId(), RolePermissionAction.READ.getId(), RolePermissionAction.UPDATE.getId(), RolePermissionAction.DELETE.getId() });
expectedPermissions.put(ApiPermission.PLAN.getName(), new char[] { RolePermissionAction.READ.getId() });
assertPermissions(expectedPermissions, permissions);
verify(membershipRepository, times(1)).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
verify(membershipRepository, times(1)).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.GROUP, GROUP_ID1);
verify(apiService, times(1)).findById(API_ID);
verify(userService, times(1)).findById(USERNAME);
verify(roleService, times(1)).findById("API_" + ROLENAME);
verify(roleService, times(1)).findById("API_" + ROLENAME2);
}
Aggregations