54 lines
1.4 KiB
Go
54 lines
1.4 KiB
Go
package tokens
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"gitea.deepak.science/deepak/gogmagog/models"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type deterministicToker struct{}
|
|
|
|
// GetDeterministicToker returns a zero security toker for testing purposes.
|
|
// Do not use in production.
|
|
func GetDeterministicToker() Toker {
|
|
return &deterministicToker{}
|
|
}
|
|
|
|
func (d *deterministicToker) EncodeUser(user *models.UserNoPassword) string {
|
|
tok := &UserToken{ID: user.UserID, Username: user.Username}
|
|
ret, _ := json.Marshal(tok)
|
|
return string(ret)
|
|
}
|
|
|
|
func (d *deterministicToker) DecodeTokenString(tokenString string) (*UserToken, error) {
|
|
var tok UserToken
|
|
err := json.Unmarshal([]byte(tokenString), &tok)
|
|
return &tok, err
|
|
}
|
|
|
|
func (d *deterministicToker) Authenticator(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
tokenString := TokenFromHeader(r)
|
|
if tokenString == "" {
|
|
log.Print("No valid token found")
|
|
unauthorized(w, r)
|
|
return
|
|
}
|
|
|
|
userToken, err := d.DecodeTokenString(tokenString)
|
|
if err != nil {
|
|
log.Printf("Error while verifying token: %s", err)
|
|
unauthorized(w, r)
|
|
return
|
|
}
|
|
|
|
log.Printf("Got user with ID: [%d]", userToken.ID)
|
|
ctx := context.WithValue(r.Context(), userIDCtxKey, userToken.ID)
|
|
ctx = context.WithValue(ctx, usernameCtxKey, userToken.Username)
|
|
// Authenticated
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|