github.com/blend/go-sdk@v1.20220411.3/web/util.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 web
     9  
    10  import (
    11  	"crypto/rand"
    12  	"encoding/base64"
    13  	"net/http"
    14  	"net/url"
    15  )
    16  
    17  // PathRedirectHandler returns a handler for AuthManager.RedirectHandler based on a path.
    18  func PathRedirectHandler(path string) func(*Ctx) *url.URL {
    19  	return func(ctx *Ctx) *url.URL {
    20  		u := *ctx.Request.URL
    21  		u.Path = path
    22  		return &u
    23  	}
    24  }
    25  
    26  // NewSessionID returns a new session id.
    27  // It is not a uuid; session ids are generated using a secure random source.
    28  // SessionIDs are generally 64 bytes.
    29  func NewSessionID() string {
    30  	b := make([]byte, 32)
    31  	_, _ = rand.Read(b)
    32  	return base64.URLEncoding.EncodeToString(b)
    33  }
    34  
    35  // Base64URLDecode decodes a base64 string.
    36  func Base64URLDecode(raw string) ([]byte, error) {
    37  	return base64.URLEncoding.DecodeString(raw)
    38  }
    39  
    40  // Base64URLEncode base64 encodes data.
    41  func Base64URLEncode(raw []byte) string {
    42  	return base64.URLEncoding.EncodeToString(raw)
    43  }
    44  
    45  // NewCookie returns a new name + value pair cookie.
    46  func NewCookie(name, value string) *http.Cookie {
    47  	return &http.Cookie{Name: name, Value: value}
    48  }
    49  
    50  // CopySingleHeaders copies headers in single value format.
    51  func CopySingleHeaders(headers map[string]string) http.Header {
    52  	output := make(http.Header)
    53  	for key, value := range headers {
    54  		output[key] = []string{value}
    55  	}
    56  	return output
    57  }
    58  
    59  // MergeHeaders merges headers.
    60  func MergeHeaders(headers ...http.Header) http.Header {
    61  	output := make(http.Header)
    62  	for _, header := range headers {
    63  		for key, values := range header {
    64  			for _, value := range values {
    65  				output.Add(key, value)
    66  			}
    67  		}
    68  	}
    69  	return output
    70  }