|
| 1 | +package com.retailsvc.http.spec.security; |
| 2 | + |
| 3 | +import com.retailsvc.http.spec.security.SecurityScheme.ApiKey; |
| 4 | +import com.retailsvc.http.spec.security.SecurityScheme.ApiKey.Location; |
| 5 | +import com.retailsvc.http.spec.security.SecurityScheme.HttpBasic; |
| 6 | +import com.retailsvc.http.spec.security.SecurityScheme.HttpBearer; |
| 7 | +import com.retailsvc.http.spec.security.SecurityScheme.Unsupported; |
| 8 | +import java.util.Locale; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.Optional; |
| 11 | + |
| 12 | +public final class SecuritySchemeParser { |
| 13 | + private SecuritySchemeParser() {} |
| 14 | + |
| 15 | + public static SecurityScheme parse(Map<String, Object> raw) { |
| 16 | + String type = (String) raw.get("type"); |
| 17 | + if (type == null) { |
| 18 | + throw new IllegalArgumentException("securityScheme missing required 'type'"); |
| 19 | + } |
| 20 | + return switch (type) { |
| 21 | + case "apiKey" -> parseApiKey(raw); |
| 22 | + case "http" -> parseHttp(raw); |
| 23 | + default -> new Unsupported(type); |
| 24 | + }; |
| 25 | + } |
| 26 | + |
| 27 | + private static SecurityScheme parseApiKey(Map<String, Object> raw) { |
| 28 | + String name = (String) raw.get("name"); |
| 29 | + String in = (String) raw.get("in"); |
| 30 | + if (name == null || in == null) { |
| 31 | + throw new IllegalArgumentException("apiKey scheme requires 'name' and 'in'"); |
| 32 | + } |
| 33 | + return new ApiKey(name, Location.valueOf(in.toUpperCase(Locale.ROOT))); |
| 34 | + } |
| 35 | + |
| 36 | + private static SecurityScheme parseHttp(Map<String, Object> raw) { |
| 37 | + String scheme = (String) raw.get("scheme"); |
| 38 | + if (scheme == null) { |
| 39 | + throw new IllegalArgumentException("http securityScheme requires 'scheme'"); |
| 40 | + } |
| 41 | + return switch (scheme.toLowerCase(Locale.ROOT)) { |
| 42 | + case "bearer" -> new HttpBearer(Optional.ofNullable((String) raw.get("bearerFormat"))); |
| 43 | + case "basic" -> new HttpBasic(); |
| 44 | + default -> new Unsupported("http:" + scheme); |
| 45 | + }; |
| 46 | + } |
| 47 | +} |
0 commit comments