2022-10-20 16:59:33 +00:00
|
|
|
package controllers
|
|
|
|
|
|
|
|
import (
|
2024-07-10 22:45:04 +00:00
|
|
|
"GoWeb/internal"
|
|
|
|
"GoWeb/internal/models"
|
2023-09-03 20:45:12 +00:00
|
|
|
"log/slog"
|
2022-10-20 16:59:33 +00:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2023-08-03 17:09:40 +00:00
|
|
|
// Post is a wrapper struct for the App struct
|
|
|
|
type Post struct {
|
2024-07-02 02:19:48 +00:00
|
|
|
App *app.Deps
|
2022-10-20 16:59:33 +00:00
|
|
|
}
|
|
|
|
|
2023-08-03 17:09:40 +00:00
|
|
|
func (p *Post) Login(w http.ResponseWriter, r *http.Request) {
|
2022-10-20 16:59:33 +00:00
|
|
|
username := r.FormValue("username")
|
|
|
|
password := r.FormValue("password")
|
2023-04-06 13:56:48 +00:00
|
|
|
remember := r.FormValue("remember") == "on"
|
2022-10-20 16:59:33 +00:00
|
|
|
|
|
|
|
if username == "" || password == "" {
|
2023-09-03 20:45:12 +00:00
|
|
|
http.Redirect(w, r, "/login", http.StatusUnauthorized)
|
2022-10-20 16:59:33 +00:00
|
|
|
}
|
|
|
|
|
2023-08-03 17:09:40 +00:00
|
|
|
_, err := models.AuthenticateUser(p.App, w, username, password, remember)
|
2022-11-01 21:14:49 +00:00
|
|
|
if err != nil {
|
2023-09-03 20:45:12 +00:00
|
|
|
http.Redirect(w, r, "/login", http.StatusUnauthorized)
|
2022-11-01 21:14:49 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
http.Redirect(w, r, "/", http.StatusFound)
|
2022-10-20 16:59:33 +00:00
|
|
|
}
|
|
|
|
|
2023-08-03 17:09:40 +00:00
|
|
|
func (p *Post) Register(w http.ResponseWriter, r *http.Request) {
|
2022-10-20 16:59:33 +00:00
|
|
|
username := r.FormValue("username")
|
|
|
|
password := r.FormValue("password")
|
2022-11-01 16:23:08 +00:00
|
|
|
createdAt := time.Now()
|
|
|
|
updatedAt := time.Now()
|
2022-10-20 16:59:33 +00:00
|
|
|
|
|
|
|
if username == "" || password == "" {
|
2023-09-03 20:45:12 +00:00
|
|
|
http.Redirect(w, r, "/register", http.StatusUnauthorized)
|
2022-10-20 16:59:33 +00:00
|
|
|
}
|
|
|
|
|
2023-08-03 17:09:40 +00:00
|
|
|
_, err := models.CreateUser(p.App, username, password, createdAt, updatedAt)
|
2022-11-01 16:23:08 +00:00
|
|
|
if err != nil {
|
2023-09-03 20:45:12 +00:00
|
|
|
// 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
|
|
|
}
|
|
|
|
|
2022-10-20 16:59:33 +00:00
|
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
|
|
|
}
|