/
sate.go
68 lines (55 loc) · 1.31 KB
/
sate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package account
import (
"crypto/rand"
"encoding/binary"
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
)
// State stored when getting Token
type State struct {
URL string
Signup bool
StateString string
}
// StateMap type to cache all states
type StateMap map[string]*State
// States cached for reuse
var States StateMap
func init() {
States = make(StateMap)
}
// Get the state by key
func (sm StateMap) Get(key string) (*State, bool) {
result, ok := sm[key]
return result, ok
}
// FindAndDelete returns the state for a given key and deletes the entry of the StateMap
func (sm StateMap) FindAndDelete(key string) *State {
if result, ok := sm[key]; ok {
delete(sm, key)
return result
}
return nil
}
// CreateState to reuse later
func (sm StateMap) CreateState(url string, signup bool) *State {
var stateSeed uint64
err := binary.Read(rand.Reader, binary.LittleEndian, &stateSeed)
if err != nil {
log.Error(err.Error())
}
stateString := fmt.Sprintf("%x", stateSeed)
state := newState(url, signup, stateString)
v, _ := json.Marshal(state)
log.Infof("State Stored: %s", string(v))
sm[stateString] = state
return state
}
func newState(url string, signup bool, stateString string) *State {
return &State{
StateString: stateString,
URL: url,
Signup: signup,
}
}