1package google
2
3import (
4	"encoding/json"
5	"errors"
6	"strings"
7	"time"
8
9	"github.com/markbates/goth"
10)
11
12// Session stores data during the auth process with Google.
13type Session struct {
14	AuthURL      string
15	AccessToken  string
16	RefreshToken string
17	ExpiresAt    time.Time
18	IDToken      string
19}
20
21// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Google provider.
22func (s Session) GetAuthURL() (string, error) {
23	if s.AuthURL == "" {
24		return "", errors.New(goth.NoAuthUrlErrorMessage)
25	}
26	return s.AuthURL, nil
27}
28
29// Authorize the session with Google and return the access token to be stored for future use.
30func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
31	p := provider.(*Provider)
32	token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
33	if err != nil {
34		return "", err
35	}
36
37	if !token.Valid() {
38		return "", errors.New("Invalid token received from provider")
39	}
40
41	s.AccessToken = token.AccessToken
42	s.RefreshToken = token.RefreshToken
43	s.ExpiresAt = token.Expiry
44	s.IDToken = token.Extra("id_token").(string)
45	return token.AccessToken, err
46}
47
48// Marshal the session into a string
49func (s Session) Marshal() string {
50	b, _ := json.Marshal(s)
51	return string(b)
52}
53
54func (s Session) String() string {
55	return s.Marshal()
56}
57
58// UnmarshalSession will unmarshal a JSON string into a session.
59func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
60	sess := &Session{}
61	err := json.NewDecoder(strings.NewReader(data)).Decode(sess)
62	return sess, err
63}
64