github.com/navikt/knorten@v0.0.0-20240419132333-1333f46ed8b6/pkg/api/auth.go (about)

     1  package api
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/navikt/knorten/pkg/api/middlewares"
    10  
    11  	"github.com/gin-gonic/gin"
    12  	"github.com/navikt/knorten/pkg/api/auth"
    13  )
    14  
    15  func (c *client) adminAuthMiddleware() gin.HandlerFunc {
    16  	if c.dryRun {
    17  		return func(ctx *gin.Context) {
    18  			user := &auth.User{
    19  				Name:    "Dum My",
    20  				Email:   "dummy@nav.no",
    21  				Expires: time.Time{},
    22  			}
    23  			ctx.Set("user", user)
    24  			ctx.Next()
    25  		}
    26  	}
    27  	return func(ctx *gin.Context) {
    28  		if !ctx.GetBool(middlewares.AdminKey) {
    29  			ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
    30  		}
    31  
    32  		ctx.Next()
    33  	}
    34  }
    35  
    36  func getUser(ctx *gin.Context) (*auth.User, error) {
    37  	var user *auth.User
    38  
    39  	anyUser, exists := ctx.Get("user")
    40  	if !exists {
    41  		return nil, fmt.Errorf("getting user")
    42  	}
    43  
    44  	user, ok := anyUser.(*auth.User)
    45  	if !ok {
    46  		return nil, fmt.Errorf("verifying user")
    47  	}
    48  
    49  	return user, nil
    50  }
    51  
    52  func getNormalizedNameFromEmail(name string) string {
    53  	name = strings.Split(name, "@")[0]
    54  	name = strings.ReplaceAll(name, ".", "-")
    55  
    56  	return strings.ToLower(name)
    57  }