Permissions.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.security.serialization;

import static org.springframework.security.acls.domain.BasePermission.*;

import org.springframework.security.acls.domain.BasePermission;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * A simple POJO for object permissions.
 */
public class Permissions {

	/** Allowed to create. */
	public boolean create;

	/** Allowed to read. */
	public boolean read;

	/** Allowed to write/modify. */
	public boolean write;

	/** Allowed to delete. */
	public boolean delete;

	/** Allowed to admin/manage. */
	public boolean manage;

	/** Anyone is allowed to read the object */
	public boolean isPublic = false;

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		var sb = new StringBuilder();
		sb.append(create ? "c" : "-");
		sb.append(isPublic ? "R" : read ? "r" : "-");
		sb.append(write ? "w" : "-");
		sb.append(delete ? "d" : "-");
		sb.append(manage ? "A" : "-"); // Admin
		return sb.toString();
	}

	/**
	 * Is Permissions granting the {@link BasePermission} by its mask?.
	 *
	 * @param mask int mask value of a single Permission
	 * @return true if granting, false otherwise
	 * @throws UnsupportedOperationException if mask is not understood
	 */
	public boolean isGranting(int mask) {
		if (CREATE.getMask() == mask) {
			return create;
		} else if (READ.getMask() == mask) {
			return read;
		} else if (WRITE.getMask() == mask) {
			return write;
		} else if (DELETE.getMask() == mask) {
			return delete;
		} else if (ADMINISTRATION.getMask() == mask) {
			return manage;
		} else {
			throw new UnsupportedOperationException("No such permission with mask=" + mask);
		}
	}

	/**
	 * Grant all.
	 *
	 * @return the permissions
	 */
	public Permissions grantAll() {
		this.create = true;
		this.read = true;
		this.write = true;
		this.delete = true;
		this.manage = true;
		return this;
	}

	/**
	 * Grant none.
	 *
	 * @return the permissions
	 */
	public Permissions grantNone() {
		this.create = false;
		this.read = false;
		this.write = false;
		this.delete = false;
		this.manage = false;
		return this;
	}

	/**
	 * Checks if is one granting.
	 *
	 * @return true, if is one granting
	 */
	@JsonIgnore
	public boolean isOneGranting() {
		return create || read || write || delete || manage;
	}
}