package db import ( "context" "fmt" "os" "sync" "time" "github.com/hhhapz/codequest/models" "golang.org/x/oauth2" "golang.org/x/oauth2/google" ) const ( base = "https://www.googleapis.com" scopeEmail = base + "/auth/userinfo.email" scopeProfile = base + "/auth/userinfo.profile" ) type OAuthState struct { config *oauth2.Config states map[string]oauthEntry m sync.Mutex } type oauthEntry struct { created time.Time callback string } func NewOAuthState(path string) (*OAuthState, error) { key, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("could not open file: %w", err) } config, err := google.ConfigFromJSON(key, scopeEmail, scopeProfile) if err != nil { return nil, fmt.Errorf("could not load config: %w", err) } return &OAuthState{ config: config, states: make(map[string]oauthEntry), m: sync.Mutex{}, }, nil } func (o *OAuthState) Create(callback string) string { o.m.Lock() defer o.m.Unlock() var state string ok := true for ok { state = createToken(32) _, ok = o.states[state] } o.states[state] = oauthEntry{ created: time.Now(), callback: callback, } return o.config.AuthCodeURL(state, oauth2.AccessTypeOffline) } func (o *OAuthState) Validate(ctx context.Context, state string, code string) (*oauth2.Token, string, error) { o.m.Lock() defer o.m.Unlock() entry, ok := o.states[state] if !ok { return nil, "", models.NewUserError("invalid state: %q", state) } delete(o.states, state) tk, err := o.config.Exchange(ctx, code, oauth2.AccessTypeOffline) return tk, entry.callback, err } func (o *OAuthState) GarbageCycle(period time.Duration, duration time.Duration) { tick := time.NewTicker(period) for range tick.C { o.m.Lock() now := time.Now() for state, entry := range o.states { if now.After(entry.created.Add(duration)) { delete(o.states, state) } } o.m.Unlock() } }