package handler

import (
	"github.com/gorilla/csrf"
	"net/http"
	"status/model"
	"status/web/handler/form"
)

func (h *Handler) checkLogin(w http.ResponseWriter, r *http.Request) {
	f := form.NewLoginForm(r)
	user, err := h.storage.VerifyUser(model.User{
		Name:     f.Username,
		Password: f.Password,
	})
	if err != nil {
		f.Error = err.Error()
		h.renderLayout(w, "login", map[string]interface{}{
			"form":           f,
			csrf.TemplateTag: csrf.TemplateField(r),
		}, "")
		return
	}
	if err := h.sess.Save(r, w, user.Name); err != nil {
		serverError(w, err)
		return
	}
	http.Redirect(w, r, "/", http.StatusFound)
}
