forked from koltyakov/gosip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
103 lines (87 loc) · 2.47 KB
/
auth.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
Package fba implements FBA (Form-based authentication)
Amongst supported platform versions are:
- On-Premise: 2019, 2016, and 2013
*/
package fba
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"github.com/pnocera/gosip"
"github.com/pnocera/gosip/cpass"
)
// AuthCnfg - FBA auth config structure
/* On-Premises config sample:
{
"siteUrl": "https://www.contoso.com/sites/test",
"username": "john.doe",
"password": "this-is-not-a-real-password"
}
*/
type AuthCnfg struct {
SiteURL string `json:"siteUrl"` // SPSite or SPWeb URL, which is the context target for the API calls
Username string `json:"username"`
Password string `json:"password"`
masterKey string
client *http.Client
}
// ReadConfig reads private config with auth options
func (c *AuthCnfg) ReadConfig(privateFile string) error {
jsonFile, err := os.Open(privateFile)
if err != nil {
return err
}
defer func() { _ = jsonFile.Close() }()
byteValue, _ := ioutil.ReadAll(jsonFile)
return c.ParseConfig(byteValue)
}
// ParseConfig parses credentials from a provided JSON byte array content
func (c *AuthCnfg) ParseConfig(byteValue []byte) error {
if err := json.Unmarshal(byteValue, &c); err != nil {
return err
}
crypt := cpass.Cpass(c.masterKey)
pass, err := crypt.Decode(c.Password)
if err == nil {
c.Password = pass
}
return nil
}
// WriteConfig writes private config with auth options
func (c *AuthCnfg) WriteConfig(privateFile string) error {
crypt := cpass.Cpass(c.masterKey)
pass, err := crypt.Encode(c.Password)
if err != nil {
pass = c.Password
}
config := &AuthCnfg{
SiteURL: c.SiteURL,
Username: c.Username,
Password: pass,
}
file, _ := json.MarshalIndent(config, "", " ")
return ioutil.WriteFile(privateFile, file, 0644)
}
// SetMasterkey defines custom masterkey
func (c *AuthCnfg) SetMasterkey(masterKey string) { c.masterKey = masterKey }
// GetAuth authenticates, receives access token
func (c *AuthCnfg) GetAuth() (string, int64, error) { return GetAuth(c) }
// GetSiteURL gets siteURL
func (c *AuthCnfg) GetSiteURL() string { return c.SiteURL }
// GetStrategy gets auth strategy name
func (c *AuthCnfg) GetStrategy() string { return "fba" }
// SetAuth authenticate request
// noinspection GoUnusedParameter
func (c *AuthCnfg) SetAuth(req *http.Request, httpClient *gosip.SPClient) error {
if c.client == nil {
c.client = &httpClient.Client
}
authCookie, _, err := c.GetAuth()
if err != nil {
return err
}
req.Header.Set("Cookie", authCookie)
return nil
}