package com.koobietech.eas.security.service.impl;

import com.koobietech.eas.common.utils.SecurityManager;
import com.koobietech.eas.security.service.SecurityAccessService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

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

/**
 * @author lc
 */
@Service("SecurityAccessService")
public class SecurityAccessServiceImpl implements SecurityAccessService {

    private PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Authentication userAuthentication= SecurityManager.getAuthentication();
        if ( userAuthentication != null ) {
            Collection<? extends GrantedAuthority> authorities = userAuthentication.getAuthorities();
            System.out.println( "URI:" + request.getRequestURI() );
            for (GrantedAuthority authority : authorities) {
                if ( pathMatcher.match( authority.getAuthority(), request.getRequestURI() ) ) {
                    return true;
                }
            }
        }
        return false;
    }
}
