-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecurity.go
64 lines (52 loc) · 1.97 KB
/
security.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
package api
import (
"encoding/base64"
"encoding/json"
"strings"
"github.com/jgolang/api/core"
)
var (
// Username basic authentication
// Default: admin
// Change this, it's insecure.
Username = "default"
// Password basic authentication
// Default: admin
// Change this, it's insecure.
Password = "default"
)
// SecurityGuaranter implementation of core.APISecurityGuaranter interface.
type SecurityGuaranter struct{}
// ValidateBasicToken validate token with a basic auth token validation method.
func (guaranter *SecurityGuaranter) ValidateBasicToken(token string) (client, secret string, valid bool) {
payload, _ := base64.StdEncoding.DecodeString(token)
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 || !ValidateBasicAuthCredentialsFunc(pair[0], pair[1]) {
return "", "", false
}
return pair[0], pair[1], true
}
// ValidateCustomToken validate token with a custom method.
func (guaranter *SecurityGuaranter) ValidateCustomToken(token string, validator core.CustomTokenValidator) (json.RawMessage, bool) {
return validator(token)
}
func validateCredentials(username, password string) bool {
if username == Username && password == Password {
return true
}
return false
}
// ValidateCustomToken validate token with a custom method.
func ValidateCustomToken(token string) (json.RawMessage, bool) {
return api.ValidateCustomToken(token, CustomTokenValidatorFunc)
}
// ValidateCredentials func type.
type ValidateCredentials func(string, string) bool
// CustomTokenValidatorFunc define custom function to validate custom token.
var CustomTokenValidatorFunc core.CustomTokenValidator
// ValidateBasicAuthCredentialsFunc define custom function for validate basic authentication credential.
var ValidateBasicAuthCredentialsFunc ValidateCredentials = validateCredentials
// ValidateBasicToken validate token with a basic auth token validation method.
func ValidateBasicToken(token string) (client, secret string, valid bool) {
return api.ValidateBasicToken(token)
}