github.com/blend/go-sdk@v1.20220411.3/webutil/decode_basic_auth.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package webutil 9 10 import ( 11 "encoding/base64" 12 "net/http" 13 "strings" 14 15 "github.com/blend/go-sdk/ex" 16 ) 17 18 // DecodeBasicAuth pulls a basic auth header from a request and returns the 19 // username and password that were passed. 20 func DecodeBasicAuth(req *http.Request) (username, password string, err error) { 21 var rawHeader string 22 rawHeader, err = headerValue(HeaderAuthorization, req) 23 if err != nil { 24 err = ex.New(ErrUnauthorized, ex.OptInner(err)) 25 return 26 } 27 28 auth := strings.SplitN(rawHeader, " ", 2) 29 if len(auth) != 2 || auth[0] != "Basic" { 30 err = ex.New(ErrUnauthorized) 31 return 32 } 33 34 var payload []byte 35 payload, err = base64.StdEncoding.DecodeString(auth[1]) 36 if err != nil { 37 err = ex.New(ErrUnauthorized, ex.OptInner(err)) 38 return 39 } 40 41 username, password, err = SplitColon(string(payload)) 42 if err != nil { 43 err = ex.New(ErrUnauthorized, ex.OptInner(err)) 44 return 45 } 46 47 return 48 } 49 50 func headerValue(key string, req *http.Request) (value string, err error) { 51 if value = req.Header.Get(key); len(value) > 0 { 52 return 53 } 54 err = ErrParameterMissing 55 return 56 }