github.com/gofiber/fiber/v2@v2.47.0/middleware/basicauth/basicauth.go (about)

     1  package basicauth
     2  
     3  import (
     4  	"encoding/base64"
     5  	"strings"
     6  
     7  	"github.com/gofiber/fiber/v2"
     8  	"github.com/gofiber/fiber/v2/utils"
     9  )
    10  
    11  // New creates a new middleware handler
    12  func New(config Config) fiber.Handler {
    13  	// Set default config
    14  	cfg := configDefault(config)
    15  
    16  	// Return new handler
    17  	return func(c *fiber.Ctx) error {
    18  		// Don't execute middleware if Next returns true
    19  		if cfg.Next != nil && cfg.Next(c) {
    20  			return c.Next()
    21  		}
    22  
    23  		// Get authorization header
    24  		auth := c.Get(fiber.HeaderAuthorization)
    25  
    26  		// Check if the header contains content besides "basic".
    27  		if len(auth) <= 6 || !utils.EqualFold(auth[:6], "basic ") {
    28  			return cfg.Unauthorized(c)
    29  		}
    30  
    31  		// Decode the header contents
    32  		raw, err := base64.StdEncoding.DecodeString(auth[6:])
    33  		if err != nil {
    34  			return cfg.Unauthorized(c)
    35  		}
    36  
    37  		// Get the credentials
    38  		creds := utils.UnsafeString(raw)
    39  
    40  		// Check if the credentials are in the correct form
    41  		// which is "username:password".
    42  		index := strings.Index(creds, ":")
    43  		if index == -1 {
    44  			return cfg.Unauthorized(c)
    45  		}
    46  
    47  		// Get the username and password
    48  		username := creds[:index]
    49  		password := creds[index+1:]
    50  
    51  		if cfg.Authorizer(username, password) {
    52  			c.Locals(cfg.ContextUsername, username)
    53  			c.Locals(cfg.ContextPassword, password)
    54  			return c.Next()
    55  		}
    56  
    57  		// Authentication failed
    58  		return cfg.Unauthorized(c)
    59  	}
    60  }