package com.yuchen.saas.manage.scope.api.handler;

import com.yuchen.saas.manage.scope.api.cache.ApiScopeCache;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.handler.IPermissionHandler;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.utils.WebUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


public class ApiScopePermissionHandler implements IPermissionHandler {

	@Override
	public boolean permissionAll() {
		HttpServletRequest request = WebUtil.getRequest();
		ContextUser user = AuthUtil.getUser();
		if (request == null || user == null) {
			return false;
		}
		String uri = request.getRequestURI();
		List<String> paths = ApiScopeCache.permissionPath(user.getRoleId());
		if (paths == null || paths.size() == 0) {
			return false;
		}
		return paths.stream().anyMatch(uri::contains);
	}

	@Override
	public boolean hasPermission(String permission) {
		HttpServletRequest request = WebUtil.getRequest();
		ContextUser user = AuthUtil.getUser();
		if (request == null || user == null) {
			return false;
		}
		List<String> codes = ApiScopeCache.permissionCode(permission, user.getRoleId());
		return codes != null && codes.size() != 0;
	}

}
