package de.champonthis.buntspecht.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import de.champonthis.buntspecht.security.LocalUserDetails;

public class BaseController {

	protected boolean authenticated() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		return auth != null && auth.isAuthenticated();
	}

	protected String getCurrentUsername() {
		LocalUserDetails userDetails = getLocalUserDetails();
		return userDetails != null ? userDetails.getUsername() : null;
	}

	protected boolean hasRole(String role) {
		LocalUserDetails userDetails = getLocalUserDetails();
		return userDetails != null ? userDetails.getAuthorities().contains(new SimpleGrantedAuthority(role)) : false;
	}

	protected LocalUserDetails getLocalUserDetails() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		return (auth != null && auth.getPrincipal() instanceof LocalUserDetails)
				? (LocalUserDetails) auth.getPrincipal()
				: null;
	}
}
