GoWeb/controllers/post.go

53 lines
1.3 KiB
Go
Raw Permalink Normal View History

package controllers
import (
"GoWeb/app"
2023-02-09 01:39:53 +00:00
"GoWeb/models"
"log/slog"
"net/http"
"time"
)
// Post is a wrapper struct for the App struct
type Post struct {
App *app.App
}
func (p *Post) Login(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
remember := r.FormValue("remember") == "on"
if username == "" || password == "" {
http.Redirect(w, r, "/login", http.StatusUnauthorized)
}
_, err := models.AuthenticateUser(p.App, w, username, password, remember)
if err != nil {
http.Redirect(w, r, "/login", http.StatusUnauthorized)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
func (p *Post) Register(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
2022-11-01 16:23:08 +00:00
createdAt := time.Now()
updatedAt := time.Now()
if username == "" || password == "" {
http.Redirect(w, r, "/register", http.StatusUnauthorized)
}
_, err := models.CreateUser(p.App, username, password, createdAt, updatedAt)
2022-11-01 16:23:08 +00:00
if err != nil {
// TODO: if err == bcrypt.ErrPasswordTooLong display error to user, this will require a flash message system with cookies
slog.Error("error creating user: " + err.Error())
http.Redirect(w, r, "/register", http.StatusInternalServerError)
2022-11-01 16:23:08 +00:00
}
http.Redirect(w, r, "/login", http.StatusFound)
}