aboutsummaryrefslogtreecommitdiff
path: root/controllers/user.go
diff options
context:
space:
mode:
Diffstat (limited to 'controllers/user.go')
-rw-r--r--controllers/user.go59
1 files changed, 59 insertions, 0 deletions
diff --git a/controllers/user.go b/controllers/user.go
new file mode 100644
index 0000000..a605c25
--- /dev/null
+++ b/controllers/user.go
@@ -0,0 +1,59 @@
+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)
+
+ (*sess)["user"] = u
+
+ mux.Redirect(w, 302, "/")
+ return
+ }
+
+ mux.Render(w, r, views.Login(req.Email))
+}
+
+func (rt *Router) Logout(w http.ResponseWriter, r *http.Request) {
+ session.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))
+}