70 lines
1.5 KiB
Go
70 lines
1.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"html/template"
|
|
"net/http"
|
|
"synlotto-website/models"
|
|
|
|
"github.com/gorilla/csrf"
|
|
)
|
|
|
|
func Login(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
tmpl := template.Must(template.ParseFiles(
|
|
"templates/layout.html",
|
|
"templates/account/login.html",
|
|
))
|
|
|
|
tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{
|
|
"csrfField": csrf.TemplateField(r),
|
|
})
|
|
return
|
|
}
|
|
|
|
username := r.FormValue("username")
|
|
password := r.FormValue("password")
|
|
|
|
user := models.GetUserByUsername(username)
|
|
if user == nil || !CheckPasswordHash(user.PasswordHash, password) {
|
|
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
session, _ := GetSession(w, r)
|
|
session.Values["user_id"] = user.Id
|
|
session.Save(r, w)
|
|
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
}
|
|
|
|
func Signup(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
tmpl := template.Must(template.ParseFiles(
|
|
"templates/layout.html",
|
|
"templates/account/signup.html",
|
|
))
|
|
|
|
tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{
|
|
"csrfField": csrf.TemplateField(r),
|
|
})
|
|
return
|
|
}
|
|
|
|
username := r.FormValue("username")
|
|
password := r.FormValue("password")
|
|
|
|
hashed, err := HashPassword(password)
|
|
if err != nil {
|
|
http.Error(w, "Server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
err = models.CreateUser(username, hashed)
|
|
if err != nil {
|
|
http.Error(w, "Could not create user", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
}
|