File: session.go

package info (click to toggle)
golang-github-markbates-goth 1.42.0-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 968 kB
  • sloc: makefile: 3
file content (72 lines) | stat: -rw-r--r-- 2,459 bytes parent folder | download | duplicates (3)
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
69
70
71
72
package salesforce

import (
	"encoding/json"
	"errors"
	"strings"

	"github.com/markbates/goth"
)

// Session stores data during the auth process with Salesforce.
// Expiry of access token is not provided by Salesforce, it is just controlled by timeout configured in auth2 settings
// by individual users
// Only way to check whether access token has expired or not is based on the response you receive if you try using
// access token and get some error
// Also, For salesforce refresh token to work follow these else remove scopes from here
//On salesforce.com, navigate to where you app is configured. (Setup > Create > Apps)
//Under Connected Apps, click on your application's name to view its settings, then click Edit.
//Under Selected OAuth Scopes, ensure that "Perform requests on your behalf at any time" is selected. You must include this even if you already chose "Full access".
//Save, then try your OAuth flow again. It make take a short while for the update to propagate.
type Session struct {
	AuthURL      string
	AccessToken  string
	RefreshToken string
	ID           string //Required to get the user info from sales force
}

var _ goth.Session = &Session{}

// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Salesforce provider.
func (s Session) GetAuthURL() (string, error) {
	if s.AuthURL == "" {
		return "", errors.New(goth.NoAuthUrlErrorMessage)
	}
	return s.AuthURL, nil
}

// Authorize the session with Salesforce and return the access token to be stored for future use.
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
	p := provider.(*Provider)
	token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))

	if err != nil {
		return "", err
	}

	if !token.Valid() {
		return "", errors.New("Invalid token received from provider")
	}

	s.AccessToken = token.AccessToken
	s.RefreshToken = token.RefreshToken
	s.ID = token.Extra("id").(string) //Required to get the user info from sales force
	return token.AccessToken, err
}

// Marshal the session into a string
func (s Session) Marshal() string {
	b, _ := json.Marshal(s)
	return string(b)
}

func (s Session) String() string {
	return s.Marshal()
}

// UnmarshalSession wil unmarshal a JSON string into a session.
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
	s := &Session{}
	err := json.NewDecoder(strings.NewReader(data)).Decode(s)
	return s, err
}