2022-10-20 16:59:33 +00:00
|
|
|
package controllers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"GoWeb/app"
|
2023-02-09 01:39:53 +00:00
|
|
|
"GoWeb/models"
|
2022-10-20 16:59:33 +00:00
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// PostController is a wrapper struct for the App struct
|
|
|
|
type PostController struct {
|
|
|
|
App *app.App
|
|
|
|
}
|
|
|
|
|
2022-11-01 16:23:08 +00:00
|
|
|
func (postController *PostController) 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 == "" {
|
2022-11-01 21:14:49 +00:00
|
|
|
log.Println("Tried to login user with empty username or password")
|
|
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
2022-10-20 16:59:33 +00:00
|
|
|
}
|
|
|
|
|
2023-07-21 16:59:55 +00:00
|
|
|
_, err := models.AuthenticateUser(postController.App, w, username, password, remember)
|
2022-11-01 21:14:49 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Println("Error authenticating user")
|
|
|
|
log.Println(err)
|
|
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
http.Redirect(w, r, "/", http.StatusFound)
|
2022-10-20 16:59:33 +00:00
|
|
|
}
|
|
|
|
|
2022-11-01 16:23:08 +00:00
|
|
|
func (postController *PostController) 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 == "" {
|
|
|
|
log.Println("Tried to create user with empty username or password")
|
|
|
|
http.Redirect(w, r, "/register", http.StatusFound)
|
|
|
|
}
|
|
|
|
|
2023-07-21 16:59:55 +00:00
|
|
|
_, err := models.CreateUser(postController.App, username, password, createdAt, updatedAt)
|
2022-11-01 16:23:08 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Println("Error creating user")
|
|
|
|
log.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-10-20 16:59:33 +00:00
|
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
|
|
|
}
|