001/*- 002 * #%L 003 * Smile CDR - CDR 004 * %% 005 * Copyright (C) 2016 - 2024 Smile CDR, Inc. 006 * %% 007 * All rights reserved. 008 * #L% 009 */ 010package ca.cdr.api.model.json; 011 012import ca.cdr.api.model.enm.PermissionEnum; 013import io.swagger.v3.oas.annotations.Operation; 014import io.swagger.v3.oas.annotations.Parameter; 015import org.apache.commons.lang3.StringUtils; 016 017import java.util.List; 018import java.util.TreeSet; 019import java.util.stream.Collectors; 020 021import static ca.cdr.api.model.json.UserDetailsJson.toPermissionEnum; 022 023public interface IHasAuthorities { 024 025 /** 026 * Returns the authorities that are granted to the user/session 027 */ 028 List<GrantedAuthorityJson> getPermissions(); 029 030 /** 031 * Returns true if the user has an authority matching this permission, including any that require arguments (in other words, this 032 * check is not argument aware) 033 */ 034 default boolean hasAuthority(PermissionEnum thePermission) { 035 return getPermissions().stream().anyMatch(t -> t.getPermission().equals(thePermission)); 036 } 037 038 /** 039 * Called from javascript 040 */ 041 @SuppressWarnings({"unused", "NonApiType"}) 042 default TreeSet<String> hasArgumentsForAuthority(PermissionEnum thePermission) { 043 return getPermissions().stream() 044 .filter(t -> t.getPermission().equals(thePermission)) 045 .map(GrantedAuthorityJson::getArgument) 046 .filter(StringUtils::isNotBlank) 047 .collect(Collectors.toCollection(TreeSet::new)); 048 } 049 050 @Operation(summary = "addAuthority", description = "Add an authority/permission to the given user") 051 default void addAuthority( 052 @Parameter(name = "thePermission", description = "The Smile CDR permission name") String thePermission) { 053 getPermissions().add(new GrantedAuthorityJson(toPermissionEnum(thePermission))); 054 } 055 056 default void addAuthority(PermissionEnum thePermission, String theArgument) { 057 getPermissions().add(new GrantedAuthorityJson(thePermission, theArgument)); 058 } 059 060 @Operation(summary = "addAuthority", description = "Add an authority/permission with an argument to the given user") 061 default void addAuthority( 062 @Parameter(name = "thePermission", description = "The Smile CDR permission name") String thePermission, 063 @Parameter(name = "theArgument", description = "The argument associated with this permission") 064 String theArgument) { 065 getPermissions().add(new GrantedAuthorityJson(toPermissionEnum(thePermission), theArgument)); 066 } 067}