package com.keao.edu.config;

import com.keao.edu.auth.api.client.SysUserFeignService;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.auth.api.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component("pcs")
public class PermissionCheckService {

	@Autowired
	private SysUserFeignService sysUserFeignService;

	public boolean hasPermissions(String... permissions) {
		Authentication authentication = SecurityUtils.getAuthentication();
		if (authentication == null) {
			return false;
		}

		SysUser user = sysUserFeignService.queryUserInfo();
		if (user.getIsSuperAdmin()) {
			return true;
		}

		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

		for (String perm : permissions) {
			for (GrantedAuthority authority : authorities) {
				if (StringUtils.equalsIgnoreCase(perm, authority.getAuthority())) {
					return true;
				}
			}
		}

		return false;
	}

	public boolean hasRoles(String... roles) {

		return hasPermissions(roles);
	}

}
