Creating handler to log in
This commit is contained in:
		@ -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)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user