oauth2/session/session.go
2024-10-01 13:38:43 -04:00

75 lines
1.2 KiB
Go

package session
import (
"crypto/rand"
"encoding/hex"
"somehole.com/common/security/signature"
)
type SessionId string
func NewSessionId() SessionId {
b := make([]byte, 8)
rand.Read(b)
return SessionId(hex.EncodeToString(b))
}
type State string
func NewState(id SessionId, signer *signature.Keypair) State {
sig, err := signer.Sign([]byte(id))
if err != nil {
panic(err)
}
return State(hex.EncodeToString(sig[:]))
}
type Code string
type AccessToken string
type RefreshToken string
type TokenChoice uint8
const (
TokenChoiceAccess TokenChoice = iota
TokenChoiceRefresh
)
func (t TokenChoice) String() (out string) {
switch t {
case TokenChoiceAccess:
out = "access_token"
case TokenChoiceRefresh:
out = "refresh_token"
}
return
}
type Session struct {
SessionId SessionId
State State
Code Code
AccessToken AccessToken
RefreshToken RefreshToken
}
func NewSession() *Session {
id := NewSessionId()
return &Session{
SessionId: id,
}
}
func (s *Session) GetToken(choice TokenChoice) (token string) {
switch choice {
case TokenChoiceAccess:
token = string(s.AccessToken)
case TokenChoiceRefresh:
token = string(s.RefreshToken)
}
return
}