argos/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java

48 lines
1.9 KiB
Java

package eu.eudat.handlers;
import eu.eudat.exceptions.UnauthorisedException;
import eu.eudat.models.security.Principal;
import eu.eudat.services.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.Date;
import java.util.UUID;
/**
* Created by ikalyvas on 12/15/2017.
*/
public final class PrincipalArgumentResolver implements HandlerMethodArgumentResolver {
private AuthenticationService authenticationService;
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(Principal.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
String token = nativeWebRequest.getHeader("AuthToken");
if (token == null) throw new UnauthorisedException("Authentication Information Is Missing");
UUID authToken;
try {
authToken = UUID.fromString(token);
} catch (IllegalArgumentException ex) {
throw new UnauthorisedException("Authentication Information Is Missing");
}
Principal principal = this.authenticationService.Touch(authToken);
if (principal == null) throw new UnauthorisedException("Authentication Information Missing");
return principal;
}
public PrincipalArgumentResolver(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
}