package com.zsc.edu.gateway.framework.security;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;
import java.util.Optional;

/**
 * @author Yao
 */
public class SecurityUtil {

    public static UserDetailsImpl getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            return new UserDetailsImpl();
        }
        return (UserDetailsImpl) authentication.getPrincipal();
    }

    public static Optional<String> getCurrentAuditor() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication instanceof AnonymousAuthenticationToken) {
                return Optional.of("system");
            } else {
                if (authentication == null) {
                    return Optional.of("system");
                }
                UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
                return Optional.of(user.getUsername());
            }
        } catch (Exception ex) {
            // log.error("get user Authentication failed: " + ex.getMessage(), ex);
            return Optional.of("system");
        }
    }

}
