94 lines
2.3 KiB
Java
94 lines
2.3 KiB
Java
package tech.nevets.todoserver;
|
|
|
|
import com.google.gson.JsonArray;
|
|
import com.google.gson.JsonObject;
|
|
import spark.Request;
|
|
|
|
import java.io.File;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
import static spark.Spark.*;
|
|
|
|
public class Server {
|
|
|
|
private static final List<String> AUTH_KEYS = new ArrayList<>();
|
|
|
|
public static void main(String[] args) {
|
|
loadAuthKeys();
|
|
port(8080);
|
|
|
|
path("/todo", () -> {
|
|
before("/*");
|
|
|
|
get("/:listId", (req, res) -> {
|
|
checkAuth(req);
|
|
|
|
return "To Do List: " + req.params("listId");
|
|
});
|
|
|
|
get("/:listId/:itemId", (req, res) -> {
|
|
checkAuth(req);
|
|
|
|
return "To Do List Item: " + req.params("itemId");
|
|
});
|
|
|
|
post("/create/:listId", (req, res) -> {
|
|
checkAuth(req);
|
|
|
|
return "Create To Do List";
|
|
});
|
|
|
|
post("/create/:listId/:itemId", (req, res) -> {
|
|
checkAuth(req);
|
|
|
|
return "Create Item";
|
|
});
|
|
|
|
put("/update/:listId", (req, res) -> {
|
|
checkAuth(req);
|
|
return "Updated List success code";
|
|
});
|
|
|
|
put("/update/:listId/:itemId", (req, res) -> {
|
|
checkAuth(req);
|
|
|
|
return "Update Item success code";
|
|
});
|
|
|
|
delete("/delete/:listId", (req, res) -> {
|
|
checkAuth(req);
|
|
|
|
return "Deleted List success code";
|
|
});
|
|
|
|
delete("/delete/:listId/:itemId", (req, res) -> {
|
|
checkAuth(req);
|
|
|
|
return "Deleted Item success code";
|
|
});
|
|
|
|
});
|
|
}
|
|
|
|
private static void checkAuth(Request req) {
|
|
boolean authenticated = false;
|
|
for (String authKey : AUTH_KEYS) {
|
|
if (req.headers("Authorization").contains(authKey)) {
|
|
authenticated = true;
|
|
}
|
|
}
|
|
if (!authenticated) {
|
|
halt(403, "Unauthorized");
|
|
}
|
|
}
|
|
|
|
private static void loadAuthKeys() {
|
|
JsonObject jo = JSONLoader.loadJsonFile(new File("./auth-keys.json"));
|
|
JsonArray ja = jo.get("auth-keys").getAsJsonArray();
|
|
for (int i = 0; i < ja.size(); i++) {
|
|
AUTH_KEYS.add(ja.get(i).getAsString());
|
|
}
|
|
}
|
|
}
|