package com.noblelift.ota.config; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ResponseStatusException; @Component public class AgentTokenAuthenticator { private static final String TOKEN_HEADER = "X-OTA-TOKEN"; private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String BEARER_PREFIX = "Bearer "; private final OtaProperties otaProperties; public AgentTokenAuthenticator(OtaProperties otaProperties) { this.otaProperties = otaProperties; } public void verify(HttpServletRequest request) { String expectedToken = trimToNull(otaProperties.getAuthToken()); if (expectedToken == null) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "OTA agent token is not configured"); } String providedToken = extractToken(request); if (!expectedToken.equals(providedToken)) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid OTA agent token"); } } private String extractToken(HttpServletRequest request) { String token = trimToNull(request.getHeader(TOKEN_HEADER)); if (token != null) { return token; } String authorization = trimToNull(request.getHeader(AUTHORIZATION_HEADER)); if (authorization != null && authorization.regionMatches(true, 0, BEARER_PREFIX, 0, BEARER_PREFIX.length())) { return trimToNull(authorization.substring(BEARER_PREFIX.length())); } return null; } private String trimToNull(String value) { if (value == null) { return null; } String trimmed = value.trim(); return trimmed.isEmpty() ? null : trimmed; } }