forked from facesea/banshee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
44 lines (38 loc) · 1.02 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
32
33
34
35
36
37
38
39
40
41
42
43
44
// Copyright 2015 Eleme Inc. All rights reserved.
package webapp
import (
"github.com/julienschmidt/httprouter"
"net/http"
)
// authHandler provides basic auth utils.
type authHandler struct {
user string
pass string
}
// newAuthHandler creates a authHandler.
func newAuthHandler(user, pass string) *authHandler {
return &authHandler{user, pass}
}
// handler returns a httprouter handler with basic auth protection.
func (a *authHandler) handler(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if a.auth(w, r) {
h(w, r, ps)
}
}
}
func (a *authHandler) auth(w http.ResponseWriter, r *http.Request) bool {
if len(a.user) == 0 {
// Config auth user length 0 for no auth.
return true
}
user, pass, ok := r.BasicAuth()
if ok && user == a.user && pass == a.pass {
// Ok
return true
}
// Fail
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return false
}