forked from motiv-labs/janus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
password_verifier.go
90 lines (74 loc) · 1.97 KB
/
password_verifier.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
package basic
import (
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
const (
contentTypeJSON string = "application/json"
)
// user represents a user that wants to login
type user struct {
Username string `json:"username"`
Password string `json:"password"`
}
// Equals compares one user to another
func (u *user) Equals(user *user) bool {
return user.Username == u.Username && user.Password == u.Password
}
// PasswordVerifier checks if the current user `matches any of the given passwords
type PasswordVerifier struct {
users []*user
}
// NewPasswordVerifier creates a new instance of PasswordVerifier
func NewPasswordVerifier(users []*user) *PasswordVerifier {
return &PasswordVerifier{users}
}
// Verify makes a check and return a boolean if the check was successful or not
func (v *PasswordVerifier) Verify(r *http.Request, httpClient *http.Client) (bool, error) {
currentUser, err := v.getUserFromRequest(r)
if err != nil {
return false, errors.Wrap(err, "could not get user from request")
}
for _, user := range v.users {
if user.Equals(currentUser) {
return true, nil
}
}
return false, errors.New("incorrect username or password")
}
func (v *PasswordVerifier) getUserFromRequest(r *http.Request) (*user, error) {
var u *user
//checks basic auth
username, password, ok := r.BasicAuth()
if ok {
u = &user{
Username: username,
Password: password,
}
}
// checks if the content is json otherwise just get from the form params
contentType := filterFlags(r.Header.Get("Content-Type"))
switch contentType {
case contentTypeJSON:
err := json.NewDecoder(r.Body).Decode(&u)
if err != nil {
return u, errors.Wrap(err, "could not parse the json body")
}
default:
r.ParseForm()
u = &user{
Username: r.Form.Get("username"),
Password: r.Form.Get("password"),
}
}
return u, nil
}
func filterFlags(content string) string {
for i, char := range content {
if char == ' ' || char == ';' {
return content[:i]
}
}
return content
}