101 lines
2.3 KiB
Go
101 lines
2.3 KiB
Go
package handlers
|
||
|
||
import (
|
||
"html/template"
|
||
"net/http"
|
||
"synlotto-website/helpers"
|
||
"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",
|
||
))
|
||
|
||
session, _ := helpers.GetSession(w, r)
|
||
|
||
var flash string
|
||
if f, ok := session.Values["flash"].(string); ok {
|
||
flash = f
|
||
delete(session.Values, "flash")
|
||
session.Save(r, w)
|
||
}
|
||
|
||
tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{
|
||
"csrfField": csrf.TemplateField(r),
|
||
"Flash": flash,
|
||
})
|
||
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, err := helpers.GetSession(w, r)
|
||
if err != nil {
|
||
http.Error(w, "Session error", http.StatusInternalServerError)
|
||
return
|
||
}
|
||
session.Options.MaxAge = -1
|
||
session.Save(r, w)
|
||
|
||
newSession, _ := helpers.GetSession(w, r)
|
||
newSession.Values["user_id"] = user.Id
|
||
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 := 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)
|
||
}
|