lets-go:12.2 request context for authz
This commit is contained in:
parent
1a59a9e720
commit
4f7fcf863c
5
snippetbox/cmd/web/context.go
Normal file
5
snippetbox/cmd/web/context.go
Normal file
@ -0,0 +1,5 @@
|
||||
package main
|
||||
|
||||
type contextKey string
|
||||
|
||||
const isAuthenticatedContextKey = contextKey("isAuthenticated")
|
@ -85,5 +85,10 @@ func (app *application) decodePostForm(r *http.Request, dst any) error {
|
||||
}
|
||||
|
||||
func (app *application) isAuthenticated(r *http.Request) bool {
|
||||
return app.sessionManager.Exists(r.Context(), "authenticatedUserID")
|
||||
isAuthenticated, ok := r.Context().Value(isAuthenticatedContextKey).(bool)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return isAuthenticated
|
||||
}
|
||||
|
@ -1,12 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/justinas/nosurf"
|
||||
)
|
||||
|
||||
func (app *application) authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := app.sessionManager.GetInt(r.Context(), "authenticatedUserID")
|
||||
if id == 0 {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := app.users.Exists(id)
|
||||
if err != nil {
|
||||
app.serverError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
if exists {
|
||||
ctx := context.WithValue(r.Context(), isAuthenticatedContextKey, true)
|
||||
r = r.WithContext(ctx)
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// logRequest ...
|
||||
func (app *application) logRequest(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
@ -23,7 +23,7 @@ func (app *application) routes() http.Handler {
|
||||
fileServer := http.FileServer(http.Dir("./ui/static"))
|
||||
router.Handler(http.MethodGet, "/static/*filepath", http.StripPrefix("/static", fileServer))
|
||||
|
||||
dynamic := alice.New(app.sessionManager.LoadAndSave, noSurf)
|
||||
dynamic := alice.New(app.sessionManager.LoadAndSave, noSurf, app.authenticate)
|
||||
|
||||
router.Handler(http.MethodGet, "/", dynamic.ThenFunc(app.home))
|
||||
router.Handler(http.MethodGet, "/snippet/view/:id", dynamic.ThenFunc(app.snippetView))
|
||||
|
@ -76,5 +76,10 @@ func (m *UserModel) Authenticate(email, password string) (int, error) {
|
||||
|
||||
// Exists
|
||||
func (m *UserModel) Exists(id int) (bool, error) {
|
||||
return false, nil
|
||||
var exists bool
|
||||
|
||||
stmt := "SELECT EXISTS(SELECT true FROM users WHERE id = ?)"
|
||||
|
||||
err := m.DB.QueryRow(stmt, id).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user