-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticate.go
56 lines (48 loc) · 1.37 KB
/
authenticate.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
45
46
47
48
49
50
51
52
53
54
55
56
package middleware
import (
"context"
"net/http"
"strings"
"github.com/kara9renai/yokattar-go/internal/app"
"github.com/kara9renai/yokattar-go/pkg/domain/object"
"github.com/kara9renai/yokattar-go/pkg/server/handler/httperror"
)
var contextKey struct{}
func Authenticate(app *app.App) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
a := r.Header.Get("Authentication")
pair := strings.SplitN(a, " ", 2)
if len(pair) < 2 {
httperror.Error(w, http.StatusUnauthorized)
return
}
authType := pair[0]
if !strings.EqualFold(authType, "username") {
httperror.Error(w, http.StatusUnauthorized)
return
}
username := pair[1]
if account, err := app.Dao.Account().FindByUsername(ctx, username); err != nil {
httperror.InternalServerError(w, err)
return
} else if account == nil {
httperror.Error(w, http.StatusUnauthorized)
return
} else {
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), contextKey, account)))
}
})
}
}
// Read Account data from authorized request
func AccountOf(r *http.Request) *object.Account {
if cv := r.Context().Value(contextKey); cv == nil {
return nil
} else if account, ok := cv.(*object.Account); !ok {
return nil
} else {
return account
}
}