package com.izouma.jmrh.utils;

import com.izouma.jmrh.domain.User;
import com.izouma.jmrh.security.Authority;
import com.izouma.jmrh.security.JwtUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;

public class SecurityUtils {
    public static User getAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = null;
        if (authentication != null && authentication.getPrincipal() instanceof JwtUser) {
            user = ((JwtUser) authentication.getPrincipal()).getUser();
        }
        return user;
    }

    public static boolean hasRole(Authority.NAMES authorityName) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) return false;
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return authorities.contains(new SimpleGrantedAuthority(authorityName.name()));
    }
}
