Writing auth middleware

This commit is contained in:
vinchent 2024-07-19 18:40:19 +02:00
parent a6dca00199
commit a0853cf880
4 changed files with 22 additions and 3 deletions

View File

@ -2,6 +2,7 @@ package main
import (
"fmt"
"go-udemy-web-1/internal/helpers"
"net/http"
"github.com/justinas/nosurf"
@ -34,3 +35,15 @@ func NoSurf(next http.Handler) http.Handler {
func SessionLoad(next http.Handler) http.Handler {
return session.LoadAndSave(next)
}
func Auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !helpers.IsAuthenticated(r) {
session.Put(r.Context(), "error", "Log in first!")
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}

View File

@ -474,9 +474,11 @@ func (m *Repository) PostShowLogin(w http.ResponseWriter, r *http.Request) {
password := r.Form.Get("password")
form := forms.New(r.PostForm)
form.Required("email", "password")
form.IsEmail("email")
if !form.Valid() {
// TODO
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
render.Template(w, r, "login.page.tmpl", &models.TemplateData{
Form: form,
})
return
}

View File

@ -24,3 +24,7 @@ func ServerError(w http.ResponseWriter, err error) {
app.ErrorLog.Println(trace)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
func IsAuthenticated(r *http.Request) bool {
return app.Session.Exists(r.Context(), "user_id")
}

View File

@ -4,7 +4,7 @@
<div class="row">
<div class="col">
<h1>Login</h1>
<form method="post" action="/user/login">
<form method="post" action="/user/login" novalidate>
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<div class="form-group mt-5">
<label for="email">Email:</label>