Creating handler to log in

This commit is contained in:
2024-07-19 10:02:58 +02:00
parent d32fd432d2
commit a6dca00199
3 changed files with 41 additions and 4 deletions

View File

@ -10,6 +10,7 @@ import (
"go-udemy-web-1/internal/render"
"go-udemy-web-1/internal/repository"
"go-udemy-web-1/internal/repository/dbrepo"
"log"
"net/http"
"strconv"
"strings"
@ -457,3 +458,37 @@ func (m *Repository) ShowLogin(w http.ResponseWriter, r *http.Request) {
Form: forms.New(nil),
})
}
// PostShowLogin handles logging the user in
func (m *Repository) PostShowLogin(w http.ResponseWriter, r *http.Request) {
_ = m.App.Session.RenewToken(r.Context())
err := r.ParseForm()
if err != nil {
m.App.Session.Put(r.Context(), "error", "Can't parse form")
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
return
}
email := r.Form.Get("email")
password := r.Form.Get("password")
form := forms.New(r.PostForm)
form.Required("email", "password")
if !form.Valid() {
// TODO
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
return
}
id, _, err := m.DB.Authenticate(email, password)
if err != nil {
log.Println(err)
m.App.Session.Put(r.Context(), "error", "Invalid login credentials")
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
return
}
m.App.Session.Put(r.Context(), "user_id", id)
m.App.Session.Put(r.Context(), "flash", "Logged in successfully")
http.Redirect(w, r, "/", http.StatusSeeOther)
}