|
| 1 | +package convex.restapi.api; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashSet; |
| 5 | + |
| 6 | +import convex.peer.Server; |
| 7 | +import convex.restapi.RESTServer; |
| 8 | +import convex.restapi.model.CreateAccountResponse; |
| 9 | +import io.javalin.Javalin; |
| 10 | +import io.javalin.http.Context; |
| 11 | +import io.javalin.http.InternalServerErrorResponse; |
| 12 | +import io.javalin.openapi.HttpMethod; |
| 13 | +import io.javalin.openapi.OpenApi; |
| 14 | +import io.javalin.openapi.OpenApiContent; |
| 15 | +import io.javalin.openapi.OpenApiResponse; |
| 16 | + |
| 17 | +public class PeerAdminAPI extends ABaseAPI { |
| 18 | + |
| 19 | + public Server server; |
| 20 | + |
| 21 | + public PeerAdminAPI(RESTServer restServer) { |
| 22 | + super(restServer); |
| 23 | + server = restServer.getServer(); |
| 24 | + } |
| 25 | + |
| 26 | + private static final String ROUTE = "/api/v1/"; |
| 27 | + |
| 28 | + @Override |
| 29 | + public void addRoutes(Javalin app) { |
| 30 | + String prefix = ROUTE; |
| 31 | + |
| 32 | + app.post(prefix + "peer/shutdown", this::shutDown); |
| 33 | + |
| 34 | + } |
| 35 | + |
| 36 | + @OpenApi(path = ROUTE + "peer/shutdown", |
| 37 | + methods = HttpMethod.POST, |
| 38 | + operationId = "shutdownPeer", |
| 39 | + tags = { "Admin"}, |
| 40 | + summary = "Shut down the current peer", |
| 41 | + responses = { |
| 42 | + @OpenApiResponse( |
| 43 | + status = "200", |
| 44 | + description = "Peer shutdown initiated", |
| 45 | + content = { |
| 46 | + @OpenApiContent( |
| 47 | + type = "application/json", |
| 48 | + from = CreateAccountResponse.class) }) |
| 49 | + }) |
| 50 | + public void shutDown(Context ctx) { |
| 51 | + ensureLocalAdmin(ctx); |
| 52 | + try { |
| 53 | + server.shutdown(); |
| 54 | + } catch (Exception e) { |
| 55 | + e.printStackTrace(); |
| 56 | + throw new InternalServerErrorResponse("Failed to initiate sutdown: "+e.getMessage()); |
| 57 | + } |
| 58 | + ctx.result("Shutdown initiated."); |
| 59 | + } |
| 60 | + |
| 61 | + private HashSet<String> authorisedIPs = new HashSet<String>(Arrays.asList("127.0.0.1","::1","[0:0:0:0:0:0:0:1]")); |
| 62 | + |
| 63 | + private void ensureLocalAdmin(Context ctx) { |
| 64 | + String ip=ctx.ip(); |
| 65 | + if (authorisedIPs.contains(ip)) { |
| 66 | + return; |
| 67 | + } else { |
| 68 | + throw new io.javalin.http.UnauthorizedResponse("Can't performa admin actions from IP: "+ip); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | +} |
0 commit comments