package cz.utb.tadis.security;

import cz.utb.tadis.auth.model.User;
import cz.utb.tadis.auth.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.NoSuchElementException;

@Component
public class SecurityContextUtil {

    @Autowired
    UserRepository userRepository;

    public User getUserFromContext() {
        try {
            SecurityContext context = SecurityContextHolder.getContext();
            Authentication authentication = context.getAuthentication();
            UserSecurity currentUser = (UserSecurity) authentication.getPrincipal();
            User user = userRepository.findByEmailAndActive(currentUser.getUsername(), true).get();
            return user;
        } catch(Exception e){
            throw new NoSuchElementException("user from context not found");
        }
    }
}
