From cbf2cc6d0cf885ba74f0c5707ebc4f1a389939ef Mon Sep 17 00:00:00 2001 From: UnicodingUnicorn <7555ic@gmail.com> Date: Sun, 24 Feb 2019 04:02:03 +0800 Subject: [PATCH] backend-auth integration --- README.md | 19 +++++++++++++------ main.go | 23 ++++++++++++++++------- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index ad05118..e40e227 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ Beep backend records and makes available the last seen times of users. +**To run this service securely means to run it behind traefik forwarding auth to `backend-auth`** + ## Environment variables Supply environment variables by either exporting them or editing ```.env```. @@ -45,18 +47,23 @@ An [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) s ### Ping Server ``` -POST /ping/:userid/client/:clientid +POST /ping ``` Ping the server. -#### URL Params +#### Required headers -| Name | Type | Description | Required | -| ---- | ---- | ----------- | -------- | -| userid | String | User's ID. | ✓ | -| clientid | String | User's device's ID. | ✓ | +| Name | Description | +| ---- | ----------- | +| X-User-Claim | Stringified user claim, populated by `backend-auth` called by `traefik` | #### Success Response (200 OK) Empty body. + +#### Errors + +| Code | Description | +| ---- | ----------- | +| 400 | Invalid user claims header. | diff --git a/main.go b/main.go index 08c9b5a..74be42c 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "fmt" "log" "net/http" @@ -17,8 +18,8 @@ var listen string var redisHost string type RawClient struct { - UserId string - ClientId string + UserId string `json:"userid"` + ClientId string `json:"clientid"` } var connections map[RawClient][]chan []byte @@ -45,7 +46,7 @@ func main() { // Routes router := httprouter.New() router.GET("/subscribe/:userid/client/:clientid", Subscribe) - router.POST("/ping/:userid/client/:clientid", PostTime) + router.POST("/ping", PostTime) // Start server log.Printf("starting server on %s", listen) @@ -96,11 +97,19 @@ func Subscribe(w http.ResponseWriter, r *http.Request, p httprouter.Params) { } } -// TODO: Take client data from token func PostTime(w http.ResponseWriter, r *http.Request, p httprouter.Params) { - client := RawClient { - UserId: p.ByName("userid"), - ClientId: p.ByName("clientid"), + ua := r.Header.Get("X-User-Claim") + if ua == "" { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + + var client RawClient + err := json.Unmarshal([]byte(ua), &client) + + if err != nil { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return } time := []byte(strconv.FormatInt(time.Now().UTC().Unix(), 10)) // UTC Epoch Time in []byte