package controllers
import (
"net/http"
"gitrepo.ru/neonxp/gorum/models"
"gitrepo.ru/neonxp/gorum/views"
"go.neonxp.ru/mux"
"go.neonxp.ru/mux/middleware/session"
)
func (rt *Router) Login(w http.ResponseWriter, r *http.Request) {
req := new(loginRequest)
if r.Method == http.MethodPost {
if err := mux.Bind(r, req); err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
u, err := rt.userRepo.Login(req.Email, req.Password)
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
sess := session.FromRequest(r)
values := sess.Values(r.Context())
values["user"] = u
if err := sess.Save(w, r, values); err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
mux.Redirect(w, 302, "/")
return
}
mux.Render(w, r, views.Login(req.Email))
}
func (rt *Router) Logout(w http.ResponseWriter, r *http.Request) {
sess := session.FromRequest(r)
sess.Clear(w, r)
mux.Redirect(w, 302, "/")
}
func (rt *Router) Register(w http.ResponseWriter, r *http.Request) {
req := new(registerRequest)
if err := mux.Bind(r, req); err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
if r.Method == http.MethodPost {
if err := rt.userRepo.Create(req.Email, req.Password, req.Username, models.RoleUser); err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
mux.Redirect(w, 302, "/login")
return
}
mux.Render(w, r, views.Register(req.Username, req.Email))
}