OAuthClient.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.blocks.oauth.model;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.persistence.Basic;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.model.Copyable;
import org.genesys.blocks.model.JsonViews;
import org.genesys.blocks.security.model.AclSid;
import org.hibernate.annotations.Type;
import org.springframework.security.core.GrantedAuthority;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;

import lombok.Getter;
import lombok.Setter;

/**
 * OAuth Client information.
 *
 * @author Matija Obreza
 */
@Entity
@Table(name = "oauthclient")
@DiscriminatorValue(value = "2")
@Getter
@Setter
public class OAuthClient extends AclSid implements Copyable<OAuthClient> {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -4204753722663196007L;

	/** The client id. */
	@JsonView(JsonViews.Public.class)
	@Column(unique = true, nullable = false, length = 100)
	private String clientId;

	/** The client secret. */
	@JsonView(JsonViews.Protected.class)
	@Column(nullable = true, length = 100)
	private String clientSecret;

	/** The resource. */
	@JsonIgnore
	@Column(nullable = true, length = 200)
	private String resource;

	/** The resource ids. */
	@JsonView(JsonViews.Protected.class)
	@Transient
	private Set<String> resourceIds = new HashSet<>();

	/** The auto approve. */
	@Column(nullable = false)
	boolean autoApprove = false;

	/** The auto approve scope. */
	@JsonIgnore
	@Column(nullable = true, length = 200)
	private String autoApproveScope;

	/** The auto approve scopes. */
	@JsonView(JsonViews.Protected.class)
	@Transient
	private Set<String> autoApproveScopes = new HashSet<>();

	/** The scope. */
	@JsonIgnore
	@Column(nullable = true, length = 200)
	private String scope;

	/** The scopes. */
	@JsonView(JsonViews.Protected.class)
	@Transient
	private Set<String> scopes = new HashSet<>();

	/** The grants. */
	@JsonIgnore
	@Column(nullable = true, length = 200)
	private String grants;

	/** The grant types. */
	@JsonView(JsonViews.Protected.class)
	@Transient
	private Set<String> grantTypes = new HashSet<>();

	/** The redirect. */
	@JsonIgnore
	@Column(nullable = true, length = 200)
	private String redirect;

	/** The redirect uris. */
	@JsonView(JsonViews.Protected.class)
	@Transient
	private Set<String> redirectUris = new HashSet<>();

	/** The roles. */
	@JsonView(JsonViews.Protected.class)
	@ElementCollection(fetch = FetchType.EAGER)
	@Enumerated(EnumType.STRING)
	@CollectionTable(name = "oauthclientrole", joinColumns = @JoinColumn(name = "clientId"))
	@Column(name = "oauthclientrole")
	private Set<OAuthRole> roles = new HashSet<>();

	/** The additional information. */
	@Transient
	private Map<String, Object> additionalInformation = null;

	/** The access token validity. */
	private Integer accessTokenValidity;

	/** The refresh token validity. */
	private Integer refreshTokenValidity;

	/** The title. */
	@Column(nullable = false, length = 200)
	private String title;

	/** The description. */
	@Lob
	@Type(type = "org.hibernate.type.TextType")
	private String description;

	/** Allowed CORS origins */
	@Transient
	@JsonView(JsonViews.Protected.class)
	private Set<String> allowedOrigins = new HashSet<>();

	/** The origins. */
	@JsonIgnore
	@Column(nullable = true, length = 200)
	private String origins;

	/** The private reCAPTCHA key. */
	@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
	@Column(nullable = true, length = 50)
	private String privateRecaptchaKey;

	/** The public reCAPTCHA key. */
	@Column(nullable = true, length = 50)
	@JsonView(JsonViews.Protected.class)
	private String publicRecaptchaKey;

	/** The contact email of the Client user. */
	@Column(length = 60)
	private String contactEmail;
	
	/** The note. */
	@JsonView(JsonViews.Protected.class)
	@Basic
	@Column
	@Lob
	private String contactNote;
	
	/**
	 * The {@code runtimeAuthorities} are the actual authorities of the client.
	 * They are usually a list of dynamic + assigned roles + default roles IN THAT ORDER!
	 * The order of authorities is important! 
	 */
	@Transient
	@JsonIgnore
	private List<GrantedAuthority> runtimeAuthorities;

	/**
	 * Instantiates a new o auth client.
	 */
	public OAuthClient() {
		setPrincipal(true);
	}

	@PrePersist
	@PreUpdate
	private void assignSid() {
		flatten();

		// Use clientId as SID name
		setSid(clientId);
	}

	/**
	 * Flatten.
	 */
	private void flatten() {
		resource = resourceIds.stream().collect(Collectors.joining(";"));
		scope = scopes.stream().collect(Collectors.joining(";"));
		autoApproveScope = autoApproveScopes.stream().collect(Collectors.joining(";"));
		grants = grantTypes.stream().collect(Collectors.joining(";"));
		redirect = redirectUris.stream().collect(Collectors.joining(";"));
		origins = allowedOrigins.stream().collect(Collectors.joining(";"));
	}

	/**
	 * Inflate.
	 */
	@PostLoad
	private void inflate() {
		if (resource != null) {
			Arrays.stream(StringUtils.split(resource, ";")).filter(r -> StringUtils.isNotBlank(r)).forEach(r -> resourceIds.add(r));
		}
		if (scope != null) {
			Arrays.stream(StringUtils.split(scope, ";")).filter(r -> StringUtils.isNotBlank(r)).forEach(s -> scopes.add(s));
		}
		if (autoApproveScope != null) {
			Arrays.stream(StringUtils.split(autoApproveScope, ";")).filter(r -> StringUtils.isNotBlank(r)).forEach(s -> autoApproveScopes.add(s));
		}
		if (grants != null) {
			Arrays.stream(StringUtils.split(grants, ";")).filter(r -> StringUtils.isNotBlank(r)).forEach(g -> grantTypes.add(g));
		}
		if (redirect != null) {
			Arrays.stream(StringUtils.split(redirect, ";")).filter(r -> StringUtils.isNotBlank(r)).forEach(u -> redirectUris.add(u));
		}
		if (origins != null) {
			Arrays.stream(StringUtils.split(origins, ";")).filter(r -> StringUtils.isNotBlank(r)).forEach(u -> allowedOrigins.add(u));
		}
	}

	/**
	 * Client secret is required when provided.
	 *
	 * @return true, if is secret required
	 */
	public boolean isSecretRequired() {
		return clientSecret != null;
	}

	/**
	 * Does the client have any scopes defined?
	 * @return {@code true} if client has defined scopes, {@code false} otherwise
	 */
	public boolean isScoped() {
		return !scopes.isEmpty();
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.security.oauth2.provider.ClientDetails#getScope()
	 */
	@JsonProperty("clientScopes")
	public Set<String> getScope() {
		return scopes;
	}
	
	/**
	 * Sets the scopes.
	 *
	 * @param scopes the new scopes
	 */
	@JsonProperty("clientScopes")
	public void setScopes(Set<String> scopes) {
		this.scopes = scopes;
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.security.oauth2.provider.ClientDetails#
	 * getAuthorizedGrantTypes()
	 */
	@JsonView(JsonViews.Protected.class)
	public Set<String> getAuthorizedGrantTypes() {
		return grantTypes;
	}

	@JsonView(JsonViews.Protected.class)
	public Set<String> getRegisteredRedirectUri() {
		return redirectUris;
	}
	
	@Transient
	@JsonIgnore
	public Collection<? extends GrantedAuthority> getAuthorities() {
	// runtimeAuthorities contain the final set!
		if (CollectionUtils.isNotEmpty(runtimeAuthorities)) {
			return runtimeAuthorities;
		}
		throw new RuntimeException("BUG: runtimeAuthorities are not set!");
	}

	public Integer getAccessTokenValiditySeconds() {
		return accessTokenValidity;
	}

	public Integer getRefreshTokenValiditySeconds() {
		return refreshTokenValidity;
	}

	public boolean isAutoApprove(final String scope) {
		return autoApprove || autoApproveScopes.contains(scope);
	}

	@Override
	public String getFullName() {
		return this.clientId;
	}

	/**
	 * Returns null.
	 *
	 * @return the o auth client
	 */
	@Override
	public OAuthClient copy() {
		// Unsupported
		return null;
	}

	@Override
	public OAuthClient apply(OAuthClient source) {
		String oldSecret = this.clientSecret;
		Copyable.super.apply(source);
		// Keep old secret
		this.clientSecret = oldSecret;

		this.autoApproveScopes.clear();
		this.autoApproveScopes.addAll(source.autoApproveScopes);

		this.grantTypes.clear();
		this.grantTypes.addAll(source.grantTypes);

		this.redirectUris.clear();
		this.redirectUris.addAll(source.redirectUris);

		this.resourceIds.clear();
		this.resourceIds.addAll(source.resourceIds);

		this.roles.clear();
		this.roles.addAll(source.roles);

		this.scopes.clear();
		this.scopes.addAll(source.scopes);

		this.allowedOrigins.clear();
		this.allowedOrigins.addAll(source.allowedOrigins);

		this.active = source.isActive();

		return this;
	}

	/**
	 * Set the actual authorities to use at runtime. See {@link #runtimeAuthorities}.
	 *
	 * @param authorities the new runtime authorities
	 */
	public void setRuntimeAuthorities(List<GrantedAuthority> authorities) {
		this.runtimeAuthorities = ListUtils.unmodifiableList(authorities);
	}

	@Override
	public String toString() {
		return this.clientId;
	}
}