1package api
2
3import (
4	"crypto/subtle"
5	"net/http"
6)
7
8// BasicAuthenticatedRequest parses the provided HTTP request for basic authentication credentials
9// and returns true if the provided credentials match the expected username and password.
10// Returns false if the request is unauthenticated.
11// Uses constant-time comparison in order to mitigate timing attacks.
12func BasicAuthenticatedRequest(req *http.Request, expectedUser, expectedPass string) bool {
13	user, pass, ok := req.BasicAuth()
14	if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(expectedUser)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(expectedPass)) != 1 {
15		return false
16	}
17
18	return true
19}
20