package cn.reghao.oss.console.account.service;

import cn.reghao.oss.console.account.model.po.User;
import cn.reghao.oss.console.account.security.form.AccountAuthToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collections;
import java.util.Set;

/**
 * @author reghao
 * @date 2023-12-01 10:31:52
 */
public class UserContext {
    public static String getUsername() {
        User user = getUser();
        if (user == null) {
            return null;
        }

        return user.getScreenName();
    }

    public static User getUser() {
        Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
        if (authToken instanceof AccountAuthToken) {
            return (User) authToken.getDetails();
        }

        return null;
    }

    public static String getUserRole() {
        User user = getUser();
        if (user != null && !user.getRole().isEmpty()) {
            return user.getRole().iterator().next();
        }

        return "";
    }

    public static Set<String> getUserRoles() {
        User user = getUser();
        if (user != null) {
            return user.getRole();
        }

        return Collections.emptySet();
    }
}
