~emersion/kimchi

86eca566a5411bdf1fbd8f50eb82e9529d3fd720 — Simon Ser 10 months ago f176d67
Add basic_auth directive

Closes: https://todo.sr.ht/~emersion/kimchi/6
2 files changed, 23 insertions(+), 1 deletions(-)

M directives.go
M kimchi.1.scd
M directives.go => directives.go +20 -1
@@ 1,6 1,7 @@
package main

import (
	"crypto/subtle"
	"fmt"
	"net"
	"net/http"


@@ 60,7 61,7 @@ func parseSite(srv *Server, dir *scfg.Directive) error {
			return fmt.Errorf("invalid path %q", path)
		}

		pattern := host+path
		pattern := host + path

		// First process handler directives
		var handler http.Handler


@@ 147,6 148,24 @@ func parseMiddleware(dir *scfg.Directive, next http.Handler) (http.Handler, erro
			}
			next.ServeHTTP(w, r)
		}), nil
	case "basic_auth":
		var username, password string
		if err := dir.ParseParams(&username, &password); err != nil {
			return nil, err
		}

		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			u, p, ok := r.BasicAuth()
			usernameOK := subtle.ConstantTimeCompare([]byte(username), []byte(u))
			passwordOK := subtle.ConstantTimeCompare([]byte(password), []byte(p))
			if !ok || (usernameOK&passwordOK) != 1 {
				w.Header().Set("WWW-Authenticate", "Basic")
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			next.ServeHTTP(w, r)
		}), nil
	default:
		return nil, fmt.Errorf("unknown directive")
	}

M kimchi.1.scd => kimchi.1.scd +3 -0
@@ 77,6 77,9 @@ The following directives are supported:
}
		Set an HTTP header field.

	*basic_auth* <username> <password>
		Sets up HTTP basic authentication.

# FILES

_/etc/kimchi/config_