proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/GenderConverter.java
|
GenderConverter
|
internalConvert
|
class GenderConverter extends AbstractAttributeConverter {
private final Pattern maleText;
private final Pattern femaleText;
/**
* <p>Constructor for GenderConverter.</p>
*/
public GenderConverter() {
super(Gender.class);
this.maleText = Pattern.compile("(^m$)|(^male$)", Pattern.CASE_INSENSITIVE);
this.femaleText = Pattern.compile("(^f$)|(^female$)", Pattern.CASE_INSENSITIVE);
}
/**
* <p>Constructor for GenderConverter.</p>
*
* @param maleText a {@link String} object
* @param femaleText a {@link String} object
*/
public GenderConverter(final String maleText, final String femaleText) {
super(Gender.class);
this.maleText = Pattern.compile(maleText);
this.femaleText = Pattern.compile(femaleText);
}
/** {@inheritDoc} */
@Override
protected Gender internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
}
|
val s = attribute.toString().toLowerCase();
if (maleText.matcher(s).matches()) {
return Gender.MALE;
} else if (femaleText.matcher(s).matches()) {
return Gender.FEMALE;
} else {
return Gender.UNSPECIFIED;
}
| 300
| 92
| 392
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/IntegerConverter.java
|
IntegerConverter
|
internalConvert
|
class IntegerConverter extends AbstractAttributeConverter {
/**
* <p>Constructor for IntegerConverter.</p>
*/
public IntegerConverter() {
super(Integer.class);
}
/** {@inheritDoc} */
@Override
protected Integer internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
}
|
if (attribute instanceof String) {
return Integer.parseInt((String) attribute);
}
return null;
| 88
| 32
| 120
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/LocaleConverter.java
|
LocaleConverter
|
internalConvert
|
class LocaleConverter extends AbstractAttributeConverter {
/**
* <p>Constructor for LocaleConverter.</p>
*/
public LocaleConverter() {
super(Locale.class);
}
/** {@inheritDoc} */
@Override
protected Locale internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
}
|
if (attribute instanceof String str) {
val s = str.replaceAll("-", "_");
val parts = s.split("_");
val length = parts.length;
if (length == 2) {
return new Locale(parts[0], parts[1]);
} else if (length == 1) {
return new Locale(parts[0]);
}
}
return null;
| 93
| 104
| 197
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/LongConverter.java
|
LongConverter
|
internalConvert
|
class LongConverter extends AbstractAttributeConverter {
/**
* <p>Constructor for LongConverter.</p>
*/
public LongConverter() {
super(Long.class);
}
/** {@inheritDoc} */
@Override
protected Long internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
}
|
if (attribute instanceof Integer) {
return Long.valueOf((Integer) attribute);
} else if (attribute instanceof String) {
return Long.parseLong((String) attribute);
}
return null;
| 88
| 55
| 143
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/UrlConverter.java
|
UrlConverter
|
internalConvert
|
class UrlConverter extends AbstractAttributeConverter {
/**
* <p>Constructor for UrlConverter.</p>
*/
public UrlConverter() {
super(URI.class);
}
/** {@inheritDoc} */
@Override
protected URI internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
}
|
if (attribute instanceof String sAttribute) {
val s = sAttribute.replaceAll("\\/", "/");
return CommonHelper.asURI(s);
}
return null;
| 91
| 49
| 140
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/creator/LocalCachingProfileCreator.java
|
LocalCachingProfileCreator
|
create
|
class LocalCachingProfileCreator extends InitializableObject implements ProfileCreator {
private ProfileCreator delegate;
private int cacheSize;
private int timeout;
private TimeUnit timeUnit;
private Store<Credentials, UserProfile> store;
/**
* <p>Constructor for LocalCachingProfileCreator.</p>
*/
public LocalCachingProfileCreator() {}
/**
* <p>Constructor for LocalCachingProfileCreator.</p>
*
* @param delegate a {@link ProfileCreator} object
* @param store a {@link Store} object
*/
public LocalCachingProfileCreator(final ProfileCreator delegate, final Store<Credentials, UserProfile> store) {
this.delegate = delegate;
this.store = store;
}
/**
* <p>Constructor for LocalCachingProfileCreator.</p>
*
* @param delegate a {@link ProfileCreator} object
* @param cacheSize a int
* @param timeout a int
* @param timeUnit a {@link TimeUnit} object
*/
public LocalCachingProfileCreator(final ProfileCreator delegate, final int cacheSize,
final int timeout, final TimeUnit timeUnit) {
this.delegate = delegate;
this.cacheSize = cacheSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
}
/** {@inheritDoc} */
@Override
public Optional<UserProfile> create(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
if (this.store == null) {
this.store = new GuavaStore<>(cacheSize, timeout, timeUnit);
}
if (delegate instanceof InitializableObject initializableObject) {
initializableObject.init(forceReinit);
}
}
/**
* <p>removeFromCache.</p>
*
* @param credentials a {@link Credentials} object
*/
public void removeFromCache(final Credentials credentials) {
this.store.remove(credentials);
}
/**
* <p>isCached.</p>
*
* @param credentials a {@link Credentials} object
* @return a boolean
*/
public boolean isCached(final Credentials credentials) {
return this.store.get(credentials).isPresent();
}
}
|
init();
val optProfile = this.store.get(credentials);
if (optProfile.isEmpty()) {
LOGGER.debug("No cached credentials found. Delegating profile creation to {}...", delegate);
val profile = delegate.create(ctx, credentials);
if (profile.isPresent()) {
LOGGER.debug("Caching credential. Using profile {}...", profile.get());
store.set(credentials, profile.get());
}
return profile;
} else {
LOGGER.debug("Found cached credential. Using cached profile {}...", optProfile.get());
return optProfile;
}
| 641
| 158
| 799
|
<methods>public non-sealed void <init>() ,public int getNbAttempts() ,public void init() ,public void init(boolean) ,public final boolean isInitialized() ,public void reinit() <variables>private java.util.concurrent.atomic.AtomicBoolean initialized,private volatile java.lang.Long lastAttempt,private int maxAttempts,private long minTimeIntervalBetweenAttemptsInMilliseconds,private java.util.concurrent.atomic.AtomicInteger nbAttempts
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/definition/CommonProfileDefinition.java
|
CommonProfileDefinition
|
configurePrimaryAttributes
|
class CommonProfileDefinition extends ProfileDefinition {
/** Constant <code>EMAIL="email"</code> */
public static final String EMAIL = "email";
/** Constant <code>FIRST_NAME="first_name"</code> */
public static final String FIRST_NAME = "first_name";
/** Constant <code>FAMILY_NAME="family_name"</code> */
public static final String FAMILY_NAME = "family_name";
/** Constant <code>DISPLAY_NAME="display_name"</code> */
public static final String DISPLAY_NAME = "display_name";
/** Constant <code>GENDER="gender"</code> */
public static final String GENDER = "gender";
/** Constant <code>LOCALE="locale"</code> */
public static final String LOCALE = "locale";
/** Constant <code>PICTURE_URL="picture_url"</code> */
public static final String PICTURE_URL = "picture_url";
/** Constant <code>PROFILE_URL="profile_url"</code> */
public static final String PROFILE_URL = "profile_url";
/** Constant <code>LOCATION="location"</code> */
public static final String LOCATION = "location";
/**
* <p>Constructor for CommonProfileDefinition.</p>
*/
public CommonProfileDefinition() {
configurePrimaryAttributes();
}
/**
* <p>configurePrimaryAttributes.</p>
*/
protected void configurePrimaryAttributes() {<FILL_FUNCTION_BODY>}
/**
* <p>Constructor for CommonProfileDefinition.</p>
*
* @param profileFactory a {@link ProfileFactory} object
*/
public CommonProfileDefinition(final ProfileFactory profileFactory) {
this();
setProfileFactory(profileFactory);
}
}
|
primary(EMAIL, Converters.STRING);
primary(FIRST_NAME, Converters.STRING);
primary(FAMILY_NAME, Converters.STRING);
primary(DISPLAY_NAME, Converters.STRING);
primary(GENDER, new ChainingConverter(List.of(Converters.GENDER, Converters.STRING)));
primary(LOCALE, new ChainingConverter(List.of(Converters.LOCALE, Converters.STRING)));
primary(PICTURE_URL, new ChainingConverter(List.of(Converters.URL, Converters.STRING)));
primary(PROFILE_URL, new ChainingConverter(List.of(Converters.URL, Converters.STRING)));
primary(LOCATION, Converters.STRING);
primary(Pac4jConstants.USERNAME, Converters.STRING);
| 492
| 220
| 712
|
<methods>public non-sealed void <init>() ,public void convertAndAdd(org.pac4j.core.profile.UserProfile, org.pac4j.core.profile.AttributeLocation, java.lang.String, java.lang.Object) ,public void convertAndAdd(org.pac4j.core.profile.UserProfile, Map<java.lang.String,java.lang.Object>, Map<java.lang.String,java.lang.Object>) ,public transient org.pac4j.core.profile.UserProfile newProfile(java.lang.Object[]) <variables>private final Map<java.lang.String,org.pac4j.core.profile.converter.AttributeConverter> converters,protected final org.slf4j.Logger logger,private final List<java.lang.String> primaryAttributes,private org.pac4j.core.profile.factory.ProfileFactory profileFactory,private java.lang.String profileId,private boolean restoreProfileFromTypedId,private final List<java.lang.String> secondaryAttributes
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/definition/ProfileDefinition.java
|
ProfileDefinition
|
getParameter
|
class ProfileDefinition {
protected final Logger logger = LoggerFactory.getLogger(getClass());
@Setter
private String profileId = null;
private final List<String> primaryAttributes = new ArrayList<>();
private final List<String> secondaryAttributes = new ArrayList<>();
private final Map<String, AttributeConverter> converters = new HashMap<>();
@Setter
private ProfileFactory profileFactory = parameters -> new CommonProfile();
@Setter
private boolean restoreProfileFromTypedId = false;
/**
* Return the new built or restored profile.
*
* @param parameters some input parameters (the first optional one is the typed id)
* @return the new built or restored profile
*/
public UserProfile newProfile(final Object... parameters) {
if (restoreProfileFromTypedId) {
val typedId = getParameter(parameters, 0);
if (typedId instanceof String sTypedId) {
logger.debug("Building user profile based on typedId: {}", typedId);
if (sTypedId.contains(Pac4jConstants.TYPED_ID_SEPARATOR)) {
val profileClass = substringBefore(sTypedId, Pac4jConstants.TYPED_ID_SEPARATOR);
for (val profileClassPrefix : ProfileHelper.getProfileClassPrefixes()) {
if (profileClass.startsWith(profileClassPrefix)) {
try {
return ProfileHelper.buildUserProfileByClassCompleteName(profileClass);
} catch (final TechnicalException e) {
logger.error("Cannot build instance for class name: {}", profileClass, e);
}
}
}
}
}
}
return profileFactory.apply(parameters);
}
/**
* <p>getParameter.</p>
*
* @param parameters an array of {@link Object} objects
* @param num a int
* @return a {@link Object} object
*/
protected Object getParameter(final Object[] parameters, final int num) {<FILL_FUNCTION_BODY>}
/**
* Convert a profile or authentication attribute, if necessary, and add it to the profile.
*
* @param profile The profile.
* @param attributeLocation Location of the attribute inside the profile: classic profile attribute, authentication attribute, ...
* @param name The attribute name.
* @param value The attribute value.
*/
public void convertAndAdd(final UserProfile profile, final AttributeLocation attributeLocation, final String name,
final Object value) {
if (value != null) {
final Object convertedValue;
val converter = this.converters.get(name);
if (converter != null) {
convertedValue = converter.convert(value);
if (convertedValue != null) {
logger.debug("converted to => key: {} / value: {} / {}", name, convertedValue, convertedValue.getClass());
}
} else {
convertedValue = value;
logger.debug("no conversion => key: {} / value: {} / {}", name, convertedValue, convertedValue.getClass());
}
if (attributeLocation.equals(AUTHENTICATION_ATTRIBUTE)) {
profile.addAuthenticationAttribute(name, convertedValue);
} else {
profile.addAttribute(name, convertedValue);
}
}
}
/**
* Convert the profile and authentication attributes, if necessary, and add them to the profile.
*
* @param profile The profile.
* @param profileAttributes The profile attributes. May be {@code null}.
* @param authenticationAttributes The authentication attributes. May be {@code null}.
*/
public void convertAndAdd(final UserProfile profile,
final Map<String, Object> profileAttributes,
final Map<String, Object> authenticationAttributes) {
if (profileAttributes != null) {
profileAttributes.entrySet()
.forEach(entry -> convertAndAdd(profile, PROFILE_ATTRIBUTE, entry.getKey(), entry.getValue()));
}
if (authenticationAttributes != null) {
authenticationAttributes.entrySet()
.forEach(entry -> convertAndAdd(profile, AUTHENTICATION_ATTRIBUTE, entry.getKey(), entry.getValue()));
}
}
/**
* Add an attribute as a primary one and its converter.
*
* @param name name of the attribute
* @param converter converter
*/
protected void primary(final String name, final AttributeConverter converter) {
primaryAttributes.add(name);
converters.put(name, converter);
}
/**
* Add an attribute as a secondary one and its converter.
*
* @param name name of the attribute
* @param converter converter
*/
protected void secondary(final String name, final AttributeConverter converter) {
secondaryAttributes.add(name);
converters.put(name, converter);
}
}
|
if (parameters != null && parameters.length >= num) {
return parameters[num];
} else {
return null;
}
| 1,221
| 39
| 1,260
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/definition/ProfileDefinitionAware.java
|
ProfileDefinitionAware
|
setProfileDefinitionIfUndefined
|
class ProfileDefinitionAware extends InitializableObject {
private ProfileDefinition profileDefinition;
/**
* <p>Getter for the field <code>profileDefinition</code>.</p>
*
* @return a {@link ProfileDefinition} object
*/
public ProfileDefinition getProfileDefinition() {
return profileDefinition;
}
/**
* <p>Setter for the field <code>profileDefinition</code>.</p>
*
* @param profileDefinition a {@link ProfileDefinition} object
*/
public void setProfileDefinition(final ProfileDefinition profileDefinition) {
CommonHelper.assertNotNull("profileDefinition", profileDefinition);
this.profileDefinition = profileDefinition;
}
/**
* <p>setProfileDefinitionIfUndefined.</p>
*
* @param profileDefinition a {@link ProfileDefinition} object
*/
protected void setProfileDefinitionIfUndefined(final ProfileDefinition profileDefinition) {<FILL_FUNCTION_BODY>}
}
|
CommonHelper.assertNotNull("profileDefinition", profileDefinition);
if (this.profileDefinition == null) {
this.profileDefinition = profileDefinition;
}
| 252
| 42
| 294
|
<methods>public non-sealed void <init>() ,public int getNbAttempts() ,public void init() ,public void init(boolean) ,public final boolean isInitialized() ,public void reinit() <variables>private java.util.concurrent.atomic.AtomicBoolean initialized,private volatile java.lang.Long lastAttempt,private int maxAttempts,private long minTimeIntervalBetweenAttemptsInMilliseconds,private java.util.concurrent.atomic.AtomicInteger nbAttempts
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/service/InMemoryProfileService.java
|
InMemoryProfileService
|
update
|
class InMemoryProfileService<U extends CommonProfile> extends AbstractProfileService<U> {
public Map<String,Map<String,Object>> profiles;
public ProfileFactory profileFactory;
/**
* <p>Constructor for InMemoryProfileService.</p>
*
* @param profileFactory a {@link ProfileFactory} object
*/
public InMemoryProfileService(final ProfileFactory profileFactory) {
this(new HashMap<>(), profileFactory);
}
/**
* <p>Constructor for InMemoryProfileService.</p>
*
* @param profiles a {@link Map} object
* @param profileFactory a {@link ProfileFactory} object
*/
public InMemoryProfileService(final Map<String,Map<String,Object>> profiles, final ProfileFactory profileFactory) {
this.profiles = profiles;
this.profileFactory = profileFactory;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
assertNotNull("passwordEncoder", getPasswordEncoder());
setProfileDefinitionIfUndefined(new CommonProfileDefinition(profileFactory));
setSerializer(new JsonSerializer(CommonProfile.class));
super.internalInit(forceReinit);
}
/** {@inheritDoc} */
@Override
protected void insert(final Map<String, Object> attributes) {
val id = (String) attributes.get(getIdAttribute());
logger.debug("Inserting doc id: {} with attributes: {}", id, attributes);
profiles.put(id, attributes);
}
/** {@inheritDoc} */
@Override
protected void update(final Map<String, Object> attributes) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected void deleteById(final String id) {
logger.debug("Delete id: {}", id);
profiles.remove(id);
}
private Map<String, Object> populateAttributes(final Map<String, Object> rowAttributes, final Collection<String> names) {
return rowAttributes.entrySet().stream()
.filter(p -> names == null || names.contains(p.getKey()))
// not using Collators.toMap because of
// https://stackoverflow.com/questions/24630963/java-8-nullpointerexception-in-collectors-tomap
.collect(HashMap::new, (m,v)->m.put(v.getKey(), v.getValue()), HashMap::putAll);
}
/** {@inheritDoc} */
@Override
protected List<Map<String, Object>> read(final List<String> names, final String key, final String value) {
logger.debug("Reading key / value: {} / {}", key, value);
final List<Map<String, Object>> listAttributes;
if (key.equals(getIdAttribute())) {
listAttributes = new ArrayList<>();
val profile = profiles.get(value);
if (profile != null) {
listAttributes.add(populateAttributes(profile, names));
}
} else {
listAttributes = profiles.values().stream()
.filter(stringObjectMap -> stringObjectMap.get(key) != null && stringObjectMap.get(key).equals(value))
.map(stringObjectMap -> populateAttributes(stringObjectMap, names))
.collect(Collectors.toList());
}
logger.debug("Found: {}", listAttributes);
return listAttributes;
}
}
|
val id = (String) attributes.get(getIdAttribute());
logger.debug("Updating id: {} with attributes: {}", id, attributes);
val profile = profiles.get(id);
if (profile != null) {
profile.putAll(attributes);
} else {
profiles.put(id, attributes);
}
| 872
| 87
| 959
|
<methods>public non-sealed void <init>() ,public void create(U, java.lang.String) ,public U findById(java.lang.String) ,public U findByLinkedId(java.lang.String) ,public void remove(U) ,public void removeById(java.lang.String) ,public void update(U, java.lang.String) ,public Optional<org.pac4j.core.credentials.Credentials> validate(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ID,public static final java.lang.String LINKEDID,public static final java.lang.String SERIALIZED_PROFILE,protected java.lang.String[] attributeNames,private java.lang.String attributes,private java.lang.String idAttribute,protected final org.slf4j.Logger logger,private java.lang.String passwordAttribute,private org.pac4j.core.credentials.password.PasswordEncoder passwordEncoder,private org.pac4j.core.util.serializer.Serializer serializer,private java.lang.String usernameAttribute
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/resource/SpringResourceHelper.java
|
SpringResourceHelper
|
getResourceInputStream
|
class SpringResourceHelper {
/** Constant <code>RESOURCE_PREFIX="resource:"</code> */
public static final String RESOURCE_PREFIX = "resource:";
/** Constant <code>CLASSPATH_PREFIX="classpath:"</code> */
public static final String CLASSPATH_PREFIX = "classpath:";
/** Constant <code>FILE_PREFIX="file:"</code> */
public static final String FILE_PREFIX = "file:";
/**
* <p>getResourceInputStream.</p>
*
* @param resource a {@link Resource} object
* @param proxy a {@link Proxy} object
* @param sslSocketFactory a {@link SSLSocketFactory} object
* @param hostnameVerifier a {@link HostnameVerifier} object
* @param connectTimeout a int
* @param readTimeout a int
* @return a {@link InputStream} object
* @throws IOException if any.
*/
public static InputStream getResourceInputStream(final Resource resource, final Proxy proxy, final SSLSocketFactory sslSocketFactory,
final HostnameVerifier hostnameVerifier, final int connectTimeout,
final int readTimeout) throws IOException {<FILL_FUNCTION_BODY>}
/**
* <p>buildResourceFromPath.</p>
*
* @param path a {@link String} object
* @return a {@link Resource} object
*/
public static Resource buildResourceFromPath(final String path) {
CommonHelper.assertNotBlank("path", path);
try {
if (path.startsWith(RESOURCE_PREFIX)) {
return new ClassPathResource(path.substring(RESOURCE_PREFIX.length()));
}
if (path.startsWith(CLASSPATH_PREFIX)) {
return new ClassPathResource(path.substring(CLASSPATH_PREFIX.length()));
}
if (path.startsWith(HttpConstants.SCHEME_HTTP) || path.startsWith(HttpConstants.SCHEME_HTTPS)) {
return new UrlResource(new URL(path));
}
if (path.startsWith(FILE_PREFIX)) {
return new FileSystemResource(path.substring(FILE_PREFIX.length()));
}
return new FileSystemResource(path);
} catch (final Exception e) {
throw new TechnicalException(e);
}
}
/**
* <p>newUrlResource.</p>
*
* @param url a {@link String} object
* @return a {@link UrlResource} object
*/
public static UrlResource newUrlResource(final String url) {
try {
return new UrlResource(url);
} catch (final MalformedURLException e) {
throw new TechnicalException(e);
}
}
}
|
if (resource instanceof UrlResource) {
URLConnection con;
if (proxy != null) {
con = resource.getURL().openConnection(proxy);
} else {
con = resource.getURL().openConnection();
}
if (con instanceof HttpsURLConnection connection) {
if (sslSocketFactory != null) {
connection.setSSLSocketFactory(sslSocketFactory);
}
if (hostnameVerifier != null) {
connection.setHostnameVerifier(hostnameVerifier);
}
}
try {
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(readTimeout);
return con.getInputStream();
} catch (final Exception e) {
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
}
throw new TechnicalException("Error getting URL resource", e);
}
}
return resource.getInputStream();
| 717
| 241
| 958
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/resource/SpringResourceLoader.java
|
SpringResourceLoader
|
hasChanged
|
class SpringResourceLoader<M> extends InitializableObject {
private static final long NO_LAST_MODIFIED = -1;
private final Lock lock = new ReentrantLock();
private final AtomicBoolean byteArrayHasChanged = new AtomicBoolean(true);
@Getter
private long lastModified = NO_LAST_MODIFIED;
protected final Resource resource;
protected M loaded;
/** {@inheritDoc} */
protected final void internalInit(final boolean forceReinit) {
internalLoad();
hasChanged();
}
/**
* <p>load.</p>
*
* @return a M object
*/
public final M load() {
if (lock.tryLock()) {
try {
if (hasChanged()) {
internalLoad();
}
} finally {
lock.unlock();
}
}
return loaded;
}
/**
* <p>hasChanged.</p>
*
* @return a boolean
*/
public boolean hasChanged() {<FILL_FUNCTION_BODY>}
/**
* <p>internalLoad.</p>
*/
protected abstract void internalLoad();
}
|
if (resource != null) {
if (resource instanceof ByteArrayResource) {
return byteArrayHasChanged.getAndSet(false);
}
long newLastModified;
try {
newLastModified = resource.lastModified();
} catch (final Exception e) {
newLastModified = NO_LAST_MODIFIED;
}
val hasChanged = lastModified != newLastModified;
LOGGER.debug("lastModified: {} / newLastModified: {} -> hasChanged: {}", lastModified, newLastModified, hasChanged);
lastModified = newLastModified;
return hasChanged;
}
return false;
| 311
| 175
| 486
|
<methods>public non-sealed void <init>() ,public int getNbAttempts() ,public void init() ,public void init(boolean) ,public final boolean isInitialized() ,public void reinit() <variables>private java.util.concurrent.atomic.AtomicBoolean initialized,private volatile java.lang.Long lastAttempt,private int maxAttempts,private long minTimeIntervalBetweenAttemptsInMilliseconds,private java.util.concurrent.atomic.AtomicInteger nbAttempts
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/store/AbstractStore.java
|
AbstractStore
|
set
|
class AbstractStore<K, O> extends InitializableObject implements Store<K, O> {
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
}
/** {@inheritDoc} */
@Override
public Optional<O> get(final K key) {
CommonHelper.assertNotNull("key", key);
init();
return internalGet(key);
}
/** {@inheritDoc} */
@Override
public void set(final K key, final O value) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void remove(final K key) {
CommonHelper.assertNotNull("key", key);
init();
internalRemove(key);
}
/**
* <p>internalGet.</p>
*
* @param key a K object
* @return a {@link Optional} object
*/
protected abstract Optional<O> internalGet(final K key);
/**
* <p>internalSet.</p>
*
* @param key a K object
* @param value a O object
*/
protected abstract void internalSet(final K key, final O value);
/**
* <p>internalRemove.</p>
*
* @param key a K object
*/
protected abstract void internalRemove(final K key);
}
|
CommonHelper.assertNotNull("key", key);
init();
if (value == null) {
internalRemove(key);
} else {
internalSet(key, value);
}
| 358
| 53
| 411
|
<methods>public non-sealed void <init>() ,public int getNbAttempts() ,public void init() ,public void init(boolean) ,public final boolean isInitialized() ,public void reinit() <variables>private java.util.concurrent.atomic.AtomicBoolean initialized,private volatile java.lang.Long lastAttempt,private int maxAttempts,private long minTimeIntervalBetweenAttemptsInMilliseconds,private java.util.concurrent.atomic.AtomicInteger nbAttempts
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/store/GuavaStore.java
|
GuavaStore
|
internalInit
|
class GuavaStore<K, O> extends AbstractStore<K, O> {
@Getter
private Cache<K, O> cache;
@Getter
@Setter
private int size = 0;
@Getter
@Setter
private int timeout = -1;
@Getter
@Setter
private TimeUnit timeUnit;
/**
* <p>Constructor for GuavaStore.</p>
*/
public GuavaStore() {}
/**
* <p>Constructor for GuavaStore.</p>
*
* @param size a int
* @param timeout a int
* @param timeUnit a {@link TimeUnit} object
*/
public GuavaStore(final int size, final int timeout, final TimeUnit timeUnit) {
this.size = size;
this.timeout = timeout;
this.timeUnit = timeUnit;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected Optional<O> internalGet(final K key) {
return Optional.ofNullable(cache.getIfPresent(key));
}
/** {@inheritDoc} */
@Override
protected void internalSet(final K key, final O value) {
cache.put(key, value);
}
/** {@inheritDoc} */
@Override
protected void internalRemove(final K key) {
cache.invalidate(key);
}
}
|
CommonHelper.assertTrue(this.size > 0, "size mut be greater than zero");
CommonHelper.assertTrue(this.timeout >= 0, "timeout must be greater than zero");
CommonHelper.assertNotNull("timeUnit", this.timeUnit);
this.cache = CacheBuilder.newBuilder().maximumSize(this.size)
.expireAfterWrite(this.timeout, this.timeUnit).build();
| 399
| 103
| 502
|
<methods>public non-sealed void <init>() ,public Optional<O> get(K) ,public void remove(K) ,public void set(K, O) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/util/HttpActionHelper.java
|
HttpActionHelper
|
buildUnauthenticatedAction
|
class HttpActionHelper {
private static boolean useModernHttpCodes = true;
private static boolean alwaysUse401ForUnauthenticated = true;
/**
* Build the action for unauthenticated users.
*
* @param context the web context
* @return the appropriate HTTP action
*/
public static HttpAction buildUnauthenticatedAction(final WebContext context) {<FILL_FUNCTION_BODY>}
/**
* Build the appropriate redirection action for a location.
*
* @param context the web context
* @param location the location
* @return the appropriate redirection action
*/
public static RedirectionAction buildRedirectUrlAction(final WebContext context, final String location) {
if (WebContextHelper.isPost(context) && useModernHttpCodes) {
return new SeeOtherAction(location);
} else {
return new FoundAction(location);
}
}
/**
* Build the appropriate redirection action for a content which is a form post.
*
* @param context the web context
* @param content the content
* @return the appropriate redirection action
*/
public static RedirectionAction buildFormPostContentAction(final WebContext context, final String content) {
// is this an automatic form post generated by OpenSAML?
if (content != null && content.contains("onload=\"document.forms[0].submit()\"")) {
val url = StringEscapeUtils.unescapeHtml4(substringBetween(content, "<form action=\"", "\" method=\"post\">"));
if (isNotBlank(url)) {
val data = new HashMap<String, String>();
val samlRequest = StringEscapeUtils.unescapeHtml4(substringBetween(content, "name=\"SAMLRequest\" value=\"", "\"/>"));
if (isNotBlank(samlRequest)) {
data.put("SAMLRequest", samlRequest);
}
val relayState = StringEscapeUtils.unescapeHtml4(substringBetween(content, "name=\"RelayState\" value=\"", "\"/>"));
if (isNotBlank(relayState)) {
data.put("RelayState", relayState);
}
val samlResponse = StringEscapeUtils.unescapeHtml4(substringBetween(content, "name=\"SAMLResponse\" value=\"", "\"/>"));
if (isNotBlank(samlResponse)) {
data.put("SAMLResponse", samlResponse);
}
return new AutomaticFormPostAction(url, data, content);
}
}
return new OkAction(content);
}
/**
* Build a form POST content from the web context.
*
* @param context the web context
* @return the form POST content
*/
public static String buildFormPostContent(final WebContext context) {
val requestedUrl = context.getFullRequestURL();
val parameters = context.getRequestParameters();
val buffer = new StringBuilder();
buffer.append("<html>\n");
buffer.append("<body>\n");
buffer.append("<form action=\"" + escapeHtml(requestedUrl) + "\" name=\"f\" method=\"post\">\n");
if (parameters != null) {
for (val entry : parameters.entrySet()) {
val values = entry.getValue();
if (values != null && values.length > 0) {
buffer.append("<input type='hidden' name=\"" + escapeHtml(entry.getKey()) + "\" value=\"" + values[0] + "\" />\n");
}
}
}
buffer.append("<input value='POST' type='submit' />\n");
buffer.append("</form>\n");
buffer.append("<script type='text/javascript'>document.forms['f'].submit();</script>\n");
buffer.append("</body>\n");
buffer.append("</html>\n");
return buffer.toString();
}
/**
* <p>escapeHtml.</p>
*
* @param s a {@link String} object
* @return a {@link String} object
*/
protected static String escapeHtml(final String s) {
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll("\"", """);
}
/**
* <p>isUseModernHttpCodes.</p>
*
* @return a boolean
*/
public static boolean isUseModernHttpCodes() {
return useModernHttpCodes;
}
/**
* <p>Setter for the field <code>useModernHttpCodes</code>.</p>
*
* @param useModernHttpCodes a boolean
*/
public static void setUseModernHttpCodes(final boolean useModernHttpCodes) {
HttpActionHelper.useModernHttpCodes = useModernHttpCodes;
}
/**
* <p>isAlwaysUse401ForUnauthenticated.</p>
*
* @return a boolean
*/
public static boolean isAlwaysUse401ForUnauthenticated() {
return alwaysUse401ForUnauthenticated;
}
/**
* <p>Setter for the field <code>alwaysUse401ForUnauthenticated</code>.</p>
*
* @param alwaysUse401ForUnauthenticated a boolean
*/
public static void setAlwaysUse401ForUnauthenticated(final boolean alwaysUse401ForUnauthenticated) {
HttpActionHelper.alwaysUse401ForUnauthenticated = alwaysUse401ForUnauthenticated;
}
}
|
val hasHeader = context.getResponseHeader(HttpConstants.AUTHENTICATE_HEADER).isPresent();
if (alwaysUse401ForUnauthenticated) {
// add the WWW-Authenticate header to be compliant with the HTTP spec if it does not already exist
if (!hasHeader) {
context.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, HttpConstants.BEARER_HEADER_PREFIX + "realm=\"pac4j\"");
}
return new UnauthorizedAction();
} else {
if (hasHeader) {
return new UnauthorizedAction();
} else {
return new ForbiddenAction();
}
}
| 1,488
| 178
| 1,666
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/util/HttpUtils.java
|
HttpUtils
|
buildHttpErrorMessage
|
class HttpUtils {
private static int connectTimeout = HttpConstants.DEFAULT_CONNECT_TIMEOUT;
private static int readTimeout = HttpConstants.DEFAULT_READ_TIMEOUT;
private HttpUtils() {
}
/**
* Build error message from connection in case of failure
*
* @param connection HttpURLConnection
* @return String by combining response code, message and error stream
* @throws IOException an IO exception
*/
public static String buildHttpErrorMessage(final HttpURLConnection connection) throws IOException {<FILL_FUNCTION_BODY>}
/**
* <p>openPostConnection.</p>
*
* @param url a {@link URL} object
* @return a {@link HttpURLConnection} object
* @throws IOException if any.
*/
public static HttpURLConnection openPostConnection(final URL url) throws IOException {
return openConnection(url, HttpConstants.HTTP_METHOD.POST.name(), null);
}
/**
* <p>openPostConnection.</p>
*
* @param url a {@link URL} object
* @param headers a {@link Map} object
* @return a {@link HttpURLConnection} object
* @throws IOException if any.
*/
public static HttpURLConnection openPostConnection(final URL url, final Map<String, String> headers) throws IOException {
return openConnection(url, HttpConstants.HTTP_METHOD.POST.name(), headers);
}
/**
* <p>openDeleteConnection.</p>
*
* @param url a {@link URL} object
* @return a {@link HttpURLConnection} object
* @throws IOException if any.
*/
public static HttpURLConnection openDeleteConnection(final URL url) throws IOException {
return openConnection(url, HttpConstants.HTTP_METHOD.DELETE.name(), null);
}
/**
* <p>openConnection.</p>
*
* @param url a {@link URL} object
* @param requestMethod a {@link String} object
* @param headers a {@link Map} object
* @return a {@link HttpURLConnection} object
* @throws IOException if any.
*/
protected static HttpURLConnection openConnection(final URL url, final String requestMethod, final Map<String, String> headers)
throws IOException {
val connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod(requestMethod);
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
if (headers != null) {
for (val entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return connection;
}
/**
* <p>readBody.</p>
*
* @param connection a {@link HttpURLConnection} object
* @return a {@link String} object
* @throws IOException if any.
*/
public static String readBody(final HttpURLConnection connection) throws IOException {
try (var isr = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);
var br = new BufferedReader(isr)) {
val sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
return sb.toString();
}
}
/**
* <p>encodeQueryParam.</p>
*
* @param paramName a {@link String} object
* @param paramValue a {@link String} object
* @return a {@link String} object
*/
public static String encodeQueryParam(final String paramName, final String paramValue) {
return CommonHelper.urlEncode(paramName) + "=" + CommonHelper.urlEncode(paramValue);
}
/**
* <p>closeConnection.</p>
*
* @param connection a {@link HttpURLConnection} object
*/
public static void closeConnection(final HttpURLConnection connection) {
if (connection != null) {
connection.disconnect();
}
}
/**
* <p>Getter for the field <code>connectTimeout</code>.</p>
*
* @return a int
*/
public static int getConnectTimeout() {
return connectTimeout;
}
/**
* <p>Setter for the field <code>connectTimeout</code>.</p>
*
* @param connectTimeout a int
*/
public static void setConnectTimeout(final int connectTimeout) {
HttpUtils.connectTimeout = connectTimeout;
}
/**
* <p>Getter for the field <code>readTimeout</code>.</p>
*
* @return a int
*/
public static int getReadTimeout() {
return readTimeout;
}
/**
* <p>Setter for the field <code>readTimeout</code>.</p>
*
* @param readTimeout a int
*/
public static void setReadTimeout(final int readTimeout) {
HttpUtils.readTimeout = readTimeout;
}
}
|
val messageBuilder = new StringBuilder("(").append(connection.getResponseCode()).append(")");
if (connection.getResponseMessage() != null) {
messageBuilder.append(" ");
messageBuilder.append(connection.getResponseMessage());
}
try (var isr = new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8);
var br = new BufferedReader(isr)) {
String output;
messageBuilder.append("[");
while ((output = br.readLine()) != null) {
messageBuilder.append(output);
}
messageBuilder.append("]");
} finally {
connection.disconnect();
}
return messageBuilder.toString();
| 1,326
| 181
| 1,507
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/util/InitializableObject.java
|
InitializableObject
|
init
|
class InitializableObject {
private AtomicBoolean initialized = new AtomicBoolean(false);
@Setter
private int maxAttempts = 3;
private AtomicInteger nbAttempts = new AtomicInteger(0);
private volatile Long lastAttempt;
@Setter
private long minTimeIntervalBetweenAttemptsInMilliseconds = 5000;
/**
* Initialize the object.
*/
public void init() {
init(false);
}
/**
* Re-initialize the object.
*/
public void reinit() {
init(true);
}
/**
* (Re)-initialize the object.
*
* @param forceReinit whether the object should be re-initialized
*/
public void init(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>isInitialized.</p>
*
* @return a boolean
*/
public final boolean isInitialized() {
return initialized.get();
}
/**
* <p>shouldInitialize.</p>
*
* @param forceReinit a boolean
* @return a boolean
*/
protected boolean shouldInitialize(final boolean forceReinit) {
if (forceReinit) {
return true;
}
final boolean notInitialized = !initialized.get();
final boolean notTooManyAttempts = maxAttempts == -1 || nbAttempts.get() < maxAttempts;
final boolean enoughTimeSinceLastAttempt = lastAttempt == null
|| (System.currentTimeMillis() - lastAttempt) > minTimeIntervalBetweenAttemptsInMilliseconds;
return notInitialized && notTooManyAttempts && enoughTimeSinceLastAttempt;
}
/**
* Internal initialization of the object.
*
* @param forceReinit a boolean
*/
protected abstract void internalInit(final boolean forceReinit);
/**
* <p>beforeInternalInit.</p>
*
* @param forceReinit a boolean
*/
protected void beforeInternalInit(final boolean forceReinit) {}
/**
* <p>afterInternalInit.</p>
*
* @param forceReinit a boolean
*/
protected void afterInternalInit(final boolean forceReinit) {}
/**
* <p>Getter for the field <code>nbAttempts</code>.</p>
*
* @return a int
*/
public int getNbAttempts() {
return nbAttempts.get();
}
}
|
if (shouldInitialize(forceReinit)) {
synchronized (this) {
if (shouldInitialize(forceReinit)) {
LOGGER.debug("Initializing: {} (nb: {}, last: {})", this.getClass().getSimpleName(), nbAttempts, lastAttempt);
nbAttempts.incrementAndGet();
lastAttempt = System.currentTimeMillis();
beforeInternalInit(forceReinit);
internalInit(forceReinit);
afterInternalInit(forceReinit);
initialized.set(true);
}
}
}
| 683
| 148
| 831
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/util/security/SecurityEndpointBuilder.java
|
SecurityEndpointBuilder
|
buildConfig
|
class SecurityEndpointBuilder {
private static final AtomicInteger internalNumber = new AtomicInteger(1);
/**
* <p>buildConfig.</p>
*
* @param endpoint a {@link SecurityEndpoint} object
* @param parameters a {@link Object} object
*/
public static void buildConfig(final SecurityEndpoint endpoint, Object... parameters) {<FILL_FUNCTION_BODY>}
private static String addElement(final String elements, final String element) {
if (CommonHelper.isNotBlank(elements)) {
return elements + Pac4jConstants.ELEMENT_SEPARATOR + element;
} else {
return element;
}
}
}
|
Config config = null;
var configProvided = false;
for (val parameter : parameters) {
if (parameter instanceof Config) {
if (config != null) {
throw new TechnicalException("Only one Config can be used");
} else {
config = (Config) parameter;
configProvided = true;
}
}
}
if (config == null) {
config = new Config();
}
var clients = Pac4jConstants.EMPTY_STRING;
var authorizers = Pac4jConstants.EMPTY_STRING;
var matchers = Pac4jConstants.EMPTY_STRING;
val paramList = new ArrayList<>();
for (val parameter : parameters) {
if (parameter instanceof Collection<?> collection) {
collection.forEach(element -> paramList.add(element));
} else if (parameter instanceof Object[] objects) {
Arrays.stream(objects).forEach(element -> paramList.add(element));
} else {
paramList.add(parameter);
}
}
int numString = 0;
for (val parameter : paramList) {
if (parameter instanceof String s) {
if (!configProvided) {
throw new TechnicalException("Cannot accept strings without a provided Config");
}
if (numString == 0) {
clients = s;
} else if (numString == 1) {
authorizers = s;
} else if (numString == 2) {
matchers = s;
} else {
throw new TechnicalException("Too many strings used in constructor");
}
numString++;
} else if (parameter instanceof Client client) {
val clientName = client.getName();
val configClients = config.getClients();
if (configClients.findClient(clientName).isEmpty()) {
configClients.addClient(client);
}
clients = addElement(clients, clientName);
} else if (parameter instanceof Authorizer authorizer) {
var internalName = "$int_authorizer" + internalNumber.getAndIncrement();
config.addAuthorizer(internalName, authorizer);
authorizers = addElement(authorizers, internalName);
} else if (parameter instanceof Matcher matcher) {
var internalName = "$int_matcher" + internalNumber.getAndIncrement();
config.addMatcher(internalName, matcher);
matchers = addElement(matchers, internalName);
} else if (!(parameter instanceof Config)) {
throw new TechnicalException("Unsupported parameter type: " + parameter);
}
}
endpoint.setConfig(config);
if (CommonHelper.isNotBlank(clients)) {
endpoint.setClients(clients);
}
if (CommonHelper.isNotBlank(authorizers)) {
endpoint.setAuthorizers(authorizers);
}
if (CommonHelper.isNotBlank(matchers)) {
endpoint.setMatchers(matchers);
}
| 173
| 755
| 928
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/util/serializer/AbstractSerializer.java
|
AbstractSerializer
|
deserializeFromString
|
class AbstractSerializer implements Serializer {
/** {@inheritDoc} */
@Override
public final String serializeToString(final Object obj) {
if (obj == null) {
return null;
}
return internalSerializeToString(obj);
}
/**
* <p>internalSerializeToString.</p>
*
* @param obj a {@link Object} object
* @return a {@link String} object
*/
protected String internalSerializeToString(final Object obj) {
return Base64.getEncoder().encodeToString(internalSerializeToBytes(obj));
}
/** {@inheritDoc} */
@Override
public final byte[] serializeToBytes(final Object obj) {
if (obj == null) {
return null;
}
return internalSerializeToBytes(obj);
}
/**
* <p>internalSerializeToBytes.</p>
*
* @param obj a {@link Object} object
* @return an array of {@link byte} objects
*/
protected byte[] internalSerializeToBytes(final Object obj) {
return internalSerializeToString(obj).getBytes(StandardCharsets.UTF_8);
}
/** {@inheritDoc} */
@Override
public final Object deserializeFromString(final String encoded) {<FILL_FUNCTION_BODY>}
/**
* <p>internalDeserializeFromString.</p>
*
* @param encoded a {@link String} object
* @return a {@link Object} object
*/
protected Object internalDeserializeFromString(final String encoded) {
val enc = Base64.getDecoder().decode(encoded);
return internalDeserializeFromBytes(enc);
}
/** {@inheritDoc} */
@Override
public final Object deserializeFromBytes(final byte[] encoded) {
if (encoded == null) {
return null;
}
return internalDeserializeFromBytes(encoded);
}
/**
* <p>internalDeserializeFromBytes.</p>
*
* @param encoded an array of {@link byte} objects
* @return a {@link Object} object
*/
protected Object internalDeserializeFromBytes(final byte[] encoded) {
return internalDeserializeFromString(new String(encoded, StandardCharsets.UTF_8));
}
}
|
if (encoded == null) {
return null;
}
return internalDeserializeFromString(encoded);
| 608
| 35
| 643
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/util/serializer/JavaSerializer.java
|
RestrictedObjectInputStream
|
resolveClass
|
class RestrictedObjectInputStream extends ObjectInputStream {
private final Set<String> trustedPackages;
private final Map<String, Class<?>> trustedClasses; // className -> Class
private RestrictedObjectInputStream(final InputStream in, final Set<String> trustedPackages,
final Collection<Class<?>> trustedClasses) throws IOException {
super(in);
this.trustedPackages = trustedPackages;
this.trustedClasses = trustedClasses.stream().collect(Collectors.toMap(Class::getName, Function.identity()));
}
@Override
protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
@Override
protected Class<?> resolveProxyClass(String[] interfaces) throws ClassNotFoundException {
throw new ClassNotFoundException("Wont resolve proxy classes at all.");
}
}
|
val qualifiedClassName = desc.getName();
val clazz = trustedClasses.get(qualifiedClassName);
if (Objects.nonNull(clazz)) {
return clazz;
} else if (trustedPackages.stream().anyMatch(qualifiedClassName::startsWith)) {
return super.resolveClass(desc);
} else {
throw new ClassNotFoundException("Wont resolve untrusted class: " + qualifiedClassName);
}
| 222
| 115
| 337
|
<methods>public non-sealed void <init>() ,public final java.lang.Object deserializeFromBytes(byte[]) ,public final java.lang.Object deserializeFromString(java.lang.String) ,public final byte[] serializeToBytes(java.lang.Object) ,public final java.lang.String serializeToString(java.lang.Object) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/util/serializer/JsonSerializer.java
|
JsonSerializer
|
internalSerializeToString
|
class JsonSerializer extends AbstractSerializer {
@Setter
@Getter
private ObjectMapper objectMapper;
private Class<? extends Object> clazz;
public JsonSerializer() {
this(Object.class);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
}
/**
* <p>Constructor for JsonSerializer.</p>
*
* @param clazz a {@link Class} object
*/
public JsonSerializer(final Class<? extends Object> clazz) {
assertNotNull("clazz", clazz);
this.clazz = clazz;
objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
}
/** {@inheritDoc} */
@Override
protected String internalSerializeToString(final Object obj) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected Object internalDeserializeFromString(final String encoded) {
try {
return objectMapper.readValue(encoded, clazz);
} catch (final JsonProcessingException e) {
LOGGER.error("Cannot decode string", e);
return null;
}
}
}
|
try {
return objectMapper.writeValueAsString(obj);
} catch (final JsonProcessingException e) {
LOGGER.error("Cannot encode object", e);
return null;
}
| 351
| 54
| 405
|
<methods>public non-sealed void <init>() ,public final java.lang.Object deserializeFromBytes(byte[]) ,public final java.lang.Object deserializeFromString(java.lang.String) ,public final byte[] serializeToBytes(java.lang.Object) ,public final java.lang.String serializeToString(java.lang.Object) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-couch/src/main/java/org/pac4j/couch/profile/service/CouchProfileService.java
|
CouchProfileService
|
deleteById
|
class CouchProfileService extends AbstractProfileService<CouchProfile> {
private CouchDbConnector couchDbConnector;
private ObjectMapper objectMapper;
private static final TypeReference<HashMap<String,Object>> TYPE_REFERENCE = new TypeReference<>() {
};
/** Constant <code>COUCH_ID="_id"</code> */
public static final String COUCH_ID = "_id";
/**
* <p>Constructor for CouchProfileService.</p>
*
* @param couchDbConnector a {@link CouchDbConnector} object
* @param attributes a {@link String} object
* @param passwordEncoder a {@link PasswordEncoder} object
*/
public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes, final PasswordEncoder passwordEncoder) {
setIdAttribute(COUCH_ID);
objectMapper = new ObjectMapper();
this.couchDbConnector = couchDbConnector;
setAttributes(attributes);
setPasswordEncoder(passwordEncoder);
}
/**
* <p>Constructor for CouchProfileService.</p>
*/
public CouchProfileService() {
this(null, null, null);
}
/**
* <p>Constructor for CouchProfileService.</p>
*
* @param couchDbConnector a {@link CouchDbConnector} object
*/
public CouchProfileService(final CouchDbConnector couchDbConnector) {
this(couchDbConnector, null, null);
}
/**
* <p>Constructor for CouchProfileService.</p>
*
* @param couchDbConnector a {@link CouchDbConnector} object
* @param attributes a {@link String} object
*/
public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes) {
this(couchDbConnector, attributes, null);
}
/**
* <p>Constructor for CouchProfileService.</p>
*
* @param couchDbConnector a {@link CouchDbConnector} object
* @param passwordEncoder a {@link PasswordEncoder} object
*/
public CouchProfileService(final CouchDbConnector couchDbConnector, final PasswordEncoder passwordEncoder) {
this(couchDbConnector, null, passwordEncoder);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
assertNotNull("passwordEncoder", getPasswordEncoder());
assertNotNull("couchDbConnector", this.couchDbConnector);
setProfileDefinitionIfUndefined(new CommonProfileDefinition(x -> new CouchProfile()));
setSerializer(new JsonSerializer(CouchProfile.class));
super.internalInit(forceReinit);
}
/** {@inheritDoc} */
@Override
protected void insert(final Map<String, Object> attributes) {
logger.debug("Insert doc: {}", attributes);
couchDbConnector.create(attributes);
}
/** {@inheritDoc} */
@Override
protected void update(final Map<String, Object> attributes) {
val id = (String) attributes.get(COUCH_ID);
try {
val oldDocStream = couchDbConnector.getAsStream(id);
val res = objectMapper.readValue(oldDocStream, TYPE_REFERENCE);
res.putAll(attributes);
couchDbConnector.update(res);
logger.debug("Updating id: {} with attributes: {}", id, attributes);
} catch (DocumentNotFoundException e) {
logger.debug("Insert doc (not found by update(): {}", attributes);
couchDbConnector.create(attributes);
} catch (IOException e) {
logger.error("Unexpected IO CouchDB Exception", e);
}
}
/** {@inheritDoc} */
@Override
protected void deleteById(final String id) {<FILL_FUNCTION_BODY>}
private Map<String, Object> populateAttributes(final Map<String, Object> rowAttributes, final Collection<String> names) {
Map<String, Object> newAttributes = new HashMap<>();
for (val entry : rowAttributes.entrySet()) {
val name = entry.getKey();
if (names == null || names.contains(name)) {
newAttributes.put(name, entry.getValue());
}
}
return newAttributes;
}
/** {@inheritDoc} */
@Override
protected List<Map<String, Object>> read(final List<String> names, final String key, final String value) {
logger.debug("Reading key / value: {} / {}", key, value);
List<Map<String, Object>> listAttributes = new ArrayList<>();
if (key.equals(COUCH_ID)) {
try {
val oldDocStream = couchDbConnector.getAsStream(value);
val res = objectMapper.readValue(oldDocStream, TYPE_REFERENCE);
listAttributes.add(populateAttributes(res, names));
} catch (DocumentNotFoundException e) {
logger.debug("Document id {} not found", value);
} catch (IOException e) {
logger.error("Unexpected IO CouchDB Exception", e);
}
}
else {
// supposes a by_$key view in the design document, see documentation
val query = new ViewQuery()
.designDocId("_design/pac4j")
.viewName("by_"+key)
.key(value);
val result = couchDbConnector.queryView(query);
for (val row : result.getRows()) {
val stringValue = row.getValue();
Map<String, Object> res = null;
try {
res = objectMapper.readValue(stringValue, TYPE_REFERENCE);
listAttributes.add(populateAttributes(res, names));
} catch (IOException e) {
logger.error("Unexpected IO CouchDB Exception", e);
}
}
}
logger.debug("Found: {}", listAttributes);
return listAttributes;
}
}
|
logger.debug("Delete id: {}", id);
try {
val oldDocStream = couchDbConnector.getAsStream(id);
val oldDoc = objectMapper.readTree(oldDocStream);
val rev = oldDoc.get("_rev").asText();
couchDbConnector.delete(id, rev);
} catch (DocumentNotFoundException e) {
logger.debug("id {} is not in the database", id);
} catch (IOException e) {
logger.error("Unexpected IO CouchDB Exception", e);
}
| 1,554
| 139
| 1,693
|
<methods>public non-sealed void <init>() ,public void create(org.pac4j.couch.profile.CouchProfile, java.lang.String) ,public org.pac4j.couch.profile.CouchProfile findById(java.lang.String) ,public org.pac4j.couch.profile.CouchProfile findByLinkedId(java.lang.String) ,public void remove(org.pac4j.couch.profile.CouchProfile) ,public void removeById(java.lang.String) ,public void update(org.pac4j.couch.profile.CouchProfile, java.lang.String) ,public Optional<org.pac4j.core.credentials.Credentials> validate(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ID,public static final java.lang.String LINKEDID,public static final java.lang.String SERIALIZED_PROFILE,protected java.lang.String[] attributeNames,private java.lang.String attributes,private java.lang.String idAttribute,protected final org.slf4j.Logger logger,private java.lang.String passwordAttribute,private org.pac4j.core.credentials.password.PasswordEncoder passwordEncoder,private org.pac4j.core.util.serializer.Serializer serializer,private java.lang.String usernameAttribute
|
pac4j_pac4j
|
pac4j/pac4j-gae/src/main/java/org/pac4j/gae/client/GaeUserServiceClient.java
|
GaeUserServiceClient
|
internalInit
|
class GaeUserServiceClient extends IndirectClient {
private static final ProfileDefinition PROFILE_DEFINITION
= new CommonProfileDefinition(x -> new GaeUserServiceProfile());
protected UserService service;
protected String authDomain = null;
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* Set the authDomain for connect to google apps for domain with the UserService
*
* @param authDomain the authentication domain
*/
public void setAuthDomain(final String authDomain) {
this.authDomain = authDomain;
}
/**
* <p>Getter for the field <code>authDomain</code>.</p>
*
* @return a {@link String} object
*/
public String getAuthDomain() {
return authDomain;
}
}
|
service = UserServiceFactory.getUserService();
CommonHelper.assertNotNull("service", this.service);
setRedirectionActionBuilderIfUndefined(ctx -> {
val webContext = ctx.webContext();
val destinationUrl = computeFinalCallbackUrl(webContext);
val loginUrl = authDomain == null ? service.createLoginURL(destinationUrl)
: service.createLoginURL(destinationUrl, authDomain);
return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, loginUrl));
});
setCredentialsExtractorIfUndefined(ctx -> {
val credentials = new GaeUserCredentials();
credentials.setUser(service.getCurrentUser());
return Optional.of(credentials);
});
setAuthenticatorIfUndefined((ctx, credentials) -> {
val user = ((GaeUserCredentials) credentials).getUser();
if (user != null) {
UserProfile profile = (GaeUserServiceProfile) PROFILE_DEFINITION.newProfile();
profile.setId(user.getEmail());
PROFILE_DEFINITION.convertAndAdd(profile, PROFILE_ATTRIBUTE, CommonProfileDefinition.EMAIL, user.getEmail());
PROFILE_DEFINITION.convertAndAdd(profile, PROFILE_ATTRIBUTE, CommonProfileDefinition.DISPLAY_NAME, user.getNickname());
if (service.isUserAdmin()) {
profile.addRole(GaeUserServiceProfile.PAC4J_GAE_GLOBAL_ADMIN_ROLE);
}
credentials.setUserProfile(profile);
}
return Optional.of(credentials);
});
| 231
| 413
| 644
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/client/direct/DirectBasicAuthClient.java
|
DirectBasicAuthClient
|
addAuthenticateHeader
|
class DirectBasicAuthClient extends DirectClient {
private String realmName = Pac4jConstants.DEFAULT_REALM_NAME;
/**
* <p>Constructor for DirectBasicAuthClient.</p>
*/
public DirectBasicAuthClient() {
}
/**
* <p>Constructor for DirectBasicAuthClient.</p>
*
* @param usernamePasswordAuthenticator a {@link Authenticator} object
*/
public DirectBasicAuthClient(final Authenticator usernamePasswordAuthenticator) {
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
}
/**
* <p>Constructor for DirectBasicAuthClient.</p>
*
* @param usernamePasswordAuthenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public DirectBasicAuthClient(final Authenticator usernamePasswordAuthenticator,
final ProfileCreator profileCreator) {
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
assertNotBlank("realmName", this.realmName);
setCredentialsExtractorIfUndefined(new BasicAuthExtractor());
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> getCredentials(final CallContext ctx) {
addAuthenticateHeader(ctx.webContext());
return super.getCredentials(ctx);
}
/**
* <p>addAuthenticateHeader.</p>
*
* @param context a {@link WebContext} object
*/
protected void addAuthenticateHeader(final WebContext context) {<FILL_FUNCTION_BODY>}
}
|
// set the www-authenticate in case of error
context.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Basic realm=\"" + realmName + "\"");
| 470
| 50
| 520
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/client/direct/DirectBearerAuthClient.java
|
DirectBearerAuthClient
|
getCredentials
|
class DirectBearerAuthClient extends DirectClient {
private String realmName = Pac4jConstants.DEFAULT_REALM_NAME;
/**
* <p>Constructor for DirectBearerAuthClient.</p>
*/
public DirectBearerAuthClient() {
}
/**
* <p>Constructor for DirectBearerAuthClient.</p>
*
* @param tokenAuthenticator a {@link Authenticator} object
*/
public DirectBearerAuthClient(final Authenticator tokenAuthenticator) {
setAuthenticatorIfUndefined(tokenAuthenticator);
}
/**
* <p>Constructor for DirectBearerAuthClient.</p>
*
* @param profileCreator a {@link ProfileCreator} object
*/
public DirectBearerAuthClient(final ProfileCreator profileCreator) {
setAuthenticatorIfUndefined(Authenticator.ALWAYS_VALIDATE);
setProfileCreatorIfUndefined(profileCreator);
}
/**
* <p>Constructor for DirectBearerAuthClient.</p>
*
* @param tokenAuthenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public DirectBearerAuthClient(final Authenticator tokenAuthenticator,
final ProfileCreator profileCreator) {
setAuthenticatorIfUndefined(tokenAuthenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
assertNotBlank("realmName", this.realmName);
setCredentialsExtractorIfUndefined(new BearerAuthExtractor());
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> getCredentials(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
// set the www-authenticate in case of error
ctx.webContext().setResponseHeader(HttpConstants.AUTHENTICATE_HEADER,
HttpConstants.BEARER_HEADER_PREFIX + "realm=\"" + realmName + "\"");
return super.getCredentials(ctx);
| 492
| 80
| 572
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/client/direct/DirectDigestAuthClient.java
|
DirectDigestAuthClient
|
calculateNonce
|
class DirectDigestAuthClient extends DirectClient {
private String realm = "pac4jRealm";
/**
* <p>Constructor for DirectDigestAuthClient.</p>
*/
public DirectDigestAuthClient() {
}
/**
* <p>Constructor for DirectDigestAuthClient.</p>
*
* @param digestAuthenticator a {@link Authenticator} object
*/
public DirectDigestAuthClient(final Authenticator digestAuthenticator) {
setAuthenticatorIfUndefined(digestAuthenticator);
}
/**
* <p>Constructor for DirectDigestAuthClient.</p>
*
* @param digestAuthenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public DirectDigestAuthClient(final Authenticator digestAuthenticator,
final ProfileCreator profileCreator) {
setAuthenticatorIfUndefined(digestAuthenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
setCredentialsExtractorIfUndefined(new DigestAuthExtractor());
}
/**
* {@inheritDoc}
*
* Per RFC 2617
* If a server receives a request for an access-protected object, and an
* acceptable Authorization header is not sent, the server responds with
* a "401 Unauthorized" status code, and a WWW-Authenticate header
*/
@Override
public Optional<Credentials> getCredentials(final CallContext ctx) {
// set the www-authenticate in case of error
val nonce = calculateNonce();
ctx.webContext().setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Digest realm=\"" + realm + "\", qop=\"auth\", nonce=\""
+ nonce + "\"");
return super.getCredentials(ctx);
}
/**
* A server-specified data string which should be uniquely generated each time a 401 response is made (RFC 2617)
* Based on current time including nanoseconds
*/
private String calculateNonce() {<FILL_FUNCTION_BODY>}
}
|
val time = LocalDateTime.now();
val formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd:HH:mm:ss.SSS");
val fmtTime = formatter.format(time);
return CredentialUtil.encryptMD5(fmtTime + CommonHelper.randomString(10));
| 601
| 81
| 682
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/client/direct/HeaderClient.java
|
HeaderClient
|
internalInit
|
class HeaderClient extends DirectClient {
private String headerName = Pac4jConstants.EMPTY_STRING;
private String prefixHeader = Pac4jConstants.EMPTY_STRING;
/**
* <p>Constructor for HeaderClient.</p>
*/
public HeaderClient() {}
/**
* <p>Constructor for HeaderClient.</p>
*
* @param headerName a {@link String} object
* @param tokenAuthenticator a {@link Authenticator} object
*/
public HeaderClient(final String headerName, final Authenticator tokenAuthenticator) {
this.headerName = headerName;
setAuthenticatorIfUndefined(tokenAuthenticator);
}
/**
* <p>Constructor for HeaderClient.</p>
*
* @param headerName a {@link String} object
* @param prefixHeader a {@link String} object
* @param tokenAuthenticator a {@link Authenticator} object
*/
public HeaderClient(final String headerName, final String prefixHeader,
final Authenticator tokenAuthenticator) {
this.headerName = headerName;
this.prefixHeader = prefixHeader;
setAuthenticatorIfUndefined(tokenAuthenticator);
}
/**
* <p>Constructor for HeaderClient.</p>
*
* @param headerName a {@link String} object
* @param tokenAuthenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public HeaderClient(final String headerName, final Authenticator tokenAuthenticator,
final ProfileCreator profileCreator) {
this.headerName = headerName;
setAuthenticatorIfUndefined(tokenAuthenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/**
* <p>Constructor for HeaderClient.</p>
*
* @param headerName a {@link String} object
* @param profileCreator a {@link ProfileCreator} object
*/
public HeaderClient(final String headerName, final ProfileCreator profileCreator) {
this.headerName = headerName;
setAuthenticatorIfUndefined(Authenticator.ALWAYS_VALIDATE);
setProfileCreatorIfUndefined(profileCreator);
}
/**
* <p>Constructor for HeaderClient.</p>
*
* @param headerName a {@link String} object
* @param prefixHeader a {@link String} object
* @param tokenAuthenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public HeaderClient(final String headerName, final String prefixHeader,
final Authenticator tokenAuthenticator, final ProfileCreator profileCreator) {
this.headerName = headerName;
this.prefixHeader = prefixHeader;
setAuthenticatorIfUndefined(tokenAuthenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/**
* <p>Constructor for HeaderClient.</p>
*
* @param headerName a {@link String} object
* @param prefixHeader a {@link String} object
* @param profileCreator a {@link ProfileCreator} object
*/
public HeaderClient(final String headerName, final String prefixHeader, final ProfileCreator profileCreator) {
this.headerName = headerName;
this.prefixHeader = prefixHeader;
setAuthenticatorIfUndefined(Authenticator.ALWAYS_VALIDATE);
setProfileCreatorIfUndefined(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
if (getCredentialsExtractor() == null) {
CommonHelper.assertNotBlank("headerName", this.headerName);
CommonHelper.assertNotNull("prefixHeader", this.prefixHeader);
setCredentialsExtractorIfUndefined(new HeaderExtractor(this.headerName, this.prefixHeader));
}
| 969
| 83
| 1,052
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/client/indirect/FormClient.java
|
FormClient
|
getCredentials
|
class FormClient extends IndirectClient {
private String loginUrl;
/** Constant <code>ERROR_PARAMETER="error"</code> */
public final static String ERROR_PARAMETER = "error";
/** Constant <code>MISSING_FIELD_ERROR="missing_field"</code> */
public final static String MISSING_FIELD_ERROR = "missing_field";
private String usernameParameter = Pac4jConstants.USERNAME;
private String passwordParameter = Pac4jConstants.PASSWORD;
/**
* <p>Constructor for FormClient.</p>
*/
public FormClient() {
}
/**
* <p>Constructor for FormClient.</p>
*
* @param loginUrl a {@link String} object
* @param usernamePasswordAuthenticator a {@link Authenticator} object
*/
public FormClient(final String loginUrl, final Authenticator usernamePasswordAuthenticator) {
this.loginUrl = loginUrl;
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
}
/**
* <p>Constructor for FormClient.</p>
*
* @param loginUrl a {@link String} object
* @param usernameParameter a {@link String} object
* @param passwordParameter a {@link String} object
* @param usernamePasswordAuthenticator a {@link Authenticator} object
*/
public FormClient(final String loginUrl, final String usernameParameter, final String passwordParameter,
final Authenticator usernamePasswordAuthenticator) {
this.loginUrl = loginUrl;
this.usernameParameter = usernameParameter;
this.passwordParameter = passwordParameter;
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
}
/**
* <p>Constructor for FormClient.</p>
*
* @param loginUrl a {@link String} object
* @param usernamePasswordAuthenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public FormClient(final String loginUrl, final Authenticator usernamePasswordAuthenticator,
final ProfileCreator profileCreator) {
this.loginUrl = loginUrl;
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
assertNotBlank("loginUrl", this.loginUrl);
assertNotBlank("usernameParameter", this.usernameParameter);
assertNotBlank("passwordParameter", this.passwordParameter);
setRedirectionActionBuilderIfUndefined(ctx -> {
val webContext = ctx.webContext();
val finalLoginUrl = getUrlResolver().compute(this.loginUrl, webContext);
return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, finalLoginUrl));
});
setCredentialsExtractorIfUndefined(new FormExtractor(usernameParameter, passwordParameter));
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> getCredentials(final CallContext ctx) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected Optional<Credentials> internalValidateCredentials(final CallContext ctx, final Credentials credentials) {
assertNotNull("authenticator", getAuthenticator());
val username = ((UsernamePasswordCredentials) credentials).getUsername();
try {
return getAuthenticator().validate(ctx, credentials);
} catch (final CredentialsException e) {
throw handleInvalidCredentials(ctx, username,
"Credentials validation fails -> return to the form with error", computeErrorMessage(e));
}
}
/**
* <p>handleInvalidCredentials.</p>
*
* @param ctx a {@link CallContext} object
* @param username a {@link String} object
* @param message a {@link String} object
* @param errorMessage a {@link String} object
* @return a {@link HttpAction} object
*/
protected HttpAction handleInvalidCredentials(final CallContext ctx, final String username, String message, String errorMessage) {
val webContext = ctx.webContext();
// it's an AJAX request -> unauthorized (instead of a redirection)
if (getAjaxRequestResolver().isAjax(ctx)) {
logger.info("AJAX request detected -> returning 401");
return HttpActionHelper.buildUnauthenticatedAction(webContext);
} else {
var redirectionUrl = addParameter(this.loginUrl, this.usernameParameter, username);
redirectionUrl = addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage);
logger.debug("redirectionUrl: {}", redirectionUrl);
return HttpActionHelper.buildRedirectUrlAction(webContext, redirectionUrl);
}
}
/**
* Return the error message depending on the thrown exception. Can be overriden for other message computation.
*
* @param e the technical exception
* @return the error message
*/
protected String computeErrorMessage(final Exception e) {
return e.getClass().getSimpleName();
}
}
|
init();
assertNotNull("credentialsExtractor", getCredentialsExtractor());
val username = ctx.webContext().getRequestParameter(this.usernameParameter).orElse(null);
final Optional<Credentials> credentials;
try {
credentials = getCredentialsExtractor().extract(ctx);
logger.debug("usernamePasswordCredentials: {}", credentials);
if (credentials.isEmpty()) {
throw handleInvalidCredentials(ctx, username,
"Username and password cannot be blank -> return to the form with error", MISSING_FIELD_ERROR);
}
return credentials;
} catch (final CredentialsException e) {
throw handleInvalidCredentials(ctx, username,
"Credentials validation fails -> return to the form with error", computeErrorMessage(e));
}
| 1,322
| 200
| 1,522
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/client/indirect/IndirectBasicAuthClient.java
|
IndirectBasicAuthClient
|
getCredentials
|
class IndirectBasicAuthClient extends IndirectClient {
private String realmName = Pac4jConstants.DEFAULT_REALM_NAME;
/**
* <p>Constructor for IndirectBasicAuthClient.</p>
*/
public IndirectBasicAuthClient() {}
/**
* <p>Constructor for IndirectBasicAuthClient.</p>
*
* @param usernamePasswordAuthenticator a {@link Authenticator} object
*/
public IndirectBasicAuthClient(final Authenticator usernamePasswordAuthenticator) {
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
}
/**
* <p>Constructor for IndirectBasicAuthClient.</p>
*
* @param realmName a {@link String} object
* @param usernamePasswordAuthenticator a {@link Authenticator} object
*/
public IndirectBasicAuthClient(final String realmName, final Authenticator usernamePasswordAuthenticator) {
this.realmName = realmName;
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
}
/**
* <p>Constructor for IndirectBasicAuthClient.</p>
*
* @param usernamePasswordAuthenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public IndirectBasicAuthClient(final Authenticator usernamePasswordAuthenticator, final ProfileCreator profileCreator) {
setAuthenticatorIfUndefined(usernamePasswordAuthenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
assertNotBlank("realmName", this.realmName);
setRedirectionActionBuilderIfUndefined(ctx -> {
val webContext = ctx.webContext();
return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, computeFinalCallbackUrl(webContext)));
});
setCredentialsExtractorIfUndefined(new BasicAuthExtractor());
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> getCredentials(final CallContext ctx) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected Optional<Credentials> internalValidateCredentials(final CallContext ctx, final Credentials credentials) {
assertNotNull("authenticator", getAuthenticator());
val webContext = ctx.webContext();
// set the www-authenticate in case of error
webContext.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER,
HttpConstants.BASIC_HEADER_PREFIX + "realm=\"" + realmName + "\"");
try {
return getAuthenticator().validate(ctx, credentials);
} catch (final CredentialsException e) {
throw HttpActionHelper.buildUnauthenticatedAction(webContext);
}
}
}
|
init();
assertNotNull("credentialsExtractor", getCredentialsExtractor());
val webContext = ctx.webContext();
// set the www-authenticate in case of error
webContext.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, HttpConstants.BASIC_HEADER_PREFIX + "realm=\"" + realmName + "\"");
final Optional<Credentials> credentials;
try {
credentials = getCredentialsExtractor().extract(ctx);
logger.debug("credentials : {}", credentials);
if (credentials.isEmpty()) {
throw HttpActionHelper.buildUnauthenticatedAction(webContext);
}
return credentials;
} catch (final CredentialsException e) {
throw HttpActionHelper.buildUnauthenticatedAction(webContext);
}
| 746
| 209
| 955
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/CredentialUtil.java
|
CredentialUtil
|
encryptMD5
|
class CredentialUtil {
/**
* Defined in rfc 2617 as H(data) = MD5(data);
*
* @param data data
* @return MD5(data)
*/
public static String encryptMD5(String data) {<FILL_FUNCTION_BODY>}
/**
* Defined in rfc 2617 as KD(secret, data) = H(concat(secret, ":", data))
*
* @param data data
* @param secret secret
* @return H(concat(secret, ":", data));
*/
public static String encryptMD5(String secret, String data) {
return encryptMD5(secret + ":" + data);
}
}
|
try {
var digest = MessageDigest.getInstance("MD5");
return copyValueOf(Hex.encodeHex(digest.digest(data.getBytes(StandardCharsets.UTF_8))));
} catch (final NoSuchAlgorithmException ex) {
throw new TechnicalException("Failed to instantiate an MD5 algorithm", ex);
}
| 194
| 90
| 284
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/DigestCredentials.java
|
DigestCredentials
|
generateDigest
|
class DigestCredentials extends TokenCredentials {
@Serial
private static final long serialVersionUID = -5130296967270874521L;
@ToString.Include
@Getter
private String username;
private String realm;
private String nonce;
private String uri;
private String cnonce;
private String nc;
private String qop;
private String httpMethod;
/**
* the token represents the client response attribute value in digest authorization header
*
* @param token the token
* @param httpMethod the HTTP method
* @param username the user name
* @param realm the realm
* @param nonce nonce
* @param uri uri
* @param cnonce cnonce
* @param nc nc
* @param qop qop
*/
public DigestCredentials(final String token, final String httpMethod, final String username, final String realm,
final String nonce, final String uri, final String cnonce, final String nc,
final String qop) {
super(token);
this.username = username;
this.realm = realm;
this.nonce = nonce;
this.uri = uri;
this.cnonce = cnonce;
this.nc = nc;
this.qop = qop;
this.httpMethod = httpMethod;
}
/**
* This calculates the server digest value based on user stored password. If the server stores password in clear format
* then passwordAlreadyEncoded should be false. If the server stores the password in ha1, digest then the
* passwordAlreadyEncoded should be true.
*
* @param passwordAlreadyEncoded false if the server stored password is in clear, true otherwise
* @param password user password stored server-side
* @return digest value. This value must match the client "response" value in the Authorization http header
* for a successful digest authentication
*/
public String calculateServerDigest(boolean passwordAlreadyEncoded, String password) {
return generateDigest(passwordAlreadyEncoded, username,
realm, password, httpMethod, uri, qop, nonce, nc, cnonce);
}
/**
* generate digest token based on RFC 2069 and RFC 2617 guidelines
*
* @return digest token
*/
private String generateDigest(boolean passwordAlreadyEncoded, String username,
String realm, String password, String httpMethod, String uri, String qop,
String nonce, String nc, String cnonce) {<FILL_FUNCTION_BODY>}
}
|
String ha1;
var a2 = httpMethod + ":" + uri;
var ha2 = CredentialUtil.encryptMD5(a2);
if (passwordAlreadyEncoded) {
ha1 = password;
} else {
ha1 = CredentialUtil.encryptMD5(username + ":" + realm + ":" +password);
}
String digest;
if (qop == null) {
digest = CredentialUtil.encryptMD5(ha1, nonce + ":" + ha2);
} else if ("auth".equals(qop)) {
digest = CredentialUtil.encryptMD5(ha1, nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2);
} else {
throw new TechnicalException("Invalid qop: '" + qop + "'");
}
return digest;
| 666
| 229
| 895
|
<methods>public non-sealed void <init>() <variables>private static final long serialVersionUID,private java.lang.String token
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/X509Credentials.java
|
X509Credentials
|
toString
|
class X509Credentials extends Credentials {
@Serial
private static final long serialVersionUID = 2733744949087200768L;
private final X509Certificate certificate;
/**
* <p>Constructor for X509Credentials.</p>
*
* @param certificate a {@link X509Certificate} object
*/
public X509Credentials(final X509Certificate certificate) {
this.certificate = certificate;
}
/** {@inheritDoc} */
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "X509Credentials(certificate.serialNumber=" + (certificate != null ? certificate.getSerialNumber() : null) + ")";
| 175
| 41
| 216
|
<methods>public non-sealed void <init>() ,public boolean isForAuthentication() <variables>protected org.pac4j.core.logout.LogoutType logoutType,private static final long serialVersionUID,protected java.lang.String source,private org.pac4j.core.profile.UserProfile userProfile
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/authenticator/IpRegexpAuthenticator.java
|
IpRegexpAuthenticator
|
validate
|
class IpRegexpAuthenticator extends AbstractRegexpAuthenticator implements Authenticator {
/**
* <p>Constructor for IpRegexpAuthenticator.</p>
*/
public IpRegexpAuthenticator() { }
/**
* <p>Constructor for IpRegexpAuthenticator.</p>
*
* @param regexpPattern a {@link String} object
*/
public IpRegexpAuthenticator(final String regexpPattern) {
setRegexpPattern(regexpPattern);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotNull("pattern", pattern);
setProfileDefinitionIfUndefined(new CommonProfileDefinition(x -> new IpProfile()));
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>}
}
|
init();
val ip = ((TokenCredentials) credentials).getToken();
if (!this.pattern.matcher(ip).matches()) {
throw new CredentialsException("Unauthorized IP address: " + ip);
}
UserProfile profile = (IpProfile) getProfileDefinition().newProfile();
profile.setId(ip);
logger.debug("profile: {}", profile);
credentials.setUserProfile(profile);
return Optional.of(credentials);
| 258
| 125
| 383
|
<methods>public non-sealed void <init>() ,public void setRegexpPattern(java.lang.String) <variables>protected final org.slf4j.Logger logger,protected java.util.regex.Pattern pattern,protected java.lang.String regexpPattern
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/authenticator/RestAuthenticator.java
|
RestAuthenticator
|
validate
|
class RestAuthenticator extends ProfileDefinitionAware implements Authenticator {
private ObjectMapper mapper;
private String url;
/**
* <p>Constructor for RestAuthenticator.</p>
*/
public RestAuthenticator() {}
/**
* <p>Constructor for RestAuthenticator.</p>
*
* @param url a {@link String} object
*/
public RestAuthenticator(final String url) {
this.url = url;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotBlank("url", url);
setProfileDefinitionIfUndefined(new CommonProfileDefinition(x -> new RestProfile()));
if (mapper == null) {
mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials cred) {<FILL_FUNCTION_BODY>}
/**
* <p>buildProfile.</p>
*
* @param credentials a {@link UsernamePasswordCredentials} object
* @param body a {@link String} object
*/
protected void buildProfile(final UsernamePasswordCredentials credentials, final String body) {
val profileClass = (RestProfile) getProfileDefinition().newProfile();
final RestProfile profile;
try {
profile = mapper.readValue(body, profileClass.getClass());
} catch (final IOException e) {
throw new TechnicalException(e);
}
LOGGER.debug("profile: {}", profile);
credentials.setUserProfile(profile);
}
/**
* Return the body from the REST API, passing the username/pasword auth.
* To be overridden using another HTTP client if necessary.
*
* @param username the username
* @param password the password
* @return the response body
*/
protected String callRestApi(final String username, final String password) {
val basicAuth = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
Map<String, String> headers = new HashMap<>();
headers.put(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + basicAuth);
HttpURLConnection connection = null;
try {
connection = HttpUtils.openPostConnection(new URL(url), headers);
val code = connection.getResponseCode();
if (code == 200) {
LOGGER.debug("Authentication success for username: {}", username);
return HttpUtils.readBody(connection);
} else if (code == 401 || code == 403) {
LOGGER.info("Authentication failure for username: {} -> {}", username, HttpUtils.buildHttpErrorMessage(connection));
return null;
} else {
LOGGER.warn("Unexpected error for username: {} -> {}", username, HttpUtils.buildHttpErrorMessage(connection));
return null;
}
} catch (final IOException e) {
throw new TechnicalException(e);
} finally {
HttpUtils.closeConnection(connection);
}
}
}
|
init();
val credentials = (UsernamePasswordCredentials) cred;
val username = credentials.getUsername();
val password = credentials.getPassword();
if (CommonHelper.isBlank(username) || CommonHelper.isBlank(password)) {
LOGGER.info("Empty username or password");
return Optional.of(credentials);
}
val body = callRestApi(username, password);
LOGGER.debug("body: {}", body);
if (body != null) {
buildProfile(credentials, body);
}
return Optional.of(credentials);
| 900
| 153
| 1,053
|
<methods>public non-sealed void <init>() ,public org.pac4j.core.profile.definition.ProfileDefinition getProfileDefinition() ,public void setProfileDefinition(org.pac4j.core.profile.definition.ProfileDefinition) <variables>private org.pac4j.core.profile.definition.ProfileDefinition profileDefinition
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/authenticator/X509Authenticator.java
|
X509Authenticator
|
validate
|
class X509Authenticator extends AbstractRegexpAuthenticator implements Authenticator {
public X509Authenticator() {
setRegexpPattern("CN=(.*?)(?:,|$)");
}
public X509Authenticator(final String regexpPattern) {
setRegexpPattern(regexpPattern);
}
@Override
protected void internalInit(final boolean forceReinit) {
setProfileDefinitionIfUndefined(new CommonProfileDefinition(x -> new X509Profile()));
}
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>}
protected void extractExtensionFromCertificate(UserProfile profile, final X509Certificate certificate,
final String attribute, final int oid) {
try {
val subjectAlternativeNames = certificate.getSubjectAlternativeNames();
if (subjectAlternativeNames != null) {
val values = subjectAlternativeNames
.stream()
.filter(entry -> entry.size() == 2)
.filter(entry -> entry.get(0).equals(oid))
.map(entry -> entry.get(1).toString())
.toList();
if (!values.isEmpty()) {
profile.addAttribute(attribute, values);
}
}
} catch (Exception e) {
logger.debug("Unable to extract extension", e);
}
}
}
|
init();
val certificate = ((X509Credentials) credentials).getCertificate();
if (certificate == null) {
throw new CredentialsException("No X509 certificate");
}
val principal = certificate.getSubjectDN();
if (principal == null) {
throw new CredentialsException("No X509 principal");
}
val subjectDN = principal.getName();
logger.debug("subjectDN: {}", subjectDN);
if (subjectDN == null) {
throw new CredentialsException("No X509 subjectDN");
}
val matcher = this.pattern.matcher(subjectDN);
if (!matcher.find()) {
throw new CredentialsException("No matching for pattern: " + regexpPattern + " in subjectDN: " + subjectDN);
}
if (matcher.groupCount() != 1) {
throw new CredentialsException("Too many matches for pattern: " + regexpPattern + " in subjectDN: " + subjectDN);
}
val id = matcher.group(1);
val profile = getProfileDefinition().newProfile();
profile.setId(id);
try {
profile.addAttribute("x509-certificate", Base64.getEncoder().encodeToString(certificate.getEncoded()));
} catch (final Exception e) {
throw new CredentialsException("Unable to encode the certificate", e);
}
profile.addAttribute("x509-subjectDN", subjectDN);
profile.addAttribute("x509-notAfter", certificate.getNotAfter());
profile.addAttribute("x509-notBefore", certificate.getNotBefore());
profile.addAttribute("x509-sigAlgName", certificate.getSigAlgName());
profile.addAttribute("x509-sigAlgOid", certificate.getSigAlgOID());
extractExtensionFromCertificate(profile, certificate, "x509-sanEmail", 1);
extractExtensionFromCertificate(profile, certificate, "x509-sanDNS", 2);
extractExtensionFromCertificate(profile, certificate, "x509-sanURI", 6);
extractExtensionFromCertificate(profile, certificate, "x509-sanIP", 7);
extractExtensionFromCertificate(profile, certificate, "x509-sanRegisteredID", 8);
extractExtensionFromCertificate(profile, certificate, "x509-sanDirectory", 9);
val issuerDN = certificate.getIssuerDN();
if (issuerDN != null) {
profile.addAttribute("x509-issuer", issuerDN.getName());
}
val issuerX500Principal = certificate.getIssuerX500Principal();
if (issuerX500Principal != null) {
profile.addAttribute("x509-issuerX500", issuerX500Principal.getName());
}
logger.debug("profile: {}", profile);
credentials.setUserProfile(profile);
return Optional.of(credentials);
| 373
| 807
| 1,180
|
<methods>public non-sealed void <init>() ,public void setRegexpPattern(java.lang.String) <variables>protected final org.slf4j.Logger logger,protected java.util.regex.Pattern pattern,protected java.lang.String regexpPattern
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/extractor/CookieExtractor.java
|
CookieExtractor
|
extract
|
class CookieExtractor implements CredentialsExtractor {
private final String cookieName;
/**
* <p>Constructor for CookieExtractor.</p>
*
* @param cookieName a {@link String} object
*/
public CookieExtractor(final String cookieName) {
this.cookieName = cookieName;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val col = ctx.webContext().getRequestCookies();
for (val c : col) {
if (c.getName().equals(this.cookieName)) {
return Optional.of(new TokenCredentials(c.getValue()));
}
}
return Optional.empty();
| 133
| 75
| 208
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/extractor/DigestAuthExtractor.java
|
DigestAuthExtractor
|
extract
|
class DigestAuthExtractor implements CredentialsExtractor {
private final HeaderExtractor extractor;
/**
* <p>Constructor for DigestAuthExtractor.</p>
*/
public DigestAuthExtractor() {
this(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.DIGEST_HEADER_PREFIX);
}
/**
* <p>Constructor for DigestAuthExtractor.</p>
*
* @param headerName a {@link String} object
* @param prefixHeader a {@link String} object
*/
public DigestAuthExtractor(final String headerName, final String prefixHeader) {
this.extractor = new HeaderExtractor(headerName, prefixHeader);
}
/**
* {@inheritDoc}
*
* Extracts digest Authorization header components.
* As per RFC 2617 :
* username is the user's name in the specified realm
* qop is quality of protection
* uri is the request uri
* response is the client response
* nonce is a server-specified data string which should be uniquely generated
* each time a 401 response is made
* cnonce is the client nonce
* nc is the nonce count
* If in the Authorization header it is not specified a username and response, we throw CredentialsException because
* the client uses an username and a password to authenticate. response is just a MD5 encoded value
* based on user provided password and RFC 2617 digest authentication encoding rules
*/
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
private Map<String, String> parseTokenValue(String token) {
val tokenizer = new StringTokenizer(token, ", ");
String keyval;
Map<String, String> map = new HashMap<>();
while (tokenizer.hasMoreElements()) {
keyval = tokenizer.nextToken();
if (keyval.contains("=")) {
val key = keyval.substring(0, keyval.indexOf("="));
val value = keyval.substring(keyval.indexOf("=") + 1);
map.put(key.trim(), value.replaceAll("\"", Pac4jConstants.EMPTY_STRING).trim());
}
}
return map;
}
}
|
val credentials = this.extractor.extract(ctx);
if (credentials.isEmpty()) {
return Optional.empty();
}
val token = ((TokenCredentials) credentials.get()).getToken();
val valueMap = parseTokenValue(token);
val username = valueMap.get("username");
val response = valueMap.get("response");
if (CommonHelper.isBlank(username) || CommonHelper.isBlank(response)) {
throw new CredentialsException("Bad format of the digest auth header");
}
val realm = valueMap.get("realm");
val nonce = valueMap.get("nonce");
val uri = valueMap.get("uri");
val cnonce = valueMap.get("cnonce");
val nc = valueMap.get("nc");
val qop = valueMap.get("qop");
val method = ctx.webContext().getRequestMethod();
return Optional.of(new DigestCredentials(response, method, username, realm, nonce, uri, cnonce, nc, qop));
| 599
| 270
| 869
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/extractor/IpExtractor.java
|
IpExtractor
|
extract
|
class IpExtractor implements CredentialsExtractor {
private List<String> alternateIpHeaders = Collections.emptyList();
@Getter
private String proxyIp = Pac4jConstants.EMPTY_STRING;
/**
* <p>Constructor for IpExtractor.</p>
*/
public IpExtractor() {}
/**
* <p>Constructor for IpExtractor.</p>
*
* @param alternateIpHeaders a {@link String} object
*/
public IpExtractor(String... alternateIpHeaders) {
this.alternateIpHeaders = Arrays.asList(alternateIpHeaders);
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
private Optional<String> ipFromHeaders(WebContext context) {
Optional<String> ip;
for (var header : alternateIpHeaders) {
ip = context.getRequestHeader(header);
if (ip.isPresent() && !ip.get().isEmpty()) {
return ip;
}
}
return Optional.empty();
}
/**
* <p>Setter for the field <code>proxyIp</code>.</p>
*
* @param proxyIp Set the IP to verify the proxy request source.
* Setting {@code null} or {@code ""} (empty string) disabled the proxy IP check.
*/
public void setProxyIp(String proxyIp) {
this.proxyIp = proxyIp == null ? Pac4jConstants.EMPTY_STRING : proxyIp;
}
/**
* <p>Setter for the field <code>alternateIpHeaders</code>.</p>
*
* @param alternateIpHeaders Sets alternate headers to search for IP.
* The first match will be returned as specified for {@code enhanced for} iteration over arrays.
*/
public void setAlternateIpHeaders(final String... alternateIpHeaders) {
CommonHelper.assertNotNull("alternateIpHeaders", alternateIpHeaders);
this.alternateIpHeaders = Arrays.asList(alternateIpHeaders);
}
}
|
val webContext = ctx.webContext();
final Optional<String> ip;
if (alternateIpHeaders.isEmpty()) {
ip = Optional.ofNullable(webContext.getRemoteAddr());
} else {
val requestSourceIp = webContext.getRemoteAddr();
if (this.proxyIp.isEmpty()) {
ip = ipFromHeaders(webContext);
}
// if using proxy, check if the ip proxy is correct
else if (this.proxyIp.equals(requestSourceIp)) {
ip = ipFromHeaders(webContext);
} else {
ip = Optional.empty();
}
}
if (ip.isEmpty()) {
return Optional.empty();
}
return Optional.of(new TokenCredentials(ip.get()));
| 571
| 200
| 771
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-http/src/main/java/org/pac4j/http/credentials/extractor/X509CredentialsExtractor.java
|
X509CredentialsExtractor
|
extract
|
class X509CredentialsExtractor implements CredentialsExtractor {
/** Constant <code>CERTIFICATE_REQUEST_ATTRIBUTE="jakarta.servlet.request.X509Certificate"</code> */
public static final String CERTIFICATE_REQUEST_ATTRIBUTE = "jakarta.servlet.request.X509Certificate";
private String headerName = CERTIFICATE_REQUEST_ATTRIBUTE;
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val certificates = (Optional<X509Certificate[]>) ctx.webContext().getRequestAttribute(headerName);
if (certificates.isPresent() && certificates.get().length > 0) {
val certificate = certificates.get()[0];
LOGGER.debug("X509 certificate: {}", certificate);
return Optional.of(new X509Credentials(certificate));
}
LOGGER.debug("No X509 certificate in request");
return Optional.empty();
| 152
| 131
| 283
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-jakartaee/src/main/java/org/pac4j/jee/adapter/JEEFrameworkAdapter.java
|
JEEFrameworkAdapter
|
compareManagers
|
class JEEFrameworkAdapter extends DefaultFrameworkAdapter {
/** {@inheritDoc} */
@Override
public int compareManagers(final Object obj1, final Object obj2) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void applyDefaultSettingsIfUndefined(final Config config) {
super.applyDefaultSettingsIfUndefined(config);
config.setWebContextFactoryIfUndefined(JEEContextFactory.INSTANCE);
config.setSessionStoreFactoryIfUndefined(JEESessionStoreFactory.INSTANCE);
config.setHttpActionAdapterIfUndefined(JEEHttpActionAdapter.INSTANCE);
}
/** {@inheritDoc} */
@Override
public String toString() {
return "JakartaEE";
}
}
|
var p1 = 100;
var p2 = 100;
val p1a = obj1.getClass().getAnnotation(Priority.class);
if (p1a != null) {
p1 = p1a.value();
}
val p2a = obj2.getClass().getAnnotation(Priority.class);
if (p2a != null) {
p2 = p2a.value();
}
if (p1 < p2) {
return -1;
} else if (p1 > p2) {
return 1;
} else {
return obj2.getClass().getSimpleName().compareTo(obj1.getClass().getSimpleName());
}
| 205
| 185
| 390
|
<methods>public non-sealed void <init>() ,public void applyDefaultSettingsIfUndefined(org.pac4j.core.config.Config) ,public int compareManagers(java.lang.Object, java.lang.Object) ,public java.lang.String toString() <variables>
|
pac4j_pac4j
|
pac4j/pac4j-jakartaee/src/main/java/org/pac4j/jee/config/AbstractConfigFilter.java
|
AbstractConfigFilter
|
getBooleanParam
|
class AbstractConfigFilter implements Filter {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private static Config CONFIG;
@Getter
private Config config;
/** {@inheritDoc} */
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
val configFactoryParam = filterConfig.getInitParameter(Pac4jConstants.CONFIG_FACTORY);
if (configFactoryParam != null) {
val builtConfig = ConfigBuilder.build(configFactoryParam);
if (builtConfig != null) {
this.config = builtConfig;
AbstractConfigFilter.CONFIG = builtConfig;
}
}
}
/**
* <p>getStringParam.</p>
*
* @param filterConfig a {@link FilterConfig} object
* @param name a {@link String} object
* @param defaultValue a {@link String} object
* @return a {@link String} object
*/
protected String getStringParam(final FilterConfig filterConfig, final String name, final String defaultValue) {
val param = filterConfig.getInitParameter(name);
final String value;
if (param != null) {
value = param;
} else {
value = defaultValue;
}
logger.debug("String param: {}: {}", name, value);
return value;
}
/**
* <p>getBooleanParam.</p>
*
* @param filterConfig a {@link FilterConfig} object
* @param name a {@link String} object
* @param defaultValue a {@link Boolean} object
* @return a {@link Boolean} object
*/
protected Boolean getBooleanParam(final FilterConfig filterConfig, final String name, final Boolean defaultValue) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
val req = (HttpServletRequest) request;
val resp = (HttpServletResponse) response;
internalFilter(req, resp, chain);
}
/**
* <p>internalFilter.</p>
*
* @param request a {@link HttpServletRequest} object
* @param response a {@link HttpServletResponse} object
* @param chain a {@link FilterChain} object
* @throws IOException if any.
* @throws ServletException if any.
*/
protected abstract void internalFilter(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain chain) throws IOException, ServletException;
/**
* <p>getSharedConfig.</p>
*
* @return a {@link Config} object
*/
public Config getSharedConfig() {
if (this.config == null) {
return AbstractConfigFilter.CONFIG;
}
return this.config;
}
/**
* <p>Setter for the field <code>config</code>.</p>
*
* @param config a {@link Config} object
*/
public void setConfig(final Config config) {
CommonHelper.assertNotNull("config", config);
this.config = config;
}
}
|
val param = filterConfig.getInitParameter(name);
final Boolean value;
if (param != null) {
value = Boolean.parseBoolean(param);
} else {
value = defaultValue;
}
logger.debug("Boolean param: {}: {}", name, value);
return value;
| 818
| 81
| 899
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-jakartaee/src/main/java/org/pac4j/jee/context/JEEContext.java
|
JEEContext
|
getRequestHeader
|
class JEEContext implements WebContext {
private final HttpServletRequest request;
private final HttpServletResponse response;
private String body;
/**
* Build a JEE context from the current HTTP request and response.
*
* @param request the current request
* @param response the current response
*/
public JEEContext(final HttpServletRequest request, final HttpServletResponse response) {
CommonHelper.assertNotNull("request", request);
CommonHelper.assertNotNull("response", response);
this.request = request;
this.response = response;
}
/** {@inheritDoc} */
@Override
public Optional<String> getRequestParameter(final String name) {
return Optional.ofNullable(this.request.getParameter(name));
}
/** {@inheritDoc} */
@Override
public Optional getRequestAttribute(final String name) {
return Optional.ofNullable(this.request.getAttribute(name));
}
/** {@inheritDoc} */
@Override
public void setRequestAttribute(final String name, final Object value) {
this.request.setAttribute(name, value);
}
/** {@inheritDoc} */
@Override
public Map<String, String[]> getRequestParameters() {
return this.request.getParameterMap();
}
/** {@inheritDoc} */
@Override
public Optional<String> getRequestHeader(final String name) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public String getRequestMethod() {
return this.request.getMethod();
}
/** {@inheritDoc} */
@Override
public String getRemoteAddr() {
return this.request.getRemoteAddr();
}
/**
* Return the native HTTP request.
*
* @return the native HTTP request
*/
public HttpServletRequest getNativeRequest() {
return this.request;
}
/**
* Return the native HTTP response.
*
* @return the native HTTP response
*/
public HttpServletResponse getNativeResponse() {
return this.response;
}
/** {@inheritDoc} */
@Override
public void setResponseHeader(final String name, final String value) {
this.response.setHeader(name, value);
}
/** {@inheritDoc} */
@Override
public Optional<String> getResponseHeader(final String name) {
return Optional.ofNullable(this.response.getHeader(name));
}
/** {@inheritDoc} */
@Override
public void setResponseContentType(final String content) {
this.response.setContentType(content);
}
/** {@inheritDoc} */
@Override
public String getServerName() {
return this.request.getServerName();
}
/** {@inheritDoc} */
@Override
public int getServerPort() {
return this.request.getServerPort();
}
/** {@inheritDoc} */
@Override
public String getScheme() {
return this.request.getScheme();
}
/** {@inheritDoc} */
@Override
public boolean isSecure() {
return this.request.isSecure();
}
/** {@inheritDoc} */
@Override
public String getRequestURL() {
val url = request.getRequestURL().toString();
var idx = url.indexOf('?');
if (idx != -1) {
return url.substring(0, idx);
}
return url;
}
/** {@inheritDoc} */
@Override
public String getFullRequestURL() {
val requestURL = request.getRequestURL();
val queryString = request.getQueryString();
if (queryString == null) {
return requestURL.toString();
}
return requestURL.append('?').append(queryString).toString();
}
/** {@inheritDoc} */
@Override
public Collection<Cookie> getRequestCookies() {
final Collection<Cookie> pac4jCookies = new LinkedHashSet<>();
val cookies = this.request.getCookies();
if (cookies != null) {
for (val c : cookies) {
val cookie = new Cookie(c.getName(), c.getValue());
cookie.setDomain(c.getDomain());
cookie.setHttpOnly(c.isHttpOnly());
cookie.setMaxAge(c.getMaxAge());
cookie.setPath(c.getPath());
cookie.setSecure(c.getSecure());
pac4jCookies.add(cookie);
}
}
return pac4jCookies;
}
/** {@inheritDoc} */
@Override
public void addResponseCookie(Cookie cookie) {
this.response.addHeader("Set-Cookie", WebContextHelper.createCookieHeader(cookie));
}
/**
* {@inheritDoc}
*
* This is not implemented using {@link HttpServletRequest#getServletPath()} or
* {@link HttpServletRequest#getPathInfo()} because they both have strange behaviours
* in different contexts (inside servlets, inside filters, various container implementation, etc)
*/
@Override
public String getPath() {
var fullPath = request.getRequestURI();
// it shouldn't be null, but in case it is, it's better to return empty string
if (fullPath == null) {
return Pac4jConstants.EMPTY_STRING;
}
// very strange use case
if (fullPath.startsWith("//")) {
fullPath = fullPath.substring(1);
}
val context = request.getContextPath();
// this one shouldn't be null either, but in case it is, then let's consider it is empty
if (context != null) {
return fullPath.substring(context.length());
}
return fullPath;
}
/** {@inheritDoc} */
@Override
public String getRequestContent() {
if (body == null) {
try {
body = request.getReader()
.lines()
.reduce(Pac4jConstants.EMPTY_STRING, String::concat);
} catch (final IOException e) {
throw new TechnicalException(e);
}
}
return body;
}
/** {@inheritDoc} */
@Override
public String getProtocol() {
return request.getProtocol();
}
/** {@inheritDoc} */
@Override
public Optional<String> getQueryString() {
return Optional.ofNullable(request.getQueryString());
}
}
|
val names = request.getHeaderNames();
if (names != null) {
while (names.hasMoreElements()) {
val headerName = names.nextElement();
if (headerName != null && headerName.equalsIgnoreCase(name)) {
return Optional.ofNullable(this.request.getHeader(headerName));
}
}
}
return Optional.empty();
| 1,684
| 100
| 1,784
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-jakartaee/src/main/java/org/pac4j/jee/context/JEEContextFactory.java
|
JEEContextFactory
|
newContext
|
class JEEContextFactory implements WebContextFactory {
/** Constant <code>INSTANCE</code> */
public static final WebContextFactory INSTANCE = new JEEContextFactory();
/** {@inheritDoc} */
@Override
public JEEContext newContext(final FrameworkParameters parameters) {<FILL_FUNCTION_BODY>}
}
|
if (parameters instanceof JEEFrameworkParameters jeeFrameworkParameters) {
return new JEEContext(jeeFrameworkParameters.getRequest(), jeeFrameworkParameters.getResponse());
}
throw new TechnicalException("Bad parameters type");
| 87
| 57
| 144
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-jakartaee/src/main/java/org/pac4j/jee/context/session/JEESessionStore.java
|
JEESessionStore
|
get
|
class JEESessionStore extends PrefixedSessionStore {
protected HttpSession httpSession;
/**
* <p>Constructor for JEESessionStore.</p>
*/
public JEESessionStore() {}
/**
* <p>Constructor for JEESessionStore.</p>
*
* @param httpSession a {@link HttpSession} object
*/
protected JEESessionStore(final HttpSession httpSession) {
this.httpSession = httpSession;
}
/**
* <p>getNativeSession.</p>
*
* @param context a {@link WebContext} object
* @param createSession a boolean
* @return a {@link Optional} object
*/
protected Optional<HttpSession> getNativeSession(final WebContext context, final boolean createSession) {
if (httpSession != null) {
LOGGER.debug("Provided session: {}", httpSession);
return Optional.of(httpSession);
} else {
val jeeContext = (JEEContext) context;
val session = jeeContext.getNativeRequest().getSession(createSession);
LOGGER.debug("createSession: {}, retrieved session: {}", createSession, session);
return Optional.ofNullable(session);
}
}
/** {@inheritDoc} */
@Override
public Optional<String> getSessionId(final WebContext context, final boolean createSession) {
val httpSession = getNativeSession(context, createSession);
if (httpSession.isPresent()) {
val sessionId = httpSession.get().getId();
LOGGER.debug("Get sessionId: {}", sessionId);
return Optional.of(sessionId);
} else {
LOGGER.debug("No sessionId");
return Optional.empty();
}
}
/** {@inheritDoc} */
@Override
public Optional<Object> get(final WebContext context, final String key) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void set(final WebContext context, final String key, final Object value) {
val prefixedKey = computePrefixedKey(key);
if (value == null) {
val httpSession = getNativeSession(context, false);
if (httpSession.isPresent()) {
LOGGER.debug("Remove value for key: {}", prefixedKey);
httpSession.get().removeAttribute(prefixedKey);
}
} else {
val httpSession = getNativeSession(context, true);
if (value instanceof Exception) {
LOGGER.debug("Set key: {} for value: {}", prefixedKey, value.toString());
} else {
LOGGER.debug("Set key: {} for value: {}", prefixedKey, value);
}
httpSession.get().setAttribute(prefixedKey, value);
}
}
/** {@inheritDoc} */
@Override
public boolean destroySession(final WebContext context) {
val httpSession = getNativeSession(context, false);
if (httpSession.isPresent()) {
val session = httpSession.get();
LOGGER.debug("Invalidate session: {}", session);
session.invalidate();
}
return true;
}
/** {@inheritDoc} */
@Override
public Optional<Object> getTrackableSession(final WebContext context) {
val httpSession = getNativeSession(context, false);
if (httpSession.isPresent()) {
val session = httpSession.get();
LOGGER.debug("Return trackable session: {}", session);
return Optional.of(session);
} else {
LOGGER.debug("No trackable session");
return Optional.empty();
}
}
/** {@inheritDoc} */
@Override
public Optional<SessionStore> buildFromTrackableSession(final WebContext context, final Object trackableSession) {
if (trackableSession != null) {
LOGGER.debug("Rebuild session from trackable session: {}", trackableSession);
val sessionStore = new JEESessionStore((HttpSession) trackableSession);
sessionStore.setPrefix(this.getPrefix());
return Optional.of(sessionStore);
} else {
LOGGER.debug("Unable to build session from trackable session");
return Optional.empty();
}
}
/** {@inheritDoc} */
@Override
public boolean renewSession(final WebContext context) {
Map<String, Object> attributes = new HashMap<>();
val request = ((JEEContext) context).getNativeRequest();
val session = request.getSession(false);
if (session != null) {
LOGGER.debug("Discard old session: {}", session.getId());
attributes = Collections.list(session.getAttributeNames())
.stream()
.collect(Collectors.toMap(k -> k, session::getAttribute, (a, b) -> b));
session.invalidate();
}
val newSession = request.getSession(true);
LOGGER.debug("And copy all data to the new one: {}", newSession.getId());
attributes.forEach(newSession::setAttribute);
return true;
}
}
|
val httpSession = getNativeSession(context, false);
val prefixedKey = computePrefixedKey(key);
if (httpSession.isPresent()) {
val value = httpSession.get().getAttribute(prefixedKey);
LOGGER.debug("Get value: {} for key: {}", value, prefixedKey);
return Optional.ofNullable(value);
} else {
LOGGER.debug("Can't get value for key: {}, no session available", prefixedKey);
return Optional.empty();
}
| 1,294
| 130
| 1,424
|
<methods>public non-sealed void <init>() ,public java.lang.String computePrefixedKey(java.lang.String) <variables>private java.lang.String prefix
|
pac4j_pac4j
|
pac4j/pac4j-jakartaee/src/main/java/org/pac4j/jee/http/adapter/JEEHttpActionAdapter.java
|
JEEHttpActionAdapter
|
adapt
|
class JEEHttpActionAdapter implements HttpActionAdapter {
/** Constant <code>INSTANCE</code> */
public static final HttpActionAdapter INSTANCE = new JEEHttpActionAdapter();
/**
* <p>Constructor for JEEHttpActionAdapter.</p>
*/
protected JEEHttpActionAdapter() {}
/** {@inheritDoc} */
@Override
public Object adapt(final HttpAction action, final WebContext context) {<FILL_FUNCTION_BODY>}
}
|
if (action != null) {
var code = action.getCode();
val response = ((JEEContext) context).getNativeResponse();
if (code < 400) {
response.setStatus(code);
} else {
try {
response.sendError(code);
} catch (final IOException e) {
throw new TechnicalException(e);
}
}
if (action instanceof WithLocationAction withLocationAction) {
context.setResponseHeader(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
} else if (action instanceof WithContentAction withContentAction) {
val content = withContentAction.getContent();
if (content != null) {
try {
response.getWriter().write(content);
} catch (final IOException e) {
throw new TechnicalException(e);
}
}
}
return null;
}
throw new TechnicalException("No action provided");
| 125
| 246
| 371
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-jakartaee/src/main/java/org/pac4j/jee/saml/metadata/Saml2MetadataFilter.java
|
Saml2MetadataFilter
|
internalFilter
|
class Saml2MetadataFilter extends AbstractConfigFilter {
private String clientName;
/** {@inheritDoc} */
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
this.clientName = getStringParam(filterConfig, Pac4jConstants.CLIENT_NAME, this.clientName);
}
/** {@inheritDoc} */
@Override
protected void internalFilter(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void destroy() {
}
}
|
CommonHelper.assertNotNull("config", getSharedConfig());
CommonHelper.assertNotNull("clientName", clientName);
SAML2Client client;
val result = getSharedConfig().getClients().findClient(this.clientName);
if (result.isPresent()) {
client = (SAML2Client) result.get();
} else {
throw new TechnicalException("No SAML2 client: " + this.clientName);
}
client.init();
response.getWriter().write(client.getServiceProviderMetadataResolver().getMetadata());
response.getWriter().flush();
| 176
| 153
| 329
|
<methods>public non-sealed void <init>() ,public void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws java.io.IOException, jakarta.servlet.ServletException,public org.pac4j.core.config.Config getSharedConfig() ,public void init(jakarta.servlet.FilterConfig) throws jakarta.servlet.ServletException,public void setConfig(org.pac4j.core.config.Config) <variables>private static org.pac4j.core.config.Config CONFIG,private org.pac4j.core.config.Config config,protected final org.slf4j.Logger logger
|
pac4j_pac4j
|
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/adapter/JEEFrameworkAdapter.java
|
JEEFrameworkAdapter
|
compareManagers
|
class JEEFrameworkAdapter extends DefaultFrameworkAdapter {
/** {@inheritDoc} */
@Override
public int compareManagers(final Object obj1, final Object obj2) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void applyDefaultSettingsIfUndefined(final Config config) {
super.applyDefaultSettingsIfUndefined(config);
config.setWebContextFactoryIfUndefined(JEEContextFactory.INSTANCE);
config.setSessionStoreFactoryIfUndefined(JEESessionStoreFactory.INSTANCE);
config.setHttpActionAdapterIfUndefined(JEEHttpActionAdapter.INSTANCE);
}
/** {@inheritDoc} */
@Override
public String toString() {
return "JavaEE";
}
}
|
var p1 = 100;
var p2 = 100;
val p1a = obj1.getClass().getAnnotation(Priority.class);
if (p1a != null) {
p1 = p1a.value();
}
val p2a = obj2.getClass().getAnnotation(Priority.class);
if (p2a != null) {
p2 = p2a.value();
}
if (p1 < p2) {
return -1;
} else if (p1 > p2) {
return 1;
} else {
return obj2.getClass().getSimpleName().compareTo(obj1.getClass().getSimpleName());
}
| 202
| 185
| 387
|
<methods>public non-sealed void <init>() ,public void applyDefaultSettingsIfUndefined(org.pac4j.core.config.Config) ,public int compareManagers(java.lang.Object, java.lang.Object) ,public java.lang.String toString() <variables>
|
pac4j_pac4j
|
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/config/AbstractConfigFilter.java
|
AbstractConfigFilter
|
getStringParam
|
class AbstractConfigFilter implements Filter {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private static Config CONFIG;
@Getter
private Config config;
/** {@inheritDoc} */
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
val configFactoryParam = filterConfig.getInitParameter(Pac4jConstants.CONFIG_FACTORY);
if (configFactoryParam != null) {
val builtConfig = ConfigBuilder.build(configFactoryParam);
if (builtConfig != null) {
this.config = builtConfig;
AbstractConfigFilter.CONFIG = builtConfig;
}
}
}
/**
* <p>getStringParam.</p>
*
* @param filterConfig a {@link FilterConfig} object
* @param name a {@link String} object
* @param defaultValue a {@link String} object
* @return a {@link String} object
*/
protected String getStringParam(final FilterConfig filterConfig, final String name, final String defaultValue) {<FILL_FUNCTION_BODY>}
/**
* <p>getBooleanParam.</p>
*
* @param filterConfig a {@link FilterConfig} object
* @param name a {@link String} object
* @param defaultValue a {@link Boolean} object
* @return a {@link Boolean} object
*/
protected Boolean getBooleanParam(final FilterConfig filterConfig, final String name, final Boolean defaultValue) {
val param = filterConfig.getInitParameter(name);
final Boolean value;
if (param != null) {
value = Boolean.parseBoolean(param);
} else {
value = defaultValue;
}
logger.debug("Boolean param: {}: {}", name, value);
return value;
}
/** {@inheritDoc} */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
val req = (HttpServletRequest) request;
val resp = (HttpServletResponse) response;
internalFilter(req, resp, chain);
}
/**
* <p>internalFilter.</p>
*
* @param request a {@link HttpServletRequest} object
* @param response a {@link HttpServletResponse} object
* @param chain a {@link FilterChain} object
* @throws IOException if any.
* @throws ServletException if any.
*/
protected abstract void internalFilter(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain chain) throws IOException, ServletException;
/**
* <p>getSharedConfig.</p>
*
* @return a {@link Config} object
*/
public Config getSharedConfig() {
if (this.config == null) {
return AbstractConfigFilter.CONFIG;
}
return this.config;
}
/**
* <p>Setter for the field <code>config</code>.</p>
*
* @param config a {@link Config} object
*/
public void setConfig(final Config config) {
CommonHelper.assertNotNull("config", config);
this.config = config;
}
}
|
val param = filterConfig.getInitParameter(name);
final String value;
if (param != null) {
value = param;
} else {
value = defaultValue;
}
logger.debug("String param: {}: {}", name, value);
return value;
| 823
| 76
| 899
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/context/JEEContext.java
|
JEEContext
|
getRequestCookies
|
class JEEContext implements WebContext {
private final HttpServletRequest request;
private final HttpServletResponse response;
private String body;
/**
* Build a JEE context from the current HTTP request and response.
*
* @param request the current request
* @param response the current response
*/
public JEEContext(final HttpServletRequest request, final HttpServletResponse response) {
CommonHelper.assertNotNull("request", request);
CommonHelper.assertNotNull("response", response);
this.request = request;
this.response = response;
}
/** {@inheritDoc} */
@Override
public Optional<String> getRequestParameter(final String name) {
return Optional.ofNullable(this.request.getParameter(name));
}
/** {@inheritDoc} */
@Override
public Optional getRequestAttribute(final String name) {
return Optional.ofNullable(this.request.getAttribute(name));
}
/** {@inheritDoc} */
@Override
public void setRequestAttribute(final String name, final Object value) {
this.request.setAttribute(name, value);
}
/** {@inheritDoc} */
@Override
public Map<String, String[]> getRequestParameters() {
return this.request.getParameterMap();
}
/** {@inheritDoc} */
@Override
public Optional<String> getRequestHeader(final String name) {
val names = request.getHeaderNames();
if (names != null) {
while (names.hasMoreElements()) {
val headerName = names.nextElement();
if (headerName != null && headerName.equalsIgnoreCase(name)) {
return Optional.ofNullable(this.request.getHeader(headerName));
}
}
}
return Optional.empty();
}
/** {@inheritDoc} */
@Override
public String getRequestMethod() {
return this.request.getMethod();
}
/** {@inheritDoc} */
@Override
public String getRemoteAddr() {
return this.request.getRemoteAddr();
}
/**
* Return the native HTTP request.
*
* @return the native HTTP request
*/
public HttpServletRequest getNativeRequest() {
return this.request;
}
/**
* Return the native HTTP response.
*
* @return the native HTTP response
*/
public HttpServletResponse getNativeResponse() {
return this.response;
}
/** {@inheritDoc} */
@Override
public void setResponseHeader(final String name, final String value) {
this.response.setHeader(name, value);
}
/** {@inheritDoc} */
@Override
public Optional<String> getResponseHeader(final String name) {
return Optional.ofNullable(this.response.getHeader(name));
}
/** {@inheritDoc} */
@Override
public void setResponseContentType(final String content) {
this.response.setContentType(content);
}
/** {@inheritDoc} */
@Override
public String getServerName() {
return this.request.getServerName();
}
/** {@inheritDoc} */
@Override
public int getServerPort() {
return this.request.getServerPort();
}
/** {@inheritDoc} */
@Override
public String getScheme() {
return this.request.getScheme();
}
/** {@inheritDoc} */
@Override
public boolean isSecure() {
return this.request.isSecure();
}
/** {@inheritDoc} */
@Override
public String getRequestURL() {
val url = request.getRequestURL().toString();
var idx = url.indexOf('?');
if (idx != -1) {
return url.substring(0, idx);
}
return url;
}
/** {@inheritDoc} */
@Override
public String getFullRequestURL() {
val requestURL = request.getRequestURL();
val queryString = request.getQueryString();
if (queryString == null) {
return requestURL.toString();
}
return requestURL.append('?').append(queryString).toString();
}
/** {@inheritDoc} */
@Override
public Collection<Cookie> getRequestCookies() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void addResponseCookie(Cookie cookie) {
this.response.addHeader("Set-Cookie", WebContextHelper.createCookieHeader(cookie));
}
/**
* {@inheritDoc}
*
* This is not implemented using {@link HttpServletRequest#getServletPath()} or
* {@link HttpServletRequest#getPathInfo()} because they both have strange behaviours
* in different contexts (inside servlets, inside filters, various container implementation, etc)
*/
@Override
public String getPath() {
var fullPath = request.getRequestURI();
// it shouldn't be null, but in case it is, it's better to return empty string
if (fullPath == null) {
return Pac4jConstants.EMPTY_STRING;
}
// very strange use case
if (fullPath.startsWith("//")) {
fullPath = fullPath.substring(1);
}
val context = request.getContextPath();
// this one shouldn't be null either, but in case it is, then let's consider it is empty
if (context != null) {
return fullPath.substring(context.length());
}
return fullPath;
}
/** {@inheritDoc} */
@Override
public String getRequestContent() {
if (body == null) {
try {
body = request.getReader()
.lines()
.reduce(Pac4jConstants.EMPTY_STRING, String::concat);
} catch (final IOException e) {
throw new TechnicalException(e);
}
}
return body;
}
/** {@inheritDoc} */
@Override
public String getProtocol() {
return request.getProtocol();
}
/** {@inheritDoc} */
@Override
public Optional<String> getQueryString() {
return Optional.ofNullable(request.getQueryString());
}
}
|
final Collection<Cookie> pac4jCookies = new LinkedHashSet<>();
val cookies = this.request.getCookies();
if (cookies != null) {
for (val c : cookies) {
val cookie = new Cookie(c.getName(), c.getValue());
cookie.setDomain(c.getDomain());
cookie.setHttpOnly(c.isHttpOnly());
cookie.setMaxAge(c.getMaxAge());
cookie.setPath(c.getPath());
cookie.setSecure(c.getSecure());
pac4jCookies.add(cookie);
}
}
return pac4jCookies;
| 1,613
| 171
| 1,784
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/context/JEEContextFactory.java
|
JEEContextFactory
|
newContext
|
class JEEContextFactory implements WebContextFactory {
/** Constant <code>INSTANCE</code> */
public static final WebContextFactory INSTANCE = new JEEContextFactory();
/** {@inheritDoc} */
@Override
public JEEContext newContext(final FrameworkParameters parameters) {<FILL_FUNCTION_BODY>}
}
|
if (parameters instanceof JEEFrameworkParameters jeeFrameworkParameters) {
return new JEEContext(jeeFrameworkParameters.getRequest(), jeeFrameworkParameters.getResponse());
}
throw new TechnicalException("Bad parameters type");
| 87
| 57
| 144
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/context/session/JEESessionStore.java
|
JEESessionStore
|
set
|
class JEESessionStore extends PrefixedSessionStore {
protected HttpSession httpSession;
/**
* <p>Constructor for JEESessionStore.</p>
*/
public JEESessionStore() {}
/**
* <p>Constructor for JEESessionStore.</p>
*
* @param httpSession a {@link HttpSession} object
*/
public JEESessionStore(final HttpSession httpSession) {
this.httpSession = httpSession;
}
/**
* <p>getNativeSession.</p>
*
* @param context a {@link WebContext} object
* @param createSession a boolean
* @return a {@link Optional} object
*/
protected Optional<HttpSession> getNativeSession(final WebContext context, final boolean createSession) {
if (httpSession != null) {
LOGGER.debug("Provided session: {}", httpSession);
return Optional.of(httpSession);
} else {
val jeeContext = (JEEContext) context;
val session = jeeContext.getNativeRequest().getSession(createSession);
LOGGER.debug("createSession: {}, retrieved session: {}", createSession, session);
return Optional.ofNullable(session);
}
}
/** {@inheritDoc} */
@Override
public Optional<String> getSessionId(final WebContext context, final boolean createSession) {
val httpSession = getNativeSession(context, createSession);
if (httpSession.isPresent()) {
val sessionId = httpSession.get().getId();
LOGGER.debug("Get sessionId: {}", sessionId);
return Optional.of(sessionId);
} else {
LOGGER.debug("No sessionId");
return Optional.empty();
}
}
/** {@inheritDoc} */
@Override
public Optional<Object> get(final WebContext context, final String key) {
val httpSession = getNativeSession(context, false);
val prefixedKey = computePrefixedKey(key);
if (httpSession.isPresent()) {
val value = httpSession.get().getAttribute(prefixedKey);
LOGGER.debug("Get value: {} for key: {}", value, prefixedKey);
return Optional.ofNullable(value);
} else {
LOGGER.debug("Can't get value for key: {}, no session available", prefixedKey);
return Optional.empty();
}
}
/** {@inheritDoc} */
@Override
public void set(final WebContext context, final String key, final Object value) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public boolean destroySession(final WebContext context) {
val httpSession = getNativeSession(context, false);
if (httpSession.isPresent()) {
val session = httpSession.get();
LOGGER.debug("Invalidate session: {}", session);
session.invalidate();
}
return true;
}
/** {@inheritDoc} */
@Override
public Optional<Object> getTrackableSession(final WebContext context) {
val httpSession = getNativeSession(context, false);
if (httpSession.isPresent()) {
val session = httpSession.get();
LOGGER.debug("Return trackable session: {}", session);
return Optional.of(session);
} else {
LOGGER.debug("No trackable session");
return Optional.empty();
}
}
/** {@inheritDoc} */
@Override
public Optional<SessionStore> buildFromTrackableSession(final WebContext context, final Object trackableSession) {
if (trackableSession != null) {
LOGGER.debug("Rebuild session from trackable session: {}", trackableSession);
val sessionStore = new JEESessionStore((HttpSession) trackableSession);
sessionStore.setPrefix(this.getPrefix());
return Optional.of(sessionStore);
} else {
LOGGER.debug("Unable to build session from trackable session");
return Optional.empty();
}
}
/** {@inheritDoc} */
@Override
public boolean renewSession(final WebContext context) {
Map<String, Object> attributes = new HashMap<>();
val request = ((JEEContext) context).getNativeRequest();
val session = request.getSession(false);
if (session != null) {
LOGGER.debug("Discard old session: {}", session.getId());
attributes = Collections.list(session.getAttributeNames())
.stream()
.collect(Collectors.toMap(k -> k, session::getAttribute, (a, b) -> b));
session.invalidate();
}
val newSession = request.getSession(true);
LOGGER.debug("And copy all data to the new one: {}", newSession.getId());
attributes.forEach(newSession::setAttribute);
return true;
}
}
|
val prefixedKey = computePrefixedKey(key);
if (value == null) {
val httpSession = getNativeSession(context, false);
if (httpSession.isPresent()) {
LOGGER.debug("Remove value for key: {}", prefixedKey);
httpSession.get().removeAttribute(prefixedKey);
}
} else {
val httpSession = getNativeSession(context, true);
if (value instanceof Exception) {
LOGGER.debug("Set key: {} for value: {}", prefixedKey, value.toString());
} else {
LOGGER.debug("Set key: {} for value: {}", prefixedKey, value);
}
httpSession.get().setAttribute(prefixedKey, value);
}
| 1,237
| 187
| 1,424
|
<methods>public non-sealed void <init>() ,public java.lang.String computePrefixedKey(java.lang.String) <variables>private java.lang.String prefix
|
pac4j_pac4j
|
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/http/adapter/JEEHttpActionAdapter.java
|
JEEHttpActionAdapter
|
adapt
|
class JEEHttpActionAdapter implements HttpActionAdapter {
/** Constant <code>INSTANCE</code> */
public static final HttpActionAdapter INSTANCE = new JEEHttpActionAdapter();
/**
* <p>Constructor for JEEHttpActionAdapter.</p>
*/
protected JEEHttpActionAdapter() {}
/** {@inheritDoc} */
@Override
public Object adapt(final HttpAction action, final WebContext context) {<FILL_FUNCTION_BODY>}
}
|
if (action != null) {
var code = action.getCode();
val response = ((JEEContext) context).getNativeResponse();
if (code < 400) {
response.setStatus(code);
} else {
try {
response.sendError(code);
} catch (final IOException e) {
throw new TechnicalException(e);
}
}
if (action instanceof WithLocationAction withLocationAction) {
context.setResponseHeader(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
} else if (action instanceof WithContentAction withContentAction) {
val content = withContentAction.getContent();
if (content != null) {
try {
response.getWriter().write(content);
} catch (final IOException e) {
throw new TechnicalException(e);
}
}
}
return null;
}
throw new TechnicalException("No action provided");
| 125
| 246
| 371
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/saml/metadata/Saml2MetadataFilter.java
|
Saml2MetadataFilter
|
internalFilter
|
class Saml2MetadataFilter extends AbstractConfigFilter {
private String clientName;
/** {@inheritDoc} */
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
this.clientName = getStringParam(filterConfig, Pac4jConstants.CLIENT_NAME, this.clientName);
}
/** {@inheritDoc} */
@Override
protected void internalFilter(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void destroy() {
}
}
|
CommonHelper.assertNotNull("config", getSharedConfig());
CommonHelper.assertNotNull("clientName", clientName);
SAML2Client client;
val result = getSharedConfig().getClients().findClient(this.clientName);
if (result.isPresent()) {
client = (SAML2Client) result.get();
} else {
throw new TechnicalException("No SAML2 client: " + this.clientName);
}
client.init();
response.getWriter().write(client.getServiceProviderMetadataResolver().getMetadata());
response.getWriter().flush();
| 176
| 153
| 329
|
<methods>public non-sealed void <init>() ,public void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws java.io.IOException, jakarta.servlet.ServletException,public org.pac4j.core.config.Config getSharedConfig() ,public void init(jakarta.servlet.FilterConfig) throws jakarta.servlet.ServletException,public void setConfig(org.pac4j.core.config.Config) <variables>private static org.pac4j.core.config.Config CONFIG,private org.pac4j.core.config.Config config,protected final org.slf4j.Logger logger
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/config/encryption/AbstractEncryptionConfiguration.java
|
AbstractEncryptionConfiguration
|
encrypt
|
class AbstractEncryptionConfiguration extends InitializableObject implements EncryptionConfiguration {
protected JWEAlgorithm algorithm;
protected EncryptionMethod method;
/** {@inheritDoc} */
@Override
public String encrypt(final JWT jwt) {<FILL_FUNCTION_BODY>}
/**
* Build the appropriate encrypter.
*
* @return the appropriate encrypter
*/
protected abstract JWEEncrypter buildEncrypter();
/** {@inheritDoc} */
@Override
public void decrypt(final EncryptedJWT encryptedJWT) throws JOSEException {
init();
// decrypt
encryptedJWT.decrypt(buildDecrypter());
}
/**
* Build the appropriate decrypter.
*
* @return the appropriate decrypter
*/
protected abstract JWEDecrypter buildDecrypter();
}
|
init();
if (jwt instanceof SignedJWT signedJWT) {
// Create JWE object with signed JWT as payload
val jweObject = new JWEObject(
new JWEHeader.Builder(this.algorithm, this.method).contentType("JWT").build(),
new Payload(signedJWT));
try {
// Perform encryption
jweObject.encrypt(buildEncrypter());
} catch (final JOSEException e) {
throw new TechnicalException(e);
}
// Serialise to JWE compact form
return jweObject.serialize();
} else {
// create header
val header = new JWEHeader(this.algorithm, this.method);
try {
// encrypted jwt
val encryptedJwt = new EncryptedJWT(header, jwt.getJWTClaimsSet());
// Perform encryption
encryptedJwt.encrypt(buildEncrypter());
// serialize
return encryptedJwt.serialize();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
}
| 239
| 296
| 535
|
<methods>public non-sealed void <init>() ,public int getNbAttempts() ,public void init() ,public void init(boolean) ,public final boolean isInitialized() ,public void reinit() <variables>private java.util.concurrent.atomic.AtomicBoolean initialized,private volatile java.lang.Long lastAttempt,private int maxAttempts,private long minTimeIntervalBetweenAttemptsInMilliseconds,private java.util.concurrent.atomic.AtomicInteger nbAttempts
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/config/encryption/ECEncryptionConfiguration.java
|
ECEncryptionConfiguration
|
internalInit
|
class ECEncryptionConfiguration extends AbstractEncryptionConfiguration {
@Getter @Setter
private ECPublicKey publicKey;
@Getter @Setter
private ECPrivateKey privateKey;
/**
* <p>Constructor for ECEncryptionConfiguration.</p>
*/
public ECEncryptionConfiguration() {
}
/**
* <p>Constructor for ECEncryptionConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public ECEncryptionConfiguration(final KeyPair keyPair) {
setKeyPair(keyPair);
}
/**
* <p>Constructor for ECEncryptionConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
* @param algorithm a {@link JWEAlgorithm} object
* @param method a {@link EncryptionMethod} object
*/
public ECEncryptionConfiguration(final KeyPair keyPair, final JWEAlgorithm algorithm, final EncryptionMethod method) {
setKeyPair(keyPair);
this.algorithm = algorithm;
this.method = method;
}
/** {@inheritDoc} */
@Override
public boolean supports(final JWEAlgorithm algorithm, final EncryptionMethod method) {
return algorithm != null && method != null
&& ECDHDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)
&& ECDHDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(method);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected JWEEncrypter buildEncrypter() {
CommonHelper.assertNotNull("publicKey", publicKey);
try {
return new ECDHEncrypter(this.publicKey);
} catch (final JOSEException e) {
throw new TechnicalException(e);
}
}
/** {@inheritDoc} */
@Override
protected JWEDecrypter buildDecrypter() {
CommonHelper.assertNotNull("privateKey", privateKey);
try {
return new ECDHDecrypter(this.privateKey);
} catch (final JOSEException e) {
throw new TechnicalException(e);
}
}
/**
* <p>setKeyPair.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public void setKeyPair(final KeyPair keyPair) {
CommonHelper.assertNotNull("keyPair", keyPair);
this.privateKey = (ECPrivateKey) keyPair.getPrivate();
this.publicKey = (ECPublicKey) keyPair.getPublic();
}
/**
* <p>setKeysFromJwk.</p>
*
* @param json a {@link String} object
*/
public void setKeysFromJwk(final String json) {
val pair = JWKHelper.buildECKeyPairFromJwk(json);
this.publicKey = (ECPublicKey) pair.getPublic();
this.privateKey = (ECPrivateKey) pair.getPrivate();
}
}
|
CommonHelper.assertNotNull("algorithm", algorithm);
CommonHelper.assertNotNull("method", method);
if (!supports(this.algorithm, this.method)) {
throw new TechnicalException("Only Elliptic-curve algorithms are supported with the appropriate encryption method");
}
| 839
| 70
| 909
|
<methods>public non-sealed void <init>() ,public void decrypt(com.nimbusds.jwt.EncryptedJWT) throws com.nimbusds.jose.JOSEException,public java.lang.String encrypt(com.nimbusds.jwt.JWT) <variables>protected com.nimbusds.jose.JWEAlgorithm algorithm,protected com.nimbusds.jose.EncryptionMethod method
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/config/encryption/RSAEncryptionConfiguration.java
|
RSAEncryptionConfiguration
|
setKeyPair
|
class RSAEncryptionConfiguration extends AbstractEncryptionConfiguration {
private RSAPublicKey publicKey;
private RSAPrivateKey privateKey;
/**
* <p>Constructor for RSAEncryptionConfiguration.</p>
*/
public RSAEncryptionConfiguration() {
}
/**
* <p>Constructor for RSAEncryptionConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public RSAEncryptionConfiguration(final KeyPair keyPair) {
setKeyPair(keyPair);
}
/**
* <p>Constructor for RSAEncryptionConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
* @param algorithm a {@link JWEAlgorithm} object
* @param method a {@link EncryptionMethod} object
*/
public RSAEncryptionConfiguration(final KeyPair keyPair, final JWEAlgorithm algorithm, final EncryptionMethod method) {
setKeyPair(keyPair);
this.algorithm = algorithm;
this.method = method;
}
/** {@inheritDoc} */
@Override
public boolean supports(final JWEAlgorithm algorithm, final EncryptionMethod method) {
return algorithm != null && method != null
&& RSADecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)
&& RSADecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(method);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotNull("algorithm", algorithm);
CommonHelper.assertNotNull("method", method);
if (!supports(this.algorithm, this.method)) {
throw new TechnicalException("Only RSA algorithms are supported with the appropriate encryption method");
}
}
/** {@inheritDoc} */
@Override
protected JWEEncrypter buildEncrypter() {
CommonHelper.assertNotNull("publicKey", publicKey);
return new RSAEncrypter(this.publicKey);
}
/** {@inheritDoc} */
@Override
protected JWEDecrypter buildDecrypter() {
CommonHelper.assertNotNull("privateKey", privateKey);
return new RSADecrypter(this.privateKey);
}
/**
* <p>setKeyPair.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public void setKeyPair(final KeyPair keyPair) {<FILL_FUNCTION_BODY>}
/**
* <p>setKeysFromJwk.</p>
*
* @param json a {@link String} object
*/
public void setKeysFromJwk(final String json) {
val pair = JWKHelper.buildRSAKeyPairFromJwk(json);
this.publicKey = (RSAPublicKey) pair.getPublic();
this.privateKey = (RSAPrivateKey) pair.getPrivate();
}
}
|
CommonHelper.assertNotNull("keyPair", keyPair);
this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
this.publicKey = (RSAPublicKey) keyPair.getPublic();
| 774
| 55
| 829
|
<methods>public non-sealed void <init>() ,public void decrypt(com.nimbusds.jwt.EncryptedJWT) throws com.nimbusds.jose.JOSEException,public java.lang.String encrypt(com.nimbusds.jwt.JWT) <variables>protected com.nimbusds.jose.JWEAlgorithm algorithm,protected com.nimbusds.jose.EncryptionMethod method
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/config/encryption/SecretEncryptionConfiguration.java
|
SecretEncryptionConfiguration
|
supports
|
class SecretEncryptionConfiguration extends AbstractEncryptionConfiguration {
private byte[] secret;
/**
* <p>Constructor for SecretEncryptionConfiguration.</p>
*/
public SecretEncryptionConfiguration() {
algorithm = JWEAlgorithm.DIR;
method = EncryptionMethod.A256GCM;
}
/**
* <p>Constructor for SecretEncryptionConfiguration.</p>
*
* @param secret an array of {@link byte} objects
*/
public SecretEncryptionConfiguration(final byte[] secret){
this();
this.secret = Arrays.copyOf(secret, secret.length);
}
/**
* <p>Constructor for SecretEncryptionConfiguration.</p>
*
* @param secret a {@link String} object
*/
public SecretEncryptionConfiguration(final String secret) {
this(secret.getBytes(UTF_8));
}
/**
* <p>Constructor for SecretEncryptionConfiguration.</p>
*
* @param secret an array of {@link byte} objects
* @param algorithm a {@link JWEAlgorithm} object
* @param method a {@link EncryptionMethod} object
*/
public SecretEncryptionConfiguration(final byte[] secret, final JWEAlgorithm algorithm, final EncryptionMethod method) {
this.secret = Arrays.copyOf(secret,secret.length);
this.algorithm = algorithm;
this.method = method;
}
/**
* <p>Constructor for SecretEncryptionConfiguration.</p>
*
* @param secret a {@link String} object
* @param algorithm a {@link JWEAlgorithm} object
* @param method a {@link EncryptionMethod} object
*/
public SecretEncryptionConfiguration(final String secret, final JWEAlgorithm algorithm, final EncryptionMethod method) {
this(secret.getBytes(UTF_8), algorithm, method);
}
/** {@inheritDoc} */
@Override
public boolean supports(final JWEAlgorithm algorithm, final EncryptionMethod method) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotNull("secret", secret);
CommonHelper.assertNotNull("algorithm", algorithm);
CommonHelper.assertNotNull("method", method);
if (!supports(this.algorithm, this.method)) {
throw new TechnicalException("Only the direct and AES algorithms are supported with the appropriate encryption method");
}
}
/** {@inheritDoc} */
@Override
protected JWEEncrypter buildEncrypter() {
try {
if (DirectDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)) {
return new DirectEncrypter(this.secret);
} else {
return new AESEncrypter(this.secret);
}
} catch (final KeyLengthException e) {
throw new TechnicalException(e);
}
}
/** {@inheritDoc} */
@Override
protected JWEDecrypter buildDecrypter() {
try {
if (DirectDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)) {
return new DirectDecrypter(this.secret);
} else {
return new AESDecrypter(this.secret);
}
} catch (final KeyLengthException e) {
throw new TechnicalException(e);
}
}
/**
* <p>Getter for the field <code>secret</code>.</p>
*
* @return a {@link String} object
*/
public String getSecret() {
return new String(secret,UTF_8);
}
/**
* <p>Setter for the field <code>secret</code>.</p>
*
* @param secret a {@link String} object
*/
public void setSecret(final String secret) {
this.secret = secret.getBytes(UTF_8);
}
/**
* <p>getSecretBytes.</p>
*
* @return an array of {@link byte} objects
*/
public byte[] getSecretBytes() {
return Arrays.copyOf(secret,secret.length);
}
/**
* <p>setSecretBytes.</p>
*
* @param secretBytes an array of {@link byte} objects
*/
public void setSecretBytes(final byte[] secretBytes) {
this.secret = Arrays.copyOf(secretBytes,secretBytes.length);
}
/**
* <p>getSecretBase64.</p>
*
* @return a {@link String} object
*/
public String getSecretBase64() {
return Base64.encode(secret).toString();
}
/**
* <p>setSecretBase64.</p>
*
* @param secret a {@link String} object
*/
public void setSecretBase64(final String secret) {
this.secret = new Base64(secret).decode();
}
}
|
if (algorithm != null && method != null) {
val isDirect = DirectDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)
&& DirectDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(method);
val isAes = AESDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)
&& AESDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(method);
return isDirect || isAes;
}
return false;
| 1,301
| 143
| 1,444
|
<methods>public non-sealed void <init>() ,public void decrypt(com.nimbusds.jwt.EncryptedJWT) throws com.nimbusds.jose.JOSEException,public java.lang.String encrypt(com.nimbusds.jwt.JWT) <variables>protected com.nimbusds.jose.JWEAlgorithm algorithm,protected com.nimbusds.jose.EncryptionMethod method
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/config/signature/ECSignatureConfiguration.java
|
ECSignatureConfiguration
|
internalInit
|
class ECSignatureConfiguration extends AbstractSignatureConfiguration {
private ECPublicKey publicKey;
private ECPrivateKey privateKey;
/**
* <p>Constructor for ECSignatureConfiguration.</p>
*/
public ECSignatureConfiguration() {
algorithm = JWSAlgorithm.ES256;
}
/**
* <p>Constructor for ECSignatureConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public ECSignatureConfiguration(final KeyPair keyPair) {
this();
setKeyPair(keyPair);
}
/**
* <p>Constructor for ECSignatureConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
* @param algorithm a {@link JWSAlgorithm} object
*/
public ECSignatureConfiguration(final KeyPair keyPair, final JWSAlgorithm algorithm) {
setKeyPair(keyPair);
this.algorithm = algorithm;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public boolean supports(final JWSAlgorithm algorithm) {
return algorithm != null && ECDSAVerifier.SUPPORTED_ALGORITHMS.contains(algorithm);
}
/** {@inheritDoc} */
@Override
public SignedJWT sign(JWTClaimsSet claims) {
init();
CommonHelper.assertNotNull("privateKey", privateKey);
try {
JWSSigner signer = new ECDSASigner(this.privateKey);
val signedJWT = new SignedJWT(new JWSHeader(algorithm), claims);
signedJWT.sign(signer);
return signedJWT;
} catch (final JOSEException e) {
throw new TechnicalException(e);
}
}
/** {@inheritDoc} */
@Override
public boolean verify(final SignedJWT jwt) throws JOSEException {
init();
CommonHelper.assertNotNull("publicKey", publicKey);
JWSVerifier verifier = new ECDSAVerifier(this.publicKey);
return jwt.verify(verifier);
}
/**
* <p>setKeyPair.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public void setKeyPair(final KeyPair keyPair) {
CommonHelper.assertNotNull("keyPair", keyPair);
this.privateKey = (ECPrivateKey) keyPair.getPrivate();
this.publicKey = (ECPublicKey) keyPair.getPublic();
}
/**
* <p>setKeysFromJwk.</p>
*
* @param json a {@link String} object
*/
public void setKeysFromJwk(final String json) {
val pair = JWKHelper.buildECKeyPairFromJwk(json);
this.publicKey = (ECPublicKey) pair.getPublic();
this.privateKey = (ECPrivateKey) pair.getPrivate();
}
}
|
CommonHelper.assertNotNull("algorithm", algorithm);
if (!supports(this.algorithm)) {
throw new TechnicalException("Only the ES256, ES384 and ES512 algorithms are supported for elliptic curve signature");
}
| 822
| 63
| 885
|
<methods>public non-sealed void <init>() <variables>protected com.nimbusds.jose.JWSAlgorithm algorithm
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/config/signature/RSASignatureConfiguration.java
|
RSASignatureConfiguration
|
sign
|
class RSASignatureConfiguration extends AbstractSignatureConfiguration {
private RSAPublicKey publicKey;
private RSAPrivateKey privateKey;
/**
* <p>Constructor for RSASignatureConfiguration.</p>
*/
public RSASignatureConfiguration() {
algorithm = JWSAlgorithm.RS256;
}
/**
* <p>Constructor for RSASignatureConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public RSASignatureConfiguration(final KeyPair keyPair) {
this();
setKeyPair(keyPair);
}
/**
* <p>Constructor for RSASignatureConfiguration.</p>
*
* @param keyPair a {@link KeyPair} object
* @param algorithm a {@link JWSAlgorithm} object
*/
public RSASignatureConfiguration(final KeyPair keyPair, final JWSAlgorithm algorithm) {
setKeyPair(keyPair);
this.algorithm = algorithm;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotNull("algorithm", algorithm);
if (!supports(this.algorithm)) {
throw new TechnicalException("Only the RS256, RS384, RS512, PS256, PS384 and PS512 algorithms are supported for RSA signature");
}
}
/** {@inheritDoc} */
@Override
public boolean supports(final JWSAlgorithm algorithm) {
return algorithm != null && RSASSAVerifier.SUPPORTED_ALGORITHMS.contains(algorithm);
}
/** {@inheritDoc} */
@Override
public SignedJWT sign(JWTClaimsSet claims) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public boolean verify(final SignedJWT jwt) throws JOSEException {
init();
CommonHelper.assertNotNull("publicKey", publicKey);
JWSVerifier verifier = new RSASSAVerifier(this.publicKey);
return jwt.verify(verifier);
}
/**
* <p>setKeyPair.</p>
*
* @param keyPair a {@link KeyPair} object
*/
public void setKeyPair(final KeyPair keyPair) {
CommonHelper.assertNotNull("keyPair", keyPair);
this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
this.publicKey = (RSAPublicKey) keyPair.getPublic();
}
/**
* <p>setKeysFromJwk.</p>
*
* @param json a {@link String} object
*/
public void setKeysFromJwk(final String json) {
val pair = JWKHelper.buildRSAKeyPairFromJwk(json);
this.publicKey = (RSAPublicKey) pair.getPublic();
this.privateKey = (RSAPrivateKey) pair.getPrivate();
}
}
|
init();
CommonHelper.assertNotNull("privateKey", privateKey);
try {
JWSSigner signer = new RSASSASigner(this.privateKey);
val signedJWT = new SignedJWT(new JWSHeader(algorithm), claims);
signedJWT.sign(signer);
return signedJWT;
} catch (final JOSEException e) {
throw new TechnicalException(e);
}
| 782
| 117
| 899
|
<methods>public non-sealed void <init>() <variables>protected com.nimbusds.jose.JWSAlgorithm algorithm
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/config/signature/SecretSignatureConfiguration.java
|
SecretSignatureConfiguration
|
sign
|
class SecretSignatureConfiguration extends AbstractSignatureConfiguration {
private byte[] secret;
/**
* <p>Constructor for SecretSignatureConfiguration.</p>
*/
public SecretSignatureConfiguration() {
algorithm = JWSAlgorithm.HS256;
}
/**
* <p>Constructor for SecretSignatureConfiguration.</p>
*
* @param secret a {@link String} object
*/
public SecretSignatureConfiguration(final String secret) {
this(secret.getBytes(UTF_8));
}
/**
* <p>Constructor for SecretSignatureConfiguration.</p>
*
* @param secret an array of {@link byte} objects
*/
public SecretSignatureConfiguration(final byte[] secret) {
this();
this.secret = Arrays.copyOf(secret,secret.length);
}
/**
* <p>Constructor for SecretSignatureConfiguration.</p>
*
* @param secret a {@link String} object
* @param algorithm a {@link JWSAlgorithm} object
*/
public SecretSignatureConfiguration(final String secret, final JWSAlgorithm algorithm) {
this(secret.getBytes(UTF_8),algorithm);
}
/**
* <p>Constructor for SecretSignatureConfiguration.</p>
*
* @param secret an array of {@link byte} objects
* @param algorithm a {@link JWSAlgorithm} object
*/
public SecretSignatureConfiguration(final byte[] secret, final JWSAlgorithm algorithm) {
this.secret = Arrays.copyOf(secret,secret.length);
this.algorithm = algorithm;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotNull("algorithm", algorithm);
CommonHelper.assertNotNull("secret", secret);
if (!supports(this.algorithm)) {
throw new TechnicalException("Only the HS256, HS384 and HS512 algorithms are supported for HMac signature");
}
}
/** {@inheritDoc} */
@Override
public boolean supports(final JWSAlgorithm algorithm) {
return algorithm != null && MACVerifier.SUPPORTED_ALGORITHMS.contains(algorithm);
}
/** {@inheritDoc} */
@Override
public SignedJWT sign(final JWTClaimsSet claims) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public boolean verify(final SignedJWT jwt) throws JOSEException {
init();
JWSVerifier verifier = new MACVerifier(this.secret);
return jwt.verify(verifier);
}
/**
* <p>Getter for the field <code>secret</code>.</p>
*
* @return a {@link String} object
*/
public String getSecret() {
return new String(secret,UTF_8);
}
/**
* <p>Setter for the field <code>secret</code>.</p>
*
* @param secret a {@link String} object
*/
public void setSecret(final String secret) {
this.secret = secret.getBytes(UTF_8);
}
/**
* <p>getSecretBytes.</p>
*
* @return an array of {@link byte} objects
*/
public byte[] getSecretBytes() {
return Arrays.copyOf(secret,secret.length);
}
/**
* <p>setSecretBytes.</p>
*
* @param secretBytes an array of {@link byte} objects
*/
public void setSecretBytes(final byte[] secretBytes) {
this.secret = Arrays.copyOf(secretBytes,secretBytes.length);
}
/**
* <p>getSecretBase64.</p>
*
* @return a {@link String} object
*/
public String getSecretBase64() {
return Base64.encode(secret).toString();
}
/**
* <p>setSecretBase64.</p>
*
* @param secret a {@link String} object
*/
public void setSecretBase64(final String secret) {
this.secret = new Base64(secret).decode();
}
}
|
init();
try {
JWSSigner signer = new MACSigner(this.secret);
val signedJWT = new SignedJWT(new JWSHeader(algorithm), claims);
signedJWT.sign(signer);
return signedJWT;
} catch (final JOSEException e) {
throw new TechnicalException(e);
}
| 1,104
| 99
| 1,203
|
<methods>public non-sealed void <init>() <variables>protected com.nimbusds.jose.JWSAlgorithm algorithm
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/profile/JwtGenerator.java
|
JwtGenerator
|
generate
|
class JwtGenerator {
/** Constant <code>INTERNAL_ROLES="$int_roles"</code> */
public static final String INTERNAL_ROLES = "$int_roles";
/** Constant <code>INTERNAL_LINKEDID="$int_linkid"</code> */
public static final String INTERNAL_LINKEDID = "$int_linkid";
private SignatureConfiguration signatureConfiguration;
private EncryptionConfiguration encryptionConfiguration;
private Date expirationTime;
/**
* <p>Constructor for JwtGenerator.</p>
*/
public JwtGenerator() {}
/**
* <p>Constructor for JwtGenerator.</p>
*
* @param signatureConfiguration a {@link SignatureConfiguration} object
*/
public JwtGenerator(final SignatureConfiguration signatureConfiguration) {
this.signatureConfiguration = signatureConfiguration;
}
/**
* <p>Constructor for JwtGenerator.</p>
*
* @param signatureConfiguration a {@link SignatureConfiguration} object
* @param encryptionConfiguration a {@link EncryptionConfiguration} object
*/
public JwtGenerator(final SignatureConfiguration signatureConfiguration, final EncryptionConfiguration encryptionConfiguration) {
this.signatureConfiguration = signatureConfiguration;
this.encryptionConfiguration = encryptionConfiguration;
}
/**
* Generate a JWT from a map of claims.
*
* @param claims the map of claims
* @return the created JWT
*/
public String generate(final Map<String, Object> claims) {<FILL_FUNCTION_BODY>}
/**
* Generate a JWT from a user profile.
*
* @param profile the given user profile
* @return the created JWT
*/
public String generate(final UserProfile profile) {
verifyProfile(profile);
return internalGenerate(buildJwtClaimsSet(profile));
}
/**
* Generate a JWT from a claims set.
*
* @param claimsSet the claims set
* @return the JWT
*/
protected String internalGenerate(final JWTClaimsSet claimsSet) {
JWT jwt;
// signature?
if (signatureConfiguration == null) {
jwt = new PlainJWT(claimsSet);
} else {
jwt = signatureConfiguration.sign(claimsSet);
}
// encryption?
if (encryptionConfiguration != null) {
return encryptionConfiguration.encrypt(jwt);
} else {
return jwt.serialize();
}
}
/**
* <p>verifyProfile.</p>
*
* @param profile a {@link UserProfile} object
*/
protected void verifyProfile(final UserProfile profile) {
CommonHelper.assertNotNull("profile", profile);
CommonHelper.assertNull(INTERNAL_ROLES, profile.getAttribute(INTERNAL_ROLES));
CommonHelper.assertNull(INTERNAL_LINKEDID, profile.getAttribute(INTERNAL_LINKEDID));
}
/**
* <p>buildJwtClaimsSet.</p>
*
* @param profile a {@link UserProfile} object
* @return a {@link JWTClaimsSet} object
*/
protected JWTClaimsSet buildJwtClaimsSet(final UserProfile profile) {
// claims builder with subject and issue time
val builder = new JWTClaimsSet.Builder()
.issueTime(new Date());
if (this.expirationTime != null) {
builder.expirationTime(this.expirationTime);
}
// add attributes
val attributes = profile.getAttributes();
for (val entry : attributes.entrySet()) {
builder.claim(entry.getKey(), entry.getValue());
}
builder.claim(INTERNAL_ROLES, profile.getRoles());
builder.claim(INTERNAL_LINKEDID, profile.getLinkedId());
builder.subject(profile.getTypedId());
// claims
return builder.build();
}
/**
* <p>Getter for the field <code>expirationTime</code>.</p>
*
* @return a {@link Date} object
*/
public Date getExpirationTime() {
return new Date(expirationTime.getTime());
}
/**
* <p>Setter for the field <code>expirationTime</code>.</p>
*
* @param expirationTime a {@link Date} object
*/
public void setExpirationTime(final Date expirationTime) {
this.expirationTime = new Date(expirationTime.getTime());
}
}
|
// claims builder
val builder = new JWTClaimsSet.Builder();
// add claims
for (val entry : claims.entrySet()) {
builder.claim(entry.getKey(), entry.getValue());
}
if (this.expirationTime != null) {
builder.expirationTime(this.expirationTime);
}
return internalGenerate(builder.build());
| 1,209
| 102
| 1,311
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/profile/JwtProfileDefinition.java
|
JwtProfileDefinition
|
convertAndAdd
|
class JwtProfileDefinition extends CommonProfileDefinition {
private boolean keepNestedAttributes = true;
/**
* <p>Constructor for JwtProfileDefinition.</p>
*/
public JwtProfileDefinition() {
super(x -> new JwtProfile());
setRestoreProfileFromTypedId(true);
}
/** {@inheritDoc} */
@Override
public void convertAndAdd(UserProfile profile, AttributeLocation attributeLocation, String name, Object value) {<FILL_FUNCTION_BODY>}
/**
* <p>Setter for the field <code>keepNestedAttributes</code>.</p>
*
* @param keepNestedAttributes a boolean
*/
public void setKeepNestedAttributes(boolean keepNestedAttributes) {
this.keepNestedAttributes = keepNestedAttributes;
}
}
|
if (value instanceof Map) {
var jsonObject = (Map<String, ?>) value;
jsonObject.forEach((key, objectValue) -> super.convertAndAdd(profile, attributeLocation, key, objectValue));
if (keepNestedAttributes) {
super.convertAndAdd(profile, attributeLocation, name, value);
}
} else {
super.convertAndAdd(profile, attributeLocation, name, value);
}
| 217
| 113
| 330
|
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) <variables>public static final java.lang.String DISPLAY_NAME,public static final java.lang.String EMAIL,public static final java.lang.String FAMILY_NAME,public static final java.lang.String FIRST_NAME,public static final java.lang.String GENDER,public static final java.lang.String LOCALE,public static final java.lang.String LOCATION,public static final java.lang.String PICTURE_URL,public static final java.lang.String PROFILE_URL
|
pac4j_pac4j
|
pac4j/pac4j-jwt/src/main/java/org/pac4j/jwt/util/JWKHelper.java
|
JWKHelper
|
buildECKeyPairFromJwk
|
class JWKHelper {
/**
* Build the secret from the JWK JSON.
*
* @param json the json
* @return the secret
*/
public static String buildSecretFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
val octetSequenceKey = OctetSequenceKey.parse(json);
return new String(octetSequenceKey.toByteArray(), "UTF-8");
} catch (final UnsupportedEncodingException | ParseException e) {
throw new TechnicalException(e);
}
}
/**
* Build the RSA key pair from the JWK JSON.
*
* @param json the json
* @return the key pair
*/
public static KeyPair buildRSAKeyPairFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
val rsaKey = RSAKey.parse(json);
return rsaKey.toKeyPair();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
}
/**
* Build the EC key pair from the JWK JSON.
*
* @param json the json
* @return the key pair
*/
public static KeyPair buildECKeyPairFromJwk(final String json) {<FILL_FUNCTION_BODY>}
}
|
CommonHelper.assertNotBlank("json", json);
try {
val ecKey = ECKey.parse(json);
return ecKey.toKeyPair();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
| 364
| 73
| 437
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-kerberos/src/main/java/org/pac4j/kerberos/client/direct/DirectKerberosClient.java
|
DirectKerberosClient
|
getCredentials
|
class DirectKerberosClient extends DirectClient {
/**
* <p>Constructor for DirectKerberosClient.</p>
*/
public DirectKerberosClient() {
}
/**
* <p>Constructor for DirectKerberosClient.</p>
*
* @param authenticator a {@link Authenticator} object
*/
public DirectKerberosClient(final Authenticator authenticator) {
setAuthenticator(authenticator);
}
/**
* <p>Constructor for DirectKerberosClient.</p>
*
* @param authenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public DirectKerberosClient(final Authenticator authenticator, final ProfileCreator profileCreator) {
setAuthenticator(authenticator);
setProfileCreator(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
setCredentialsExtractorIfUndefined(new KerberosExtractor());
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> getCredentials(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
// Set the WWW-Authenticate: Negotiate header in case no credentials are found
// to trigger the SPNEGO process by replying with 401 Unauthorized
ctx.webContext().setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Negotiate");
return super.getCredentials(ctx);
| 334
| 85
| 419
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-kerberos/src/main/java/org/pac4j/kerberos/client/indirect/IndirectKerberosClient.java
|
IndirectKerberosClient
|
getCredentials
|
class IndirectKerberosClient extends IndirectClient {
/**
* <p>Constructor for IndirectKerberosClient.</p>
*/
public IndirectKerberosClient() {}
/**
* <p>Constructor for IndirectKerberosClient.</p>
*
* @param authenticator a {@link Authenticator} object
*/
public IndirectKerberosClient(final Authenticator authenticator) {
setAuthenticatorIfUndefined(authenticator);
}
/**
* <p>Constructor for IndirectKerberosClient.</p>
*
* @param authenticator a {@link Authenticator} object
* @param profileCreator a {@link ProfileCreator} object
*/
public IndirectKerberosClient(final Authenticator authenticator, final ProfileCreator profileCreator) {
setAuthenticatorIfUndefined(authenticator);
setProfileCreatorIfUndefined(profileCreator);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
setRedirectionActionBuilderIfUndefined(ctx -> {
val webContext = ctx.webContext();
return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, computeFinalCallbackUrl(webContext)));
});
setCredentialsExtractorIfUndefined(new KerberosExtractor());
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> getCredentials(final CallContext ctx) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected Optional<Credentials> internalValidateCredentials(final CallContext ctx, final Credentials credentials) {
CommonHelper.assertNotNull("authenticator", getAuthenticator());
val webContext = ctx.webContext();
// set the www-authenticate in case of error
webContext.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Negotiate");
try {
return getAuthenticator().validate(ctx, credentials);
} catch (final CredentialsException e) {
throw HttpActionHelper.buildUnauthenticatedAction(webContext);
}
}
}
|
init();
CommonHelper.assertNotNull("credentialsExtractor", getCredentialsExtractor());
val webContext = ctx.webContext();
// set the www-authenticate in case of error
webContext.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Negotiate");
final Optional<Credentials> credentials;
try {
credentials = getCredentialsExtractor().extract(ctx);
logger.debug("kerberos credentials : {}", credentials);
if (credentials.isEmpty()) {
throw HttpActionHelper.buildUnauthenticatedAction(webContext);
}
return credentials;
} catch (final CredentialsException e) {
throw HttpActionHelper.buildUnauthenticatedAction(webContext);
}
| 572
| 191
| 763
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-kerberos/src/main/java/org/pac4j/kerberos/credentials/KerberosCredentials.java
|
KerberosCredentials
|
equals
|
class KerberosCredentials extends Credentials {
private byte[] kerberosTicket;
/**
*
*/
@Serial
private static final long serialVersionUID = -4264156105410684508L;
/**
* <p>Constructor for KerberosCredentials.</p>
*
* @param kerberosTicket an array of {@link byte} objects
*/
public KerberosCredentials(byte[] kerberosTicket) {
this.kerberosTicket = kerberosTicket.clone();
}
/**
* <p>getKerberosTicketAsString.</p>
*
* @return a {@link String} object
*/
public String getKerberosTicketAsString() {
return getTicketAsString(kerberosTicket);
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public int hashCode() {
return kerberosTicket != null ? getTicketAsString(kerberosTicket).hashCode() : 0;
}
private String getTicketAsString(byte[] kerberosTicket) {
return new String(kerberosTicket, StandardCharsets.UTF_8);
}
/**
* <p>Getter for the field <code>kerberosTicket</code>.</p>
*
* @return an array of {@link byte} objects
*/
public byte[] getKerberosTicket() {
return kerberosTicket.clone();
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
var that = (KerberosCredentials) o;
return !(kerberosTicket != null ? !getTicketAsString(kerberosTicket).equals(getTicketAsString(that.kerberosTicket))
: that.kerberosTicket != null);
| 451
| 113
| 564
|
<methods>public non-sealed void <init>() ,public boolean isForAuthentication() <variables>protected org.pac4j.core.logout.LogoutType logoutType,private static final long serialVersionUID,protected java.lang.String source,private org.pac4j.core.profile.UserProfile userProfile
|
pac4j_pac4j
|
pac4j/pac4j-kerberos/src/main/java/org/pac4j/kerberos/credentials/authenticator/KerberosAuthenticator.java
|
KerberosAuthenticator
|
validate
|
class KerberosAuthenticator implements Authenticator {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected KerberosTicketValidator ticketValidator;
/**
* Initializes the authenticator that will validate Kerberos tickets.
*
* @param ticketValidator The ticket validator used to validate the Kerberos ticket.
* @since 2.1.0
*/
public KerberosAuthenticator(KerberosTicketValidator ticketValidator) {
CommonHelper.assertNotNull("ticketValidator", ticketValidator);
this.ticketValidator = ticketValidator;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials cred) {<FILL_FUNCTION_BODY>}
}
|
val credentials = (KerberosCredentials) cred;
logger.trace("Try to validate Kerberos Token:" + credentials.getKerberosTicketAsString());
var ticketValidation = this.ticketValidator.validateTicket(credentials.getKerberosTicket());
logger.debug("Kerberos Token validated");
var subject = ticketValidation.username();
logger.debug("Succesfully validated " + subject);
UserProfile profile = new KerberosProfile(ticketValidation.getGssContext());
profile.setId(subject);
credentials.setUserProfile(profile);
return Optional.of(credentials);
| 206
| 168
| 374
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-kerberos/src/main/java/org/pac4j/kerberos/credentials/authenticator/KerberosTicketValidation.java
|
KerberosTicketValidation
|
subject
|
class KerberosTicketValidation {
private final String username;
private final byte[] responseToken;
private final GSSContext gssContext;
private final String servicePrincipal;
/**
* <p>Constructor for KerberosTicketValidation.</p>
*
* @param username a {@link String} object
* @param servicePrincipal a {@link String} object
* @param responseToken an array of {@link byte} objects
* @param gssContext a GSSContext object
*/
public KerberosTicketValidation(String username, String servicePrincipal, byte[] responseToken, GSSContext gssContext) {
this.username = username;
this.servicePrincipal = servicePrincipal;
if (responseToken != null) {
this.responseToken = responseToken.clone();
} else {
this.responseToken = null;
}
this.gssContext = gssContext;
}
/**
* <p>username.</p>
*
* @return a {@link String} object
*/
public String username() {
return username;
}
/**
* <p>responseToken.</p>
*
* @return an array of {@link byte} objects
*/
public byte[] responseToken() {
return responseToken.clone();
}
/**
* <p>Getter for the field <code>gssContext</code>.</p>
*
* @return a GSSContext object
*/
public GSSContext getGssContext() {
return gssContext;
}
/**
* <p>subject.</p>
*
* @return a {@link Subject} object
*/
public Subject subject() {<FILL_FUNCTION_BODY>}
}
|
final Set<KerberosPrincipal> princs = new HashSet<>();
princs.add(new KerberosPrincipal(servicePrincipal));
return new Subject(false, princs, new HashSet<>(), new HashSet<>());
| 466
| 67
| 533
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-kerberos/src/main/java/org/pac4j/kerberos/credentials/extractor/KerberosExtractor.java
|
KerberosExtractor
|
extract
|
class KerberosExtractor implements CredentialsExtractor {
/** {@inheritDoc} */
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val optHeader = ctx.webContext().getRequestHeader(HttpConstants.AUTHORIZATION_HEADER);
if (optHeader.isEmpty()) {
return Optional.empty();
}
val header = optHeader.get();
if (!(header.startsWith("Negotiate ") || header.startsWith("Kerberos "))) {
// "Authorization" header do not indicate Kerberos mechanism yet,
// so the extractor shouldn't throw an exception
return Optional.empty();
}
var base64Token = header.substring(header.indexOf(" ") + 1).getBytes(StandardCharsets.UTF_8);
var kerberosTicket = Base64.getDecoder().decode(base64Token);
return Optional.of(new KerberosCredentials(kerberosTicket));
| 58
| 211
| 269
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-mongo/src/main/java/org/pac4j/mongo/profile/service/MongoProfileService.java
|
MongoProfileService
|
insert
|
class MongoProfileService extends AbstractProfileService<MongoProfile> {
private MongoClient mongoClient;
private String usersDatabase = "users";
private String usersCollection = "users";
/**
* <p>Constructor for MongoProfileService.</p>
*/
public MongoProfileService() {}
/**
* <p>Constructor for MongoProfileService.</p>
*
* @param mongoClient a {@link MongoClient} object
*/
public MongoProfileService(final MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
/**
* <p>Constructor for MongoProfileService.</p>
*
* @param mongoClient a {@link MongoClient} object
* @param attributes a {@link String} object
*/
public MongoProfileService(final MongoClient mongoClient, final String attributes) {
this.mongoClient = mongoClient;
setAttributes(attributes);
}
/**
* <p>Constructor for MongoProfileService.</p>
*
* @param mongoClient a {@link MongoClient} object
* @param attributes a {@link String} object
* @param passwordEncoder a {@link PasswordEncoder} object
*/
public MongoProfileService(final MongoClient mongoClient, final String attributes, final PasswordEncoder passwordEncoder) {
this.mongoClient = mongoClient;
setAttributes(attributes);
setPasswordEncoder(passwordEncoder);
}
/**
* <p>Constructor for MongoProfileService.</p>
*
* @param mongoClient a {@link MongoClient} object
* @param passwordEncoder a {@link PasswordEncoder} object
*/
public MongoProfileService(final MongoClient mongoClient, final PasswordEncoder passwordEncoder) {
this.mongoClient = mongoClient;
setPasswordEncoder(passwordEncoder);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotNull("passwordEncoder", getPasswordEncoder());
CommonHelper.assertNotNull("mongoClient", this.mongoClient);
CommonHelper.assertNotBlank("usersDatabase", this.usersDatabase);
CommonHelper.assertNotBlank("usersCollection", this.usersCollection);
setProfileDefinitionIfUndefined(new CommonProfileDefinition(x -> new MongoProfile()));
setSerializer(new JsonSerializer(MongoProfile.class));
super.internalInit(forceReinit);
}
/** {@inheritDoc} */
@Override
protected void insert(final Map<String, Object> attributes) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected void update(final Map<String, Object> attributes) {
String id = null;
val doc = new Document();
for (val entry : attributes.entrySet()) {
val name = entry.getKey();
val value = entry.getValue();
if (getIdAttribute().equals(name)) {
id = (String) value;
} else {
doc.append(entry.getKey(), entry.getValue());
}
}
CommonHelper.assertNotNull(ID, id);
logger.debug("Updating id: {} with doc: {}", id, doc);
getCollection().updateOne(eq(getIdAttribute(), id), new Document("$set", doc));
}
/** {@inheritDoc} */
@Override
protected void deleteById(final String id) {
logger.debug("Delete id: {}", id);
getCollection().deleteOne(eq(getIdAttribute(), id));
}
/** {@inheritDoc} */
@Override
protected List<Map<String, Object>> read(final List<String> names, final String key, final String value) {
logger.debug("Reading key / value: {} / {}", key, value);
List<Map<String, Object>> listAttributes = new ArrayList<>();
try (val cursor = getCollection().find(eq(key, value)).iterator()) {
var i = 0;
while (cursor.hasNext() && i <= 2) {
val result = cursor.next();
Map<String, Object> newAttributes = new HashMap<>();
// filter on names
for (val entry : result.entrySet()) {
val name = entry.getKey();
if (names == null || names.contains(name)) {
newAttributes.put(name, entry.getValue());
}
}
listAttributes.add(newAttributes);
i++;
}
}
logger.debug("Found: {}", listAttributes);
return listAttributes;
}
/**
* <p>getCollection.</p>
*
* @return a {@link MongoCollection} object
*/
protected MongoCollection<Document> getCollection() {
val db = mongoClient.getDatabase(usersDatabase);
return db.getCollection(usersCollection);
}
}
|
val doc = new Document();
for (val entry : attributes.entrySet()) {
doc.append(entry.getKey(), entry.getValue());
}
logger.debug("Insert doc: {}", doc);
getCollection().insertOne(doc);
| 1,268
| 66
| 1,334
|
<methods>public non-sealed void <init>() ,public void create(org.pac4j.mongo.profile.MongoProfile, java.lang.String) ,public org.pac4j.mongo.profile.MongoProfile findById(java.lang.String) ,public org.pac4j.mongo.profile.MongoProfile findByLinkedId(java.lang.String) ,public void remove(org.pac4j.mongo.profile.MongoProfile) ,public void removeById(java.lang.String) ,public void update(org.pac4j.mongo.profile.MongoProfile, java.lang.String) ,public Optional<org.pac4j.core.credentials.Credentials> validate(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ID,public static final java.lang.String LINKEDID,public static final java.lang.String SERIALIZED_PROFILE,protected java.lang.String[] attributeNames,private java.lang.String attributes,private java.lang.String idAttribute,protected final org.slf4j.Logger logger,private java.lang.String passwordAttribute,private org.pac4j.core.credentials.password.PasswordEncoder passwordEncoder,private org.pac4j.core.util.serializer.Serializer serializer,private java.lang.String usernameAttribute
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/BitbucketClient.java
|
BitbucketClient
|
internalInit
|
class BitbucketClient extends OAuth10Client {
/**
* <p>Constructor for BitbucketClient.</p>
*/
public BitbucketClient() {
}
/**
* <p>Constructor for BitbucketClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public BitbucketClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
configuration.setApi(new BitBucketApi());
configuration.setProfileDefinition(new BitbucketProfileDefinition());
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://bitbucket.org/account/signout/")));
super.internalInit(forceReinit);
| 175
| 101
| 276
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth10Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/CasOAuthWrapperClient.java
|
CasOAuthWrapperClient
|
setCasOAuthUrl
|
class CasOAuthWrapperClient extends OAuth20Client {
/**
* The CAS OAuth server url (without a trailing slash).
* For example: http://localhost:8080/cas/oauth2.0
*/
private String casOAuthUrl;
private String casLogoutUrl;
// can be false for older CAS server versions
private boolean isJsonTokenExtractor = true;
// can be Verb.PUT for older CAS server versions
private Verb accessTokenVerb = Verb.POST;
private boolean implicitFlow = false;
/**
* <p>Constructor for CasOAuthWrapperClient.</p>
*/
public CasOAuthWrapperClient() {
}
/**
* <p>Constructor for CasOAuthWrapperClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
* @param casOAuthUrl a {@link String} object
*/
public CasOAuthWrapperClient(final String key, final String secret, final String casOAuthUrl) {
setKey(key);
setSecret(secret);
setCasOAuthUrl(casOAuthUrl);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotBlank("casOAuthUrl", this.casOAuthUrl);
configuration.setApi(new CasOAuthWrapperApi20(this.casOAuthUrl, this.isJsonTokenExtractor, this.accessTokenVerb));
configuration.setProfileDefinition(new CasOAuthWrapperProfileDefinition());
if (this.implicitFlow) {
configuration.setResponseType("token");
} else {
configuration.setResponseType("code");
}
setLogoutActionBuilderIfUndefined(new CasLogoutActionBuilder(casLogoutUrl, "service"));
super.internalInit(forceReinit);
}
/**
* <p>Setter for the field <code>casOAuthUrl</code>.</p>
*
* @param casOAuthUrl a {@link String} object
*/
public void setCasOAuthUrl(final String casOAuthUrl) {<FILL_FUNCTION_BODY>}
}
|
CommonHelper.assertNotBlank("casOAuthUrl", casOAuthUrl);
if (casOAuthUrl.endsWith("/")) {
this.casOAuthUrl = casOAuthUrl.substring(0, casOAuthUrl.length() - 1);
} else {
this.casOAuthUrl = casOAuthUrl;
}
| 575
| 89
| 664
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/CronofyClient.java
|
CronofyClient
|
internalInit
|
class CronofyClient extends OAuth20Client {
private String sdkIdentifier = Pac4jConstants.EMPTY_STRING;
private String scope = "read_free_busy";
/**
* <p>Constructor for CronofyClient.</p>
*/
public CronofyClient() {
}
/**
* <p>Constructor for CronofyClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public CronofyClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>Getter for the field <code>scope</code>.</p>
*
* @return a {@link String} object
*/
public String getScope() {
return scope;
}
/**
* <p>Setter for the field <code>scope</code>.</p>
*
* @param scope a {@link String} object
*/
public void setScope(final String scope) {
this.scope = scope;
}
/**
* <p>Getter for the field <code>sdkIdentifier</code>.</p>
*
* @return a {@link String} object
*/
public String getSdkIdentifier() {
return sdkIdentifier;
}
/**
* <p>Setter for the field <code>sdkIdentifier</code>.</p>
*
* @param sdkIdentifier a {@link String} object
*/
public void setSdkIdentifier(final String sdkIdentifier) {
this.sdkIdentifier = sdkIdentifier;
}
}
|
configuration.setApi(new CronofyApi20(sdkIdentifier));
configuration.setProfileDefinition(new CronofyProfileDefinition());
configuration.setScope(scope);
configuration.setWithState(true);
setProfileCreatorIfUndefined(new CronofyProfileCreator(configuration, this));
super.internalInit(forceReinit);
| 490
| 93
| 583
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/DropBoxClient.java
|
DropBoxClient
|
internalInit
|
class DropBoxClient extends OAuth20Client {
/**
* <p>Constructor for DropBoxClient.</p>
*/
public DropBoxClient() {
}
/**
* <p>Constructor for DropBoxClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public DropBoxClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
configuration.setApi(DropboxApi20.INSTANCE);
configuration.setProfileDefinition(new DropBoxProfileDefinition());
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://www.dropbox.com/logout")));
setProfileCreatorIfUndefined(new DropBoxProfileCreator(configuration, this));
super.internalInit(forceReinit);
| 170
| 124
| 294
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/FacebookClient.java
|
FacebookClient
|
internalInit
|
class FacebookClient extends OAuth20Client {
/**
* <p>Constructor for FacebookClient.</p>
*/
public FacebookClient() {
configuration = new FacebookConfiguration();
}
/**
* <p>Constructor for FacebookClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public FacebookClient(final String key, final String secret) {
configuration = new FacebookConfiguration();
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public FacebookConfiguration getConfiguration() {
return (FacebookConfiguration) configuration;
}
/**
* <p>getScope.</p>
*
* @return a {@link String} object
*/
public String getScope() {
return getConfiguration().getScope();
}
/**
* <p>setScope.</p>
*
* @param scope a {@link String} object
*/
public void setScope(final String scope) {
getConfiguration().setScope(scope);
}
/**
* <p>getFields.</p>
*
* @return a {@link String} object
*/
public String getFields() {
return getConfiguration().getFields();
}
/**
* <p>setFields.</p>
*
* @param fields a {@link String} object
*/
public void setFields(final String fields) {
getConfiguration().setFields(fields);
}
/**
* <p>getLimit.</p>
*
* @return a int
*/
public int getLimit() {
return getConfiguration().getLimit();
}
/**
* <p>setLimit.</p>
*
* @param limit a int
*/
public void setLimit(final int limit) {
getConfiguration().setLimit(limit);
}
}
|
CommonHelper.assertNotBlank("fields", getConfiguration().getFields());
configuration.setApi(FacebookApi.instance());
configuration.setProfileDefinition(new FacebookProfileDefinition());
configuration.setHasBeenCancelledFactory(ctx -> {
val error = ctx.getRequestParameter(OAuthCredentialsException.ERROR).orElse(null);
val errorReason = ctx.getRequestParameter(OAuthCredentialsException.ERROR_REASON).orElse(null);
val userDenied = "access_denied".equals(error) && "user_denied".equals(errorReason);
val errorCode = ctx.getRequestParameter("error_code").orElse(null);
val errorMessage = ctx.getRequestParameter("error_message").orElse(null);
val hasError = CommonHelper.isNotBlank(errorCode) || CommonHelper.isNotBlank(errorMessage);
if (userDenied || hasError) {
return true;
} else {
return false;
}
});
configuration.setWithState(true);
setProfileCreatorIfUndefined(new FacebookProfileCreator(configuration, this));
super.internalInit(forceReinit);
| 550
| 296
| 846
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/FigShareClient.java
|
FigShareClient
|
internalInit
|
class FigShareClient extends OAuth20Client {
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
val api = new FigShareApi20();
configuration.setApi(api);
val profileDefinition = new FigShareProfileDefinition();
profileDefinition.setProfileId("id");
configuration.setProfileDefinition(profileDefinition);
configuration.setScope("all");
configuration.setWithState(true);
setProfileCreatorIfUndefined(new FigShareProfileCreator(configuration, this));
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) -> Optional
.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://figshare.com/account/logout")));
super.internalInit(forceReinit);
| 53
| 171
| 224
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/FoursquareClient.java
|
FoursquareClient
|
internalInit
|
class FoursquareClient extends OAuth20Client {
/**
* <p>Constructor for FoursquareClient.</p>
*/
public FoursquareClient() {}
/**
* <p>Constructor for FoursquareClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public FoursquareClient(String key, String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
CommonHelper.assertNotNull("configuration", configuration);
configuration.setApi(Foursquare2Api.instance());
configuration.setProfileDefinition(new FoursquareProfileDefinition());
configuration.setScope("user");
setProfileCreatorIfUndefined(new FoursquareProfileCreator(configuration, this));
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://www.foursquare.com/logout")));
super.internalInit(forceReinit);
| 170
| 146
| 316
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/GenericOAuth20Client.java
|
GenericOAuth20Client
|
internalInit
|
class GenericOAuth20Client extends OAuth20Client {
private String authUrl;
private String tokenUrl;
private String profileUrl;
private String profilePath;
private String profileId;
private String scope;
private boolean withState;
private String clientAuthenticationMethod;
private Verb profileVerb;
private Map<String, String> profileAttrs;
private Map<String, String> customParams;
private List<Class<? extends AbstractAttributeConverter>> converterClasses;
/**
* <p>Constructor for GenericOAuth20Client.</p>
*/
public GenericOAuth20Client() {
}
private static List<Class<? extends AbstractAttributeConverter>> findAttributeConverterClasses() {
try {
var reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage(AttributeConverter.class.getPackageName())));
var subTypes = reflections.getSubTypesOf(AbstractAttributeConverter.class);
return subTypes.stream()
.filter(c -> !Modifier.isAbstract(c.getModifiers()))
.collect(Collectors.toList());
} catch (Exception e) {
LOGGER.warn(e.toString());
}
return new ArrayList<>(0);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
AbstractAttributeConverter getConverter(final String typeName) {
try {
var acceptableConverters = this.converterClasses.stream()
.filter(x -> {
try {
var converter = (AbstractAttributeConverter) x.getDeclaredConstructor().newInstance();
var accept = AbstractAttributeConverter.class.getDeclaredMethod("accept", String.class);
return (Boolean) accept.invoke(converter, typeName);
} catch (ReflectiveOperationException e) {
LOGGER.warn("Ignore type which no parameterless constructor:" + x.getName());
}
return false;
});
var converterClazz = acceptableConverters.findFirst().orElse(null);
if (converterClazz != null) {
return converterClazz.getDeclaredConstructor().newInstance();
}
} catch (Exception e) {
LOGGER.warn(e.toString());
}
return null;
}
/**
* <p>getConverters.</p>
*
* @return a {@link List} object
*/
public List<Class<? extends AbstractAttributeConverter>> getConverters() {
return List.copyOf(converterClasses);
}
/**
* Add attribute converter.
*
* @param converter the converter
*/
public void addAttributeConverter(final Class<AbstractAttributeConverter> converter) {
this.converterClasses.add(converter);
}
}
|
this.converterClasses = findAttributeConverterClasses();
val genApi = new GenericApi20(authUrl, tokenUrl);
configuration.setApi(genApi);
if (clientAuthenticationMethod != null) {
genApi.setClientAuthenticationMethod(clientAuthenticationMethod);
}
configuration.setCustomParams(customParams);
var profileDefinition = new GenericOAuth20ProfileDefinition();
profileDefinition.setFirstNodePath(profilePath);
profileDefinition.setProfileVerb(profileVerb);
profileDefinition.setProfileUrl(profileUrl);
profileDefinition.setProfileId(Objects.requireNonNullElse(profileId, "id"));
if (profileAttrs != null) {
for (var entry : profileAttrs.entrySet()) {
var key = entry.getKey();
var value = entry.getValue();
var tokens = value.split("\\|");
if (tokens.length == 2) {
profileDefinition.profileAttribute(key, tokens[1], getConverter(tokens[0]));
} else if (tokens.length == 1) {
profileDefinition.profileAttribute(key, value, null);
} else {
LOGGER.warn("Ignored incorrect attribute value expressions: {}", value);
}
}
}
configuration.setProfileDefinition(profileDefinition);
configuration.setScope(scope);
configuration.setWithState(withState);
super.internalInit(forceReinit);
| 726
| 363
| 1,089
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/GitHubClient.java
|
GitHubClient
|
internalInit
|
class GitHubClient extends OAuth20Client {
/** Constant <code>DEFAULT_SCOPE="user"</code> */
public static final String DEFAULT_SCOPE = "user";
/**
* <p>Constructor for GitHubClient.</p>
*/
public GitHubClient() {
setScope(DEFAULT_SCOPE);
}
/**
* <p>Constructor for GitHubClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public GitHubClient(final String key, final String secret) {
setScope(DEFAULT_SCOPE);
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>getScope.</p>
*
* @return a {@link String} object
*/
public String getScope() {
return getConfiguration().getScope();
}
/**
* <p>setScope.</p>
*
* @param scope a {@link String} object
*/
public void setScope(final String scope) {
getConfiguration().setScope(scope);
}
}
|
configuration.setApi(GitHubApi.instance());
configuration.setProfileDefinition(new GitHubProfileDefinition());
configuration.setTokenAsHeader(true);
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://github.com/logout")));
super.internalInit(forceReinit);
| 343
| 107
| 450
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/Google2Client.java
|
Google2Client
|
internalInit
|
class Google2Client extends OAuth20Client {
public enum Google2Scope {
EMAIL,
PROFILE,
EMAIL_AND_PROFILE
}
/** Constant <code>PROFILE_SCOPE="profile"</code> */
protected final static String PROFILE_SCOPE = "profile";
/** Constant <code>EMAIL_SCOPE="email"</code> */
protected final static String EMAIL_SCOPE = "email";
protected Google2Scope scope = Google2Scope.EMAIL_AND_PROFILE;
/**
* <p>Constructor for Google2Client.</p>
*/
public Google2Client() {
}
/**
* <p>Constructor for Google2Client.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public Google2Client(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>Getter for the field <code>scope</code>.</p>
*
* @return a {@link Google2Client.Google2Scope} object
*/
public Google2Scope getScope() {
return this.scope;
}
/**
* <p>Setter for the field <code>scope</code>.</p>
*
* @param scope a {@link Google2Client.Google2Scope} object
*/
public void setScope(final Google2Scope scope) {
this.scope = scope;
}
}
|
CommonHelper.assertNotNull("scope", this.scope);
final String scopeValue;
if (this.scope == Google2Scope.EMAIL) {
scopeValue = this.EMAIL_SCOPE;
} else if (this.scope == Google2Scope.PROFILE) {
scopeValue = this.PROFILE_SCOPE;
} else {
scopeValue = this.PROFILE_SCOPE + " " + this.EMAIL_SCOPE;
}
configuration.setApi(GoogleApi20.instance());
configuration.setProfileDefinition(new Google2ProfileDefinition());
configuration.setScope(scopeValue);
configuration.setWithState(true);
configuration.setHasBeenCancelledFactory(ctx -> {
val error = ctx.getRequestParameter(OAuthCredentialsException.ERROR).orElse(null);
// user has denied autorization
if ("access_denied".equals(error)) {
return true;
}
return false;
});
setLogoutActionBuilderIfUndefined(new GoogleLogoutActionBuilder());
super.internalInit(forceReinit);
| 453
| 281
| 734
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/HiOrgServerClient.java
|
HiOrgServerClient
|
internalInit
|
class HiOrgServerClient extends OAuth20Client {
private final static String LOGOUT_URL = "https://www.hiorg-server.de/logout.php";
/**
* <p>Constructor for HiOrgServerClient.</p>
*/
public HiOrgServerClient() {
configuration = new HiOrgServerConfiguration();
}
/**
* <p>Constructor for HiOrgServerClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public HiOrgServerClient(final String key, final String secret) {
configuration = new HiOrgServerConfiguration();
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
configuration.setApi(HiOrgServerApi20.instance());
configuration.setProfileDefinition(new HiOrgServerProfileDefinition());
configuration.setHasBeenCancelledFactory(ctx -> {
val error = ctx.getRequestParameter(OAuthCredentialsException.ERROR).orElse(null);
val errorDescription = ctx.getRequestParameter(OAuthCredentialsException.ERROR_DESCRIPTION).orElse(null);
// user has denied authorizations
if ("access_denied".equals(error)) {
logger.debug(errorDescription);
return true;
} else {
return false;
}
});
configuration.setWithState(true);
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), LOGOUT_URL)));
super.internalInit(forceReinit);
| 234
| 229
| 463
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/LinkedIn2Client.java
|
LinkedIn2Client
|
internalInit
|
class LinkedIn2Client extends OAuth20Client {
/**
* <p>Constructor for LinkedIn2Client.</p>
*/
public LinkedIn2Client() {
configuration = new LinkedIn2Configuration();
}
/**
* <p>Constructor for LinkedIn2Client.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public LinkedIn2Client(final String key, final String secret) {
this();
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public LinkedIn2Configuration getConfiguration() {
return (LinkedIn2Configuration) configuration;
}
/**
* <p>getScope.</p>
*
* @return a {@link String} object
*/
public String getScope() {
return getConfiguration().getScope();
}
/**
* <p>setScope.</p>
*
* @param scope a {@link String} object
*/
public void setScope(final String scope) {
getConfiguration().setScope(scope);
}
}
|
CommonHelper.assertNotBlank("scope", getConfiguration().getScope());
configuration.setApi(LinkedInApi20.instance());
configuration.setProfileDefinition(new LinkedIn2ProfileDefinition());
configuration.setWithState(true);
configuration.setHasBeenCancelledFactory(ctx -> {
val error = ctx.getRequestParameter(OAuthCredentialsException.ERROR).orElse(null);
val errorDescription = ctx.getRequestParameter(OAuthCredentialsException.ERROR_DESCRIPTION).orElse(null);
// user has denied authorizations
if ("access_denied".equals(error)
&& ("the+user+denied+your+request".equals(errorDescription) || "the user denied your request"
.equals(errorDescription))) {
return true;
}
return false;
});
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://www.linkedin.com/uas/logout")));
setProfileCreatorIfUndefined(new LinkedIn2ProfileCreator(configuration, this));
super.internalInit(forceReinit);
| 342
| 301
| 643
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/OAuth10Client.java
|
OAuth10Client
|
internalInit
|
class OAuth10Client extends IndirectClient {
@Getter
@Setter
protected OAuth10Configuration configuration = new OAuth10Configuration();
/** {@inheritDoc} */
@Override
protected void beforeInternalInit(final boolean forceReinit) {
super.beforeInternalInit(forceReinit);
CommonHelper.assertNotNull("configuration", configuration);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>getKey.</p>
*
* @return a {@link String} object
*/
public String getKey() {
return configuration.getKey();
}
/**
* <p>setKey.</p>
*
* @param key a {@link String} object
*/
public void setKey(final String key) {
configuration.setKey(key);
}
/**
* <p>getSecret.</p>
*
* @return a {@link String} object
*/
public String getSecret() {
return configuration.getSecret();
}
/**
* <p>setSecret.</p>
*
* @param secret a {@link String} object
*/
public void setSecret(final String secret) {
configuration.setSecret(secret);
}
}
|
setRedirectionActionBuilderIfUndefined(new OAuth10RedirectionActionBuilder(configuration, this));
setCredentialsExtractorIfUndefined(new OAuth10CredentialsExtractor(configuration, this));
setAuthenticatorIfUndefined(new OAuth10Authenticator(configuration, this));
setProfileCreatorIfUndefined(new OAuth10ProfileCreator(configuration, this));
| 360
| 103
| 463
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/OAuth20Client.java
|
OAuth20Client
|
internalInit
|
class OAuth20Client extends IndirectClient {
@Getter
@Setter
protected OAuth20Configuration configuration = new OAuth20Configuration();
/** {@inheritDoc} */
@Override
protected void beforeInternalInit(final boolean forceReinit) {
super.beforeInternalInit(forceReinit);
CommonHelper.assertNotNull("configuration", configuration);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>getKey.</p>
*
* @return a {@link String} object
*/
public String getKey() {
return configuration.getKey();
}
/**
* <p>setKey.</p>
*
* @param key a {@link String} object
*/
public void setKey(final String key) {
configuration.setKey(key);
}
/**
* <p>getSecret.</p>
*
* @return a {@link String} object
*/
public String getSecret() {
return configuration.getSecret();
}
/**
* <p>setSecret.</p>
*
* @param secret a {@link String} object
*/
public void setSecret(final String secret) {
configuration.setSecret(secret);
}
}
|
setRedirectionActionBuilderIfUndefined(new OAuth20RedirectionActionBuilder(configuration, this));
setCredentialsExtractorIfUndefined(new OAuth20CredentialsExtractor(configuration, this));
setAuthenticatorIfUndefined(new OAuth20Authenticator(configuration, this));
setProfileCreatorIfUndefined(new OAuth20ProfileCreator(configuration, this));
| 360
| 103
| 463
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/PayPalClient.java
|
PayPalClient
|
internalInit
|
class PayPalClient extends OAuth20Client {
/** Constant <code>DEFAULT_SCOPE="openid profile email address"</code> */
public final static String DEFAULT_SCOPE = "openid profile email address";
/**
* <p>Constructor for PayPalClient.</p>
*/
public PayPalClient() {
setScope(DEFAULT_SCOPE);
}
/**
* <p>Constructor for PayPalClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public PayPalClient(final String key, final String secret) {
setScope(DEFAULT_SCOPE);
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>getScope.</p>
*
* @return a {@link String} object
*/
public String getScope() {
return getConfiguration().getScope();
}
/**
* <p>setScope.</p>
*
* @param scope a {@link String} object
*/
public void setScope(final String scope) {
getConfiguration().setScope(scope);
}
}
|
CommonHelper.assertNotBlank("scope", getConfiguration().getScope());
configuration.setApi(new PayPalApi20());
configuration.setProfileDefinition(new PayPalProfileDefinition());
configuration.setTokenAsHeader(true);
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://www.paypal.com/myaccount/logout")));
super.internalInit(forceReinit);
| 351
| 131
| 482
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/QQClient.java
|
QQClient
|
getOAuthScope
|
class QQClient extends OAuth20Client {
public enum QQScope {
/**
* Get the nickname, avatar, and gender of the logged in user
*/
GET_USER_INFO,
/**
* Get basic information about QQ VIP
*/
GET_VIP_INFO,
/**
* Get advanced information about QQ VIP
*/
GET_VIP_RICH_INFO,
/**
* Get user QQZone album list
*/
LIST_ALBUM,
/**
* Upload a photo to the QQZone album
*/
UPLOAD_PIC,
/**
* Create a new personal album in the user's QQZone album
*/
ADD_ALBUM,
/**
* Get a list of photos in the user's QQZone album
*/
LIST_PHOTO,
/**
* Get the delivery address of Tenpay users
*/
GET_TENPAY_ADDR
}
protected List<QQScope> scopes;
/**
* <p>Constructor for QQClient.</p>
*/
public QQClient() {
}
/**
* <p>Constructor for QQClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public QQClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
configuration.setApi(new QQApi20());
configuration.setScope(getOAuthScope());
configuration.setProfileDefinition(new QQProfileDefinition());
configuration.setWithState(true);
setProfileCreatorIfUndefined(new QQProfileCreator(configuration, this));
super.internalInit(forceReinit);
}
private String getOAuthScope() {<FILL_FUNCTION_BODY>}
/**
* <p>Getter for the field <code>scopes</code>.</p>
*
* @return a {@link List} object
*/
public List<QQScope> getScopes() {
return scopes;
}
/**
* <p>Setter for the field <code>scopes</code>.</p>
*
* @param scopes a {@link List} object
*/
public void setScopes(List<QQScope> scopes) {
this.scopes = scopes;
}
/**
* <p>addScope.</p>
*
* @param scopes a {@link QQClient.QQScope} object
*/
public void addScope(QQScope scopes) {
if (this.scopes == null)
this.scopes = new ArrayList<>();
this.scopes.add(scopes);
}
}
|
StringBuilder builder = null;
if (scopes != null) {
for (var value : scopes) {
if (builder == null) {
builder = new StringBuilder();
} else {
builder.append(",");
}
builder.append(value.toString().toLowerCase());
}
} else {
builder = new StringBuilder();
builder.append(QQScope.GET_USER_INFO.toString().toLowerCase());
}
return builder == null ? null : builder.toString();
| 766
| 134
| 900
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/StravaClient.java
|
StravaClient
|
internalInit
|
class StravaClient extends OAuth20Client {
/**
* approvalPrompt is by default "auto". <br>
* If "force", then the authorization dialog is always displayed by Strava.
*/
private String approvalPrompt = "auto";
/**
* <p>Constructor for StravaClient.</p>
*/
public StravaClient() {
}
/**
* <p>Constructor for StravaClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public StravaClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>Getter for the field <code>approvalPrompt</code>.</p>
*
* @return a {@link String} object
*/
public String getApprovalPrompt() {
return approvalPrompt;
}
/**
* <p>Setter for the field <code>approvalPrompt</code>.</p>
*
* @param approvalPrompt a {@link String} object
*/
public void setApprovalPrompt(final String approvalPrompt) {
this.approvalPrompt = approvalPrompt;
}
/**
* <p>getScope.</p>
*
* @return a {@link String} object
*/
public String getScope() {
return getConfiguration().getScope();
}
/**
* <p>setScope.</p>
*
* @param scope a {@link String} object
*/
public void setScope(final String scope) {
getConfiguration().setScope(scope);
}
}
|
configuration.setApi(new StravaApi20(approvalPrompt));
configuration.setProfileDefinition(new StravaProfileDefinition());
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://www.strava.com/session")));
super.internalInit(forceReinit);
| 491
| 103
| 594
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/TwitterClient.java
|
TwitterClient
|
getApi
|
class TwitterClient extends OAuth10Client {
private boolean alwaysConfirmAuthorization = false;
private boolean includeEmail = false;
/**
* <p>Constructor for TwitterClient.</p>
*/
public TwitterClient() {}
/**
* <p>Constructor for TwitterClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public TwitterClient(final String key, final String secret) {
this(key, secret, false);
}
/**
* <p>Constructor for TwitterClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
* @param includeEmail a boolean
*/
public TwitterClient(final String key, final String secret, boolean includeEmail) {
setKey(key);
setSecret(secret);
this.includeEmail = includeEmail;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
configuration.setApi(getApi());
configuration.setProfileDefinition(new TwitterProfileDefinition(includeEmail));
configuration.setHasBeenCancelledFactory(ctx -> {
val denied = ctx.getRequestParameter("denied");
if (denied.isPresent()) {
return true;
} else {
return false;
}
});
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://twitter.com/logout")));
super.internalInit(forceReinit);
}
/**
* <p>getApi.</p>
*
* @return a {@link DefaultApi10a} object
*/
protected DefaultApi10a getApi() {<FILL_FUNCTION_BODY>}
/**
* <p>isAlwaysConfirmAuthorization.</p>
*
* @return a boolean
*/
public boolean isAlwaysConfirmAuthorization() {
return this.alwaysConfirmAuthorization;
}
/**
* <p>Setter for the field <code>alwaysConfirmAuthorization</code>.</p>
*
* @param alwaysConfirmAuthorization a boolean
*/
public void setAlwaysConfirmAuthorization(final boolean alwaysConfirmAuthorization) {
this.alwaysConfirmAuthorization = alwaysConfirmAuthorization;
}
/**
* <p>isIncludeEmail.</p>
*
* @return a boolean
*/
public boolean isIncludeEmail() {
return includeEmail;
}
/**
* <p>Setter for the field <code>includeEmail</code>.</p>
*
* @param includeEmail a boolean
*/
public void setIncludeEmail(final boolean includeEmail) {
this.includeEmail = includeEmail;
}
}
|
final DefaultApi10a api;
if (this.alwaysConfirmAuthorization == false) {
api = TwitterApi.Authenticate.instance();
} else {
api = TwitterApi.instance();
}
return api;
| 766
| 63
| 829
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth10Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/WechatClient.java
|
WechatClient
|
getOAuthScope
|
class WechatClient extends OAuth20Client {
public enum WechatScope {
/**
* Only for WeChat QRCode login. Get the nickname, avatar, and gender of the logged in user.
*/
SNSAPI_LOGIN,
/**
* Exchange code for access_token, refresh_token, and authorized scope
*/
SNSAPI_BASE,
/**
* Get user personal information
*/
SNSAPI_USERINFO
}
protected List<WechatScope> scopes;
/**
* <p>Constructor for WechatClient.</p>
*/
public WechatClient() {
}
/**
* <p>Constructor for WechatClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public WechatClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
configuration.setApi(new WechatApi20());
configuration.setScope(getOAuthScope());
configuration.setProfileDefinition(new WechatProfileDefinition());
configuration.setWithState(true);
setProfileCreatorIfUndefined(new WechatProfileCreator(configuration, this));
super.internalInit(forceReinit);
}
/**
* <p>getOAuthScope.</p>
*
* @return a {@link String} object
*/
protected String getOAuthScope() {<FILL_FUNCTION_BODY>}
/**
* <p>Getter for the field <code>scopes</code>.</p>
*
* @return a {@link List} object
*/
public List<WechatScope> getScopes() {
return scopes;
}
/**
* <p>Setter for the field <code>scopes</code>.</p>
*
* @param scopes a {@link List} object
*/
public void setScopes(List<WechatScope> scopes) {
this.scopes = scopes;
}
/**
* <p>addScope.</p>
*
* @param scopes a {@link WechatClient.WechatScope} object
*/
public void addScope(WechatScope scopes) {
if (this.scopes == null)
this.scopes = new ArrayList<>();
this.scopes.add(scopes);
}
}
|
StringBuilder builder = null;
if (scopes == null || scopes.isEmpty()) {
scopes = new ArrayList<>();
scopes.add(WechatScope.SNSAPI_BASE);
}
if (scopes != null) {
for (var value : scopes) {
if (builder == null) {
builder = new StringBuilder();
} else {
builder.append(",");
}
builder.append(value.toString().toLowerCase());
}
}
return builder == null ? null : builder.toString();
| 665
| 143
| 808
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/WeiboClient.java
|
WeiboClient
|
internalInit
|
class WeiboClient extends OAuth20Client {
/**
* WeiboScope.
* <p>More info at: <a href=
* "http://open.weibo.com/wiki/Scope">Scope</a></p>
*/
public enum WeiboScope {
ALL, // Request all of the following scope permissions
EMAIL, // User's contact mailbox
DIRECT_MESSAGES_WRITE, // Private message sending interface
DIRECT_MESSAGES_READ, // Private message reading interfac
INVITATION_WRITE, // Invitation to send interface
FRIENDSHIPS_GROUPS_READ,// Friend group read interface group
FRIENDSHIPS_GROUPS_WRITE,// Friend group write interface group
STATUSES_TO_ME_READ, // Directional microblog reading interface group
FOLLOW_APP_OFFICIAL_MICROBLOG // Pay attention to the application of official Weibo
}
protected WeiboScope scope = WeiboScope.EMAIL;
protected String scopeValue;
/**
* <p>Constructor for WeiboClient.</p>
*/
public WeiboClient() {
}
/**
* <p>Constructor for WeiboClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public WeiboClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>Getter for the field <code>scope</code>.</p>
*
* @return a {@link WeiboClient.WeiboScope} object
*/
public WeiboScope getScope() {
return this.scope;
}
/**
* <p>Setter for the field <code>scope</code>.</p>
*
* @param scope a {@link WeiboClient.WeiboScope} object
*/
public void setScope(final WeiboScope scope) {
this.scope = scope;
}
}
|
CommonHelper.assertNotNull("scope", this.scope);
if (this.scope == null)
this.scope = WeiboScope.EMAIL;
this.scopeValue = this.scope.toString().toLowerCase();
configuration.setApi(new WeiboApi20());
configuration.setScope(scopeValue);
configuration.setProfileDefinition(new WeiboProfileDefinition());
configuration.setWithState(true);
configuration.setHasBeenCancelledFactory(ctx -> {
val error = ctx.getRequestParameter(OAuthCredentialsException.ERROR).orElse(null);
if ("access_denied".equals(error)) {
return true;
}
return false;
});
super.internalInit(forceReinit);
| 606
| 192
| 798
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/WindowsLiveClient.java
|
WindowsLiveClient
|
internalInit
|
class WindowsLiveClient extends OAuth20Client {
/**
* <p>Constructor for WindowsLiveClient.</p>
*/
public WindowsLiveClient() {
}
/**
* <p>Constructor for WindowsLiveClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public WindowsLiveClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
configuration.setApi(LiveApi.instance());
configuration.setProfileDefinition(new WindowsLiveProfileDefinition());
configuration.setScope("wl.basic");
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://account.microsoft.com/auth/complete-signout")));
super.internalInit(forceReinit);
| 170
| 111
| 281
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/WordPressClient.java
|
WordPressClient
|
internalInit
|
class WordPressClient extends OAuth20Client {
/**
* <p>Constructor for WordPressClient.</p>
*/
public WordPressClient() {
}
/**
* <p>Constructor for WordPressClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public WordPressClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
configuration.setApi(new WordPressApi20());
configuration.setProfileDefinition(new WordPressProfileDefinition());
configuration.setTokenAsHeader(true);
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "https://wordpress.com/wp-login.php?action=logout")));
super.internalInit(forceReinit);
| 165
| 114
| 279
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth20Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/client/YahooClient.java
|
YahooClient
|
internalInit
|
class YahooClient extends OAuth10Client {
/**
* <p>Constructor for YahooClient.</p>
*/
public YahooClient() {
}
/**
* <p>Constructor for YahooClient.</p>
*
* @param key a {@link String} object
* @param secret a {@link String} object
*/
public YahooClient(final String key, final String secret) {
setKey(key);
setSecret(secret);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
configuration.setApi(YahooApi.instance());
configuration.setProfileDefinition(new YahooProfileDefinition());
setProfileCreatorIfUndefined(new YahooProfileCreator(configuration, this));
setLogoutActionBuilderIfUndefined((ctx, profile, targetUrl) ->
Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), "http://login.yahoo.com/config/login?logout=1")));
super.internalInit(forceReinit);
| 170
| 127
| 297
|
<methods>public non-sealed void <init>() ,public java.lang.String getKey() ,public java.lang.String getSecret() ,public void setKey(java.lang.String) ,public void setSecret(java.lang.String) <variables>protected org.pac4j.oauth.config.OAuth10Configuration configuration
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/config/OAuth10Configuration.java
|
OAuth10Configuration
|
buildService
|
class OAuth10Configuration extends OAuthConfiguration {
/** Constant <code>OAUTH_VERIFIER="oauth_verifier"</code> */
public static final String OAUTH_VERIFIER = "oauth_verifier";
/** Constant <code>REQUEST_TOKEN="requestToken"</code> */
public static final String REQUEST_TOKEN = "requestToken";
/**
* {@inheritDoc}
*
* Build an OAuth service from the web context.
*/
@Override
public OAuthService buildService(final WebContext context, final IndirectClient client) {<FILL_FUNCTION_BODY>}
/**
* Return the name of the attribute storing in session the request token.
*
* @param clientName the client name
* @return the name of the attribute storing in session the request token
*/
public String getRequestTokenSessionAttributeName(final String clientName) {
return clientName + "#" + REQUEST_TOKEN;
}
}
|
init();
val finalCallbackUrl = client.computeFinalCallbackUrl(context);
return ((DefaultApi10a) api)
.createService(this.key, this.secret, finalCallbackUrl, this.scope, null, null, this.httpClientConfig, null);
| 258
| 71
| 329
|
<methods>public non-sealed void <init>() ,public abstract com.github.scribejava.core.oauth.OAuthService buildService(org.pac4j.core.context.WebContext, org.pac4j.core.client.IndirectClient) <variables>public static final java.lang.String OAUTH_TOKEN,public static final java.lang.String RESPONSE_TYPE_CODE,protected java.lang.Object api,protected org.pac4j.oauth.config.HasBeenCancelledFactory hasBeenCancelledFactory,protected com.github.scribejava.core.httpclient.HttpClientConfig httpClientConfig,protected java.lang.String key,protected org.pac4j.oauth.profile.definition.OAuthProfileDefinition profileDefinition,protected java.lang.String responseType,protected java.lang.String scope,protected java.lang.String secret,protected boolean tokenAsHeader
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/config/OAuth20Configuration.java
|
OAuth20Configuration
|
buildService
|
class OAuth20Configuration extends OAuthConfiguration {
/** Constant <code>OAUTH_CODE="code"</code> */
public static final String OAUTH_CODE = "code";
/** Constant <code>STATE_REQUEST_PARAMETER="state"</code> */
public static final String STATE_REQUEST_PARAMETER = "state";
/* Map containing user defined parameters */
private Map<String, String> customParams = new HashMap<>();
private boolean withState;
private ValueGenerator stateGenerator = new RandomValueGenerator();
/**
* {@inheritDoc}
*
* Build an OAuth service from the web context.
*/
@Override
public OAuthService buildService(final WebContext context, final IndirectClient client) {<FILL_FUNCTION_BODY>}
/**
* <p>Setter for the field <code>stateGenerator</code>.</p>
*
* @param stateGenerator a {@link ValueGenerator} object
*/
public void setStateGenerator(final ValueGenerator stateGenerator) {
CommonHelper.assertNotNull("stateGenerator", stateGenerator);
this.stateGenerator = stateGenerator;
}
}
|
init();
val finalCallbackUrl = client.computeFinalCallbackUrl(context);
return ((DefaultApi20) api).createService(this.key, this.secret, finalCallbackUrl, this.scope,
this.responseType, null, null, this.httpClientConfig, null);
| 300
| 74
| 374
|
<methods>public non-sealed void <init>() ,public abstract com.github.scribejava.core.oauth.OAuthService buildService(org.pac4j.core.context.WebContext, org.pac4j.core.client.IndirectClient) <variables>public static final java.lang.String OAUTH_TOKEN,public static final java.lang.String RESPONSE_TYPE_CODE,protected java.lang.Object api,protected org.pac4j.oauth.config.HasBeenCancelledFactory hasBeenCancelledFactory,protected com.github.scribejava.core.httpclient.HttpClientConfig httpClientConfig,protected java.lang.String key,protected org.pac4j.oauth.profile.definition.OAuthProfileDefinition profileDefinition,protected java.lang.String responseType,protected java.lang.String scope,protected java.lang.String secret,protected boolean tokenAsHeader
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/config/OAuthConfiguration.java
|
OAuthConfiguration
|
internalInit
|
class OAuthConfiguration extends BaseClientConfiguration {
/** Constant <code>OAUTH_TOKEN="oauth_token"</code> */
public static final String OAUTH_TOKEN = "oauth_token";
/** Constant <code>RESPONSE_TYPE_CODE="code"</code> */
public static final String RESPONSE_TYPE_CODE = "code";
protected String key;
protected String secret;
protected boolean tokenAsHeader;
protected String responseType = RESPONSE_TYPE_CODE;
protected String scope;
protected HasBeenCancelledFactory hasBeenCancelledFactory = ctx -> false;
protected OAuthProfileDefinition profileDefinition;
protected HttpClientConfig httpClientConfig;
protected Object api;
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* <p>buildService.</p>
*
* @param context a {@link WebContext} object
* @param client a {@link IndirectClient} object
* @return a {@link OAuthService} object
*/
public abstract OAuthService buildService(final WebContext context, final IndirectClient client);
}
|
CommonHelper.assertNotNull("api", api);
CommonHelper.assertNotBlank("key", this.key);
CommonHelper.assertNotBlank("secret", this.secret);
CommonHelper.assertNotNull("hasBeenCancelledFactory", hasBeenCancelledFactory);
CommonHelper.assertNotNull("profileDefinition", profileDefinition);
| 323
| 83
| 406
|
<methods>public non-sealed void <init>() <variables>
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/credentials/authenticator/OAuth10Authenticator.java
|
OAuth10Authenticator
|
retrieveAccessToken
|
class OAuth10Authenticator extends OAuthAuthenticator {
/**
* <p>Constructor for OAuth10Authenticator.</p>
*
* @param configuration a {@link OAuth10Configuration} object
* @param client a {@link IndirectClient} object
*/
public OAuth10Authenticator(final OAuth10Configuration configuration, final IndirectClient client) {
super(configuration, client);
}
/** {@inheritDoc} */
@Override
protected void retrieveAccessToken(final WebContext context, final Credentials credentials) {<FILL_FUNCTION_BODY>}
}
|
var oAuth10Credentials = (OAuth10Credentials) credentials;
val tokenRequest = oAuth10Credentials.getRequestToken();
val token = oAuth10Credentials.getToken();
val verifier = oAuth10Credentials.getVerifier();
logger.debug("tokenRequest: {}", tokenRequest);
logger.debug("token: {}", token);
logger.debug("verifier: {}", verifier);
if (tokenRequest == null) {
val message = "Token request expired";
throw new OAuthCredentialsException(message);
}
val savedToken = tokenRequest.getToken();
logger.debug("savedToken: {}", savedToken);
if (savedToken == null || !savedToken.equals(token)) {
val message = "Token received: " + token + " is different from saved token: " + savedToken;
throw new OAuthCredentialsException(message);
}
final OAuth1AccessToken accessToken;
try {
accessToken = ((OAuth10aService) this.configuration.buildService(context, client)).getAccessToken(tokenRequest, verifier);
} catch (final IOException | InterruptedException | ExecutionException e) {
throw new HttpCommunicationException("Error getting token:" + e.getMessage());
}
logger.debug("accessToken: {}", accessToken);
oAuth10Credentials.setAccessToken(accessToken);
| 160
| 354
| 514
|
<methods>public Optional<org.pac4j.core.credentials.Credentials> validate(CallContext, org.pac4j.core.credentials.Credentials) <variables>protected org.pac4j.core.client.IndirectClient client,protected org.pac4j.oauth.config.OAuthConfiguration configuration,protected final org.slf4j.Logger logger
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/credentials/authenticator/OAuth20Authenticator.java
|
OAuth20Authenticator
|
retrieveAccessToken
|
class OAuth20Authenticator extends OAuthAuthenticator {
/**
* <p>Constructor for OAuth20Authenticator.</p>
*
* @param configuration a {@link OAuth20Configuration} object
* @param client a {@link IndirectClient} object
*/
public OAuth20Authenticator(final OAuth20Configuration configuration, final IndirectClient client) {
super(configuration, client);
}
/** {@inheritDoc} */
@Override
protected void retrieveAccessToken(final WebContext context, final Credentials credentials) {<FILL_FUNCTION_BODY>}
}
|
var oAuth20Credentials = (OAuth20Credentials) credentials;
// no request token saved in context and no token (OAuth v2.0)
val code = oAuth20Credentials.getCode();
logger.debug("code: {}", code);
final OAuth2AccessToken accessToken;
try {
accessToken = ((OAuth20Service) this.configuration.buildService(context, client)).getAccessToken(code);
} catch (final IOException | InterruptedException | ExecutionException e) {
throw new HttpCommunicationException("Error getting token:" + e.getMessage());
}
logger.debug("accessToken: {}", accessToken);
oAuth20Credentials.setAccessToken(accessToken);
| 160
| 184
| 344
|
<methods>public Optional<org.pac4j.core.credentials.Credentials> validate(CallContext, org.pac4j.core.credentials.Credentials) <variables>protected org.pac4j.core.client.IndirectClient client,protected org.pac4j.oauth.config.OAuthConfiguration configuration,protected final org.slf4j.Logger logger
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/credentials/authenticator/OAuthAuthenticator.java
|
OAuthAuthenticator
|
validate
|
class OAuthAuthenticator implements Authenticator {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected OAuthConfiguration configuration;
protected IndirectClient client;
/**
* <p>Constructor for OAuthAuthenticator.</p>
*
* @param configuration a {@link OAuthConfiguration} object
* @param client a {@link IndirectClient} object
*/
protected OAuthAuthenticator(final OAuthConfiguration configuration, final IndirectClient client) {
CommonHelper.assertNotNull("client", client);
CommonHelper.assertNotNull("configuration", configuration);
this.configuration = configuration;
this.client = client;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>}
/**
* Retrieve the access token from OAuth credentials.
*
* @param context the web context
* @param credentials credentials
*/
protected abstract void retrieveAccessToken(WebContext context, Credentials credentials);
}
|
try {
retrieveAccessToken(ctx.webContext(), credentials);
} catch (final OAuthException e) {
throw new TechnicalException(e);
}
return Optional.of(credentials);
| 276
| 54
| 330
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/credentials/extractor/OAuth10CredentialsExtractor.java
|
OAuth10CredentialsExtractor
|
getOAuthCredentials
|
class OAuth10CredentialsExtractor extends OAuthCredentialsExtractor {
/**
* <p>Constructor for OAuth10CredentialsExtractor.</p>
*
* @param configuration a {@link OAuth10Configuration} object
* @param client a {@link IndirectClient} object
*/
public OAuth10CredentialsExtractor(final OAuth10Configuration configuration, final IndirectClient client) {
super(configuration, client);
}
/** {@inheritDoc} */
@Override
protected Optional<Credentials> getOAuthCredentials(final WebContext context, final SessionStore sessionStore) {<FILL_FUNCTION_BODY>}
}
|
val tokenParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_TOKEN);
val verifierParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_VERIFIER);
if (tokenParameter.isPresent() && verifierParameter.isPresent()) {
// get request token from session
val tokenSession = (OAuth1RequestToken) sessionStore
.get(context, ((OAuth10Configuration) configuration)
.getRequestTokenSessionAttributeName(client.getName())).orElse(null);
logger.debug("tokenRequest: {}", tokenSession);
val token = OAuthEncoder.decode(tokenParameter.get());
val verifier = OAuthEncoder.decode(verifierParameter.get());
logger.debug("token: {} / verifier: {}", token, verifier);
return Optional.of(new OAuth10Credentials(tokenSession, token, verifier));
} else {
logger.debug("No credential found");
return Optional.empty();
}
| 170
| 254
| 424
|
<methods>public Optional<org.pac4j.core.credentials.Credentials> extract(CallContext) <variables>protected org.pac4j.core.client.IndirectClient client,protected org.pac4j.oauth.config.OAuthConfiguration configuration,protected final org.slf4j.Logger logger
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.