repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/DisabledSecurity.java | src/main/java/org/ohdsi/webapi/shiro/management/DisabledSecurity.java | package org.ohdsi.webapi.shiro.management;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.shiro.filters.CorsFilter;
import org.ohdsi.webapi.shiro.filters.HideResourceFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.*;
/**
*
* @author gennadiy.anisimov
*/
@Component
@Primary
@ConditionalOnProperty(name = "security.provider", havingValue = Constants.SecurityProviders.DISABLED)
@DependsOn("flyway")
public class DisabledSecurity extends Security {
@Override
public Map<String, String> getFilterChain() {
Map<String, String> filterChain = new HashMap<>();
filterChain.put("/user/**", HIDE_RESOURCE.getTemplateName());
filterChain.put("/role/**", HIDE_RESOURCE.getTemplateName());
filterChain.put("/permission/**", HIDE_RESOURCE.getTemplateName());
filterChain.put("/**", CORS.getTemplateName());
return filterChain;
}
@Override
public Map<FilterTemplates, Filter> getFilters() {
Map<FilterTemplates, Filter> filters = new HashMap<>();
filters.put(HIDE_RESOURCE, new HideResourceFilter());
filters.put(CORS, new CorsFilter());
return filters;
}
@Override
public Set<Realm> getRealms() {
return new HashSet<>();
}
@Override
public ModularRealmAuthenticator getAuthenticator() {
return new ModularRealmAuthenticator();
}
@Override
public String getSubject() {
return "anonymous";
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/AtlasSecurity.java | src/main/java/org/ohdsi/webapi/shiro/management/AtlasSecurity.java | package org.ohdsi.webapi.shiro.management;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.filter.authz.SslFilter;
import org.apache.shiro.web.filter.session.NoSessionCreationFilter;
import org.ohdsi.webapi.OidcConfCreator;
import org.ohdsi.webapi.cohortcharacterization.CcImportEvent;
import org.ohdsi.webapi.security.model.EntityPermissionSchemaResolver;
import org.ohdsi.webapi.security.model.EntityType;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.ohdsi.webapi.shiro.filters.CorsFilter;
import org.ohdsi.webapi.shiro.filters.ForceSessionCreationFilter;
import org.ohdsi.webapi.shiro.filters.ResponseNoCacheFilter;
import org.ohdsi.webapi.shiro.filters.UrlBasedAuthorizingFilter;
import org.ohdsi.webapi.source.SourceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import waffle.shiro.negotiate.NegotiateAuthenticationStrategy;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.AUTHZ;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.CORS;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.FORCE_SESSION_CREATION;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.JWT_AUTHC;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.NO_CACHE;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.NO_SESSION_CREATION;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.SSL;
/**
*
* @author gennadiy.anisimov
*/
public abstract class AtlasSecurity extends Security {
public static final String TOKEN_ATTRIBUTE = "TOKEN";
public static final String AUTH_CLIENT_ATTRIBUTE = "AUTH_CLIENT";
public static final String AUTH_FILTER_ATTRIBUTE = "AuthenticatingFilter";
public static final String PERMISSIONS_ATTRIBUTE = "PERMISSIONS";
public static final String AUTH_CLIENT_SAML = "AUTH_CLIENT_SAML";
public static final String AUTH_CLIENT_ALL = "ALL";
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
protected PermissionManager authorizer;
@Autowired
protected SourceRepository sourceRepository;
@Autowired
protected OidcConfCreator oidcConfCreator;
@Value("${server.port}")
private int sslPort;
@Value("${security.ssl.enabled}")
private boolean sslEnabled;
private final EntityPermissionSchemaResolver permissionSchemaResolver;
protected final Set<String> defaultRoles = new LinkedHashSet<>();
private final Map<String, String> featureAnalysisPermissionTemplates;
private final Map<FilterTemplates, Filter> filters = new HashMap<>();
public AtlasSecurity(EntityPermissionSchemaResolver permissionSchemaResolver) {
this.defaultRoles.add("public");
this.permissionSchemaResolver = permissionSchemaResolver;
featureAnalysisPermissionTemplates = permissionSchemaResolver.getForType(EntityType.FE_ANALYSIS).getAllPermissions();
}
@PostConstruct
private void init() {
fillFilters();
}
@Override
public Map<String, String> getFilterChain() {
return getFilterChainBuilder().build();
}
protected abstract FilterChainBuilder getFilterChainBuilder();
protected FilterChainBuilder setupProtectedPaths(FilterChainBuilder filterChainBuilder) {
return filterChainBuilder
// version info
.addRestPath("/info")
// DDL service
.addRestPath("/ddl/results")
.addRestPath("/ddl/cemresults")
.addRestPath("/ddl/achilles")
.addRestPath("/ddl/extra")
.addRestPath("/saml/saml-metadata")
.addRestPath("/saml/slo")
//executionservice callbacks
.addRestPath("/executionservice/callbacks/**")
.addRestPath("/permission/access/**/*", JWT_AUTHC) // Authorization check is done inside controller
//i18n
.addRestPath("/i18n")
.addRestPath("/i18n/**")
.addProtectedRestPath("/**/*");
}
@Override
public Map<FilterTemplates, Filter> getFilters(){
return new HashMap<>(filters);
}
private void fillFilters() {
filters.put(NO_SESSION_CREATION, new NoSessionCreationFilter());
filters.put(FORCE_SESSION_CREATION, new ForceSessionCreationFilter());
filters.put(AUTHZ, new UrlBasedAuthorizingFilter());
filters.put(CORS, new CorsFilter());
filters.put(SSL, this.getSslFilter());
filters.put(NO_CACHE, this.getNoCacheFilter());
}
@Override
public Set<Realm> getRealms() {
return new LinkedHashSet<>();
}
@Override
public ModularRealmAuthenticator getAuthenticator() {
ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
authenticator.setAuthenticationStrategy(new NegotiateAuthenticationStrategy());
return authenticator;
}
private Filter getSslFilter() {
SslFilter sslFilter = new SslFilter();
sslFilter.setPort(sslPort);
sslFilter.setEnabled(sslEnabled);
return sslFilter;
}
private Filter getNoCacheFilter() {
return new ResponseNoCacheFilter();
}
@Override
public String getSubject() {
try {
if (SecurityUtils.getSubject().isAuthenticated()) {
return authorizer.getSubjectName();
}
} catch (UnavailableSecurityManagerException e) {
log.warn("No security manager is available, authenticated as anonymous");
}
return "anonymous";
}
// Since we need to create permissions only for certain analyses, we cannot go with `addProcessEntityFilter`
@EventListener
public void onCcImport(CcImportEvent event) throws Exception {
for (Integer id : event.getSavedAnalysesIds()) {
authorizer.addPermissionsFromTemplate(featureAnalysisPermissionTemplates, id.toString());
}
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/AtlasGoogleSecurity.java | src/main/java/org/ohdsi/webapi/shiro/management/AtlasGoogleSecurity.java | package org.ohdsi.webapi.shiro.management;
import org.apache.shiro.realm.Realm;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.security.model.EntityPermissionSchemaResolver;
import org.ohdsi.webapi.shiro.filters.GoogleIapJwtAuthFilter;
import org.ohdsi.webapi.shiro.realms.JwtAuthRealm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import java.util.Map;
import java.util.Set;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.AUTHZ;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.CORS;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.JWT_AUTHC;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.NO_CACHE;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.NO_SESSION_CREATION;
import static org.ohdsi.webapi.shiro.management.FilterTemplates.SSL;
@Component
@ConditionalOnProperty(name = "security.provider", havingValue = Constants.SecurityProviders.GOOGLE)
@DependsOn("flyway")
public class AtlasGoogleSecurity extends AtlasSecurity {
// Execute in console to get the ID:
// gcloud config get-value account | tr -cd "[0-9]"
@Value("${security.googleIap.cloudProjectId}")
private Long googleCloudProjectId;
// Execute in console to get the ID:
// gcloud compute backend-services describe my-backend-service --global --format="value(id)"
@Value("${security.googleIap.backendServiceId}")
private Long googleBackendServiceId;
public AtlasGoogleSecurity(EntityPermissionSchemaResolver permissionSchemaResolver) {
super(permissionSchemaResolver);
}
@Override
protected FilterChainBuilder getFilterChainBuilder() {
FilterChainBuilder filterChainBuilder = new FilterChainBuilder()
.setRestFilters(SSL, NO_SESSION_CREATION, CORS, NO_CACHE)
.setAuthcFilter(JWT_AUTHC)
.setAuthzFilter(AUTHZ);
setupProtectedPaths(filterChainBuilder);
return filterChainBuilder.addRestPath("/**");
}
@Override
public Map<FilterTemplates, Filter> getFilters() {
Map<FilterTemplates, Filter> filters = super.getFilters();
filters.put(JWT_AUTHC, new GoogleIapJwtAuthFilter(authorizer, defaultRoles, googleCloudProjectId, googleBackendServiceId));
return filters;
}
@Override
public Set<Realm> getRealms() {
Set<Realm> realms = super.getRealms();
realms.add(new JwtAuthRealm(this.authorizer));
return realms;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/FilterChainBuilder.java | src/main/java/org/ohdsi/webapi/shiro/management/FilterChainBuilder.java | package org.ohdsi.webapi.shiro.management;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class FilterChainBuilder {
private Map<String, String> filterChain = new LinkedHashMap<>();
private String restFilters;
private String authcFilter;
private String authzFilter;
private String filtersBeforeOAuth;
private String filtersAfterOAuth;
public FilterChainBuilder setRestFilters(FilterTemplates... restFilters) {
this.restFilters = convertArrayToString(restFilters);
return this;
}
public FilterChainBuilder setBeforeOAuthFilters(FilterTemplates... filtersBeforeOAuth) {
this.filtersBeforeOAuth = convertArrayToString(filtersBeforeOAuth);
return this;
}
public FilterChainBuilder setAfterOAuthFilters(FilterTemplates... filtersAfterOAuth) {
this.filtersAfterOAuth = convertArrayToString(filtersAfterOAuth);
return this;
}
public FilterChainBuilder setAuthcFilter(FilterTemplates... authcFilters) {
this.authcFilter = convertArrayToString(authcFilters);
return this;
}
public FilterChainBuilder setAuthzFilter(FilterTemplates... authzFilters) {
this.authzFilter = convertArrayToString(authzFilters);
return this;
}
public FilterChainBuilder addRestPath(String path, String filters) {
return this.addPath(path, this.restFilters + ", " + filters);
}
public FilterChainBuilder addRestPath(String path, FilterTemplates... filters) {
return addRestPath(path, convertArrayToString(filters));
}
public FilterChainBuilder addRestPath(String path) {
return this.addPath(path, this.restFilters);
}
public FilterChainBuilder addOAuthPath(String path, FilterTemplates... oauthFilters) {
return this.addPath(path, filtersBeforeOAuth + ", " + convertArrayToString(oauthFilters) + ", " + filtersAfterOAuth);
}
public FilterChainBuilder addProtectedRestPath(String path) {
return this.addRestPath(path, this.authcFilter + ", " + this.authzFilter);
}
public FilterChainBuilder addProtectedRestPath(String path, FilterTemplates... filters) {
String filtersStr = convertArrayToString(filters);
return this.addRestPath(path, authcFilter + ", " + authzFilter + ", " + filtersStr);
}
public FilterChainBuilder addPath(String path, FilterTemplates... filters) {
return addPath(path, convertArrayToString(filters));
}
public FilterChainBuilder addPath(String path, String filters) {
path = path.replaceAll("/+$", "");
this.filterChain.put(path, filters);
// If path ends with non wildcard character, need to add two paths -
// one without slash at the end and one with slash at the end, because
// both URLs like www.domain.com/myapp/mypath and www.domain.com/myapp/mypath/
// (note the slash at the end) are falling into the same method, but
// for filter chain these are different paths
if (!path.endsWith("*")) {
this.filterChain.put(path + "/", filters);
}
return this;
}
public Map<String, String> build() {
return filterChain;
}
private String convertArrayToString(FilterTemplates... templates){
return Arrays.stream(templates)
.map(FilterTemplates::getTemplateName)
.collect(Collectors.joining(", "));
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/Security.java | src/main/java/org/ohdsi/webapi/shiro/management/Security.java | package org.ohdsi.webapi.shiro.management;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
/**
*
* @author gennadiy.anisimov
*/
public abstract class Security {
public static final String SOURCE_ACCESS_PERMISSION = "source:%s:access";
public static String PROFILE_VIEW_DATES_PERMISSION = "*:person:*:get:dates";
public abstract String getSubject();
public abstract Set<Realm> getRealms();
public abstract Map<FilterTemplates, Filter> getFilters();
public abstract Map<String, String> getFilterChain();
public abstract ModularRealmAuthenticator getAuthenticator();
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/DataSourceAccessBeanPostProcessor.java | src/main/java/org/ohdsi/webapi/shiro/management/DataSourceAccessBeanPostProcessor.java | package org.ohdsi.webapi.shiro.management;
import org.aopalliance.intercept.MethodInterceptor;
import org.ohdsi.webapi.shiro.annotations.DataSourceAccess;
import org.ohdsi.webapi.shiro.management.datasource.AccessorParameterBinding;
import org.ohdsi.webapi.shiro.management.datasource.DataSourceAccessParameterResolver;
import org.ohdsi.webapi.util.AnnotationReflectionUtils;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.*;
public class DataSourceAccessBeanPostProcessor implements BeanPostProcessor {
private Boolean proxyTargetClass;
private DataSourceAccessParameterResolver accessParameterResolver;
public DataSourceAccessBeanPostProcessor(DataSourceAccessParameterResolver accessParameterResolver, Boolean proxyTargetClass) {
this.accessParameterResolver = accessParameterResolver;
this.proxyTargetClass = proxyTargetClass;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class type = bean.getClass();
final List<Method> annotatedMethods = getMethodsAnnotatedWith(type);
Object result = bean;
if (!annotatedMethods.isEmpty()) {
ProxyFactory factory = new ProxyFactory(bean);
factory.setProxyTargetClass(proxyTargetClass);
factory.addAdvice((MethodInterceptor) invocation -> {
Method method = invocation.getMethod();
Object[] args = invocation.getArguments();
Optional<Method> originalAnnotatedMethod = annotatedMethods.stream().filter(m ->
Objects.equals(m.getName(), method.getName())
&& Objects.equals(m.getReturnType(), method.getReturnType())
&& Arrays.equals(m.getParameterTypes(), method.getParameterTypes())).findFirst();
if (originalAnnotatedMethod.isPresent()) {
AccessorParameterBinding<Object> binding = accessParameterResolver.resolveParameterBinding(originalAnnotatedMethod.get());
if (Objects.nonNull(binding)) {
Object value = args[binding.getParameterIndex()];
binding.getDataSourceAccessor().checkAccess(value);
}
}
return method.invoke(bean, args);
});
result = factory.getProxy();
}
return result;
}
private Method findMethod(Method m1, Method m2) {
if (m2.getDeclaringClass().isAssignableFrom(m2.getDeclaringClass())) {
if (Objects.equals(m1.getName(), m2.getName())) {
return ReflectionUtils.findMethod(m1.getDeclaringClass(), m1.getName(), m1.getParameterTypes());
}
}
return null;
}
private List<Method> getMethodsAnnotatedWith(final Class<?> type) {
List<Method> methods = AnnotationReflectionUtils.getMethodsAnnotatedWith(type, DataSourceAccess.class);
methods.forEach(m -> {
if (Objects.isNull(accessParameterResolver.resolveParameterBinding(m))) {
throw new BeanInitializationException(String.format("One of method: %s parameters should be annotated with SourceKey of CcGenerationId", m.toString()));
}
});
return methods;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/PathwayAnalysisGenerationIdAccessor.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/PathwayAnalysisGenerationIdAccessor.java | package org.ohdsi.webapi.shiro.management.datasource;
import org.ohdsi.webapi.pathway.repository.PathwayAnalysisGenerationRepository;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.util.EntityUtils;
import org.springframework.stereotype.Component;
import javax.ws.rs.NotFoundException;
@Component
public class PathwayAnalysisGenerationIdAccessor extends BaseDataSourceAccessor<Long> {
private PathwayAnalysisGenerationRepository repository;
public PathwayAnalysisGenerationIdAccessor(PathwayAnalysisGenerationRepository repository) {
this.repository = repository;
}
@Override
protected Source extractSource(Long id) {
return repository.findById(id, EntityUtils.fromAttributePaths("source")).orElseThrow(NotFoundException::new).getSource();
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/DataSourceAccessParameterResolver.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/DataSourceAccessParameterResolver.java | package org.ohdsi.webapi.shiro.management.datasource;
import org.ohdsi.webapi.shiro.annotations.CcGenerationId;
import org.ohdsi.webapi.shiro.annotations.PathwayAnalysisGenerationId;
import org.ohdsi.webapi.shiro.annotations.SourceId;
import org.ohdsi.webapi.shiro.annotations.SourceKey;
import org.ohdsi.webapi.source.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
@Component
public class DataSourceAccessParameterResolver {
@Autowired
private SourceKeyAccessor sourceKeyAccessor;
@Autowired
private SourceIdAccessor sourceIdAccessor;
@Autowired
private CcGenerationIdAccessor generationIdAccessor;
@Autowired
private PathwayAnalysisGenerationIdAccessor pathwayAnalysisGenerationIdAccessor;
@Autowired
private SourceAccessor sourceAccessor;
public <T> AccessorParameterBinding<T> resolveParameterBinding(Method method){
Annotation[][] annotations = method.getParameterAnnotations();
for(int i = 0; i < annotations.length; i++) {
DataSourceAccessor<?> result = null;
if (isAnnotated(annotations[i], SourceKey.class)) {
result = sourceKeyAccessor;
} else if (isAnnotated(annotations[i], SourceId.class)) {
result = sourceIdAccessor;
} else if (isAnnotated(annotations[i], CcGenerationId.class)) {
result = generationIdAccessor;
} else if (isAnnotated(annotations[i], PathwayAnalysisGenerationId.class)) {
result = pathwayAnalysisGenerationIdAccessor;
}
if (Objects.nonNull(result)) {
return new AccessorParameterBinding(i, result);
}
}
Class<?>[] parameterTypes = method.getParameterTypes();
for(int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i].isAssignableFrom(Source.class)) {
return new AccessorParameterBinding(i, sourceAccessor);
}
}
return null;
}
private boolean isAnnotated(Annotation[] annotations, Class<? extends Annotation> annotation) {
return Arrays.stream(annotations).anyMatch(annotation::isInstance);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/SourceIdAccessor.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/SourceIdAccessor.java | package org.ohdsi.webapi.shiro.management.datasource;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.source.SourceRepository;
import org.springframework.stereotype.Component;
@Component
public class SourceIdAccessor extends BaseDataSourceAccessor<Integer> {
private SourceRepository sourceRepository;
public SourceIdAccessor(SourceRepository sourceRepository) {
this.sourceRepository = sourceRepository;
}
@Override
protected Source extractSource(Integer sourceId) {
return sourceRepository.findBySourceId(sourceId);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/CcGenerationIdAccessor.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/CcGenerationIdAccessor.java | package org.ohdsi.webapi.shiro.management.datasource;
import org.ohdsi.webapi.cohortcharacterization.repository.CcGenerationEntityRepository;
import org.ohdsi.webapi.source.Source;
import org.springframework.stereotype.Component;
import javax.ws.rs.NotFoundException;
@Component
public class CcGenerationIdAccessor extends BaseDataSourceAccessor<Long> {
private CcGenerationEntityRepository ccGenerationRepository;
public CcGenerationIdAccessor(CcGenerationEntityRepository ccGenerationRepository) {
this.ccGenerationRepository = ccGenerationRepository;
}
@Override
protected Source extractSource(Long id) {
return ccGenerationRepository.findById(id).orElseThrow(NotFoundException::new).getSource();
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/SourceKeyAccessor.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/SourceKeyAccessor.java | package org.ohdsi.webapi.shiro.management.datasource;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.source.SourceRepository;
import org.springframework.stereotype.Component;
@Component
public class SourceKeyAccessor extends BaseDataSourceAccessor<String> {
private SourceRepository sourceRepository;
public SourceKeyAccessor(SourceRepository sourceRepository) {
this.sourceRepository = sourceRepository;
}
@Override
protected Source extractSource(String sourceKey) {
return sourceRepository.findBySourceKey(sourceKey);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/DataSourceAccessor.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/DataSourceAccessor.java | package org.ohdsi.webapi.shiro.management.datasource;
@FunctionalInterface
public interface DataSourceAccessor<T> {
void checkAccess(T value);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/BaseDataSourceAccessor.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/BaseDataSourceAccessor.java | package org.ohdsi.webapi.shiro.management.datasource;
import org.apache.shiro.SecurityUtils;
import org.ohdsi.webapi.shiro.management.DisabledSecurity;
import org.ohdsi.webapi.shiro.management.Security;
import org.ohdsi.webapi.source.Source;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.ForbiddenException;
public abstract class BaseDataSourceAccessor<T> implements DataSourceAccessor<T> {
@Autowired(required = false)
private DisabledSecurity disabledSecurity;
public void checkAccess(T s) {
if (!hasAccess(s)) {
throw new ForbiddenException();
}
}
public boolean hasAccess(T s) {
if (disabledSecurity != null) {
return true;
}
Source source = extractSource(s);
if (source == null) {
return false;
}
return SecurityUtils.getSubject().isPermitted(String.format(Security.SOURCE_ACCESS_PERMISSION, source.getSourceKey()));
}
protected abstract Source extractSource(T source);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/AccessorParameterBinding.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/AccessorParameterBinding.java | package org.ohdsi.webapi.shiro.management.datasource;
public class AccessorParameterBinding<T> {
private Integer parameterIndex;
private DataSourceAccessor<T> dataSourceAccessor;
public AccessorParameterBinding(Integer parameterIndex, DataSourceAccessor<T> dataSourceAccessor) {
this.parameterIndex = parameterIndex;
this.dataSourceAccessor = dataSourceAccessor;
}
public Integer getParameterIndex() {
return parameterIndex;
}
public DataSourceAccessor<T> getDataSourceAccessor() {
return dataSourceAccessor;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/management/datasource/SourceAccessor.java | src/main/java/org/ohdsi/webapi/shiro/management/datasource/SourceAccessor.java | package org.ohdsi.webapi.shiro.management.datasource;
import org.ohdsi.webapi.source.Source;
import org.springframework.stereotype.Component;
@Component
public class SourceAccessor extends BaseDataSourceAccessor<Source> {
@Override
protected Source extractSource(Source source) {
return source;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/runas/RunAsStorage.java | src/main/java/org/ohdsi/webapi/shiro/runas/RunAsStorage.java | package org.ohdsi.webapi.shiro.runas;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.List;
public interface RunAsStorage {
void pushPrincipals(Object principal, PrincipalCollection principals);
PrincipalCollection popPrincipals(Object principal);
List<PrincipalCollection> getRunAsPrincipalStack(Object principal);
void removeRunAsStack(Object principal);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/runas/DefaultInMemoryRunAsStorage.java | src/main/java/org/ohdsi/webapi/shiro/runas/DefaultInMemoryRunAsStorage.java | package org.ohdsi.webapi.shiro.runas;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class DefaultInMemoryRunAsStorage implements RunAsStorage {
private final Map<Object, List<PrincipalCollection>> principalsMap = new ConcurrentHashMap<>();
@Override
public void pushPrincipals(Object principal, PrincipalCollection principals) {
if (Objects.isNull(principals) || principals.isEmpty()) {
throw new IllegalArgumentException("Specified Subject principals cannot be null or empty for 'run as' functionality.");
}
List<PrincipalCollection> stack = getRunAsPrincipalStack(principal);
if (Objects.isNull(stack)) {
stack = new CopyOnWriteArrayList<>();
principalsMap.put(principal, stack);
}
stack.add(0, principals);
}
@Override
public PrincipalCollection popPrincipals(Object principal) {
PrincipalCollection popped = null;
List<PrincipalCollection> stack = getRunAsPrincipalStack(principal);
if (!Objects.isNull(stack) && !stack.isEmpty()) {
popped = stack.remove(0);
if (stack.isEmpty()) {
removeRunAsStack(principal);
}
}
return popped;
}
@Override
public List<PrincipalCollection> getRunAsPrincipalStack(Object principal) {
if (Objects.isNull(principal)) {
throw new IllegalArgumentException("Token should not be null value");
}
return principalsMap.get(principal);
}
@Override
public void removeRunAsStack(Object principal) {
principalsMap.remove(principal);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/annotations/PathwayAnalysisGenerationId.java | src/main/java/org/ohdsi/webapi/shiro/annotations/PathwayAnalysisGenerationId.java | package org.ohdsi.webapi.shiro.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface PathwayAnalysisGenerationId {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/annotations/DataSourceAccess.java | src/main/java/org/ohdsi/webapi/shiro/annotations/DataSourceAccess.java | package org.ohdsi.webapi.shiro.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSourceAccess {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/annotations/CcGenerationId.java | src/main/java/org/ohdsi/webapi/shiro/annotations/CcGenerationId.java | package org.ohdsi.webapi.shiro.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface CcGenerationId {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/annotations/SourceKey.java | src/main/java/org/ohdsi/webapi/shiro/annotations/SourceKey.java | package org.ohdsi.webapi.shiro.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface SourceKey {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/annotations/SourceId.java | src/main/java/org/ohdsi/webapi/shiro/annotations/SourceId.java | package org.ohdsi.webapi.shiro.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface SourceId {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/lockout/LockEntry.java | src/main/java/org/ohdsi/webapi/shiro/lockout/LockEntry.java | package org.ohdsi.webapi.shiro.lockout;
import java.util.Objects;
class LockEntry {
private int attempts;
private long expired = 0L;
public static final long EXPIRED_NOT_SET = -1L;
public LockEntry(int attempts, long expired) {
this.attempts = attempts;
this.expired = expired;
}
public int getAttempts() {
return attempts;
}
public long getExpired() {
return expired;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LockEntry)) return false;
LockEntry lockEntry = (LockEntry) o;
return attempts == lockEntry.attempts &&
expired == lockEntry.expired;
}
@Override
public int hashCode() {
return Objects.hash(attempts, expired);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/lockout/NoLockoutPolicy.java | src/main/java/org/ohdsi/webapi/shiro/lockout/NoLockoutPolicy.java | package org.ohdsi.webapi.shiro.lockout;
public class NoLockoutPolicy implements LockoutPolicy {
@Override
public boolean isLockedOut(String principal) {
return true;
}
@Override
public boolean isLockedOut(LockEntry entry) {
return true;
}
@Override
public long getLockExpiration(String principal) {
return 0;
}
@Override
public void loginFailed(String principal) {
}
@Override
public void loginSucceeded(String principal) {
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/lockout/LockoutPolicy.java | src/main/java/org/ohdsi/webapi/shiro/lockout/LockoutPolicy.java | package org.ohdsi.webapi.shiro.lockout;
public interface LockoutPolicy {
boolean isLockedOut(String principal);
boolean isLockedOut(LockEntry entry);
long getLockExpiration(String principal);
void loginFailed(String principal);
void loginSucceeded(String principal);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/lockout/LockoutStrategy.java | src/main/java/org/ohdsi/webapi/shiro/lockout/LockoutStrategy.java | package org.ohdsi.webapi.shiro.lockout;
public interface LockoutStrategy {
long getLockDuration(int attempts);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/lockout/LockoutWebSecurityManager.java | src/main/java/org/ohdsi/webapi/shiro/lockout/LockoutWebSecurityManager.java | package org.ohdsi.webapi.shiro.lockout;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LockoutWebSecurityManager extends DefaultWebSecurityManager {
private static final Logger log = LoggerFactory.getLogger(LockoutWebSecurityManager.class);
private LockoutPolicy lockoutPolicy;
public LockoutWebSecurityManager(LockoutPolicy lockoutPolicy) {
this.lockoutPolicy = lockoutPolicy;
}
@Override
protected void onFailedLogin(AuthenticationToken token, AuthenticationException ae, Subject subject) {
log.debug("Failed to login: {}", ae.getMessage(), ae);
super.onFailedLogin(token, ae, subject);
if (token instanceof UsernamePasswordToken) {
String username = ((UsernamePasswordToken) token).getUsername();
lockoutPolicy.loginFailed(username);
}
}
@Override
protected void onSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info, Subject subject) {
super.onSuccessfulLogin(token, info, subject);
if (token instanceof UsernamePasswordToken) {
String username = ((UsernamePasswordToken) token).getUsername();
lockoutPolicy.loginSucceeded(username);
}
}
@Override
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
if (token instanceof UsernamePasswordToken) {
String username = ((UsernamePasswordToken) token).getUsername();
if (lockoutPolicy.isLockedOut(username)) {
long expiration = lockoutPolicy.getLockExpiration(username);
long now = new Date().getTime();
long tryInSeconds = TimeUnit.MILLISECONDS.toSeconds(expiration - now);
AuthenticationException ae = new LockedAccountException("Maximum login attempts is reached. Please, try again in " + tryInSeconds + " seconds.");
try {
onFailedLogin(token, ae, subject);
} catch (Exception e) {
log.info("onFailure method threw an exception.", e);
}
throw ae;
}
}
info = authenticate(token);
if (Objects.isNull(info) || Objects.isNull(info.getCredentials())) {
AuthenticationException ae = new AuthenticationException("No authentication info for token [" + token + "]");
try {
onFailedLogin(token, ae, subject);
} catch (Exception e) {
if (log.isInfoEnabled()) {
log.info("onFailedLogin method threw an " +
"exception. Logging and propagating original AuthenticationException.", e);
}
}
throw ae;
}
Subject loggedIn = createSubject(token, info, subject);
onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/lockout/ExponentLockoutStrategy.java | src/main/java/org/ohdsi/webapi/shiro/lockout/ExponentLockoutStrategy.java | package org.ohdsi.webapi.shiro.lockout;
import java.util.concurrent.TimeUnit;
public class ExponentLockoutStrategy implements LockoutStrategy {
private final long initialDuration;
private final long increment;
private final int maxAttempts;
public ExponentLockoutStrategy(long initialDuration, long increment, int maxAttempts) {
this.initialDuration = TimeUnit.SECONDS.toMillis(initialDuration);
this.increment = TimeUnit.SECONDS.toMillis(increment);
this.maxAttempts = maxAttempts;
}
@Override
public long getLockDuration(int attempts) {
return initialDuration + (attempts - maxAttempts) * increment;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/lockout/DefaultLockoutPolicy.java | src/main/java/org/ohdsi/webapi/shiro/lockout/DefaultLockoutPolicy.java | package org.ohdsi.webapi.shiro.lockout;
import com.odysseusinc.logging.event.LockoutStartEvent;
import com.odysseusinc.logging.event.LockoutStopEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class DefaultLockoutPolicy implements LockoutPolicy {
private LockoutStrategy lockoutStrategy;
private int maxAttempts;
private Map<String, LockEntry> lockEntryMap = new ConcurrentHashMap<>();
private static final LockEntry DEFAULT_LOCK = new LockEntry(0, LockEntry.EXPIRED_NOT_SET);
private ApplicationEventPublisher eventPublisher;
public DefaultLockoutPolicy(LockoutStrategy lockoutStrategy, int maxAttempts, ApplicationEventPublisher eventPublisher) {
if (maxAttempts > 0) {
this.lockoutStrategy = lockoutStrategy;
this.maxAttempts = maxAttempts;
} else {
throw new IllegalArgumentException("maxAttempts should be greater than 0");
}
this.eventPublisher = eventPublisher;
}
@Scheduled(fixedRate = 60000)
private void checkLockout() {
lockEntryMap.forEach((principal, entry) -> {
if (!isLockedOut(entry) && entry.getAttempts() >= maxAttempts) {
eventPublisher.publishEvent(new LockoutStopEvent(this, principal));
lockEntryMap.remove(principal);
}
});
}
@Override
public boolean isLockedOut(String principal) {
LockEntry lockEntry = lockEntryMap.getOrDefault(principal, DEFAULT_LOCK);
long now = new Date().getTime();
return lockEntry.getExpired() != LockEntry.EXPIRED_NOT_SET && now < lockEntry.getExpired();
}
@Override
public boolean isLockedOut(LockEntry entry) {
long now = new Date().getTime();
return entry.getExpired() != LockEntry.EXPIRED_NOT_SET && now < entry.getExpired();
}
@Override
public long getLockExpiration(String principal) {
LockEntry lockEntry = lockEntryMap.getOrDefault(principal, DEFAULT_LOCK);
return lockEntry.getExpired();
}
@Override
public void loginFailed(String principal) {
LockEntry lockEntry = lockEntryMap.getOrDefault(principal,
new LockEntry(0, LockEntry.EXPIRED_NOT_SET));
int attempts = lockEntry.getAttempts();
long expired = lockEntry.getExpired();
if (++attempts >= maxAttempts) {
if (!isLockedOut(principal)) {
eventPublisher.publishEvent(new LockoutStartEvent(this, principal));
}
long duration = lockoutStrategy.getLockDuration(attempts);
long now = new Date().getTime();
expired = now + duration;
}
lockEntry = new LockEntry(attempts, expired);
lockEntryMap.put(principal, lockEntry);
}
@Override
public void loginSucceeded(String principal) {
lockEntryMap.remove(principal);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/exception/NullJsonNodeException.java | src/main/java/org/ohdsi/webapi/shiro/exception/NullJsonNodeException.java | package org.ohdsi.webapi.shiro.exception;
public class NullJsonNodeException extends NullPointerException {
public NullJsonNodeException() {
}
public NullJsonNodeException(String message) {
super(message);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/UserRepository.java | src/main/java/org/ohdsi/webapi/shiro/Entities/UserRepository.java | package org.ohdsi.webapi.shiro.Entities;
import java.util.List;
import java.util.Set;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
/**
* Created by GMalikov on 24.08.2015.
*/
public interface UserRepository extends CrudRepository<UserEntity, Long> {
public UserEntity findByLogin(String login);
@Query("SELECT u.login FROM UserEntity u")
public Set<String> getUserLogins();
@Query("from UserEntity where login = 'testLogin'")
public UserEntity getTestUser();
List<UserEntity> findByOrigin(UserOrigin origin);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/RoleRepository.java | src/main/java/org/ohdsi/webapi/shiro/Entities/RoleRepository.java | package org.ohdsi.webapi.shiro.Entities;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* Created by GMalikov on 24.08.2015.
*/
public interface RoleRepository extends CrudRepository<RoleEntity, Long> {
RoleEntity findById(Long id);
RoleEntity findByNameAndSystemRole(String name, Boolean isSystem);
List<RoleEntity> findByNameIgnoreCaseContaining(String roleSearch);
Iterable<RoleEntity> findAllBySystemRoleTrue();
@Query("SELECT CASE WHEN COUNT(r) > 0 THEN true ELSE false END FROM RoleEntity r WHERE r.name = ?1")
boolean existsByName(String roleName);
@Query(
"SELECT r " +
"FROM RoleEntity r " +
"JOIN RolePermissionEntity rp ON r.id = rp.role.id " +
"JOIN PermissionEntity p ON rp.permission.id = p.id " +
"WHERE p.value IN :permissions " +
"GROUP BY r.id, r.name, r.systemRole " +
"HAVING COUNT(p.value) = :permissionCnt"
)
List<RoleEntity> finaAllRolesHavingPermissions(@Param("permissions") List<String> permissions, @Param("permissionCnt") Long permissionCnt);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/PermissionRepository.java | src/main/java/org/ohdsi/webapi/shiro/Entities/PermissionRepository.java | package org.ohdsi.webapi.shiro.Entities;
import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* Created by GMalikov on 24.08.2015.
*/
public interface PermissionRepository extends CrudRepository<PermissionEntity, Long> {
public PermissionEntity findById(Long id);
public PermissionEntity findByValueIgnoreCase(String permission);
List<PermissionEntity> findByValueLike(String permissionTemplate, EntityGraph entityGraph);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/UserRoleEntity.java | src/main/java/org/ohdsi/webapi/shiro/Entities/UserRoleEntity.java | package org.ohdsi.webapi.shiro.Entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
*
* @author gennadiy.anisimov
*/
@Entity(name = "UserRoleEntity")
@Table(name = "SEC_USER_ROLE")
public class UserRoleEntity implements Serializable {
private static final long serialVersionUID = 6257846375334314942L;
private Long id;
private String status;
private UserEntity user;
private RoleEntity role;
private UserOrigin origin = UserOrigin.SYSTEM;
@Id
@Column(name = "ID")
@GenericGenerator(
name = "sec_user_role_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "sec_user_role_sequence"),
@Parameter(name = "initial_value", value = "1000"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "sec_user_role_generator")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@ManyToOne
@JoinColumn(name="USER_ID", nullable=false)
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
@ManyToOne
@JoinColumn(name="ROLE_ID", nullable=false)
public RoleEntity getRole() {
return role;
}
public void setRole(RoleEntity role) {
this.role = role;
}
@Column(name = "origin", nullable = false)
@Enumerated(EnumType.STRING)
public UserOrigin getOrigin() {
return origin;
}
public void setOrigin(UserOrigin origin) {
this.origin = origin;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/RolePermissionRepository.java | src/main/java/org/ohdsi/webapi/shiro/Entities/RolePermissionRepository.java | package org.ohdsi.webapi.shiro.Entities;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
/**
*
* @author gennadiy.anisimov
*/
public interface RolePermissionRepository extends CrudRepository<RolePermissionEntity, Long> {
RolePermissionEntity findById(Long id);
RolePermissionEntity findByRoleAndPermission(RoleEntity role, PermissionEntity permission);
RolePermissionEntity findByRoleIdAndPermissionId(Long roleId, Long permissionId);
List<RolePermissionEntity> findByStatusIgnoreCase(String status);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/RoleRequest.java | src/main/java/org/ohdsi/webapi/shiro/Entities/RoleRequest.java | package org.ohdsi.webapi.shiro.Entities;
import java.io.Serializable;
/**
*
* @author gennadiy.anisimov
*/
public class RoleRequest implements Serializable {
private static final long serialVersionUID = -2697485161468660016L;
private Long id;
private String user;
private String role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/UserEntity.java | src/main/java/org/ohdsi/webapi/shiro/Entities/UserEntity.java | package org.ohdsi.webapi.shiro.Entities;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Created by GMalikov on 24.08.2015.
*/
@Entity(name = "UserEntity")
@Table(name = "SEC_USER")
public class UserEntity implements Serializable{
private static final long serialVersionUID = -2697485161468660016L;
private Long id;
private String login;
private String password;
private String salt;
private String name;
private UserOrigin origin = UserOrigin.SYSTEM;
private Set<UserRoleEntity> userRoles = new LinkedHashSet<>();
private Date lastViewedNotificationsTime;
@Id
@Column(name = "ID")
@GenericGenerator(
name = "sec_user_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "sec_user_sequence"),
@Parameter(name = "initial_value", value = "1000"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "sec_user_generator")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "LOGIN")
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
@Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
public Set<UserRoleEntity> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRoleEntity> userRoles) {
this.userRoles = userRoles;
}
@Column(name = "last_viewed_notifications_time")
public Date getLastViewedNotificationsTime() {
return lastViewedNotificationsTime;
}
public void setLastViewedNotificationsTime(Date lastViewedNotificationsTime) {
this.lastViewedNotificationsTime = lastViewedNotificationsTime;
}
@Column(name = "origin", nullable = false)
@Enumerated(EnumType.STRING)
public UserOrigin getOrigin() {
return origin;
}
public void setOrigin(UserOrigin origin) {
this.origin = origin;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/RolePermissionEntity.java | src/main/java/org/ohdsi/webapi/shiro/Entities/RolePermissionEntity.java | package org.ohdsi.webapi.shiro.Entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
*
* @author gennadiy.anisimov
*/
@Entity(name = "RolePermissionEntity")
@Table(name = "SEC_ROLE_PERMISSION")
public class RolePermissionEntity implements Serializable {
private static final long serialVersionUID = 6257846375334314942L;
@Id
@Column(name = "ID")
@GenericGenerator(
name = "sec_role_permission_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "sec_role_permission_sequence"),
@Parameter(name = "initial_value", value = "1000"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "sec_role_permission_generator")
private Long id;
@Column(name = "STATUS")
private String status;
@ManyToOne
@JoinColumn(name="ROLE_ID", nullable=false)
private RoleEntity role;
@ManyToOne
@JoinColumn(name="PERMISSION_ID", nullable=false)
private PermissionEntity permission;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public RoleEntity getRole() {
return role;
}
public void setRole(RoleEntity role) {
this.role = role;
}
public PermissionEntity getPermission() {
return permission;
}
public void setPermission(PermissionEntity permission) {
this.permission = permission;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/UserPrincipal.java | src/main/java/org/ohdsi/webapi/shiro/Entities/UserPrincipal.java | package org.ohdsi.webapi.shiro.Entities;
public class UserPrincipal {
private String name;
private String username;
private String password;
public UserPrincipal() {
}
public UserPrincipal(String username, String password, String name) {
this.username = username;
this.password = password;
this.name = name;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/PermissionRequest.java | src/main/java/org/ohdsi/webapi/shiro/Entities/PermissionRequest.java | package org.ohdsi.webapi.shiro.Entities;
import java.io.Serializable;
/**
*
* @author gennadiy.anisimov
*/
public class PermissionRequest implements Serializable{
private static final long serialVersionUID = -2697485161468660016L;
private Long id;
private String role;
private String permission;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/UserOrigin.java | src/main/java/org/ohdsi/webapi/shiro/Entities/UserOrigin.java | package org.ohdsi.webapi.shiro.Entities;
import org.ohdsi.webapi.user.importer.model.LdapProviderType;
public enum UserOrigin {
SYSTEM, AD, LDAP;
public static UserOrigin getFrom(LdapProviderType ldapProviderType) {
switch (ldapProviderType) {
case LDAP: return LDAP;
case ACTIVE_DIRECTORY: return AD;
}
return SYSTEM;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/PermissionEntity.java | src/main/java/org/ohdsi/webapi/shiro/Entities/PermissionEntity.java | package org.ohdsi.webapi.shiro.Entities;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
* Created by GMalikov on 24.08.2015.
*/
@Entity(name = "PermissionEntity")
@Table(name = "SEC_PERMISSION")
public class PermissionEntity implements Serializable {
private static final long serialVersionUID = 1810877985769153135L;
@Id
@Column(name = "ID")
@GenericGenerator(
name = "sec_permission_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "sec_permission_id_seq"),
@Parameter(name = "initial_value", value = "1000"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "sec_permission_generator")
private Long id;
@Column(name = "VALUE")
private String value;
@Column(name = "DESCRIPTION")
private String description;
@OneToMany(mappedBy = "permission", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<RolePermissionEntity> rolePermissions = new LinkedHashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<RolePermissionEntity> getRolePermissions() {
return rolePermissions;
}
public void setRolePermissions(Set<RolePermissionEntity> rolePermissions) {
this.rolePermissions = rolePermissions;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/UserRoleRepository.java | src/main/java/org/ohdsi/webapi/shiro/Entities/UserRoleRepository.java | package org.ohdsi.webapi.shiro.Entities;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
/**
*
* @author gennadiy.anisimov
*/
public interface UserRoleRepository extends CrudRepository<UserRoleEntity, Long> {
public List<UserRoleEntity> findByUser(UserEntity user);
public UserRoleEntity findByUserAndRole(UserEntity user, RoleEntity role);
public List<UserRoleEntity> findByStatusIgnoreCase(String status);
public List<UserRoleEntity> findByUserId(Long userId);
public UserRoleEntity findByUserIdAndRoleId(Long userId, Long roleId);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/RequestStatus.java | src/main/java/org/ohdsi/webapi/shiro/Entities/RequestStatus.java | package org.ohdsi.webapi.shiro.Entities;
/**
*
* @author gennadiy.anisimov
*/
public class RequestStatus {
public static final String REQUESTED = "REQUESTED";
public static final String APPROVED = "APPROVED";
public static final String REFUSED = "REFUSED";
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/Entities/RoleEntity.java | src/main/java/org/ohdsi/webapi/shiro/Entities/RoleEntity.java | package org.ohdsi.webapi.shiro.Entities;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
* Created by GMalikov on 24.08.2015.
*/
@Entity(name = "RoleEntity")
@Table(name = "SEC_ROLE")
public class RoleEntity implements Serializable{
private static final long serialVersionUID = 6257846375334314942L;
@Id
@Column(name = "ID")
@GenericGenerator(
name = "sec_role_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "sec_role_sequence"),
@Parameter(name = "initial_value", value = "1000"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "sec_role_generator")
private Long id;
@Column(name = "NAME")
private String name;
@OneToMany(mappedBy = "role", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<RolePermissionEntity> rolePermissions = new LinkedHashSet<>();
@OneToMany(mappedBy = "role", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<UserRoleEntity> userRoles = new LinkedHashSet<>();
@Column(name = "system_role")
private Boolean systemRole;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<RolePermissionEntity> getRolePermissions() {
return rolePermissions;
}
public void setRolePermissions(Set<RolePermissionEntity> rolePermissions) {
this.rolePermissions = rolePermissions;
}
public Set<UserRoleEntity> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRoleEntity> userRoles) {
this.userRoles = userRoles;
}
public Boolean isSystemRole() {
return systemRole;
}
public void setSystemRole(Boolean system) {
systemRole = system;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/subject/WebDelegatingRunAsSubjectFactory.java | src/main/java/org/ohdsi/webapi/shiro/subject/WebDelegatingRunAsSubjectFactory.java | package org.ohdsi.webapi.shiro.subject;
import org.apache.shiro.mgt.DefaultSubjectFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SubjectFactory;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.subject.WebSubjectContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class WebDelegatingRunAsSubjectFactory extends DefaultSubjectFactory implements SubjectFactory {
public WebDelegatingRunAsSubjectFactory() {
super();
}
@Override
public Subject createSubject(SubjectContext context) {
if (!(context instanceof WebSubjectContext)) {
return super.createSubject(context);
}
WebSubjectContext wsc = (WebSubjectContext) context;
SecurityManager securityManager = wsc.resolveSecurityManager();
Session session = wsc.resolveSession();
boolean sessionEnabled = wsc.isSessionCreationEnabled();
PrincipalCollection principals = wsc.resolvePrincipals();
boolean authenticated = wsc.resolveAuthenticated();
String host = wsc.resolveHost();
ServletRequest request = wsc.resolveServletRequest();
ServletResponse response = wsc.resolveServletResponse();
return new WebDelegatingRunAsSubject(principals, authenticated, host, session, sessionEnabled,
request, response, securityManager);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/subject/WebDelegatingRunAsSubject.java | src/main/java/org/ohdsi/webapi/shiro/subject/WebDelegatingRunAsSubject.java | package org.ohdsi.webapi.shiro.subject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.subject.support.WebDelegatingSubject;
import org.ohdsi.webapi.shiro.runas.DefaultInMemoryRunAsStorage;
import org.ohdsi.webapi.shiro.runas.RunAsStorage;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class WebDelegatingRunAsSubject extends WebDelegatingSubject {
private RunAsStorage runAsStorage;
public WebDelegatingRunAsSubject(PrincipalCollection principals,
boolean authenticated,
String host,
Session session,
ServletRequest request,
ServletResponse response,
SecurityManager securityManager,
RunAsStorage runAsStorage) {
super(principals, authenticated, host, session, request, response, securityManager);
this.runAsStorage = runAsStorage;
}
public WebDelegatingRunAsSubject(PrincipalCollection principals,
boolean authenticated,
String host,
Session session,
boolean sessionEnabled,
ServletRequest request,
ServletResponse response,
SecurityManager securityManager) {
super(principals, authenticated, host, session, sessionEnabled, request, response, securityManager);
this.runAsStorage = new DefaultInMemoryRunAsStorage();
}
public WebDelegatingRunAsSubject(PrincipalCollection principals,
boolean authenticated,
String host,
Session session,
boolean sessionEnabled,
ServletRequest request,
ServletResponse response,
SecurityManager securityManager,
RunAsStorage runAsStorage) {
super(principals, authenticated, host, session, sessionEnabled, request, response, securityManager);
this.runAsStorage = runAsStorage;
}
@Override
public PrincipalCollection getPrincipals() {
List<PrincipalCollection> runAsPrincipals = getRunAsPrincipalStack();
return CollectionUtils.isEmpty(runAsPrincipals) ? this.principals : runAsPrincipals.get(0);
}
@Override
public void logout() {
releaseRunAs();
super.logout();
}
@Override
public void runAs(PrincipalCollection principals) {
if (!hasPrincipals()) {
String msg = "This subject does not yet have an identity. Assuming the identity of another " +
"Subject is only allowed for Subjects with an existing identity. Try logging this subject in " +
"first, or using the " + Subject.Builder.class.getName() + " to build ad hoc Subject instances " +
"with identities as necessary.";
throw new IllegalStateException(msg);
}
if (supportsRunAs()) {
runAsStorage.pushPrincipals(this.principals.getPrimaryPrincipal(), principals);
}
}
protected boolean supportsRunAs() {
return Objects.nonNull(runAsStorage) && Objects.nonNull(this.principals);
}
@Override
public boolean isRunAs() {
List<PrincipalCollection> stack = getRunAsPrincipalStack();
return !CollectionUtils.isEmpty(stack);
}
@Override
public PrincipalCollection getPreviousPrincipals() {
PrincipalCollection previousPrincipals = null;
if (supportsRunAs()) {
final List<PrincipalCollection> stack = runAsStorage.getRunAsPrincipalStack(this.principals.getPrimaryPrincipal());
int stackSize = stack != null ? stack.size() : 0;
if (stackSize > 0) {
if (stackSize == 1) {
previousPrincipals = this.principals;
} else {
previousPrincipals = stack.get(1);
}
}
}
return previousPrincipals;
}
@Override
public PrincipalCollection releaseRunAs() {
if (supportsRunAs()) {
return runAsStorage.popPrincipals(this.principals.getPrimaryPrincipal());
} else {
return null;
}
}
protected List<PrincipalCollection> getRunAsPrincipalStack() {
if (supportsRunAs()) {
return runAsStorage.getRunAsPrincipalStack(this.principals.getPrimaryPrincipal());
} else {
return Collections.emptyList();
}
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/RunAsFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/RunAsFilter.java | package org.ohdsi.webapi.shiro.filters;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.shiro.Entities.UserEntity;
import org.ohdsi.webapi.shiro.Entities.UserRepository;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
public class RunAsFilter extends AdviceFilter {
private UserRepository userRepository;
public RunAsFilter(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
final String runAs = request.getParameter("login");
if (StringUtils.isNotBlank(runAs)) {
UserEntity userEntity = userRepository.findByLogin(runAs);
if (Objects.isNull(userEntity)) {
HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
return false;
}
AuthenticationInfo authInfo = new SimpleAuthenticationInfo(runAs, null, "runAs");
SecurityUtils.getSubject().runAs(authInfo.getPrincipals());
}
return true;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/SkipFurtherFilteringFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/SkipFurtherFilteringFilter.java | package org.ohdsi.webapi.shiro.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
/**
*
* @author gennadiy.anisimov
*/
public abstract class SkipFurtherFilteringFilter implements Filter {
@Override
public void init(FilterConfig fc) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (shouldSkip(request, response)) {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
String path = httpRequest.getServletPath() + httpRequest.getPathInfo();
RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
requestDispatcher.forward(request, response);
}
else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
protected abstract boolean shouldSkip(ServletRequest request, ServletResponse response);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/ExceptionHandlerFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/ExceptionHandlerFilter.java | package org.ohdsi.webapi.shiro.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
@Component
@Order(1)
public class ExceptionHandlerFilter implements Filter {
private final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (Throwable e) {
LOGGER.error("Error during filtering", e);
// Throw new exception without information of original exception;
RuntimeException ex = new RuntimeException("An exception ocurred: " + e.getClass().getName());
// Clean stacktrace, but keep message
ex.setStackTrace(new StackTraceElement[0]);
// Throw new exception without information of original exception;
throw ex;
}
}
@Override
public void destroy() {
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/CacheFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/CacheFilter.java | package org.ohdsi.webapi.shiro.filters;
import org.ohdsi.webapi.security.PermissionService;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
@Component
public class CacheFilter implements Filter {
@Autowired
private PermissionManager permissionManager;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
permissionManager.clearAuthorizationInfoCache();
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/SendTokenInHeaderFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/SendTokenInHeaderFilter.java | package org.ohdsi.webapi.shiro.filters;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.PERMISSIONS_ATTRIBUTE;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.TOKEN_ATTRIBUTE;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
/**
*
* @author gennadiy.anisimov
*/
public class SendTokenInHeaderFilter extends AdviceFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SendTokenInHeaderFilter.class);
private static final String ERROR_WRITING_PERMISSIONS_TO_RESPONSE_LOG = "Error writing permissions to response";
private static final String TOKEN_HEADER_NAME = "Bearer";
private final ObjectMapper objectMapper;
public SendTokenInHeaderFilter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) {
String jwt = (String)request.getAttribute(TOKEN_ATTRIBUTE);
PermissionManager.PermissionsDTO permissions = (PermissionManager.PermissionsDTO)request.getAttribute(PERMISSIONS_ATTRIBUTE);
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setHeader(TOKEN_HEADER_NAME, jwt);
httpResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
httpResponse.setStatus(HttpServletResponse.SC_OK);
try (final PrintWriter responseWriter = response.getWriter()) {
responseWriter.print(objectMapper.writeValueAsString(permissions));
} catch (IOException e) {
LOGGER.error(ERROR_WRITING_PERMISSIONS_TO_RESPONSE_LOG, e);
}
return false;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/LogoutFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/LogoutFilter.java | package org.ohdsi.webapi.shiro.filters;
import com.odysseusinc.logging.event.FailedLogoutEvent;
import com.odysseusinc.logging.event.SuccessLogoutEvent;
import io.jsonwebtoken.JwtException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.shiro.TokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author gennadiy.anisimov
*/
public class LogoutFilter extends AdviceFilter {
private ApplicationEventPublisher eventPublisher;
private final Logger log = LoggerFactory.getLogger(getClass());
public LogoutFilter(ApplicationEventPublisher eventPublisher){
this.eventPublisher = eventPublisher;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
String jwt = TokenManager.extractToken(request);
String principal;
try {
principal = TokenManager.getSubject(jwt);
} catch (JwtException e) {
throw new AuthenticationException(e);
}
if (TokenManager.invalidate(jwt)) {
httpResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
Subject subject = SecurityUtils.getSubject();
try {
subject.logout();
eventPublisher.publishEvent(new SuccessLogoutEvent(this, principal));
} catch (SessionException ise) {
log.warn("Encountered session exception during logout. This can be generally safely ignored", ise);
eventPublisher.publishEvent(new FailedLogoutEvent(this, principal));
}
return false;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/CasHandleFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/CasHandleFilter.java | package org.ohdsi.webapi.shiro.filters;
import io.buji.pac4j.token.Pac4jToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.pac4j.cas.profile.CasProfile;
import org.pac4j.core.profile.CommonProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.LinkedHashMap;
/**
* CAS authentication callback filter
*/
public class CasHandleFilter extends AtlasAuthFilter {
private final Logger logger = LoggerFactory.getLogger(CasHandleFilter.class);
/**
* attribute name to recognize CAS authentication. Get login UpdateAccessTokenFilter
* differently.
*/
public static final String CONST_CAS_AUTHN = "webapi.shiro.cas";
private TicketValidator ticketValidator;
private String casCallbackUrl;
private String casticket;
/**
* @param ticketValidator TicketValidator for service ticket validation
* @param casCallbackUrl CAS callback URL
* @param casticket parameter name for ticket to validate
*/
public CasHandleFilter(TicketValidator ticketValidator, String casCallbackUrl, String casticket) {
super();
this.ticketValidator = ticketValidator;
this.casCallbackUrl = casCallbackUrl;
this.casticket = casticket;
}
/**
* @see org.apache.shiro.web.filter.authc.AuthenticatingFilter#createToken(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse)
*/
@Override
protected AuthenticationToken createToken(ServletRequest servletRequest,
ServletResponse servletResponse) throws Exception {
final ShiroHttpServletRequest request = (ShiroHttpServletRequest) servletRequest;
HttpSession session = request.getSession();
Pac4jToken ct = null;
if (session != null) {
session.setAttribute(CONST_CAS_AUTHN, "true");
if (!SecurityUtils.getSubject().isAuthenticated()) {
String ticket = request.getParameter(this.casticket);
if (ticket != null) {
String service = casCallbackUrl;
try {
final Assertion assertion = this.ticketValidator.validate(ticket, service);
final AttributePrincipal principal = assertion.getPrincipal();
final CasProfile casProfile = new CasProfile();
casProfile.setId(principal.getName());
casProfile.addAttributes(principal.getAttributes());
Subject currentUser = SecurityUtils.getSubject();
ct = new Pac4jToken(Collections.singletonList(casProfile), currentUser.isRemembered());
/*
* let AuthenticatingFilter.executeLogin login user
*/
//currentUser.login(ct);
} catch (TicketValidationException e) {
throw new AuthenticationException(e);
}
}
}
}
return ct;
}
/**
* @see org.apache.shiro.web.filter.AccessControlFilter#onAccessDenied(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse)
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
boolean loggedIn = executeLogin(request, response);
return loggedIn;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/ForceSessionCreationFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/ForceSessionCreationFilter.java | package org.ohdsi.webapi.shiro.filters;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.servlet.AdviceFilter;
/**
*
* @author gennadiy.anisimov
*/
public class ForceSessionCreationFilter extends AdviceFilter {
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
request.setAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED, Boolean.TRUE);
Session session = SecurityUtils.getSubject().getSession(true);
if (session == null) {
throw new Exception("Can't create web session");
}
return true;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/HideResourceFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/HideResourceFilter.java | package org.ohdsi.webapi.shiro.filters;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
/**
*
* @author gennadiy.anisimov
*/
public class HideResourceFilter extends AdviceFilter {
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
return false;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/AtlasAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/AtlasAuthFilter.java | package org.ohdsi.webapi.shiro.filters;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
/**
* Filter to check for a user, who has already logged in using external service
*/
public abstract class AtlasAuthFilter extends AuthenticatingFilter {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/UpdateAccessTokenFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/UpdateAccessTokenFilter.java | package org.ohdsi.webapi.shiro.filters;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.AUTH_CLIENT_ATTRIBUTE;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.PERMISSIONS_ATTRIBUTE;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.TOKEN_ATTRIBUTE;
import io.buji.pac4j.subject.Pac4jPrincipal;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;
import java.util.Set;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.shiro.Entities.UserPrincipal;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.ohdsi.webapi.shiro.TokenManager;
import org.ohdsi.webapi.util.UserUtils;
import org.pac4j.core.profile.CommonProfile;
/**
*
* @author gennadiy.anisimov
*/
public class UpdateAccessTokenFilter extends AdviceFilter {
private final PermissionManager authorizer;
private final int tokenExpirationIntervalInSeconds;
private final Set<String> defaultRoles;
private final String onFailRedirectUrl;
public UpdateAccessTokenFilter(
PermissionManager authorizer,
Set<String> defaultRoles,
int tokenExpirationIntervalInSeconds,
String onFailRedirectUrl) {
this.authorizer = authorizer;
this.tokenExpirationIntervalInSeconds = tokenExpirationIntervalInSeconds;
this.defaultRoles = defaultRoles;
this.onFailRedirectUrl = onFailRedirectUrl;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
if (!SecurityUtils.getSubject().isAuthenticated()) {
WebUtils.toHttp(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
String login;
String name = null;
String jwt = null;
final PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
Object principal = principals.getPrimaryPrincipal();
if (principal instanceof Pac4jPrincipal) {
login = ((Pac4jPrincipal)principal).getProfile().getEmail();
name = ((Pac4jPrincipal)principal).getProfile().getDisplayName();
/**
* for CAS login
*/
ShiroHttpServletRequest requestShiro = (ShiroHttpServletRequest) request;
HttpSession shiroSession = requestShiro.getSession();
if (login == null && shiroSession.getAttribute(CasHandleFilter.CONST_CAS_AUTHN) != null
&& ((String) shiroSession.getAttribute(CasHandleFilter.CONST_CAS_AUTHN)).equalsIgnoreCase("true")) {
login = ((Pac4jPrincipal) principal).getProfile().getId();
}
if (login == null) {
// user doesn't provide email - send empty token
request.setAttribute(TOKEN_ATTRIBUTE, "");
// stop session to make logout of OAuth users possible
Session session = SecurityUtils.getSubject().getSession(false);
if (session != null) {
session.stop();
}
HttpServletResponse httpResponse = WebUtils.toHttp(response);
URI oauthFailURI = getOAuthFailUri();
httpResponse.sendRedirect(oauthFailURI.toString());
return false;
}
CommonProfile profile = (((Pac4jPrincipal) principal).getProfile());
if (Objects.nonNull(profile)) {
String clientName = profile.getClientName();
request.setAttribute(AUTH_CLIENT_ATTRIBUTE, clientName);
}
} else if (principal instanceof Principal) {
login = ((Principal) principal).getName();
} else if (principal instanceof UserPrincipal){
login = ((UserPrincipal) principal).getUsername();
name = ((UserPrincipal) principal).getName();
} else if (principal instanceof String) {
login = (String)principal;
} else {
throw new Exception("Unknown type of principal");
}
login = UserUtils.toLowerCase(login);
// stop session to make logout of OAuth users possible
Session session = SecurityUtils.getSubject().getSession(false);
if (session != null) {
session.stop();
}
if (jwt == null) {
if (name == null) {
name = login;
}
try {
this.authorizer.registerUser(login, name, defaultRoles);
} catch (Exception e) {
WebUtils.toHttp(response).setHeader("x-auth-error", e.getMessage());
throw new Exception(e);
}
String sessionId = (String) request.getAttribute(Constants.SESSION_ID);
if (sessionId == null) {
final String token = TokenManager.extractToken(request);
if (token != null) {
sessionId = (String) TokenManager.getBody(token).get(Constants.SESSION_ID);
}
}
Date expiration = this.getExpirationDate(this.tokenExpirationIntervalInSeconds);
jwt = TokenManager.createJsonWebToken(login, sessionId, expiration);
}
request.setAttribute(TOKEN_ATTRIBUTE, jwt);
PermissionManager.PermissionsDTO permissions = this.authorizer.queryUserPermissions(login);
request.setAttribute(PERMISSIONS_ATTRIBUTE, permissions);
return true;
}
private URI getOAuthFailUri() throws URISyntaxException {
return getFailUri("oauth_error_email");
}
private URI getFailUri(String failFragment) throws URISyntaxException {
URI oauthFailURI = new URI(onFailRedirectUrl);
String fragment = oauthFailURI.getFragment();
StringBuilder sbFragment = new StringBuilder();
if(fragment == null) {
sbFragment.append(failFragment).append("/");
} else if(fragment.endsWith("/")){
sbFragment.append(fragment).append(failFragment).append("/");
} else {
sbFragment.append(fragment).append("/").append(failFragment).append("/");
}
return UriBuilder.fromUri(oauthFailURI).fragment(sbFragment.toString()).build();
}
private Date getExpirationDate(final int expirationIntervalInSeconds) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, expirationIntervalInSeconds);
return calendar.getTime();
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/ResponseNoCacheFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/ResponseNoCacheFilter.java | package org.ohdsi.webapi.shiro.filters;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ResponseNoCacheFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setHeader("Cache-Control", "no-store");
httpResponse.setHeader("Pragma", "no-cache");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/CorsFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/CorsFilter.java | package org.ohdsi.webapi.shiro.filters;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.common.base.Joiner;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.Constants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
/**
*
* @author gennadiy.anisimov
*/
@Component
public class CorsFilter extends AdviceFilter{
@Value("${security.origin}")
private String origin;
@Value("${security.cors.enabled}")
private Boolean corsEnabled;
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
if (Objects.isNull(corsEnabled) || !corsEnabled) {
return true;
}
// check if it's CORS request
//
HttpServletRequest httpRequest = WebUtils.toHttp(request);
String requestOrigin = httpRequest.getHeader("Origin");
if (requestOrigin == null) {
return true;
}
// set headers
//
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setHeader("Access-Control-Allow-Origin", this.origin);
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
// stop processing if it's preflight request
//
String requestMethod = httpRequest.getHeader("Access-Control-Request-Method");
String method = httpRequest.getMethod();
if (requestMethod != null && "OPTIONS".equalsIgnoreCase(method)) {
httpResponse.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, " +
Joiner.on(",").join(Constants.Headers.AUTH_PROVIDER, Constants.Headers.USER_LANGAUGE,
Constants.Headers.ACTION_LOCATION));
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
httpResponse.setHeader("Access-Control-Max-Age", "1209600");
httpResponse.setStatus(HttpServletResponse.SC_OK);
return false;
}
// continue processing request
//
List<String> exposedHeaders = Arrays.asList(
Constants.Headers.BEARER,
Constants.Headers.X_AUTH_ERROR,
Constants.Headers.AUTH_PROVIDER,
Constants.Headers.USER_LANGAUGE,
Constants.Headers.CONTENT_DISPOSITION
);
httpResponse.setHeader(Constants.Headers.ACCESS_CONTROL_EXPOSE_HEADERS, Joiner.on(",").join(exposedHeaders));
return true;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/GoogleAccessTokenFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/GoogleAccessTokenFilter.java | package org.ohdsi.webapi.shiro.filters;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.ohdsi.webapi.shiro.TokenManager;
import org.ohdsi.webapi.shiro.tokens.JwtAuthToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public class GoogleAccessTokenFilter extends AtlasAuthFilter {
private static final String VALIDATE_URL = "https://oauth2.googleapis.com/tokeninfo?access_token=%s";
private static final Logger logger = LoggerFactory.getLogger(GoogleAccessTokenFilter.class);
private RestTemplate restTemplate;
private ObjectMapper mapper = new ObjectMapper();
private PermissionManager authorizer;
private Set<String> defaultRoles;
public GoogleAccessTokenFilter(RestTemplate restTemplate,
PermissionManager authorizer,
Set<String> roles) {
this.restTemplate = restTemplate;
this.authorizer = authorizer;
this.defaultRoles = roles;
}
@Override
protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
String token = TokenManager.extractToken(servletRequest);
String userId = getTokenInfo(token);
return Optional.ofNullable(userId).map(JwtAuthToken::new)
.orElseThrow(AuthenticationException::new);
}
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
try {
if (TokenManager.extractToken(servletRequest) != null) {
boolean loggedIn = executeLogin(servletRequest, servletResponse);
if (loggedIn) {
final PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
String name = (String) principals.getPrimaryPrincipal();
this.authorizer.registerUser(name, name, defaultRoles);
}
}
} catch (AuthenticationException ignored) {
}
return true;
}
private String getTokenInfo(String token) throws IOException {
String result = null;
try {
ResponseEntity<String> response = restTemplate.getForEntity(String.format(VALIDATE_URL, token), String.class);
if (response.getStatusCode() == HttpStatus.OK) {
JsonNode root = mapper.readTree(response.getBody());
result = getValueAsString(root, "email");
if (Objects.isNull(result)) {
result = getValueAsString(root, "aud");
}
}
} catch (HttpClientErrorException e) {
logger.warn("Access token is invalid {}", e.getMessage());
}
return result;
}
private String getValueAsString(JsonNode node, String property) {
JsonNode valueNode = node.get(property);
if (!valueNode.isNull()) {
return valueNode.textValue();
}
return null;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/GoogleIapJwtAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/GoogleIapJwtAuthFilter.java | package org.ohdsi.webapi.shiro.filters;
import com.google.common.base.Preconditions;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.ECDSAVerifier;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import io.buji.pac4j.subject.Pac4jPrincipal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.ohdsi.webapi.shiro.tokens.JwtAuthToken;
import org.pac4j.core.profile.CommonProfile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.security.interfaces.ECPublicKey;
import java.text.ParseException;
import java.time.Clock;
import java.time.Instant;
import java.util.*;
public class GoogleIapJwtAuthFilter extends AtlasAuthFilter {
private static final String PUBLIC_KEY_VERIFICATION_URL =
"https://www.gstatic.com/iap/verify/public_key-jwk";
private static final String IAP_ISSUER_URL = "https://cloud.google.com/iap";
private static final String JWT_HEADER = "x-goog-iap-jwt-assertion";
// using a simple cache with no eviction
private final Map<String, JWK> keyCache = new HashMap<>();
private static Clock clock = Clock.systemUTC();
private PermissionManager authorizer;
private Set<String> defaultRoles;
private final Long cloudProjectId;
private final Long backendServiceId;
public GoogleIapJwtAuthFilter(PermissionManager authorizer,
Set<String> defaultRoles,
Long cloudProjectId,
Long backendServiceId) {
this.authorizer = authorizer;
this.defaultRoles = defaultRoles;
this.cloudProjectId = cloudProjectId;
this.backendServiceId = backendServiceId;
}
@Override
protected JwtAuthToken createToken(ServletRequest request, ServletResponse response) throws Exception {
String jwtToken = getJwtToken(request);
String login = verifyJwt(
jwtToken,
String.format(
"/projects/%s/global/backendServices/%s",
Long.toUnsignedString(cloudProjectId), Long.toUnsignedString(backendServiceId)
)
);
return new JwtAuthToken(login);
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setHeader(Constants.Headers.AUTH_PROVIDER, Constants.SecurityProviders.GOOGLE);
boolean loggedIn = executeLogin(request, response);
if (loggedIn) {
String name, login;
final PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
final Pac4jPrincipal pac4jPrincipal = principals.oneByType(Pac4jPrincipal.class);
if (Objects.nonNull(pac4jPrincipal)) {
CommonProfile profile = pac4jPrincipal.getProfile();
login = profile.getEmail();
name = Optional.ofNullable(profile.getDisplayName()).orElse(login);
} else {
name = (String) principals.getPrimaryPrincipal();
login = name;
}
// For now we supposed name to be equal to login for google iap
this.authorizer.registerUser(login, name, defaultRoles);
} else {
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
return loggedIn;
}
private ECPublicKey getKey(String kid, String alg) throws Exception {
JWK jwk = keyCache.get(kid);
if (jwk == null) {
// update cache loading jwk public key data from url
JWKSet jwkSet = JWKSet.load(new URL(PUBLIC_KEY_VERIFICATION_URL));
for (JWK key : jwkSet.getKeys()) {
keyCache.put(key.getKeyID(), key);
}
jwk = keyCache.get(kid);
}
// confirm that algorithm matches
if (jwk != null && jwk.getAlgorithm().getName().equals(alg)) {
return ECKey.parse(jwk.toJSONString()).toECPublicKey();
}
return null;
}
private String getJwtToken(ServletRequest request) {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
return httpRequest.getHeader(JWT_HEADER);
}
private String verifyJwt(String jwtToken, String expectedAudience) throws Exception {
try {
// parse signed token into header / claims
SignedJWT signedJwt = SignedJWT.parse(jwtToken);
JWSHeader jwsHeader = signedJwt.getHeader();
// header must have algorithm("alg") and "kid"
Preconditions.checkNotNull(jwsHeader.getAlgorithm());
Preconditions.checkNotNull(jwsHeader.getKeyID());
JWTClaimsSet claims = signedJwt.getJWTClaimsSet();
// claims must have audience, issuer
Preconditions.checkArgument(claims.getAudience().contains(expectedAudience));
Preconditions.checkArgument(claims.getIssuer().equals(IAP_ISSUER_URL));
// claim must have issued at time in the past
Date currentTime = Date.from(Instant.now(clock));
Preconditions.checkArgument(claims.getIssueTime().before(currentTime));
// claim must have expiration time in the future
Preconditions.checkArgument(claims.getExpirationTime().after(currentTime));
// must have subject, email
String email = claims.getClaim("email").toString();
Preconditions.checkNotNull(claims.getSubject());
Preconditions.checkNotNull(email);
// verify using public key : lookup with key id, algorithm name provided
ECPublicKey publicKey = getKey(jwsHeader.getKeyID(), jwsHeader.getAlgorithm().getName());
Preconditions.checkNotNull(publicKey);
JWSVerifier jwsVerifier = new ECDSAVerifier(publicKey);
if (signedJwt.verify(jwsVerifier)) {
return email;
} else {
throw new AuthenticationException();
}
} catch (IllegalArgumentException | ParseException | JOSEException ex) {
throw new AuthenticationException(ex);
}
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/UrlBasedAuthorizingFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/UrlBasedAuthorizingFilter.java | package org.ohdsi.webapi.shiro.filters;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
/**
*
* @author gennadiy.anisimov
*/
public class UrlBasedAuthorizingFilter extends AdviceFilter {
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
String path = httpRequest.getPathInfo()
.replaceAll("^/+", "")
.replaceAll("/+$", "")
// replace special characters
.replace(":", ":")
.replace(",", ",")
.replace("*", "&asterisk;");
String method = httpRequest.getMethod();
String permission = String.format("%s:%s", path.replace("/", ":"), method).toLowerCase();
if (this.isPermitted(permission))
return true;
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
return false;
}
protected boolean isPermitted(String permission) {
return SecurityUtils.getSubject().isPermitted(permission);
};
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/RedirectOnFailedOAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/RedirectOnFailedOAuthFilter.java | package org.ohdsi.webapi.shiro.filters;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
/**
*
* @author gennadiy.anisimov
*/
public class RedirectOnFailedOAuthFilter extends AdviceFilter {
private String redirectUrl;
public RedirectOnFailedOAuthFilter(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
if (WebUtils.toHttp(request).getParameter("code") == null) {
WebUtils.toHttp(response).sendRedirect(redirectUrl);
return false;
}
return true;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/SendTokenInUrlFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/SendTokenInUrlFilter.java | package org.ohdsi.webapi.shiro.filters;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.helper.Guard;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.AUTH_CLIENT_ALL;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.AUTH_CLIENT_ATTRIBUTE;
/**
*
* @author gennadiy.anisimov
*/
public class SendTokenInUrlFilter extends AdviceFilter {
private String url;
public SendTokenInUrlFilter(String url) {
this.url = url;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
String jwt = (String)request.getAttribute("TOKEN");
String client = (String)request.getAttribute(AUTH_CLIENT_ATTRIBUTE);
String clientValue = StringUtils.isEmpty(client) ? AUTH_CLIENT_ALL : client;
String urlValue = url.replaceAll("/+$", "");
if (!Guard.isNullOrEmpty(jwt)) {
urlValue = urlValue + "/" + clientValue + "/" + jwt;
if (!Guard.isNullOrEmpty(request.getParameter("redirectUrl"))) {
urlValue = urlValue + "/" + URLEncoder.encode(request.getParameter("redirectUrl"), StandardCharsets.UTF_8.name());
}
}
WebUtils.toHttp(response).sendRedirect(urlValue);
return false;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/AuthenticatingPropagationFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/AuthenticatingPropagationFilter.java | package org.ohdsi.webapi.shiro.filters;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import com.odysseusinc.logging.event.FailedLoginEvent;
import com.odysseusinc.logging.event.SuccessLoginEvent;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.audittrail.events.AuditTrailLoginFailedEvent;
import org.ohdsi.webapi.audittrail.events.AuditTrailSessionCreatedEvent;
import org.ohdsi.webapi.shiro.management.AtlasSecurity;
import org.springframework.context.ApplicationEventPublisher;
import java.util.UUID;
public abstract class AuthenticatingPropagationFilter extends AuthenticatingFilter {
public static final String HEADER_AUTH_ERROR = "x-auth-error";
protected ApplicationEventPublisher eventPublisher;
protected AuthenticatingPropagationFilter(ApplicationEventPublisher eventPublisher){
this.eventPublisher = eventPublisher;
}
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
request.setAttribute(AtlasSecurity.AUTH_FILTER_ATTRIBUTE, this.getClass().getName());
String username = ((UsernamePasswordToken) token).getUsername();
eventPublisher.publishEvent(new SuccessLoginEvent(this, username));
final String sessionId = UUID.randomUUID().toString();
request.setAttribute(Constants.SESSION_ID, sessionId);
eventPublisher.publishEvent(new AuditTrailSessionCreatedEvent(this, username, sessionId, request.getRemoteHost()));
return true;
}
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
if (e instanceof LockedAccountException) {
httpResponse.setHeader(HEADER_AUTH_ERROR, e.getMessage());
}
String username = ((UsernamePasswordToken) token).getUsername();
boolean result = super.onLoginFailure(token, e, request, response);
eventPublisher.publishEvent(new FailedLoginEvent(this, username));
eventPublisher.publishEvent(new AuditTrailLoginFailedEvent(this, username, request.getRemoteHost()));
return result;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/auth/KerberosAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/auth/KerberosAuthFilter.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Pavel Grafkin
*
*/
package org.ohdsi.webapi.shiro.filters.auth;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.shiro.tokens.SpnegoToken;
public class KerberosAuthFilter extends AuthenticatingFilter {
private String getAuthHeader(ServletRequest servletRequest) {
HttpServletRequest request = WebUtils.toHttp(servletRequest);
return request.getHeader("Authorization");
}
@Override
protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
String authHeader = getAuthHeader(servletRequest);
AuthenticationToken authToken = null;
if (authHeader != null) {
byte[] token = Base64.decode(authHeader.replaceAll("^Negotiate ", ""));
authToken = new SpnegoToken(token);
}
return authToken;
}
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
boolean loggedIn = false;
String authHeader = getAuthHeader(servletRequest);
if (authHeader != null) {
try {
loggedIn = executeLogin(servletRequest, servletResponse);
} catch (AuthenticationException ae) {
loggedIn = false;
}
}
if (!loggedIn) {
HttpServletResponse response = WebUtils.toHttp(servletResponse);
response.addHeader("WWW-Authenticate", "Negotiate");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
return loggedIn;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/auth/SamlHandleFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/auth/SamlHandleFilter.java | package org.ohdsi.webapi.shiro.filters.auth;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.helper.Guard;
import org.ohdsi.webapi.shiro.filters.AtlasAuthFilter;
import org.ohdsi.webapi.shiro.tokens.JwtAuthToken;
import org.pac4j.core.context.JEEContext;
import org.pac4j.saml.client.SAML2Client;
import org.pac4j.saml.credentials.SAML2Credentials;
import org.pac4j.saml.exceptions.SAMLAuthnInstantException;
import org.pac4j.saml.profile.SAML2Profile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.AUTH_CLIENT_ATTRIBUTE;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.AUTH_CLIENT_SAML;
/**
* SAML authentication callback filter
*/
public class SamlHandleFilter extends AtlasAuthFilter {
private final SAML2Client saml2Client;
private final SAML2Client saml2ForceClient;
protected final String oauthUiCallback;
private final static String AUTH_COOKIE = "forceAuth";
public SamlHandleFilter(SAML2Client saml2Client, SAML2Client saml2ForceClient, String oauthUiCallback) {
this.saml2Client = saml2Client;
this.saml2ForceClient = saml2ForceClient;
this.oauthUiCallback = oauthUiCallback;
}
/**
* @see org.apache.shiro.web.filter.authc.AuthenticatingFilter#createToken(ServletRequest,
* ServletResponse)
*/
@Override
protected AuthenticationToken createToken(ServletRequest servletRequest,
ServletResponse servletResponse) throws Exception {
final ShiroHttpServletRequest request = (ShiroHttpServletRequest) servletRequest;
AuthenticationToken token = null;
if (request.getSession() != null) {
if (!SecurityUtils.getSubject().isAuthenticated()) {
request.setAttribute(AUTH_CLIENT_ATTRIBUTE, AUTH_CLIENT_SAML);
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
JEEContext context = new JEEContext(httpRequest, httpResponse);
SAML2Client client;
if (isForceAuth(request)) {
client = saml2ForceClient;
} else {
client = saml2Client;
}
SAML2Credentials credentials = client.getCredentials(context).get();
SAML2Profile samlProfile = (SAML2Profile)client.getUserProfile(credentials, context).get();
token = new JwtAuthToken(samlProfile.getId());
}
}
return token;
}
/**
* @see org.apache.shiro.web.filter.AccessControlFilter#onAccessDenied(ServletRequest,
* ServletResponse)
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
try {
boolean loggedIn = executeLogin(request, response);
return loggedIn;
} catch (SAMLAuthnInstantException e) {
if (!isForceAuth(request)) {
createForceAuthCookie(response);
WebUtils.toHttp(response).sendRedirect(WebUtils.toHttp(request).getContextPath() + "/user/login/samlForce");
} else {
deleteForceAuthCookie(response);
String urlValue = oauthUiCallback.replaceAll("/+$", "");
urlValue = urlValue + "/" + AUTH_CLIENT_SAML + "/reloginRequired";
WebUtils.toHttp(response).sendRedirect(urlValue);
}
}
return false;
}
private boolean isForceAuth(ServletRequest request) {
Cookie[] cookies = WebUtils.toHttp(request).getCookies();
if (Objects.nonNull(cookies)) {
for (Cookie cookie: cookies) {
if (AUTH_COOKIE.equals(cookie.getName())) {
return Boolean.TRUE.toString().equals(cookie.getValue());
}
}
}
return false;
}
private void createForceAuthCookie(ServletResponse response) {
Cookie cookie = new Cookie(AUTH_COOKIE, Boolean.TRUE.toString());
cookie.setPath("/");
WebUtils.toHttp(response).addCookie(cookie);
}
private void deleteForceAuthCookie(ServletResponse response) {
Cookie cookie = new Cookie(AUTH_COOKIE, Boolean.TRUE.toString());
cookie.setMaxAge(0);
cookie.setPath("/");
WebUtils.toHttp(response).addCookie(cookie);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/auth/ActiveDirectoryAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/auth/ActiveDirectoryAuthFilter.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Alexandr Ryabokon
*
*/
package org.ohdsi.webapi.shiro.filters.auth;
import org.ohdsi.webapi.shiro.tokens.ActiveDirectoryUsernamePasswordToken;
import org.springframework.context.ApplicationEventPublisher;
public class ActiveDirectoryAuthFilter extends AbstractLdapAuthFilter<ActiveDirectoryUsernamePasswordToken> {
public ActiveDirectoryAuthFilter(ApplicationEventPublisher eventPublisher){
super(eventPublisher);
}
@Override
protected ActiveDirectoryUsernamePasswordToken getToken() {
return new ActiveDirectoryUsernamePasswordToken();
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/auth/AbstractLdapAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/auth/AbstractLdapAuthFilter.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Alexandr Ryabokon
*
*/
package org.ohdsi.webapi.shiro.filters.auth;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.ohdsi.webapi.shiro.filters.AuthenticatingPropagationFilter;
import org.springframework.context.ApplicationEventPublisher;
public abstract class AbstractLdapAuthFilter<T extends UsernamePasswordToken> extends AuthenticatingPropagationFilter {
protected AbstractLdapAuthFilter(ApplicationEventPublisher eventPublisher) {
super(eventPublisher);
}
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
final String name = request.getParameter("login");
final String password = request.getParameter("password");
T token;
if (name != null && password != null) {
token = getToken();
token.setUsername(name);
token.setPassword(password.toCharArray());
} else {
throw new AuthenticationException("Empty credentials");
}
return token;
}
protected abstract T getToken();
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
boolean loggedIn = false;
if (request.getParameter("login") != null) {
loggedIn = executeLogin(request, response);
}
return loggedIn;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/auth/AtlasJwtAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/auth/AtlasJwtAuthFilter.java | package org.ohdsi.webapi.shiro.filters.auth;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.shiro.filters.AtlasAuthFilter;
import org.ohdsi.webapi.shiro.tokens.JwtAuthToken;
import org.ohdsi.webapi.shiro.TokenManager;
public final class AtlasJwtAuthFilter extends AtlasAuthFilter {
@Override
protected JwtAuthToken createToken(ServletRequest request, ServletResponse response) throws Exception {
String jwt = TokenManager.extractToken(request);
try {
String subject = TokenManager.getSubject(jwt);
return new JwtAuthToken(subject);
} catch (JwtException e) {
throw new AuthenticationException(e);
}
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
boolean loggedIn = false;
if (isLoginAttempt(request, response)) {
try {
loggedIn = executeLogin(request, response);
}
catch(AuthenticationException ae) {
loggedIn = false;
}
}
if (!loggedIn) {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
return loggedIn;
}
protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
return TokenManager.extractToken(request) != null;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/auth/LdapAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/auth/LdapAuthFilter.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Alexandr Ryabokon, Vitaly Koulakov
*
*/
package org.ohdsi.webapi.shiro.filters.auth;
import org.ohdsi.webapi.shiro.tokens.LdapUsernamePasswordToken;
import org.springframework.context.ApplicationEventPublisher;
public class LdapAuthFilter extends AbstractLdapAuthFilter<LdapUsernamePasswordToken> {
public LdapAuthFilter(ApplicationEventPublisher eventPublisher) {
super(eventPublisher);
}
@Override
protected LdapUsernamePasswordToken getToken() {
return new LdapUsernamePasswordToken();
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/filters/auth/JdbcAuthFilter.java | src/main/java/org/ohdsi/webapi/shiro/filters/auth/JdbcAuthFilter.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Mikhail Mironov, Pavel Grafkin
*
*/
package org.ohdsi.webapi.shiro.filters.auth;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.ohdsi.webapi.shiro.filters.AuthenticatingPropagationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
public class JdbcAuthFilter extends AuthenticatingPropagationFilter {
private static final Logger log = LoggerFactory.getLogger(JdbcAuthFilter.class);
public JdbcAuthFilter(ApplicationEventPublisher eventPublisher){
super(eventPublisher);
}
@Override
protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
final String name = servletRequest.getParameter("login");
final String password = servletRequest.getParameter("password");
UsernamePasswordToken token;
if (name != null && password != null) {
token = new UsernamePasswordToken(name, password);
} else {
throw new AuthenticationException("Empty credentials");
}
return token;
}
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
boolean loggedIn = false;
if (servletRequest.getParameter("login") != null) {
loggedIn = executeLogin(servletRequest, servletResponse);
}
return loggedIn;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/tokens/JwtAuthToken.java | src/main/java/org/ohdsi/webapi/shiro/tokens/JwtAuthToken.java | package org.ohdsi.webapi.shiro.tokens;
import org.apache.shiro.authc.AuthenticationToken;
/**
*
* @author gennadiy.anisimov
*/
public class JwtAuthToken implements AuthenticationToken {
private String subject;
public JwtAuthToken(String subject) {
this.subject = subject;
}
@Override
public Object getPrincipal() {
return this.subject;
}
@Override
public Object getCredentials() {
return "";
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/tokens/ActiveDirectoryUsernamePasswordToken.java | src/main/java/org/ohdsi/webapi/shiro/tokens/ActiveDirectoryUsernamePasswordToken.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Alexandr Ryabokon
*
*/
package org.ohdsi.webapi.shiro.tokens;
import org.apache.shiro.authc.UsernamePasswordToken;
public class ActiveDirectoryUsernamePasswordToken extends UsernamePasswordToken {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/tokens/LdapUsernamePasswordToken.java | src/main/java/org/ohdsi/webapi/shiro/tokens/LdapUsernamePasswordToken.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Vitaly Koulakov
*
*/
package org.ohdsi.webapi.shiro.tokens;
import org.apache.shiro.authc.UsernamePasswordToken;
public class LdapUsernamePasswordToken extends UsernamePasswordToken {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/tokens/SpnegoToken.java | src/main/java/org/ohdsi/webapi/shiro/tokens/SpnegoToken.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Pavel Grafkin
*
*/
package org.ohdsi.webapi.shiro.tokens;
import org.apache.shiro.authc.AuthenticationToken;
public class SpnegoToken implements AuthenticationToken {
byte[] token;
public SpnegoToken(byte[] token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return null;
}
@Override
public Object getCredentials() {
return token;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/realms/ADRealm.java | src/main/java/org/ohdsi/webapi/shiro/realms/ADRealm.java | package org.ohdsi.webapi.shiro.realms;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.activedirectory.ActiveDirectoryRealm;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.ohdsi.webapi.shiro.Entities.UserPrincipal;
import org.ohdsi.webapi.shiro.mapper.UserMapper;
import org.ohdsi.webapi.shiro.tokens.ActiveDirectoryUsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.LdapContext;
import java.util.List;
import java.util.Objects;
public class ADRealm extends ActiveDirectoryRealm {
private static final Logger LOGGER = LoggerFactory.getLogger(ADRealm.class);
private String searchFilter;
private String searchString;
private LdapTemplate ldapTemplate;
private AttributesMapper<String> dnAttributesMapper = attrs -> (String) attrs.get("distinguishedName").get();
private UserMapper userMapper;
public ADRealm() {
}
public ADRealm(LdapTemplate ldapTemplate, String searchFilter, String searchString, UserMapper userMapper) {
this.ldapTemplate = ldapTemplate;
this.searchFilter = searchFilter;
this.searchString = searchString;
this.userMapper = userMapper;
}
@Override
public boolean supports(AuthenticationToken token) {
return token != null && token.getClass() == ActiveDirectoryUsernamePasswordToken.class;
}
public void setSearchFilter(String searchFilter) {
this.searchFilter = searchFilter;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
try {
return super.doGetAuthorizationInfo(principals);
} catch (Exception e) {
LOGGER.warn(e.getMessage());
return null;
}
}
private String getUserPrincipalName(final String username) {
return StringUtils.isNotBlank(principalSuffix) ? username + principalSuffix : username;
}
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
if (Objects.nonNull(ldapTemplate) && StringUtils.isNotBlank(searchFilter) && StringUtils.isNotBlank(searchString)) {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String userPrincipalName = getUserPrincipalName(upToken.getUsername());
String userSearch = String.format(searchString, userPrincipalName);
List<UserPrincipal> result = ldapTemplate.search("", userSearch, SearchControls.SUBTREE_SCOPE,
userMapper);
if (result.size() == 1) {
UserPrincipal userPrincipal = result.iterator().next();
List<String> filterResult = ldapTemplate.search("", String.format(searchFilter, userPrincipal.getUsername()),
SearchControls.SUBTREE_SCOPE, dnAttributesMapper);
if (!filterResult.isEmpty()) {
LdapContext ctx = null;
try {
ctx = ldapContextFactory.getLdapContext(upToken.getUsername(), String.valueOf(upToken.getPassword()));
} finally {
LdapUtils.closeContext(ctx);
}
return new SimpleAuthenticationInfo(userPrincipal, upToken.getPassword(), getName());
}
} else {
LOGGER.warn("Multiple results found for {}", userPrincipalName);
}
} else {
return super.queryForAuthenticationInfo(token, ldapContextFactory);
}
return null;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/realms/JdbcAuthRealm.java | src/main/java/org/ohdsi/webapi/shiro/realms/JdbcAuthRealm.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Mikhail Mironov, Pavel Grafkin
*
*/
package org.ohdsi.webapi.shiro.realms;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.ohdsi.webapi.shiro.Entities.UserPrincipal;
import org.ohdsi.webapi.shiro.tokens.ActiveDirectoryUsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcAuthRealm extends JdbcRealm {
private static final Logger log = LoggerFactory.getLogger(JdbcAuthRealm.class);
private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
public JdbcAuthRealm(DataSource dataSource, String authenticationQuery) {
this.setDataSource(dataSource);
this.setAuthenticationQuery(authenticationQuery);
}
@Override
public boolean supports(AuthenticationToken token) {
return token != null && token.getClass() == UsernamePasswordToken.class;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
SimpleAuthenticationInfo info;
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
if (username == null) {
throw new AccountException("Null usernames are not allowed by this realm.");
} else {
UserPrincipal userPrincipal = this.getUser(username);
if (userPrincipal == null || userPrincipal.getPassword() == null ||
!bCryptPasswordEncoder.matches(new String(upToken.getPassword()), userPrincipal.getPassword())) {
throw new AuthenticationException("Incorrect username or password");
} else {
info = new SimpleAuthenticationInfo(userPrincipal, upToken.getPassword(), this.getName());
}
}
return info;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// Prevent from querying of permissions
return new SimpleAuthorizationInfo();
}
private UserPrincipal getUser(String username) {
UserPrincipal result = null;
try (
Connection conn = dataSource.getConnection();
PreparedStatement ps = createPreparedStatement(conn, username);
ResultSet rs = ps.executeQuery()
) {
for (boolean foundResult = false; rs.next(); foundResult = true) {
if (foundResult) {
throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
}
result = extractUserEntity(rs);
result.setUsername(username);
}
} catch (SQLException e) {
String message = "There was a SQL error while authenticating user [" + username + "]";
if (log.isErrorEnabled()) {
log.error(message, e);
}
result = null;
}
return result;
}
private PreparedStatement createPreparedStatement(Connection conn, String username) throws SQLException {
PreparedStatement ps = conn.prepareStatement(this.authenticationQuery);
ps.setString(1, username);
return ps;
}
private UserPrincipal extractUserEntity(ResultSet rs) throws SQLException {
UserPrincipal userEntity = new UserPrincipal();
// Old style query is used - only password is queried from database
if(rs.getMetaData().getColumnCount() == 1) {
userEntity.setPassword(rs.getString(1));
} else {
// New style query - user name is also queried from database
userEntity.setPassword(rs.getString("password"));
String firstName = trim(rs.getString("firstname"));
String midlleName = trim(rs.getString("middlename"));
String lastName = trim(rs.getString("lastname"));
StringBuilder name = new StringBuilder(firstName);
if (!midlleName.isEmpty()) {
name.append(' ').append(midlleName);
}
if (!lastName.isEmpty()) {
name.append(' ').append(lastName);
}
userEntity.setName(name.toString().trim());
}
return userEntity;
}
private String trim(String value) {
if(value != null) {
return value.trim();
}
return StringUtils.EMPTY;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/realms/LdapRealm.java | src/main/java/org/ohdsi/webapi/shiro/realms/LdapRealm.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Vitaly Koulakov
*
*/
package org.ohdsi.webapi.shiro.realms;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.ldap.JndiLdapRealm;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.ohdsi.webapi.shiro.Entities.UserPrincipal;
import org.ohdsi.webapi.shiro.mapper.UserMapper;
import org.ohdsi.webapi.shiro.tokens.ActiveDirectoryUsernamePasswordToken;
import org.ohdsi.webapi.shiro.tokens.LdapUsernamePasswordToken;
import org.ohdsi.webapi.shiro.tokens.SpnegoToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
public class LdapRealm extends JndiLdapRealm {
private static final Logger LOGGER = LoggerFactory.getLogger(LdapRealm.class);
private String searchString;
private UserMapper userMapper;
private String ldapSearchBase;
public LdapRealm(String ldapSearchString, String ldapSearchBase, UserMapper userMapper) {
this.searchString = ldapSearchString;
this.userMapper = userMapper;
this.ldapSearchBase = ldapSearchBase;
}
@Override
public boolean supports(AuthenticationToken token) {
return token != null && token.getClass() == LdapUsernamePasswordToken.class;
}
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
LdapContextFactory ldapContextFactory)
throws NamingException {
Object principal = token.getPrincipal();
Object credentials = token.getCredentials();
LOGGER.debug("Authenticating user '{}' through LDAP", principal);
principal = getLdapPrincipal(token);
LdapContext ctx = null;
try {
ctx = ldapContextFactory.getLdapContext(principal, credentials);
UserPrincipal userPrincipal = searchForUser(ctx, token);
return createAuthenticationInfo(token, userPrincipal, credentials, ctx);
} finally {
LdapUtils.closeContext(ctx);
}
}
@Override
protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal,
Object ldapCredentials, LdapContext ldapContext) {
return new SimpleAuthenticationInfo(ldapPrincipal, token.getCredentials(), getName());
}
private UserPrincipal searchForUser(LdapContext ctx, AuthenticationToken token) throws NamingException {
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
Object[] searchArguments = new Object[]{token.getPrincipal()};
NamingEnumeration results = ctx.search(ldapSearchBase, searchString, searchArguments, searchCtls);
boolean processSingleRecord = false;
UserPrincipal userPrincipal = null;
while (results.hasMore()) {
if (processSingleRecord) {
LOGGER.error("Multiple results found for {}", token.getPrincipal());
throw new RuntimeException("Multiple results found for " + token.getPrincipal());
}
processSingleRecord = true;
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
userPrincipal = userMapper.mapFromAttributes(attributes);
}
return userPrincipal;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/realms/JwtAuthRealm.java | src/main/java/org/ohdsi/webapi/shiro/realms/JwtAuthRealm.java | package org.ohdsi.webapi.shiro.realms;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.ohdsi.webapi.security.model.UserSimpleAuthorizationInfo;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.ohdsi.webapi.shiro.tokens.JwtAuthToken;
/**
*
* @author gennadiy.anisimov
*/
public class JwtAuthRealm extends AuthorizingRealm {
private final PermissionManager authorizer;
public JwtAuthRealm(PermissionManager authorizer) {
this.authorizer = authorizer;
}
@Override
public boolean supports(AuthenticationToken token) {
return token != null && token.getClass() == JwtAuthToken.class;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
final String login = (String) principals.getPrimaryPrincipal();
return authorizer.getAuthorizationInfo(login);
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
return new SimpleAuthenticationInfo(at.getPrincipal(), "", getName());
}
@Override
protected boolean isPermitted(Permission permission, AuthorizationInfo info) {
// for speed, we check the permission against the set of permissions found by the key '*' and the first element of the permission.
String permPrefix = StringUtils.split(permission.toString(), ":")[0];
// we only need to check * perms and perms that begin with the same prefix (up to first :) as the requested permission
// starting with perms that start with *
List<Permission> permsToCheck = new ArrayList(((UserSimpleAuthorizationInfo)info).getPermissionIdx().getOrDefault("*", new ArrayList<>()));
// adding those permissiosn that start with the permPrefix
permsToCheck.addAll(((UserSimpleAuthorizationInfo)info).getPermissionIdx().getOrDefault(permPrefix, new ArrayList<>()));
// do check
return permsToCheck.stream().anyMatch(permToCheck -> permToCheck.implies(permission));
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/realms/KerberosAuthRealm.java | src/main/java/org/ohdsi/webapi/shiro/realms/KerberosAuthRealm.java | /*
*
* Copyright 2017 Observational Health Data Sciences and Informatics
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Pavel Grafkin
*
*/
package org.ohdsi.webapi.shiro.realms;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;
import org.ohdsi.webapi.shiro.tokens.JwtAuthToken;
import org.ohdsi.webapi.shiro.tokens.SpnegoToken;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
// For instructions see README.MD in this package
public class KerberosAuthRealm extends AuthenticatingRealm {
private String serviceProviderName;
private String keytabPath;
private final Log logger = LogFactory.getLog(KerberosAuthRealm.class);
public KerberosAuthRealm(String serviceProviderName, String keytabPath) {
this.serviceProviderName = serviceProviderName;
this.keytabPath = keytabPath;
}
@Override
public boolean supports(AuthenticationToken token) {
return token != null && token.getClass() == SpnegoToken.class;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
SpnegoToken token = (SpnegoToken) authenticationToken;
if (token.getCredentials() instanceof byte[]) {
byte[] gssapiData = (byte[]) token.getCredentials();
String username = validateTicket(this.serviceProviderName, this.keytabPath, gssapiData);
if (username != null) {
return new SimpleAuthenticationInfo(username, gssapiData, this.getName());
}
}
throw new AuthenticationException();
}
private Configuration getJaasKrb5TicketCfg(
final String principal, final String keytabPath) {
return new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, String> options = new HashMap<String, String>() {{
put("principal", principal);
put("keyTab", keytabPath);
put("doNotPrompt", "true");
put("useKeyTab", "true");
put("storeKey", "true");
put("isInitiator", "false");
}};
return new AppConfigurationEntry[]{
new AppConfigurationEntry(
"com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
Collections.unmodifiableMap(options)
)
};
}
};
}
private String validateTicket(String spn, String keytabPath, byte[] ticket) {
LoginContext ctx = null;
try {
// define the principal who will validate the ticket
Principal principal = new KerberosPrincipal(spn, KerberosPrincipal.KRB_NT_SRV_INST);
Set<Principal> principals = new HashSet<Principal>();
principals.add(principal);
// define the subject to execute our secure action as
Subject subject = new Subject(false, principals, new HashSet<Object>(),
new HashSet<Object>());
// login the subject
Configuration cfg = getJaasKrb5TicketCfg(spn, keytabPath);
ctx = new LoginContext("doesn't matter", subject, null, cfg);
ctx.login();
// create a validator for the ticket and execute it
Krb5TicketValidateAction validateAction = new Krb5TicketValidateAction(ticket, spn);
return Subject.doAs(subject, validateAction);
} catch (LoginException e) {
logger.error("Error creating validation LoginContext for " + spn + ": " + e);
} catch (PrivilegedActionException e) {
logger.error("Invalid ticket for " + spn + ": " + e);
} finally {
try {
if(ctx!=null) { ctx.logout(); }
} catch(LoginException e) { /* noop */ }
}
return null;
}
private class Krb5TicketValidateAction implements PrivilegedExceptionAction<String> {
private final byte[] ticket;
private final String spn;
public Krb5TicketValidateAction(byte[] ticket, String spn) {
this.ticket = ticket;
this.spn = spn;
}
@Override
public String run() throws Exception {
final Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
GSSManager gssmgr = GSSManager.getInstance();
// tell the GSSManager the Kerberos name of the service
GSSName serviceName = gssmgr.createName(this.spn, GSSName.NT_USER_NAME);
// get the service's credentials. note that this run() method was called by Subject.doAs(),
// so the service's credentials (Service Principal Name and password) are already
// available in the Subject
GSSCredential serviceCredentials = gssmgr.createCredential(serviceName,
GSSCredential.INDEFINITE_LIFETIME, spnegoOid, GSSCredential.ACCEPT_ONLY);
// create a security context for decrypting the service ticket
GSSContext gssContext = gssmgr.createContext(serviceCredentials);
// decrypt the service ticket
System.out.println("Entering accpetSecContext...");
gssContext.acceptSecContext(this.ticket, 0, this.ticket.length);
// get the client name from the decrypted service ticket
// note that Active Directory created the service ticket, so we can trust it
String clientName = gssContext.getSrcName().toString();
// clean up the context
gssContext.dispose();
// return the authenticated client name
return clientName;
}
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/mapper/UserMapper.java | src/main/java/org/ohdsi/webapi/shiro/mapper/UserMapper.java | package org.ohdsi.webapi.shiro.mapper;
import org.apache.commons.lang3.StringUtils;
import org.ohdsi.webapi.shiro.Entities.UserPrincipal;
import org.springframework.ldap.core.AttributesMapper;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
public abstract class UserMapper implements AttributesMapper<UserPrincipal> {
private String getAttrCoalesce(Attributes attrList, String key) throws NamingException {
String result = null;
Attribute attribute = attrList.get(key);
if (attribute != null) {
Object value = attribute.get();
if(value instanceof String) {
result = (String) value;
}
}
return result;
}
public UserPrincipal mapFromAttributes(Attributes attrs) throws NamingException {
UserPrincipal user = new UserPrincipal();
user.setUsername(getAttrCoalesce(attrs, getUsernameAttr()));
StringBuilder name = new StringBuilder();
// If display name attribute value is set then use only it, otherwise use attributes for full name
if (StringUtils.isNotEmpty(getDisplaynameAttr())) {
processAttribute(attrs, getDisplaynameAttr(), name);
} else {
processAttribute(attrs, getFirstnameAttr(), name);
processAttribute(attrs, getMiddlenameAttr(), name);
processAttribute(attrs, getLastnameAttr(), name);
}
user.setName(name.toString().trim());
return user;
}
private void processAttribute(Attributes attrs, String key, StringBuilder name) throws NamingException {
if (key != null) {
String attrValue = getAttrCoalesce(attrs, key);
if (attrValue != null) {
name.append(' ').append(attrValue);
}
}
}
public abstract String getFirstnameAttr();
public abstract String getMiddlenameAttr();
public abstract String getLastnameAttr();
public abstract String getUsernameAttr();
public abstract String getDisplaynameAttr();
} | java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/mapper/LdapUserMapper.java | src/main/java/org/ohdsi/webapi/shiro/mapper/LdapUserMapper.java | package org.ohdsi.webapi.shiro.mapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class LdapUserMapper extends UserMapper {
@Value("${security.ldap.userMapping.firstnameAttr}")
private String firstnameKey;
@Value("${security.ldap.userMapping.middlenameAttr}")
private String middlenameKey;
@Value("${security.ldap.userMapping.lastnameAttr}")
private String lastnameKey;
@Value("${security.ldap.userMapping.usernameAttr}")
private String usernameKey;
@Value("${security.ldap.userMapping.displaynameAttr}")
private String displaynameKey;
@Override
public String getFirstnameAttr() {
return firstnameKey;
}
@Override
public String getMiddlenameAttr() {
return middlenameKey;
}
@Override
public String getLastnameAttr() {
return lastnameKey;
}
@Override
public String getUsernameAttr() {
return usernameKey;
}
@Override
public String getDisplaynameAttr() {
return displaynameKey;
}
} | java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiro/mapper/ADUserMapper.java | src/main/java/org/ohdsi/webapi/shiro/mapper/ADUserMapper.java | package org.ohdsi.webapi.shiro.mapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ADUserMapper extends UserMapper {
@Value("${security.ad.userMapping.firstnameAttr}")
private String firstnameKey;
@Value("${security.ad.userMapping.middlenameAttr}")
private String middlenameKey;
@Value("${security.ad.userMapping.lastnameAttr}")
private String lastnameKey;
@Value("${security.ad.userMapping.usernameAttr}")
private String usernameKey;
@Value("${security.ad.userMapping.displaynameAttr}")
private String displaynameKey;
@Override
public String getFirstnameAttr() {
return firstnameKey;
}
@Override
public String getMiddlenameAttr() {
return middlenameKey;
}
@Override
public String getLastnameAttr() {
return lastnameKey;
}
@Override
public String getUsernameAttr() {
return usernameKey;
}
@Override
public String getDisplaynameAttr() {
return displaynameKey;
}
} | java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/activity/Tracker.java | src/main/java/org/ohdsi/webapi/activity/Tracker.java | /*
* Copyright 2015 fdefalco.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.activity;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.ohdsi.webapi.activity.Activity.ActivityType;
/**
*
* @author fdefalco
*/
public class Tracker {
private static ConcurrentLinkedQueue<Activity> activityLog;
public static void trackActivity(ActivityType type, String caption) {
if (activityLog == null) {
activityLog = new ConcurrentLinkedQueue<>();
}
Activity activity = new Activity();
activity.caption = caption;
activity.timestamp = new Date();
activity.type = type;
activityLog.add(activity);
}
public static Object[] getActivity() {
if (activityLog == null) {
activityLog = new ConcurrentLinkedQueue<>();
}
return activityLog.toArray();
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/activity/Activity.java | src/main/java/org/ohdsi/webapi/activity/Activity.java | /*
* Copyright 2015 fdefalco.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.activity;
import java.util.Date;
/**
*
* @author fdefalco
*/
public class Activity {
public enum ActivityType {
Search, Import
};
public ActivityType type;
public String caption;
public Date timestamp;
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/CSVRecordMapper.java | src/main/java/org/ohdsi/webapi/util/CSVRecordMapper.java | package org.ohdsi.webapi.util;
import org.apache.commons.csv.CSVRecord;
@FunctionalInterface
public interface CSVRecordMapper<T> {
T mapRecord(CSVRecord record);
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/BatchStatementExecutorWithProgress.java | src/main/java/org/ohdsi/webapi/util/BatchStatementExecutorWithProgress.java | package org.ohdsi.webapi.util;
import org.apache.tika.concurrent.SimpleThreadPoolExecutor;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public class BatchStatementExecutorWithProgress {
private String[] statements;
private final TransactionTemplate transactionTemplate;
private final JdbcTemplate jdbcTemplate;
private ExecutorService executorService;
private static int PROGRESS_UPDATE_SIZE = 10;
public BatchStatementExecutorWithProgress(String[] statements,
TransactionTemplate transactionTemplate,
JdbcTemplate jdbcTemplate) {
this.statements = statements;
this.transactionTemplate = transactionTemplate;
this.jdbcTemplate = jdbcTemplate;
executorService = Executors.newSingleThreadExecutor();
}
public int[] execute(Consumer<Integer> consumer){
int[] updateCount = new int[statements.length];
return transactionTemplate.execute(status -> {
int totals = statements.length;
try {
for (int i = 0; i < totals; i++) {
String stmt = statements[i];
updateCount[i] = jdbcTemplate.execute((StatementCallback<Integer>) st -> !st.execute(stmt) ? st.getUpdateCount() : 0);
if (i % PROGRESS_UPDATE_SIZE == 0 || i == (totals - 1)) {
int progress = (int) Math.round(100.0 * i / totals);
if (Objects.nonNull(consumer)) {
executorService.execute(() -> consumer.accept(progress));
}
}
}
} finally {
executorService.shutdown();
}
return updateCount;
});
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/ExportUtil.java | src/main/java/org/ohdsi/webapi/util/ExportUtil.java | package org.ohdsi.webapi.util;
import com.opencsv.CSVWriter;
import org.ohdsi.circe.vocabulary.Concept;
import org.ohdsi.circe.vocabulary.ConceptSetExpression;
import org.ohdsi.webapi.analysis.AnalysisCohortDefinition;
import org.ohdsi.webapi.conceptset.ConceptSetExport;
import org.ohdsi.webapi.estimation.specification.EstimationAnalysisImpl;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.model.CommonEntityExt;
import org.ohdsi.webapi.prediction.specification.PatientLevelPredictionAnalysisImpl;
import org.ohdsi.webapi.service.dto.CommonEntityDTO;
import org.ohdsi.webapi.service.dto.CommonEntityExtDTO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ExportUtil {
public static ByteArrayOutputStream writeConceptSetExportToCSVAndZip(List<ConceptSetExport> conceptSetExportList) throws RuntimeException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
StringWriter sw;
CSVWriter csvWriter;
String[] headings;
try {
// Write Concept Set Expression to a CSV
sw = new StringWriter();
csvWriter = new CSVWriter(sw);
ArrayList<String[]> allLines = new ArrayList<String[]>();
headings = "Concept Set ID#Name#Concept ID#Concept Code#Concept Name#Domain#Vocabulary#Standard Concept#Exclude#Descendants#Mapped".split("#");
allLines.add(headings);
for (ConceptSetExport cs : conceptSetExportList) {
for (ConceptSetExpression.ConceptSetItem item : cs.csExpression.items) {
ArrayList<String> csItem = new ArrayList<String>();
csItem.add(String.valueOf(cs.ConceptSetId));
csItem.add(cs.ConceptSetName);
csItem.add(String.valueOf(item.concept.conceptId));
csItem.add(String.valueOf(item.concept.conceptCode));
csItem.add(item.concept.conceptName);
csItem.add(item.concept.domainId);
csItem.add(item.concept.vocabularyId);
csItem.add(item.concept.standardConcept);
csItem.add(String.valueOf(item.isExcluded));
csItem.add(String.valueOf(item.includeDescendants));
csItem.add(String.valueOf(item.includeMapped));
allLines.add(csItem.toArray(new String[0]));
}
}
csvWriter.writeAll(allLines);
csvWriter.close();
ZipEntry resultsEntry = new ZipEntry("conceptSetExpression.csv");
zos.putNextEntry(resultsEntry);
zos.write(sw.getBuffer().toString().getBytes());
// Write included concepts to a CSV
sw = new StringWriter();
csvWriter = new CSVWriter(sw);
allLines = new ArrayList<>();
headings = "Concept Set ID#Name#Concept ID#Concept Code#Concept Name#Concept Class ID#Domain#Vocabulary".split("#");
allLines.add(headings);
for (ConceptSetExport cs : conceptSetExportList) {
for (Concept c : cs.identifierConcepts) {
ArrayList<String> csItem = new ArrayList<>();
csItem.add(String.valueOf(cs.ConceptSetId));
csItem.add(cs.ConceptSetName);
csItem.add(String.valueOf(c.conceptId));
csItem.add(String.valueOf(c.conceptCode));
csItem.add(c.conceptName);
csItem.add(c.conceptClassId);
csItem.add(c.domainId);
csItem.add(c.vocabularyId);
allLines.add(csItem.toArray(new String[0]));
}
}
csvWriter.writeAll(allLines);
csvWriter.close();
resultsEntry = new ZipEntry("includedConcepts.csv");
zos.putNextEntry(resultsEntry);
zos.write(sw.getBuffer().toString().getBytes());
// Write mapped concepts to a CSV
sw = new StringWriter();
csvWriter = new CSVWriter(sw);
allLines = new ArrayList<>();
headings = "Concept Set ID#Name#Concept ID#Concept Code#Concept Name#Concept Class ID#Domain#Vocabulary".split("#");
allLines.add(headings);
for (ConceptSetExport cs : conceptSetExportList) {
for (Concept c : cs.mappedConcepts) {
ArrayList<String> csItem = new ArrayList<>();
csItem.add(String.valueOf(cs.ConceptSetId));
csItem.add(cs.ConceptSetName);
csItem.add(String.valueOf(c.conceptId));
csItem.add(String.valueOf(c.conceptCode));
csItem.add(c.conceptName);
csItem.add(c.conceptClassId);
csItem.add(c.domainId);
csItem.add(c.vocabularyId);
allLines.add(csItem.toArray(new String[0]));
}
}
csvWriter.writeAll(allLines);
csvWriter.close();
resultsEntry = new ZipEntry("mappedConcepts.csv");
zos.putNextEntry(resultsEntry);
zos.write(sw.getBuffer().toString().getBytes());
zos.closeEntry();
zos.close();
baos.flush();
baos.close();
return baos;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public static void clearCreateAndUpdateInfo(CommonEntityDTO commonEntityDTO) {
clearMetadataInfo(commonEntityDTO);
}
public static void clearCreateAndUpdateInfo(CommonEntityExtDTO commonEntityDTO) {
// prevent tags from being exported
commonEntityDTO.setTags(null);
clearMetadataInfo(commonEntityDTO);
}
private static void clearMetadataInfo(CommonEntityDTO commonEntityDTO) {
commonEntityDTO.setCreatedBy(null);
commonEntityDTO.setCreatedDate(null);
commonEntityDTO.setModifiedBy(null);
commonEntityDTO.setModifiedDate(null);
}
public static void clearCreateAndUpdateInfo(CommonEntity commonEntity) {
clearMetadataInfo(commonEntity);
}
public static void clearCreateAndUpdateInfo(CommonEntityExt commonEntity) {
// prevent tags from being exported
commonEntity.setTags(null);
clearMetadataInfo(commonEntity);
}
private static void clearMetadataInfo(CommonEntity commonEntity) {
commonEntity.setCreatedBy(null);
commonEntity.setCreatedDate(null);
commonEntity.setModifiedBy(null);
commonEntity.setModifiedDate(null);
}
public static void clearCreateAndUpdateInfo(AnalysisCohortDefinition analysisCohortDefinition) {
analysisCohortDefinition.setCreatedBy(null);
analysisCohortDefinition.setCreatedDate(null);
analysisCohortDefinition.setModifiedBy(null);
analysisCohortDefinition.setModifiedDate(null);
}
public static void clearCreateAndUpdateInfo(EstimationAnalysisImpl analysis) {
analysis.setCreatedBy(null);
analysis.setCreatedDate(null);
analysis.setModifiedBy(null);
analysis.setModifiedDate(null);
analysis.getCohortDefinitions().forEach(ExportUtil::clearCreateAndUpdateInfo);
}
public static void clearCreateAndUpdateInfo(PatientLevelPredictionAnalysisImpl analysis) {
analysis.setCreatedBy(null);
analysis.setCreatedDate(null);
analysis.setModifiedBy(null);
analysis.setModifiedDate(null);
analysis.getCohortDefinitions().forEach(ExportUtil::clearCreateAndUpdateInfo);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/CacheHelper.java | src/main/java/org/ohdsi/webapi/util/CacheHelper.java | package org.ohdsi.webapi.util;
import java.lang.management.ManagementFactory;
import java.util.HashSet;
import java.util.Set;
import javax.cache.CacheManager;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.management.CacheStatisticsMXBean;
import javax.management.MBeanServer;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
/**
*
* @author cknoll1
*/
public class CacheHelper {
public static CacheStatisticsMXBean getCacheStats(CacheManager cacheManager, String cacheName) throws RuntimeException {
try {
final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectInstance> cacheBeans = beanServer.queryMBeans(
ObjectName.getInstance("javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"),
null);
String cacheManagerName = cacheManager.getURI().toString().replace(":", ".");
ObjectInstance cacheBean = cacheBeans.stream()
.filter(b ->
b.getObjectName().getKeyProperty("CacheManager").equals(cacheManagerName)
&& b.getObjectName().getKeyProperty("Cache").equals(cacheName)
).findFirst().orElseThrow(() -> new IllegalArgumentException(String.format("No cache found for cache manager = %s, cache = %s", cacheManagerName, cacheName)));
final CacheStatisticsMXBean cacheStatisticsMXBean = MBeanServerInvocationHandler.newProxyInstance(beanServer, cacheBean.getObjectName(), CacheStatisticsMXBean.class, false);
return cacheStatisticsMXBean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Set<String> getCacheNames(CacheManager cacheManager) {
Set<String> cacheNames = new HashSet<>();
cacheManager.getCacheNames().forEach((name) -> cacheNames.add(name));
return cacheNames;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/CancelableJdbcTemplate.java | src/main/java/org/ohdsi/webapi/util/CancelableJdbcTemplate.java | package org.ohdsi.webapi.util;
import org.ohdsi.sql.BigQuerySparkTranslate;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.*;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.sql.*;
import java.util.List;
import java.util.Objects;
public class CancelableJdbcTemplate extends JdbcTemplate {
private boolean suppressApiException = true;
public CancelableJdbcTemplate() {
}
public CancelableJdbcTemplate(DataSource dataSource) {
super(dataSource);
}
public CancelableJdbcTemplate(DataSource dataSource, boolean lazyInit) {
super(dataSource, lazyInit);
}
public boolean isSuppressApiException() {
return suppressApiException;
}
public void setSuppressApiException(boolean suppressApiException) {
this.suppressApiException = suppressApiException;
}
public int[] batchUpdate(StatementCancel cancelOp, String... sql) throws DataAccessException {
Assert.notEmpty(sql, "SQL array must not be empty");
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL batch update of " + sql.length + " statements");
}
class BatchUpdateStatementCallback implements StatementCallback<int[]>, SqlProvider {
private String currSql;
@Override
public int[] doInStatement(Statement stmt) throws SQLException, DataAccessException {
int[] rowsAffected = new int[sql.length];
cancelOp.setStatement(stmt);
if (supportsBatchUpdates(stmt.getConnection())) {
for (String sqlStmt : sql) {
this.currSql = appendSql(this.currSql, sqlStmt);
stmt.addBatch(sqlStmt);
}
try {
rowsAffected = stmt.executeBatch();
}
catch (BatchUpdateException ex) {
String batchExceptionSql = null;
for (int i = 0; i < ex.getUpdateCounts().length; i++) {
if (ex.getUpdateCounts()[i] == Statement.EXECUTE_FAILED) {
batchExceptionSql = appendSql(batchExceptionSql, sql[i]);
}
}
if (StringUtils.hasLength(batchExceptionSql)) {
this.currSql = batchExceptionSql;
}
SQLException reason = ex.getNextException();
if (Objects.nonNull(reason)) {
throw reason;
} else {
throw new SQLException("Failed to execute batch update", ex);
}
}
}
else {
for (int i = 0; i < sql.length; i++) {
String connectionString = stmt.getConnection().getMetaData().getURL();
if (connectionString.startsWith("jdbc:spark") || connectionString.startsWith("jdbc:databricks")) {
this.currSql = BigQuerySparkTranslate.sparkHandleInsert(sql[i], stmt.getConnection());
if (this.currSql == "" || this.currSql.isEmpty() || this.currSql == null) {
rowsAffected[i] = -1;
continue;
}
} else {
this.currSql = sql[i];
}
if (!stmt.execute(this.currSql)) {
rowsAffected[i] = stmt.getUpdateCount();
}
else if (!suppressApiException) {
throw new InvalidDataAccessApiUsageException("Invalid batch SQL statement: " + sql[i]);
}
}
}
return rowsAffected;
}
private String appendSql(String sql, String statement) {
return (StringUtils.isEmpty(sql) ? statement : sql + "; " + statement);
}
@Override
public String getSql() {
return this.currSql;
}
}
return execute(new BatchUpdateStatementCallback());
}
public int[] batchUpdate(StatementCancel cancelOp, List<PreparedStatementCreator> statements) {
class BatchUpdateConnectionCallback implements ConnectionCallback<int[]> {
private PreparedStatementCreator current;
@Override
public int[] doInConnection(Connection con) throws SQLException, DataAccessException {
int[] rowsAffected = new int[statements.size()];
for (int i = 0; i < statements.size(); i++) {
current = statements.get(i);
PreparedStatement query = current.createPreparedStatement(con);
cancelOp.setStatement(query);
if (!query.execute()) {
rowsAffected[i] = query.getUpdateCount();
}
else if (!suppressApiException) {
throw new InvalidDataAccessApiUsageException("Invalid batch SQL statement: " + getSql(current));
}
query.close();
if (cancelOp.isCanceled()) {
break;
}
}
return rowsAffected;
}
private String getSql(PreparedStatementCreator statement) {
if (statement instanceof SqlProvider) {
return ((SqlProvider)statement).getSql();
}
return "";
}
}
return execute(new BatchUpdateConnectionCallback());
}
private boolean supportsBatchUpdates(Connection connection) throws SQLException {
// NOTE:
// com.cloudera.impala.hivecommon.dataengine.HiveJDBCDataEngine.prepareBatch throws NOT_IMPLEMENTED exception
return JdbcUtils.supportsBatchUpdates(connection)
&& !connection.getMetaData().getURL().startsWith("jdbc:impala")
&& !connection.getMetaData().getURL().startsWith("jdbc:IRIS");
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/AnnotationReflectionUtils.java | src/main/java/org/ohdsi/webapi/util/AnnotationReflectionUtils.java | package org.ohdsi.webapi.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class AnnotationReflectionUtils {
public static List<Method> getMethodsAnnotatedWith(final Class<?> type, final Class<? extends Annotation> annotation) {
List<Method> methods = new ArrayList<>();
Class<?> current = type;
while (Objects.nonNull(current) && current != Object.class) {
methods.addAll(Arrays.stream(current.getMethods())
.filter(method -> method.isAnnotationPresent(annotation))
.collect(Collectors.toList()));
current = current.getSuperclass();
}
return methods;
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/JobUtils.java | src/main/java/org/ohdsi/webapi/util/JobUtils.java | package org.ohdsi.webapi.util;
import java.util.Map;
import static org.ohdsi.webapi.Constants.Params.CDM_DATABASE_SCHEMA;
import static org.ohdsi.webapi.Constants.Params.RESULTS_DATABASE_SCHEMA;
import static org.ohdsi.webapi.Constants.Params.TARGET_DATABASE_SCHEMA;
import static org.ohdsi.webapi.Constants.Params.TEMP_DATABASE_SCHEMA;
public final class JobUtils {
private JobUtils(){}
public static String getSchema(Map<String, Object> jobParams, String qualifier){
if (jobParams.get(qualifier) != null){
return jobParams.get(qualifier).toString();
} else {
String daimonName = "";
switch (qualifier){
case RESULTS_DATABASE_SCHEMA:
case TARGET_DATABASE_SCHEMA:
daimonName = "Results";
break;
case CDM_DATABASE_SCHEMA:
daimonName = "CDM";
break;
case TEMP_DATABASE_SCHEMA:
daimonName = "Temp";
break;
}
throw new NullPointerException(String.format("DaimonType (\"%s\") not found in Source", daimonName));
}
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/TempFileUtils.java | src/main/java/org/ohdsi/webapi/util/TempFileUtils.java | package org.ohdsi.webapi.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Function;
public class TempFileUtils {
public static File copyResourceToTempFile(String resource, String prefix, String suffix) throws IOException {
File tempFile = File.createTempFile(prefix, suffix);
try(InputStream in = TempFileUtils.class.getResourceAsStream(resource)) {
try(OutputStream out = Files.newOutputStream(tempFile.toPath())) {
if(in == null) {
throw new IOException("File not found: " + resource);
}
IOUtils.copy(in, out);
}
}
return tempFile;
}
public static <F> F doInDirectory(Function<Path, F> action) {
try {
Path tempDir = Files.createTempDirectory("webapi-");
try {
return action.apply(tempDir);
} finally {
FileUtils.deleteQuietly(tempDir.toFile());
}
} catch (IOException e) {
throw new RuntimeException("Failed to create temp directory, " + e.getMessage());
}
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/OutputStreamWriter.java | src/main/java/org/ohdsi/webapi/util/OutputStreamWriter.java | package org.ohdsi.webapi.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
/**
* http://stackoverflow.com/questions/29712554/how-to-download-a-file-using-a-java-rest-service-and-a-data-stream
*
*/
@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return ByteArrayOutputStream.class == type;
}
@Override
public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
t.writeTo(entityStream);
}
} | java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/SqlUtils.java | src/main/java/org/ohdsi/webapi/util/SqlUtils.java | /*
* Copyright 2020 cknoll1.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.util;
import org.apache.commons.lang3.StringUtils;
/**
* @author cknoll1
*/
public final class SqlUtils {
/**
* Creates a DATEFROMPARTS() expression based on an input in form YYYY-MM-DD.
* @param date a string in YYYY-MM-DD format
* @return a String containing the DATEFROMPARTS expression
* @throws IllegalArgumentException
* @author cknoll1
*/
public static String dateStringToSql(String date) {
if (!date.matches("^\\d{4}-\\d{2}-\\d{2}"))
throw new IllegalArgumentException(String.format("%s is not in valid YYYY-MM-DD format.", date));
String[] dateParts = StringUtils.split(date, '-');
return String.format("DATEFROMPARTS(%s, %s, %s)", Integer.valueOf(dateParts[0]), Integer.valueOf(dateParts[1]), Integer.valueOf(dateParts[2]));
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/ResourceUtils.java | src/main/java/org/ohdsi/webapi/util/ResourceUtils.java | package org.ohdsi.webapi.util;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.util.CommonHelper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.net.MalformedURLException;
public class ResourceUtils {
public static final String RESOURCE_PREFIX = "resource:";
public static final String CLASSPATH_PREFIX = "classpath:";
public static final String FILE_PREFIX = "file:";
public static Resource mapPathToResource(final String path) {
CommonHelper.assertNotBlank("path", path);
if (path.startsWith(RESOURCE_PREFIX)) {
return new ClassPathResource(path.substring(RESOURCE_PREFIX.length()));
} else if (path.startsWith(CLASSPATH_PREFIX)) {
return new ClassPathResource(path.substring(CLASSPATH_PREFIX.length()));
} else if (path.startsWith(HttpConstants.SCHEME_HTTP) || path.startsWith(HttpConstants.SCHEME_HTTPS)) {
return newUrlResource(path);
} else if (path.startsWith(FILE_PREFIX)) {
return new FileSystemResource(path.substring(FILE_PREFIX.length()));
} else {
return new FileSystemResource(path);
}
}
private static UrlResource newUrlResource(final String url) {
try {
return new UrlResource(url);
} catch (final MalformedURLException e) {
throw new TechnicalException(e);
}
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/NameUtils.java | src/main/java/org/ohdsi/webapi/util/NameUtils.java | package org.ohdsi.webapi.util;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.ohdsi.webapi.Constants.Templates.ENTITY_COPY_PREFIX;
public final class NameUtils {
private static final String DEFAULT_DESIGN_NAME = "Design";
private NameUtils(){}
public static String getNameForCopy(String dtoName, Function<String, List<String>> getNamesLike, Optional<?> existingObject) {
String name = dtoName != null ? dtoName : DEFAULT_DESIGN_NAME;
String nameWithPrefix = String.format(ENTITY_COPY_PREFIX, name);
return existingObject.map(o -> getNameWithSuffix(nameWithPrefix, getNamesLike)).orElse(name);
}
public static String getNameWithSuffix(String dtoName, Function<String, List<String>> getNamesLike){
String name = dtoName != null ? dtoName : DEFAULT_DESIGN_NAME;
StringBuilder builder = new StringBuilder(name);
List<String> nameList = getNamesLike.apply(formatNameForLikeSearch(name) + "%");
Pattern p = Pattern.compile(Pattern.quote(name) + " \\(([0-9]+)\\)");
nameList.stream()
.map(n -> {
if (n.equalsIgnoreCase(name)) {
return "0";
} else {
Matcher m = p.matcher(n);
return m.find() ? m.group(1) : null;
}
})
.filter(Objects::nonNull)
.map(Integer::parseInt)
.max(Comparator.naturalOrder())
.ifPresent(cnt -> builder.append(" (").append(cnt + 1).append(")"));
return builder.toString();
}
public static String formatNameForLikeSearch(String name) {
return name.replace("[", "\\[").replace("]", "\\]").replace("%", "\\%").replace("_", "\\_");
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/util/JoinUtils.java | src/main/java/org/ohdsi/webapi/util/JoinUtils.java | package org.ohdsi.webapi.util;
import org.apache.commons.lang3.StringUtils;
import java.util.Optional;
public class JoinUtils {
public static String join(Iterable<?> parts) {
return join(parts, ",");
}
public static String join(Iterable<?> parts, String separator) {
return join(parts, separator, "");
}
public static String join(Iterable<?> parts, String separator, String defaultValue) {
return Optional.ofNullable(StringUtils.join(parts, separator)).orElse(defaultValue);
}
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.