Adds current user route
All checks were successful
gitea-deepak/gogmagog/pipeline/head This commit looks good

This commit is contained in:
Deepak Mallubhotla 2021-01-24 19:45:56 -06:00
parent 96b22a2254
commit 42d808165b
Signed by: deepak
GPG Key ID: 64BF53A3369104E7
5 changed files with 87 additions and 15 deletions

44
routes/currentUser.go Normal file
View File

@ -0,0 +1,44 @@
package routes
import (
"encoding/json"
"gitea.deepak.science/deepak/gogmagog/models"
"gitea.deepak.science/deepak/gogmagog/tokens"
"github.com/go-chi/chi"
"log"
"net/http"
)
// NewCurrentUserRouter returns a new router for getting the current user.
func NewCurrentUserRouter(m *models.Model) http.Handler {
router := chi.NewRouter()
router.Get("/", getMeFunc(m))
return router
}
func getMeFunc(m *models.Model) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID, err := tokens.GetUserID(r.Context())
if err != nil {
log.Print(err)
unauthorizedHandler(w, r)
return
}
username, err := tokens.GetUsername(r.Context())
if err != nil {
log.Print(err)
unauthorizedHandler(w, r)
return
}
user, err := m.UserByUsername(username, userID)
if err != nil {
serverError(w, err)
return
}
w.Header().Add("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(user); err != nil {
serverError(w, err)
}
}
}

View File

@ -12,7 +12,7 @@ import (
"time"
)
var sampleContext = tokens.GetContextForUserID(3)
var sampleContext = tokens.GetContextForUserValues(3, "testing")
func TestEmptyPlans(t *testing.T) {
// set up

View File

@ -17,6 +17,7 @@ func NewRouter(m *models.Model, tok tokens.Toker) http.Handler {
r.Use(tok.Authenticator)
r.Mount("/actions", NewActionRouter(m))
r.Mount("/plans", NewPlanRouter(m))
r.Mount("/me", NewCurrentUserRouter(m))
})
router.Mount("/auth", newAuthRouter(m, tok))
router.Mount("/health", newHealthRouter(m))

View File

@ -13,6 +13,7 @@ type contextKey struct {
}
var userIDCtxKey = &contextKey{"UserID"}
var usernameCtxKey = &contextKey{"Username"}
func unauthorized(w http.ResponseWriter, r *http.Request) {
code := http.StatusUnauthorized
@ -39,15 +40,16 @@ func (tok *jwtToker) Authenticator(next http.Handler) http.Handler {
return
}
userID, err := tok.DecodeTokenString(tokenString)
userToken, err := tok.DecodeTokenString(tokenString)
if err != nil {
log.Printf("Error while verifying token: %s", err)
unauthorized(w, r)
return
}
log.Printf("Got user with ID: [%d]", userID)
ctx := context.WithValue(r.Context(), userIDCtxKey, userID)
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))
})
@ -65,7 +67,17 @@ func GetUserID(ctx context.Context) (int, error) {
return int(userID), nil
}
// GetContextForUserID is a test helper method that creates a context with user ID set.
func GetContextForUserID(userID int) context.Context {
return context.WithValue(context.Background(), userIDCtxKey, int64(userID))
// GetUsername does something similar to GetUserID.
func GetUsername(ctx context.Context) (string, error) {
username, ok := ctx.Value(usernameCtxKey).(string)
if !ok {
return "", fmt.Errorf("Could not parse username [%s] from context", ctx.Value(usernameCtxKey))
}
return username, nil
}
// GetContextForUserValues is a test helper method that creates a context with user ID set.
func GetContextForUserValues(userID int, username string) context.Context {
ctx := context.WithValue(context.Background(), userIDCtxKey, int64(userID))
return context.WithValue(ctx, usernameCtxKey, username)
}

View File

@ -12,7 +12,7 @@ import (
// Toker represents a tokenizer, capable of encoding and verifying tokens.
type Toker interface {
EncodeUser(user *models.UserNoPassword) string
DecodeTokenString(tokenString string) (int64, error)
DecodeTokenString(tokenString string) (*UserToken, error)
Authenticator(http.Handler) http.Handler
}
@ -39,14 +39,20 @@ func (tok *jwtToker) EncodeUser(user *models.UserNoPassword) string {
return tokenString
}
func (tok *jwtToker) DecodeTokenString(tokenString string) (int64, error) {
// UserToken represents a decoded jwt token.
type UserToken struct {
ID int64
Username string
}
func (tok *jwtToker) DecodeTokenString(tokenString string) (*UserToken, error) {
token, err := tok.tokenAuth.Decode(tokenString)
if err != nil {
return -1, fmt.Errorf("Error decoding token")
return nil, fmt.Errorf("Error decoding token")
}
if token == nil {
return -1, fmt.Errorf("Token was nil")
return nil, fmt.Errorf("Token was nil")
}
err = jwt.Validate(
@ -55,16 +61,25 @@ func (tok *jwtToker) DecodeTokenString(tokenString string) (int64, error) {
jwt.WithAudience("gogmagog.deepak.science"),
)
if err != nil {
return -1, err
return nil, err
}
userIDRaw, ok := token.Get("user_id")
if !ok {
return -1, fmt.Errorf("error finding user_id claim")
return nil, fmt.Errorf("error finding user_id claim")
}
userID, ok := userIDRaw.(float64)
if !ok {
return -1, fmt.Errorf("Could not parse [%s] as userID", userIDRaw)
return nil, fmt.Errorf("Could not parse [%s] as userID", userIDRaw)
}
return int64(userID), nil
usernameRaw, ok := token.Get("username")
if !ok {
return nil, fmt.Errorf("error finding username claim")
}
username, ok := usernameRaw.(string)
if !ok {
return nil, fmt.Errorf("Could not parse [%s] as username", usernameRaw)
}
return &UserToken{ID: int64(userID), Username: username}, nil
}