|
| 1 | +// Copyright 2020 The Go-Guardian. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "log" |
| 11 | + "net/http" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/gorilla/mux" |
| 15 | + |
| 16 | + "github.com/shaj13/go-guardian/auth" |
| 17 | + "github.com/shaj13/go-guardian/auth/strategies/kubernetes" |
| 18 | + "github.com/shaj13/go-guardian/auth/strategies/token" |
| 19 | + "github.com/shaj13/go-guardian/store" |
| 20 | +) |
| 21 | + |
| 22 | +// Usage: |
| 23 | +// Run kubernetes mock api and get agent token |
| 24 | +// go run mock.go |
| 25 | +// Request server to verify token and get book author |
| 26 | +// curl -k http://127.0.0.1:8080/v1/book/1449311601 -H "Authorization: Bearer <agent-token-from-mock>" |
| 27 | + |
| 28 | +var authenticator auth.Authenticator |
| 29 | +var cache store.Cache |
| 30 | + |
| 31 | +func main() { |
| 32 | + setupGoGuardian() |
| 33 | + router := mux.NewRouter() |
| 34 | + |
| 35 | + router.HandleFunc("/v1/book/{id}", middleware(http.HandlerFunc(getBookAuthor))).Methods("GET") |
| 36 | + log.Println("server started and listening on http://127.0.0.1:8080") |
| 37 | + http.ListenAndServe("127.0.0.1:8080", router) |
| 38 | +} |
| 39 | + |
| 40 | +func getBookAuthor(w http.ResponseWriter, r *http.Request) { |
| 41 | + vars := mux.Vars(r) |
| 42 | + id := vars["id"] |
| 43 | + books := map[string]string{ |
| 44 | + "1449311601": "Ryan Boyd", |
| 45 | + "148425094X": "Yvonne Wilson", |
| 46 | + "1484220498": "Prabath Siriwarden", |
| 47 | + } |
| 48 | + body := fmt.Sprintf("Author: %s \n", books[id]) |
| 49 | + w.Write([]byte(body)) |
| 50 | +} |
| 51 | + |
| 52 | +func setupGoGuardian() { |
| 53 | + authenticator = auth.New() |
| 54 | + cache = store.NewFIFO(context.Background(), time.Minute*10) |
| 55 | + kubeStrategy := kubernetes.New(cache) |
| 56 | + authenticator.EnableStrategy(token.CachedStrategyKey, kubeStrategy) |
| 57 | +} |
| 58 | + |
| 59 | +func middleware(next http.Handler) http.HandlerFunc { |
| 60 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 61 | + log.Println("Executing Auth Middleware") |
| 62 | + user, err := authenticator.Authenticate(r) |
| 63 | + if err != nil { |
| 64 | + code := http.StatusUnauthorized |
| 65 | + http.Error(w, http.StatusText(code), code) |
| 66 | + return |
| 67 | + } |
| 68 | + log.Printf("User %s Authenticated\n", user.UserName()) |
| 69 | + next.ServeHTTP(w, r) |
| 70 | + }) |
| 71 | +} |
0 commit comments