-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
54 lines (44 loc) · 1.14 KB
/
auth.go
File metadata and controls
54 lines (44 loc) · 1.14 KB
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
package sr_auth
import (
"bytes"
"crypto/tls"
"fmt"
"github.com/dgrijalva/jwt-go"
"net/http"
)
func CreateAuth(key string, authServerAddress string, tlsConfig *tls.Config) *Auth {
return &Auth{Key: key, AuthServerAddress: authServerAddress, TlsConfig: tlsConfig}
}
func (auth *Auth) GetUserFromToken(token string) (*User, error) {
tokenParsed, err := jwt.ParseWithClaims(token, &customClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(auth.Key), nil
})
if err != nil {
return nil, err
}
return &User{username: tokenParsed.Claims.(*customClaims).Username, token: token, auth: auth}, nil
}
func (auth *Auth) PingAuthServer() error {
tr := &http.Transport{
TLSClientConfig: auth.TlsConfig,
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("GET", auth.AuthServerAddress+"/health", nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
var buffer bytes.Buffer
_, err = buffer.ReadFrom(resp.Body)
if err != nil {
return err
}
ret := string(buffer.Bytes())
if ret != "Ok" {
return fmt.Errorf("replied \"%s\" instead of \"Ok\"", ret)
}
return nil
}