|
| 1 | +package ElectermSync; |
| 2 | +import static spark.Spark.*; |
| 3 | +import io.jsonwebtoken.*; |
| 4 | +import com.google.gson.Gson; |
| 5 | +import java.util.Map; |
| 6 | +import java.io.File; |
| 7 | +import java.util.Arrays; |
| 8 | +import java.nio.charset.StandardCharsets; |
| 9 | +import java.util.Base64; |
| 10 | + |
| 11 | +public class App { |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + Gson gson = new Gson(); |
| 15 | + |
| 16 | + |
| 17 | + Config dotenv = new Config(); |
| 18 | + String secretOri = dotenv.getValue("JWT_SECRET"); |
| 19 | + byte[] bytesToEncode = secretOri.getBytes(StandardCharsets.UTF_8); |
| 20 | + |
| 21 | + // Encode the bytes using Base64 |
| 22 | + String secret = Base64.getEncoder().encodeToString(bytesToEncode); |
| 23 | + |
| 24 | + String ids = dotenv.getValue("JWT_USERS"); |
| 25 | + String[] idArrStrings = ids.split(","); |
| 26 | + Jwts.parserBuilder().setSigningKey(secret).build(); |
| 27 | + |
| 28 | + port(Integer.parseInt((dotenv.getValue("PORT")))); |
| 29 | + |
| 30 | + ipAddress(dotenv.getValue("HOST")); |
| 31 | + |
| 32 | + before("/api/sync", (request, response) -> { |
| 33 | + String authHeader = request.headers("Authorization"); |
| 34 | + try { |
| 35 | + if (authHeader == null || !authHeader.startsWith("Bearer ")) { |
| 36 | + throw new JwtException("Missing or invalid token"); |
| 37 | + } else { |
| 38 | + String token = authHeader.substring(7); |
| 39 | + Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(secret).build().parseClaimsJws(token); |
| 40 | + String id = claimsJws.getBody().get("id").toString(); |
| 41 | + boolean found = Arrays.stream(idArrStrings).anyMatch(element -> element.equals(id)); |
| 42 | + if (!found) { |
| 43 | + throw new JwtException("Unauthorized access"); |
| 44 | + } |
| 45 | + request.attribute("jwtId", id); |
| 46 | + } |
| 47 | + } catch (JwtException ex) { |
| 48 | + halt(401, "Unauthorized: " + ex.getMessage()); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + get("/api/sync", (request, response) -> { |
| 53 | + String jwtId = request.attribute("jwtId"); |
| 54 | + ReadResult r = FileStore.read(jwtId, dotenv); |
| 55 | + response.status(r.statusCode); |
| 56 | + return gson.toJson(r.fileData); |
| 57 | + }); |
| 58 | + |
| 59 | + put("/api/sync", (request, response) -> { |
| 60 | + String requestBody = request.body(); |
| 61 | + String jwtId = request.attribute("jwtId"); |
| 62 | + response.type("application/json"); |
| 63 | + WriteResult r = FileStore.write(requestBody, jwtId, dotenv); |
| 64 | + response.status(r.statusCode); |
| 65 | + return r.message; |
| 66 | + }); |
| 67 | + |
| 68 | + after((request, response) -> { |
| 69 | + response.type("application/json"); |
| 70 | + response.header("Content-Encoding", "gzip"); |
| 71 | + }); |
| 72 | + } |
| 73 | +} |
0 commit comments