59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package auth
|
|
|
|
import (
|
|
"lishwist/db"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func (auth *AuthMiddleware) LoginPost(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, "Couldn't parse form", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
username := r.Form.Get("username")
|
|
password := r.Form.Get("password")
|
|
|
|
props := NewLoginProps()
|
|
props.Username.Value = username
|
|
|
|
user, err := db.GetUserByName(username)
|
|
if user == nil || err != nil {
|
|
time.Sleep(time.Second)
|
|
props.GeneralError = "Username or password invalid"
|
|
auth.RedirectWithFlash(w, r, "/", "login_props", &props)
|
|
return
|
|
}
|
|
|
|
passHash, err := user.GetPassHash()
|
|
if err != nil {
|
|
props.GeneralError = "Something went wrong. Error code: Momo"
|
|
auth.RedirectWithFlash(w, r, "/", "login_props", &props)
|
|
return
|
|
}
|
|
|
|
err = bcrypt.CompareHashAndPassword(passHash, []byte(password))
|
|
if err != nil {
|
|
props.GeneralError = "Username or password invalid"
|
|
auth.RedirectWithFlash(w, r, "/", "login_props", &props)
|
|
return
|
|
}
|
|
|
|
// NOTE: Overwriting any existing cookie or session here. So we don't care if there's an error
|
|
session, _ := auth.Store.Get(r, "lishwist_user")
|
|
session.ID = ""
|
|
session.Values["authorized"] = true
|
|
session.Values["username"] = username
|
|
if err := session.Save(r, w); err != nil {
|
|
log.Println("Couldn't save session:", err)
|
|
http.Error(w, "Something went wrong. Error code: Zuko", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.Redirect(w, r, r.URL.Path, http.StatusSeeOther)
|
|
}
|