55 lines
1.3 KiB
Go
55 lines
1.3 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")
|
|
|
|
user, err := db.GetUserByName(username)
|
|
if user == nil || err != nil {
|
|
time.Sleep(time.Second)
|
|
http.Error(w, "Username or password invalid", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
passHash, err := user.GetPassHash()
|
|
if err != nil {
|
|
http.Error(w, "Something went wrong. Error code: Momo", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
err = bcrypt.CompareHashAndPassword(passHash, []byte(password))
|
|
if err != nil {
|
|
http.Error(w, "Username or password invalid", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
session, err := auth.Store.Get(r, "lishwist_user")
|
|
if err != nil {
|
|
http.Error(w, "Something went wrong. Error code: Sokka", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
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)
|
|
}
|