105 lines
2.4 KiB
Go
105 lines
2.4 KiB
Go
package handlers
|
||
|
||
import (
|
||
"html/template"
|
||
"net/http"
|
||
"synlotto-website/helpers"
|
||
"synlotto-website/models"
|
||
"time"
|
||
|
||
"github.com/gorilla/csrf"
|
||
)
|
||
|
||
func Login(w http.ResponseWriter, r *http.Request) {
|
||
if r.Method == http.MethodGet {
|
||
session, _ := helpers.GetSession(w, r)
|
||
if _, ok := session.Values["user_id"].(int); ok {
|
||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||
return
|
||
}
|
||
|
||
tmpl := template.Must(template.ParseFiles(
|
||
"templates/layout.html",
|
||
"templates/account/login.html",
|
||
))
|
||
|
||
context := helpers.TemplateContext(w, r)
|
||
context["csrfField"] = csrf.TemplateField(r)
|
||
|
||
tmpl.ExecuteTemplate(w, "layout", context)
|
||
return
|
||
}
|
||
|
||
username := r.FormValue("username")
|
||
password := r.FormValue("password")
|
||
|
||
user := models.GetUserByUsername(username)
|
||
if user == nil || !helpers.CheckPasswordHash(user.PasswordHash, password) {
|
||
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||
return
|
||
}
|
||
|
||
session, _ := helpers.GetSession(w, r)
|
||
session.Options.MaxAge = -1
|
||
session.Save(r, w)
|
||
|
||
remember := r.FormValue("remember") == "on"
|
||
|
||
newSession, _ := helpers.GetSession(w, r)
|
||
newSession.Values["user_id"] = user.Id
|
||
newSession.Values["last_activity"] = time.Now()
|
||
|
||
if remember {
|
||
newSession.Options.MaxAge = 60 * 60 * 24 * 30 // 30 days
|
||
} else {
|
||
newSession.Options.MaxAge = 0
|
||
}
|
||
|
||
newSession.Save(r, w)
|
||
|
||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||
}
|
||
|
||
func Logout(w http.ResponseWriter, r *http.Request) {
|
||
session, _ := helpers.GetSession(w, r)
|
||
session.Options.MaxAge = -1
|
||
session.Save(r, w)
|
||
|
||
newSession, _ := helpers.GetSession(w, r)
|
||
newSession.Values["flash"] = "You’ve been logged out"
|
||
newSession.Save(r, w)
|
||
|
||
http.Redirect(w, r, "/login", 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 := helpers.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)
|
||
}
|