summaryrefslogtreecommitdiff
path: root/srv/src/api/auth.go
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2022-05-20 11:17:31 -0600
committerBrian Picciano <mediocregopher@gmail.com>2022-05-20 11:17:31 -0600
commit09acb111a2b22f5794541fac175b024dd0f9100e (patch)
tree11d4578a42ad4aea968b42a2689f64c799f9176e /srv/src/api/auth.go
parentf69ed83de73bbfc4b7af0931de6ced8cf12dea61 (diff)
Rename api package to http
Diffstat (limited to 'srv/src/api/auth.go')
-rw-r--r--srv/src/api/auth.go74
1 files changed, 0 insertions, 74 deletions
diff --git a/srv/src/api/auth.go b/srv/src/api/auth.go
deleted file mode 100644
index 0d946a3..0000000
--- a/srv/src/api/auth.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/mediocregopher/blog.mediocregopher.com/srv/api/apiutil"
- "golang.org/x/crypto/bcrypt"
-)
-
-// NewPasswordHash returns the hash of the given plaintext password, for use
-// with Auther.
-func NewPasswordHash(plaintext string) string {
- hashedPassword, err := bcrypt.GenerateFromPassword([]byte(plaintext), 13)
- if err != nil {
- panic(err)
- }
- return string(hashedPassword)
-}
-
-// Auther determines who can do what.
-type Auther interface {
- Allowed(username, password string) bool
-}
-
-type auther struct {
- users map[string]string
-}
-
-// NewAuther initializes and returns an Auther will which allow the given
-// username and password hash combinations. Password hashes must have been
-// created using NewPasswordHash.
-func NewAuther(users map[string]string) Auther {
- return &auther{users: users}
-}
-
-func (a *auther) Allowed(username, password string) bool {
-
- hashedPassword, ok := a.users[username]
- if !ok {
- return false
- }
-
- err := bcrypt.CompareHashAndPassword(
- []byte(hashedPassword), []byte(password),
- )
-
- return err == nil
-}
-
-func authMiddleware(auther Auther, h http.Handler) http.Handler {
-
- respondUnauthorized := func(rw http.ResponseWriter, r *http.Request) {
- rw.Header().Set("WWW-Authenticate", `Basic realm="NOPE"`)
- rw.WriteHeader(http.StatusUnauthorized)
- apiutil.GetRequestLogger(r).WarnString(r.Context(), "unauthorized")
- }
-
- return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
-
- username, password, ok := r.BasicAuth()
-
- if !ok {
- respondUnauthorized(rw, r)
- return
- }
-
- if !auther.Allowed(username, password) {
- respondUnauthorized(rw, r)
- return
- }
-
- h.ServeHTTP(rw, r)
- })
-}