Skip to content

Commit

Permalink
chore: issue 104 to split basic_bearer example into basic and token
Browse files Browse the repository at this point in the history
  • Loading branch information
briwagner authored and shaj13 committed Apr 24, 2021
1 parent 3041807 commit 5cfc50e
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
80 changes: 80 additions & 0 deletions _examples/basic/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// 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"
)

// Usage:
// curl -k http://127.0.0.1:8080/v1/book/1449311601 -u admin:admin

var strategy auth.Strategy
var cacheObj libcache.Cache

func main() {
setupGoGuardian()
router := mux.NewRouter()
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 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() {
cacheObj = libcache.FIFO.New(0)
cacheObj.SetTTL(time.Minute * 5)
cacheObj.RegisterOnExpired(func(key, _ interface{}) {
cacheObj.Peek(key)
})
strategy = basic.NewCached(validateUser, cacheObj)
}

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.Authenticate(r.Context(), 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())
next.ServeHTTP(w, r)
})
}
3 changes: 2 additions & 1 deletion _examples/basic_bearer/main.go → _examples/token/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func main() {

func createToken(w http.ResponseWriter, r *http.Request) {
token := uuid.New().String()
user := auth.NewDefaultUser("admin", "1", nil, nil)
user := auth.User(r)
auth.Append(tokenStrategy, token, user)
body := fmt.Sprintf("token: %s \n", token)
w.Write([]byte(body))
Expand Down Expand Up @@ -92,6 +92,7 @@ func middleware(next http.Handler) http.HandlerFunc {
return
}
log.Printf("User %s Authenticated\n", user.GetUserName())
r = auth.RequestWithUser(user, r)
next.ServeHTTP(w, r)
})
}

0 comments on commit 5cfc50e

Please sign in to comment.