Newer
Older
teacher-diary / src / main / java / ru / mcs / diary / common / util / SecurityUtils.java
package ru.mcs.diary.common.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import ru.mcs.diary.auth.CustomUserDetails;

import java.util.Optional;

public final class SecurityUtils {

    private SecurityUtils() {}

    public static Optional<CustomUserDetails> getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.getPrincipal() instanceof CustomUserDetails) {
            return Optional.of((CustomUserDetails) auth.getPrincipal());
        }
        return Optional.empty();
    }

    public static Long getCurrentUserId() {
        return getCurrentUser()
                .map(CustomUserDetails::getId)
                .orElseThrow(() -> new IllegalStateException("User not authenticated"));
    }

    public static Long getCurrentTeacherId() {
        return getCurrentUser()
                .map(CustomUserDetails::getTeacherId)
                .orElseThrow(() -> new IllegalStateException("User not authenticated"));
    }

    public static boolean isTeacher() {
        return getCurrentUser()
                .map(CustomUserDetails::isTeacher)
                .orElse(false);
    }

    public static boolean isParent() {
        return getCurrentUser()
                .map(CustomUserDetails::isParent)
                .orElse(false);
    }
}