-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
auth.go
31 lines (27 loc) · 1.06 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
package main
import (
"fmt"
"net/http"
)
// BasicAuthMiddleware is a middleware function that adds basic authentication to a handler
func BasicAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the request is authenticated
user, pass, ok := r.BasicAuth()
if !ok || !checkCredentials(user, pass) {
// Authentication failed, send a 401 Unauthorized response
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, "Unauthorized")
return
}
// Authentication succeeded, call the next handler
next.ServeHTTP(w, r)
})
}
// checkCredentials is a dummy function to validate the username and password
func checkCredentials(username, password string) bool {
// Add your custom logic here to validate the credentials against your storage (e.g., database, file)
// This is a basic example, so we're using hard-coded credentials for demonstration purposes.
return username == c.Username && password == c.Password
}