-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
api_auth.go
157 lines (134 loc) · 4.48 KB
/
api_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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// PhishDetect
// Copyright (c) 2018-2021 Claudio Guarnieri.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"net/http"
"strings"
"github.com/botherder/go-savetime/hashes"
"golang.org/x/crypto/bcrypt"
)
const (
roleUser = "user"
roleSubmitter = "submitter"
roleAdmin = "admin"
)
var rolesRank = map[string]int{
roleUser: 0,
roleSubmitter: 1,
roleAdmin: 2,
}
func generateAPIKey(source string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return hashes.StringSHA1(string(hash))
}
func getAPIKeyFromRequest(r *http.Request) string {
// Try to get the key from the URL query.
keys, ok := r.URL.Query()["key"]
// If we did not retrieve any key from the URL query, we might be
// processing a POST request.
if !ok || len(keys) < 1 {
if r.Method == "POST" {
r.ParseForm()
keys = append(keys, r.PostFormValue("key"))
} else {
// If it's not a POST request, we return an empty string.
return ""
}
}
key := strings.ToLower(keys[0])
// If the key is a valid SHA1 hash, then we return it.
if regexSHA1Compiled.MatchString(key) {
return key
}
// Otherwise we return an empty string.
return ""
}
func authMiddleware(next http.HandlerFunc, requiredRole string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Return to the API call immediately either if no role was required,
// or if the --disable-user-auth parameter was passed to the command-line
// and the required role is just user.
if (enforceUserAuth == false && requiredRole == roleUser) || requiredRole == "" {
next(w, r)
return
}
// Try to fetch an API key.
apiKey := getAPIKeyFromRequest(r)
if apiKey == "" {
errorWithJSON(w, ErrorMsgInvalidAPIKey, http.StatusUnauthorized, nil)
return
}
// Look for a user with this API key.
user, err := db.GetUserByKey(apiKey)
if err != nil {
// The user does not exist with that API key.
errorWithJSON(w, ErrorMsgNotAuthorized, http.StatusUnauthorized, nil)
return
}
// If we didn't find a user for this API key and there is
// enforceUserAuth enabled, then we return a 401 because no API
// should be publicly accessible.
if !user.Activated && enforceUserAuth == true {
errorWithJSON(w, ErrorMsgUserNotActivated, http.StatusUnauthorized, nil)
return
}
// Which minimum role is necessary for this route?
if requiredRole == roleUser {
// At this point all these statements should be true:
// 1. The request comes from a valid user (regardless of the role).
// 2. The requested resource requires a valid user.
// 3. Whether enforceUserAuth is true or false should be irrelevant.
next(w, r)
return
} else if rolesRank[requiredRole] >= rolesRank[roleSubmitter] {
// In case of other roles (submitter and admin) we check if the
// matched has a role value >= the required role value.
if rolesRank[user.Role] >= rolesRank[requiredRole] {
next(w, r)
return
}
// Otherwise we return 401.
errorWithJSON(w, ErrorMsgNotAuthorized, http.StatusUnauthorized, nil)
return
}
errorWithJSON(w, ErrorMsgUnexpectedError, http.StatusInternalServerError, nil)
})
}
func apiAuth(w http.ResponseWriter, r *http.Request) {
apiKey := getAPIKeyFromRequest(r)
if apiKey == "" {
errorWithJSON(w, ErrorMsgInvalidAPIKey, http.StatusUnauthorized, nil)
return
}
// Look for a user with this API key.
user, err := db.GetUserByKey(apiKey)
if err != nil {
// The user does not exist with that API key.
errorWithJSON(w, "There is no user with the provided key", http.StatusUnauthorized, nil)
return
}
response := map[string]interface{}{
"name": user.Name,
"email": user.Email,
"activated": user.Activated,
"role": user.Role,
}
// This is just a dummy request used to test users.
responseWithJSON(w, response)
}