github.com/blend/go-sdk@v1.20220411.3/oauth/state.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 oauth 9 10 import ( 11 "bytes" 12 "encoding/base64" 13 "encoding/gob" 14 15 "github.com/blend/go-sdk/ex" 16 ) 17 18 // State is the oauth state. 19 type State struct { 20 // Token is a plaintext random token. 21 Token string 22 // SecureToken is the hashed version of the token. 23 // If a key is set, it validates that our app created the oauth state. 24 SecureToken string 25 // RedirectURI is the redirect uri. 26 RedirectURI string 27 // Extra includes other state you might need to encode. 28 Extra map[string]interface{} 29 } 30 31 // DeserializeState deserializes the oauth state. 32 func DeserializeState(raw string) (state State, err error) { 33 var corpus []byte 34 corpus, err = base64.RawURLEncoding.DecodeString(raw) 35 if err != nil { 36 err = ex.New(err) 37 return 38 } 39 buffer := bytes.NewBuffer(corpus) 40 if err = gob.NewDecoder(buffer).Decode(&state); err != nil { 41 err = ex.New(err) 42 return 43 } 44 45 return 46 } 47 48 // MustSerializeState serializes a state value but panics if there is an error. 49 func MustSerializeState(state State) string { 50 output, err := SerializeState(state) 51 if err != nil { 52 panic(err) 53 } 54 return output 55 } 56 57 // SerializeState serializes the oauth state. 58 func SerializeState(state State) (output string, err error) { 59 buffer := new(bytes.Buffer) 60 err = gob.NewEncoder(buffer).Encode(state) 61 if err != nil { 62 return 63 } 64 output = base64.RawURLEncoding.EncodeToString(buffer.Bytes()) 65 return 66 }