-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi_auth.go
126 lines (98 loc) · 2.08 KB
/
api_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package raptor
import (
"fmt"
"github.com/raptorbox/raptor-sdk-go/models"
)
//CreateAuth instantiate a new API client
func CreateAuth(r *Raptor) *Auth {
return &Auth{
Raptor: r,
state: &models.LoginState{},
}
}
//Auth API client
type Auth struct {
Raptor *Raptor
state *models.LoginState
}
//GetConfig return the configuration
func (a *Auth) GetConfig() models.Config {
return a.Raptor.GetConfig()
}
//GetClient return a client instance
func (a *Auth) GetClient() models.Client {
return a.Raptor.GetClient()
}
//GetUser return the authenticated user
func (a *Auth) GetUser() *models.User {
if a.state == nil {
return nil
}
return a.state.User
}
//GetToken return the authentication token
func (a *Auth) GetToken() string {
if a.state == nil {
return ""
}
return a.state.Token
}
//Login login a user with the provided credentials
func (a *Auth) Login() (*models.LoginState, error) {
var raw []byte
var err error
if a.GetConfig().GetToken() != "" {
user, err1 := a.Raptor.Admin().User().Me()
if err1 != nil {
return nil, err1
}
a.state = &models.LoginState{
Token: a.GetConfig().GetToken(),
User: user,
}
} else {
body := fmt.Sprintf(
`{ "username": "%s", "password": "%s" }`,
a.GetConfig().GetUsername(),
a.GetConfig().GetPassword())
raw, err = a.GetClient().Post(LOGIN, body, &models.ClientOptions{
SkipAuthHeader: true,
})
if err != nil {
return nil, err
}
state := &models.LoginState{}
err = a.GetClient().FromJSON(raw, state)
if err != nil {
return nil, err
}
a.state = state
}
if err != nil {
return nil, err
}
return a.state, nil
}
//Logout logout an user
func (a *Auth) Logout() error {
err := a.GetClient().Delete(LOGOUT, nil)
if err != nil {
return err
}
a.state = nil
return nil
}
//Refresh a user token
func (a *Auth) Refresh() (*models.LoginState, error) {
raw, err := a.GetClient().Get(REFRESH_TOKEN, nil)
if err != nil {
return nil, err
}
state := &models.LoginState{}
err = a.GetClient().FromJSON(raw, state)
if err != nil {
return nil, err
}
a.state = state
return a.state, nil
}