-
Notifications
You must be signed in to change notification settings - Fork 5
/
auth.go
78 lines (72 loc) · 1.73 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
// FileAuth is an authentication backend that checks tokens against a file of
// authorized tokens
type FileAuth struct {
TokensFilePath string
}
func NewFileAuth(filepath string) *FileAuth {
if filepath == "" {
filepath = ConfPath("authorized_fingerprints")
}
// creating the token file
_, err := os.Stat(filepath)
if os.IsNotExist(err) {
tokensFile, err := os.Create(filepath)
defer tokensFile.Close()
if err != nil {
return nil
}
}
return &FileAuth{TokensFilePath: filepath}
}
// ReadAuthorizedTokens reads the tokens file and returns all the tokens in it
func (a *FileAuth) ReadAuthorizedTokens() ([]string, error) {
var tokens []string
file, err := os.Open(a.TokensFilePath)
if err != nil {
return nil, fmt.Errorf("Failed to open authorized_fingerprints: %w", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// allow comment line that start with #
if len(line) > 0 && line[0] == '#' {
continue
}
// ignore the part after the first space - used for client identification
if i := strings.Index(line, " "); i != -1 {
line = line[:i]
}
// ignore empty lines
if len(line) == 0 {
continue
}
tokens = append(tokens, line)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("Failed to read authorized_fingerprints: %s", err)
}
return tokens, nil
}
// IsAuthorized checks whether a client token is authorized
func (a *FileAuth) IsAuthorized(clientTokens ...string) bool {
tokens, err := a.ReadAuthorizedTokens()
if err != nil {
return false
}
for _, ct := range clientTokens {
for _, token := range tokens {
if token == ct {
return true
}
}
}
return false
}