-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathmain.go
96 lines (83 loc) · 2.8 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright 2020 The Go-Guardian. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/shaj13/libcache"
_ "github.com/shaj13/libcache/fifo"
"github.com/shaj13/go-guardian/v2/auth"
"github.com/shaj13/go-guardian/v2/auth/strategies/basic"
"github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
"github.com/shaj13/go-guardian/v2/auth/strategies/union"
)
// Usage:
// curl -k http://127.0.0.1:8080/v1/book/1449311601 -u admin:admin
// curl -k http://127.0.0.1:8080/v1/auth/token -u admin:admin <obtain a token>
// curl -k http://127.0.0.1:8080/v1/book/1449311601 -H "Authorization: Bearer <token>"
var strategy union.Union
var keeper jwt.SecretsKeeper
func main() {
setupGoGuardian()
router := mux.NewRouter()
router.HandleFunc("/v1/auth/token", middleware(http.HandlerFunc(createToken))).Methods("GET")
router.HandleFunc("/v1/book/{id}", middleware(http.HandlerFunc(getBookAuthor))).Methods("GET")
log.Println("server started and listening on http://127.0.0.1:8080")
http.ListenAndServe("127.0.0.1:8080", router)
}
func createToken(w http.ResponseWriter, r *http.Request) {
u := auth.User(r)
token, _ := jwt.IssueAccessToken(u, keeper)
body := fmt.Sprintf("token: %s \n", token)
w.Write([]byte(body))
}
func getBookAuthor(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
books := map[string]string{
"1449311601": "Ryan Boyd",
"148425094X": "Yvonne Wilson",
"1484220498": "Prabath Siriwarden",
}
body := fmt.Sprintf("Author: %s \n", books[id])
w.Write([]byte(body))
}
func setupGoGuardian() {
keeper = jwt.StaticSecret{
ID: "secret-id",
Secret: []byte("secret"),
Algorithm: jwt.HS256,
}
cache := libcache.FIFO.New(0)
cache.SetTTL(time.Minute * 5)
basicStrategy := basic.NewCached(validateUser, cache)
jwtStrategy := jwt.New(cache, keeper)
strategy = union.New(jwtStrategy, basicStrategy)
}
func validateUser(ctx context.Context, r *http.Request, userName, password string) (auth.Info, error) {
// here connect to db or any other service to fetch user and validate it.
if userName == "admin" && password == "admin" {
return auth.NewDefaultUser("admin", "1", nil, nil), nil
}
return nil, fmt.Errorf("Invalid credentials")
}
func middleware(next http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing Auth Middleware")
_, user, err := strategy.AuthenticateRequest(r)
if err != nil {
fmt.Println(err)
code := http.StatusUnauthorized
http.Error(w, http.StatusText(code), code)
return
}
log.Printf("User %s Authenticated\n", user.GetUserName())
r = auth.RequestWithUser(user, r)
next.ServeHTTP(w, r)
})
}