All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.lontime.extpac4j.impl.BodyExtractor Maven / Gradle / Ivy

The newest version!
package com.github.lontime.extpac4j.impl;

import java.util.Optional;

import com.github.lontime.extjson.JSONInstance;
import com.github.lontime.extjson.shaded.net.minidev.json.JSONObject;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.UsernamePasswordCredentials;
import org.pac4j.core.credentials.extractor.CredentialsExtractor;

/**
 * BodyExtractor.
 * @author lontime
 * @since 1.0
 */
public class BodyExtractor implements CredentialsExtractor {

    private final String usernameParameter;

    private final String passwordParameter;

    private String path;

    public BodyExtractor(final String usernameParameter, final String passwordParameter) {
        this(usernameParameter, passwordParameter, null);
    }

    public BodyExtractor(final String usernameParameter, final String passwordParameter, final String path) {
        this.usernameParameter = usernameParameter;
        this.passwordParameter = passwordParameter;
        this.path = path;
    }

    @Override
    public Optional extract(WebContext context) {
        if (path != null && !path.equals(context.getPath())) {
            return Optional.empty();
        }
        final String requestContent = context.getRequestContent();
        if (requestContent == null) {
            return Optional.empty();
        }
        final Object object = JSONInstance.get().parseObject(requestContent);
        if (!(object instanceof JSONObject)) {
            return Optional.empty();
        }
        final JSONObject jsonObject = (JSONObject) object;
        final Optional username = Optional.ofNullable(jsonObject.getAsString(this.usernameParameter));
        final Optional password = Optional.ofNullable(jsonObject.getAsString(this.passwordParameter));
        if (!username.isPresent() || !password.isPresent()) {
            return Optional.empty();
        }

        return Optional.of(new UsernamePasswordCredentials(username.get(), password.get()));
    }

    public String getUsernameParameter() {
        return usernameParameter;
    }

    public String getPasswordParameter() {
        return passwordParameter;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy