-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
whauth.RequireBasicAuth and some mux improvements
- Loading branch information
Showing
3 changed files
with
81 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// Copyright (C) 2016 JT Olds | ||
// See LICENSE for copying information | ||
|
||
// Package whauth provides some helper methods and handlers for dealing with | ||
// HTTP basic auth | ||
package whauth // import "gopkg.in/webhelp.v1/whauth" | ||
|
||
import ( | ||
"net/http" | ||
|
||
"gopkg.in/webhelp.v1/wherr" | ||
"gopkg.in/webhelp.v1/whroute" | ||
) | ||
|
||
// RequireBasicAuth ensures that a valid user is provided, calling | ||
// wherr.Handle with wherr.Unauthorized if not. | ||
func RequireBasicAuth(h http.Handler, realm string, | ||
valid func(user, pass string) bool) http.Handler { | ||
return whroute.HandlerFunc(h, | ||
func(w http.ResponseWriter, r *http.Request) { | ||
user, pass, ok := r.BasicAuth() | ||
if !ok { | ||
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`) | ||
wherr.Handle(w, r, wherr.Unauthorized.New("basic auth required")) | ||
return | ||
} | ||
if !valid(user, pass) { | ||
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`) | ||
wherr.Handle(w, r, | ||
wherr.Unauthorized.New("invalid username or password")) | ||
return | ||
} | ||
h.ServeHTTP(w, r) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters