Using broker to authenticate

This commit is contained in:
vinchent 2024-08-28 21:40:50 +02:00
parent eaabd28fc2
commit 9edb249430
2 changed files with 89 additions and 0 deletions

View File

@ -1,9 +1,23 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"log"
"net/http"
)
type RequestPayload struct {
Action string `string:"action"`
Auth AuthPayload ` json:"auth,omitempty"`
}
type AuthPayload struct {
Email string `json:"email"`
Password string `json:"password"`
}
func (app *Config) Broker(w http.ResponseWriter, r *http.Request) {
payload := jsonResponse{
Error: false,
@ -12,3 +26,77 @@ func (app *Config) Broker(w http.ResponseWriter, r *http.Request) {
app.writeJSON(w, http.StatusOK, payload)
}
func (app *Config) HandleSubmission(w http.ResponseWriter, r *http.Request) {
var requestPayload RequestPayload
err := app.readJSON(w, r, &requestPayload)
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
switch requestPayload.Action {
case "auth":
app.authenticate(w, requestPayload.Auth)
default:
app.errorJSON(w, errors.New("unknown action"))
}
}
func (app *Config) authenticate(w http.ResponseWriter, a AuthPayload) {
// create some json we'll send to the auth microservice
authPayload, err := json.MarshalIndent(a, "", "\t")
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
// call the service
req, err := http.NewRequest(
"POST",
"http://authentication-service/authenticate",
bytes.NewBuffer(authPayload),
)
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
app.errorJSON(w, err, http.StatusInternalServerError)
return
}
defer resp.Body.Close()
log.Println(resp.Body)
// make sure we get back the correct status code
if resp.StatusCode != http.StatusAccepted {
app.errorJSON(w, errors.New("invalid credentials"))
return
}
// create a variable we'll read resp.Body into
var respPayload jsonResponse
err = json.NewDecoder(resp.Body).Decode(&respPayload)
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
if respPayload.Error {
app.errorJSON(w, errors.New(respPayload.Message), http.StatusUnauthorized)
return
}
var payload jsonResponse
payload.Error = false
payload.Message = "Authenticated!"
payload.Data = respPayload.Data
app.writeJSON(w, http.StatusOK, payload)
}

View File

@ -24,6 +24,7 @@ func (app *Config) routes() http.Handler {
mux.Use(middleware.Heartbeat("/ping"))
mux.Post("/", app.Broker)
mux.Post("/handle", app.HandleSubmission)
return mux
}