SecurityUtils.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.component.security;

import java.util.List;

import org.genesys.blocks.security.SecurityContextUtil;
import org.genesys.blocks.security.model.AclAwareModel;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.security.service.CustomAclService;

import org.gringlobal.model.security.UserRole;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * The Class SecurityUtils.
 *
 * @author Andrey Lugovskoy.
 */
@Component
public class SecurityUtils {

	@Autowired
	@Lazy
	private CustomAclService aclService;

	/**
	 * List object identity ids for current user.
	 *
	 * @param clazz the clazz
	 * @param permission the permission
	 * @return the list
	 */
	public List<Long> listObjectIdentityIdsForCurrentUser(final Class<? extends AclAwareModel> clazz, final Permission permission) {
		final AclSid userSid = SecurityContextUtil.getCurrentUser();
		// System.err.println("Current user " + userSid + " for " + permission + " for "
		// + clazz.toString());
		return aclService.listObjectIdentityIdsForSid(clazz, userSid, permission);
	}

	/**
	 * Checks for role.
	 *
	 * @param role the role
	 * @return true, if successful
	 */
	public boolean hasRole(final UserRole role) {
		final String authority = role.getAuthority();

		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication != null && !authentication.getAuthorities().isEmpty()) {
			for (final GrantedAuthority ga : authentication.getAuthorities()) {
				if (ga.getAuthority().equals(authority)) {
					return true;
				}
			}
		}

		return false;
	}
}