63 lines
1.5 KiB
Go
63 lines
1.5 KiB
Go
package endpoints
|
|
|
|
import (
|
|
"arbeitszeitmessung/models"
|
|
"arbeitszeitmessung/templates"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/alexedwards/scs/v2"
|
|
)
|
|
|
|
var Session *scs.SessionManager
|
|
|
|
func CreateSessionManager(lifetime time.Duration) *scs.SessionManager {
|
|
Session = scs.New()
|
|
Session.Lifetime = lifetime
|
|
return Session
|
|
}
|
|
|
|
func LoginHandler(w http.ResponseWriter, r *http.Request){
|
|
switch r.Method{
|
|
case http.MethodGet: showForm(w, r)
|
|
break
|
|
case http.MethodPost: loginUser(w, r)
|
|
break
|
|
default:
|
|
showForm(w, r)
|
|
break
|
|
}
|
|
}
|
|
|
|
func showForm(w http.ResponseWriter, r *http.Request){
|
|
templates.LoginForm().Render(r.Context(), w)
|
|
}
|
|
|
|
func loginUser(w http.ResponseWriter, r *http.Request){
|
|
err := r.ParseForm()
|
|
if err != nil {
|
|
log.Println("Error parsing form!", err)
|
|
http.Error(w, "Internal error", http.StatusBadRequest)
|
|
}
|
|
card_uid := r.FormValue("card_uid")
|
|
if(card_uid == ""){
|
|
log.Println("No card_uid provided!")
|
|
http.Error(w, "No card_uid provided", http.StatusBadRequest)
|
|
}
|
|
user, err := (*models.User).GetById(nil, card_uid)
|
|
if(err != nil){
|
|
log.Println("No user found under this card_uid!")
|
|
http.Error(w, "No user found!", http.StatusNotFound)
|
|
}
|
|
|
|
password := r.FormValue("password")
|
|
if(user.Login(password)){
|
|
log.Printf("New succesfull user login from %s %s!\n", user.Vorname, user.Name)
|
|
Session.Put(r.Context(), "user", user.CardUID)
|
|
http.Redirect(w, r, "/time", http.StatusSeeOther) //with this browser always uses GET
|
|
}
|
|
|
|
showForm(w, r)
|
|
}
|