package org.gcube.isdashboard.web.rest; import com.fasterxml.jackson.annotation.JsonCreator; import jakarta.servlet.http.HttpServletRequest; import java.util.Set; import java.util.stream.Collectors; import org.gcube.isdashboard.security.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class AccountResource { private final Logger log = LoggerFactory.getLogger(AccountResource.class); private static class AccountResourceException extends RuntimeException {} /** * {@code GET /account} : get the current user. * * @return the current user. * @throws AccountResourceException {@code 500 (Internal Server Error)} if the user couldn't be returned. */ @GetMapping("/account") public UserVM getAccount() { String login = SecurityUtils.getCurrentUserLogin().orElseThrow(AccountResourceException::new); Set authorities = SecurityContextHolder .getContext() .getAuthentication() .getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toSet()); return new UserVM(login, authorities); } /** * {@code GET /authenticate} : check if the user is authenticated, and return its login. * * @param request the HTTP request. * @return the login if the user is authenticated. */ @GetMapping("/authenticate") public String isAuthenticated(HttpServletRequest request) { log.debug("REST request to check if the current user is authenticated"); return request.getRemoteUser(); } private static class UserVM { private String login; private Set authorities; @JsonCreator UserVM(String login, Set authorities) { this.login = login; this.authorities = authorities; } public boolean isActivated() { return true; } public Set getAuthorities() { return authorities; } public String getLogin() { return login; } } }