/
session.go
100 lines (82 loc) · 2.45 KB
/
session.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
package gorexos
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/gookit/color"
)
// Session stores the information which gets retrieved after successful authentication. It also
// contains the token.
type Session struct {
Domain string `json:"domain"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
UserID string `json:"user_id"`
UserName string `json:"user_name"`
UserDisplayName string `json:"user_display_name"`
Jti string `json:"jti"`
Expires time.Time `json:"expires"`
}
// NewSession creates a new session of the authentication response
func NewSession(domain string, body []byte) Session {
var session Session
err := json.Unmarshal(body, &session)
if err != nil {
panic(err)
}
session.Expires = time.Now().Add(time.Second * time.Duration(session.ExpiresIn))
session.Domain = domain
return session
}
// Valid checks if the session has already expired
func (s *Session) Valid() bool {
if time.Now().Sub(s.Expires) > 0 {
return false
}
return true
}
// OpenStoredSession tries to open up a session file which got generated by a previous login operation
func OpenStoredSession() (Session, error) {
defaultSessionFile := filepath.Join(UserRexOSDir(), ".session.json")
sessionFile, err := os.Open(defaultSessionFile)
if err != nil {
color.Red.Println("No default session file found, please login first!")
return Session{}, err
}
return OpenSession(sessionFile)
}
// OpenSession opens a session from a given file reader
func OpenSession(r io.Reader) (Session, error) {
var session Session
body, err := ioutil.ReadAll(r)
if err != nil {
return session, err
}
err = json.Unmarshal(body, &session)
color.Cyan.Println("============================================================")
color.Cyan.Println("Instance:", session.Domain)
color.Cyan.Println("UserID: ", session.UserID)
color.Cyan.Println("Username:", session.UserName)
color.Cyan.Println("============================================================")
return session, err
}
func (s *Session) Write(w io.Writer) error {
data, err := json.Marshal(s)
if err != nil {
return err
}
var out bytes.Buffer
err = json.Indent(&out, data, "", " ")
if err != nil {
_, err := w.Write(data)
return err
}
_, err = w.Write(out.Bytes())
return err
}