-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
51 lines (40 loc) · 1.49 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
package httpbulb
import (
"net/http"
"strings"
"github.com/go-chi/chi/v5"
)
// BasicAuthHandle prompts the user for authorization using HTTP Basic Auth.
// It returns 401 if not authorized.
func BasicAuthHandle(w http.ResponseWriter, r *http.Request) {
basicAuthHandle(w, r, http.StatusUnauthorized)
}
// HiddenBasicAuthHandle prompts the user for authorization using HTTP Basic Auth.
// It returns 404 if not authorized.
func HiddenBasicAuthHandle(w http.ResponseWriter, r *http.Request) {
basicAuthHandle(w, r, http.StatusNotFound)
}
// BearerAuthHandle prompts the user for authorization using bearer authentication
func BearerAuthHandle(w http.ResponseWriter, r *http.Request) {
authPrefix := "Bearer "
authorization := r.Header.Get("Authorization")
if !strings.HasPrefix(authorization, authPrefix) {
w.Header().Set("WWW-Authenticate", `Bearer"`)
RenderError(w, "", http.StatusUnauthorized)
return
}
token := authorization[len(authPrefix):]
RenderResponse(w, http.StatusOK, AuthResponse{Authenticated: true, Token: token})
}
func basicAuthHandle(w http.ResponseWriter, r *http.Request, errCode int) {
userParam := chi.URLParam(r, "user")
passwdParam := chi.URLParam(r, "passwd")
user, passwd, ok := r.BasicAuth()
authenticated := user == userParam && passwd == passwdParam
if !ok || !authenticated {
w.Header().Set("WWW-Authenticate", `Basic realm="httpbulb"`)
RenderError(w, "", errCode)
return
}
RenderResponse(w, http.StatusOK, AuthResponse{Authenticated: true, User: user})
}