backend/restservice/src/main/java/com/plannaplan/controllers/TokenBasedController.java

38 lines
1.3 KiB
Java
Raw Normal View History

2020-09-30 19:15:32 +02:00
package com.plannaplan.controllers;
import java.util.Optional;
import com.plannaplan.entities.User;
2020-10-01 16:46:45 +02:00
import com.plannaplan.exceptions.UserNotFoundException;
2020-09-30 19:15:32 +02:00
import com.plannaplan.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
2021-01-16 13:57:58 +01:00
/**
* Abstract class for controllers that requires token to extra authorize action
* beyond spring security
*/
2020-09-30 19:15:32 +02:00
public abstract class TokenBasedController {
@Autowired
protected UserService userService;
public TokenBasedController() {
}
2021-01-16 13:57:58 +01:00
/**
* @return get currect user based no current spring context
* @throws UserNotFoundException if user was not fount
*/
2020-10-01 16:46:45 +02:00
protected Optional<User> getCurrentUser() throws UserNotFoundException {
2020-09-30 19:15:32 +02:00
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
return Optional.of(this.userService.getUserByEmail(authentication.getName()));
} else {
return Optional.empty();
}
}
}