Writing auth middleware
This commit is contained in:
parent
a6dca00199
commit
a0853cf880
@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"go-udemy-web-1/internal/helpers"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/justinas/nosurf"
|
"github.com/justinas/nosurf"
|
||||||
@ -34,3 +35,15 @@ func NoSurf(next http.Handler) http.Handler {
|
|||||||
func SessionLoad(next http.Handler) http.Handler {
|
func SessionLoad(next http.Handler) http.Handler {
|
||||||
return session.LoadAndSave(next)
|
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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
@ -474,9 +474,11 @@ func (m *Repository) PostShowLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
password := r.Form.Get("password")
|
password := r.Form.Get("password")
|
||||||
form := forms.New(r.PostForm)
|
form := forms.New(r.PostForm)
|
||||||
form.Required("email", "password")
|
form.Required("email", "password")
|
||||||
|
form.IsEmail("email")
|
||||||
if !form.Valid() {
|
if !form.Valid() {
|
||||||
// TODO
|
render.Template(w, r, "login.page.tmpl", &models.TemplateData{
|
||||||
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
|
Form: form,
|
||||||
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -24,3 +24,7 @@ func ServerError(w http.ResponseWriter, err error) {
|
|||||||
app.ErrorLog.Println(trace)
|
app.ErrorLog.Println(trace)
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IsAuthenticated(r *http.Request) bool {
|
||||||
|
return app.Session.Exists(r.Context(), "user_id")
|
||||||
|
}
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col">
|
<div class="col">
|
||||||
<h1>Login</h1>
|
<h1>Login</h1>
|
||||||
<form method="post" action="/user/login">
|
<form method="post" action="/user/login" novalidate>
|
||||||
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
||||||
<div class="form-group mt-5">
|
<div class="form-group mt-5">
|
||||||
<label for="email">Email:</label>
|
<label for="email">Email:</label>
|
||||||
|
Loading…
Reference in New Issue
Block a user