-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.go
59 lines (51 loc) · 1.26 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
package nap
import (
"bytes"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
)
// AuthToken for token authentication
type AuthToken struct {
Token string
}
// AuthBasic for basic authentication
type AuthBasic struct {
Username string
Password string
}
// Authentication interface
type Authentication interface {
AuthorizationHeader() string // "basic <base64-encoded string>"
}
// NewAuthToken creates a new auth token struct
func NewAuthToken(token string) *AuthToken {
return &AuthToken{
Token: token,
}
}
// AuthorizationHeader returns the token header value
func (a *AuthToken) AuthorizationHeader() string {
return fmt.Sprintf("token %s", a.Token)
}
// NewAuthBasic creates a new auth basic struct
func NewAuthBasic(username, password string) *AuthBasic {
return &AuthBasic{
Username: username,
Password: password,
}
}
// AuthorizationHeader returns the basic auth header value
func (a *AuthBasic) AuthorizationHeader() string {
buffer := &bytes.Buffer{}
enc := base64.NewEncoder(base64.URLEncoding, buffer)
encContent := fmt.Sprintf("%s:%s", a.Username, a.Password)
enc.Write([]byte(encContent))
enc.Close()
content, err := ioutil.ReadAll(buffer)
if err != nil {
log.Fatalln("Read failed:", err)
}
return fmt.Sprintf("basic %s", string(content))
}