github.com/miguelangel-nubla/oauth2commander@v0.3.7/oauth2server/helpers.go (about)

     1  package oauth2server
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/base64"
     6  	"io"
     7  	"log"
     8  	"net/http"
     9  	"net/url"
    10  
    11  	"github.com/coreos/go-oidc"
    12  	"github.com/grokify/go-pkce"
    13  	"golang.org/x/oauth2"
    14  )
    15  
    16  func (app *Oauth2Commander) oauth2Start(w http.ResponseWriter, r *http.Request, redirectURL string) {
    17  	state, err := randString(16)
    18  	if err != nil {
    19  		handleError(w, "Internal error", http.StatusInternalServerError)
    20  		return
    21  	}
    22  	nonce, err := randString(16)
    23  	if err != nil {
    24  		handleError(w, "Internal error", http.StatusInternalServerError)
    25  		return
    26  	}
    27  
    28  	flowData := oauthFlowData{State: state, Nonce: nonce, Redirect: redirectURL}
    29  	app.sessionManager.Put(r.Context(), app.oauthKey, flowData)
    30  
    31  	codeChallenge := pkce.CodeChallengeS256(app.codeVerifier)
    32  
    33  	authURL := app.config.AuthCodeURL(
    34  		state,
    35  		oidc.Nonce(nonce),
    36  		oauth2.SetAuthURLParam(pkce.ParamCodeChallenge, codeChallenge),
    37  		oauth2.SetAuthURLParam(pkce.ParamCodeChallengeMethod, pkce.MethodS256),
    38  	)
    39  
    40  	http.Redirect(w, r, authURL, http.StatusFound)
    41  }
    42  
    43  func (app *Oauth2Commander) setAuth(r *http.Request, data *authData) error {
    44  	app.sessionManager.Put(r.Context(), app.sessionKey, data)
    45  	return nil
    46  }
    47  
    48  func (app *Oauth2Commander) auth(r *http.Request) *authData {
    49  	value := app.sessionManager.Get(r.Context(), app.sessionKey)
    50  	if value == nil {
    51  		// errors.New("no authData found in session")
    52  		return nil
    53  	}
    54  
    55  	data, ok := value.(authData)
    56  	if !ok {
    57  		// errors.New("session data invalid")
    58  		return nil
    59  	}
    60  
    61  	return &data
    62  }
    63  
    64  func (app *Oauth2Commander) csrfToken(r *http.Request) string {
    65  	value := app.sessionManager.Get(r.Context(), app.csrfKey)
    66  	if value != nil {
    67  		csrfToken, ok := value.(string)
    68  		if ok {
    69  			return csrfToken
    70  		}
    71  	}
    72  
    73  	b := make([]byte, 32)
    74  	_, err := rand.Read(b)
    75  	if err != nil {
    76  		log.Fatal("Failed to generate CSRF token:", err)
    77  	}
    78  
    79  	csrfToken := base64.StdEncoding.EncodeToString(b)
    80  	app.sessionManager.Put(r.Context(), app.csrfKey, csrfToken)
    81  
    82  	return csrfToken
    83  }
    84  
    85  func (app *Oauth2Commander) validateCSRFToken(r *http.Request) bool {
    86  	headerToken := r.Header.Get("X-CSRF-Token")
    87  
    88  	value := app.sessionManager.Get(r.Context(), app.csrfKey)
    89  	if value != nil {
    90  		token, ok := value.(string)
    91  		if ok && token == headerToken {
    92  			return true
    93  		}
    94  	}
    95  
    96  	return false
    97  }
    98  
    99  func randString(nByte int) (string, error) {
   100  	b := make([]byte, nByte)
   101  	if _, err := io.ReadFull(rand.Reader, b); err != nil {
   102  		return "", err
   103  	}
   104  	return base64.RawURLEncoding.EncodeToString(b), nil
   105  }
   106  
   107  func constructURL(basePath string, redirectParameter string) (string, error) {
   108  	u, err := url.Parse(basePath)
   109  	if err != nil {
   110  		return "", err
   111  	}
   112  
   113  	query := u.Query()
   114  	query.Set("redirect", redirectParameter)
   115  	u.RawQuery = query.Encode()
   116  
   117  	return u.String(), nil
   118  }
   119  
   120  func handleError(w http.ResponseWriter, err string, code int) {
   121  	http.Error(w, err, code)
   122  }