Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add apikey #5

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
##
# MANDATORY
##

# Valeurs de configuration de l'importer
DOWNLOAD_URL=https://files.opendatarchives.fr/professionnels.ign.fr/parcellaire-express/PCI-par-DEPT_2021-04/
MAX_PARALLEL_DL=4
Expand All @@ -18,6 +22,14 @@ API_PORT=8010
# A positive number. '0' means disabled.
MAX_FEATURE=1000

##
# OPTIONAL
##

# The url path to the viewer
# Empty value or do not define to disable
# Leave empty or undefined to disable
VIEWER_URL=/viewer

# A unique secure id
# Leave empty or undefined to disable.
API_KEY=
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Il est possible de décommenter le service `adminer` dans `docker-compose.yml` p
* Configuration de l'API
* `API_PORT` : Port d'écoute de l'API. Fixé à `8010` par défaut.
* `MAX_FEATURE` : Nombre maximal d'objets retournés par l'API. Fixé à `1000` par défaut. `0` pour désactiver la limite.
* `API_KEY` : (Optionel) Bearer Authentication. Laisser vide ou non défini pour désactiver.
* Configuration du viewer
* `VIEWER_URL` : (Optionel) Url d'accès à une page de consultation des parcelles. Laisser vide ou non défini pour désactiver.
2. Des options de configuration de PostgreSQL sont définies dans le fichier `docker-compose.yml`. Utiliser [PGTune](https://pgtune.leopard.in.ua/#/) pour les adapter aux caractéristiques de la machine hôte.
Expand Down
51 changes: 37 additions & 14 deletions api/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,24 @@ func (a *App) Run(addr string) {
}

func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, err := json.Marshal(payload)
if err != nil {
log.Println("JSON marshalling error")
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if _, err := w.Write(response); err != nil {
log.Println("Could not send response")

_err := json.NewEncoder(w).Encode(payload)
if _err != nil {
log.Printf("🚧 JSON encoding error : %v\n", _err)

w.WriteHeader(http.StatusInternalServerError)

_err = json.NewEncoder(w).Encode(GeneralMessage{
Message: "jsonEncodingError",
Error: true,
Literal: "Sorry, cannot output to json",
})

log.Panicf("🚨 Cannot output error message : %v\n", _err)
}

}

func respondWithError(w http.ResponseWriter, code int, message string) {
Expand Down Expand Up @@ -119,31 +128,45 @@ func (a *App) initializeRoutes() {

theViewerUrl, isViewerUrldefined := os.LookupEnv("VIEWER_URL")
if isViewerUrldefined {
log.Printf("Html viewer is enabled : %v", isViewerUrldefined)
log.Printf("⭐️ Html viewer is enabled : %v", isViewerUrldefined)
// silent viewer route
a.Router.PathPrefix(theViewerUrl).Handler(http.StripPrefix(theViewerUrl, http.FileServer(http.Dir("./views")))).Methods("GET")
}

a.Router.Handle("/parcelle/{idu:"+iduRegex+"}", Use(LogMw).ThenFunc(a.getById)).Methods("GET")
// silent route
a.Router.HandleFunc("/status", a.healthCheckHandler).Methods("GET")

a.Router.Handle("/parcelle", Use(LogMw).ThenFunc(a.findByPosition)).Queries(
_mayBeSecured := a.Router.NewRoute().Subrouter()

_mayBeSecured.Use(LogMw)

if os.Getenv(ENV_API_KEY) != "" {
log.Printf("⭐️ Api key security is enabled")
_mayBeSecured.Use(AuthMw)
}

_mayBeSecured.HandleFunc("/parcelle/{idu:"+iduRegex+"}", a.getById).Methods("GET")

_mayBeSecured.HandleFunc("/parcelle", a.findByPosition).Queries(
"pos", "{pos:"+posRegex+"}").Methods("GET")

a.Router.Handle("/parcelle", Use(LogMw).ThenFunc(a.findByPositionSplit)).Queries(
_mayBeSecured.HandleFunc("/parcelle", a.findByPositionSplit).Queries(
"lon", "{lon:"+lonRegex+"}",
"lat", "{lat:"+latRegex+"}").Methods("GET")

a.Router.Handle("/parcelle", Use(LogMw).ThenFunc(a.findByBbox)).Queries(
_mayBeSecured.HandleFunc("/parcelle", a.findByBbox).Queries(
"bbox", "{bbox:"+bboxRegex+"}").Methods("GET")

a.Router.Handle("/parcelle", Use(LogMw).ThenFunc(a.findByBboxSplit)).Queries(
_mayBeSecured.HandleFunc("/parcelle", a.findByBboxSplit).Queries(
"lon_min", "{lon_min:"+lonRegex+"}",
"lat_min", "{lat_min:"+latRegex+"}",
"lon_max", "{lon_max:"+lonRegex+"}",
"lat_max", "{lat_max:"+latRegex+"}").Methods("GET")

// handle no argument
a.Router.Handle("/parcelle", Use(LogMw).ThenFunc(a.error(http.StatusBadRequest, "Requête invalide")))

a.Router.Handle("/status", Use(LogMw).ThenFunc(a.healthCheckHandler)).Methods("GET")

// handle root path
a.Router.PathPrefix("/").Handler(Use(LogMw).ThenFunc(a.error(http.StatusNotFound, "URL inconnue")))

}
1 change: 1 addition & 0 deletions api/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ const (
///

const ENV_VIEWER_URL = "VIEWER_URL"
const ENV_API_KEY = "API_KEY"
2 changes: 1 addition & 1 deletion api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func checkEnv() {
fmt.Printf("* %s : %s \n", theEnvName, theEnv)
}

optionalEnvs := []string{ENV_VIEWER_URL}
optionalEnvs := []string{ENV_VIEWER_URL, ENV_API_KEY}

for _, theEnvName := range optionalEnvs {
theEnv, isPresent := os.LookupEnv(theEnvName)
Expand Down
67 changes: 65 additions & 2 deletions api/utils.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
)

Expand Down Expand Up @@ -38,6 +40,17 @@ func formatLog(message string, ps ...interface{}) string {
// Http Tmux Goodies 😜
// --------------------

type GeneralMessage struct {
Message string `json:"message"`
Error bool `json:"error"`
Literal string `json:"literal"`
}

type ContentMessage struct {
GeneralMessage
Payload interface{} `json:"data"`
}

// statusWriter wraps an http response.
// As it is not possible to retrieve natively the status and the length
// this interface ensure
Expand Down Expand Up @@ -100,11 +113,11 @@ func Use(mws ...Middleware) Middleware {
}
}

// LogMw : Add logging to each controller
// LogMw : Add logging to controller
// Should be the FISRT middleware.
func LogMw(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ensure response contains status.
// ensures response contains status.
_w, okType := w.(interface{}).(statusWriter)
if !okType {
_w = statusWriter{ResponseWriter: w}
Expand All @@ -120,4 +133,54 @@ func LogMw(next http.Handler) http.Handler {
})
}

// AuthMw : Add Bearer/Token security to controller
func AuthMw(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ensures response contains status.
_w, okType := w.(interface{}).(statusWriter)
if !okType {
_w = statusWriter{ResponseWriter: w}
}

_auth := r.Header.Get("Authorization")

if _auth == "" {
_w.WriteHeader(http.StatusUnauthorized)
_err := json.NewEncoder(&_w).Encode(GeneralMessage{
Message: "requireAuthorization",
Error: true,
Literal: "Please provides correct Authorization header",
})

if _err != nil {
log.Panicf("🚨 Sorry, cannot output unauthorized error message : %v\n", _err)
}

return
}

// Supports Bearer or Token api key.
_auth = strings.Replace(_auth, "Bearer ", "", 1)
_auth = strings.Replace(_auth, "Token ", "", 1)
_auth = strings.TrimSpace(_auth)

if _auth != os.Getenv(ENV_API_KEY) {
_w.WriteHeader(http.StatusForbidden)
_err := json.NewEncoder(&_w).Encode(GeneralMessage{
Message: "unknownToken",
Error: true,
Literal: "The token is incorrect",
})

if _err != nil {
log.Panicf("🚨 Sorry, cannot output auth error message : %v\n", _err)
}

return
}

next.ServeHTTP(w, r)
})
}

// --------------------
41 changes: 39 additions & 2 deletions api/views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
// try to retrieve server information
const baseUrl = `${window.location.protocol}//${window.location.host}`;
var reqControl = undefined;
// optional apiKey
var apiKey = undefined;

// PARIS
const map = L.map("map", {
Expand Down Expand Up @@ -68,9 +70,44 @@
reqControl = new AbortController();
const { signal } = reqControl;

fetch(`${baseUrl}/parcelle?bbox=${map.getBounds().toBBoxString()}`, {
const _url = `${baseUrl}/parcelle?bbox=${map
.getBounds()
.toBBoxString()}`;

var _headers = new Headers();
if (apiKey) {
_headers.append("Authorization", `Bearer ${apiKey}`);
}

var _promise = fetch(_url, {
signal,
})
headers: _headers,
});

_promise.then((response) => {
if (response.status === 401) {
apiKey = prompt("Please provides the apiKey", "<SECURITY>");

if (apiKey) {
_headers.delete("Authorization");
_headers.append("Authorization", `Bearer ${apiKey}`);
}

_promise = fetch(_url, {
signal,
headers: _headers,
});
} else if (response.status === 403) {
console.warn(
"❌ Forbidden. Apikey is incorrect. Refresh to provide a new one."
);
apiKey = undefined;
} else {
return response;
}
});

_promise
.then((e) => e.json())
.then((data) => {
console.log("✅ - parcels recieved");
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ services:
- POSTGRES_PORT
- POSTGRES_SCHEMA
- API_PORT
- API_KEY
- MAX_FEATURE
- LIMIT_FEATURE
- VIEWER_URL
Expand Down