forked from Ouest-France/gofortiadc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_login.go
57 lines (45 loc) · 1002 Bytes
/
user_login.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
package gofortiadc
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
)
// AuthRes represents a login auth response
type AuthRes struct {
Token string `json:"token"`
}
// Login authenticates goforti client
func (c *Client) Login() error {
if len(c.Address) == 0 {
return errors.New("FortiADC address cannot be empty")
}
payload := map[string]string{
"username": c.Username,
"password": c.Password,
}
payloadJSON, err := json.Marshal(payload)
if err != nil {
return err
}
resp, err := c.Client.Post(fmt.Sprintf("%s/api/user/login", c.Address), "application/json", bytes.NewReader(payloadJSON))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("Login failed with http code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var authRes AuthRes
err = json.Unmarshal(body, &authRes)
if err != nil {
return err
}
c.Token = authRes.Token
return nil
}