2025-07-26 23:31:00 +02:00
|
|
|
package handler
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"errors"
|
2025-08-23 13:28:48 +02:00
|
|
|
"net/http"
|
|
|
|
|
|
2025-07-26 23:31:00 +02:00
|
|
|
"gitea.kleinsense.nl/DariusKlein/kleinTodo/common"
|
|
|
|
|
"gitea.kleinsense.nl/DariusKlein/kleinTodo/common/jwt"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
var user common.Credentials
|
|
|
|
|
// Decode input
|
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&user)
|
|
|
|
|
if handleError(w, http.StatusInternalServerError, err) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
// Get data store
|
|
|
|
|
db, err := common.GetTodoDataStore()
|
|
|
|
|
if handleError(w, http.StatusInternalServerError, err) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
password := db.GetFromBucketByKey(common.UserBucket, user.Username)
|
|
|
|
|
if user.ComparePasswords(password) {
|
|
|
|
|
w.Header().Set(common.AuthHeader, jwt.CreateUserJWT(user.Username))
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
|
if handleError(w, http.StatusInternalServerError, err) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
handleError(w, http.StatusUnauthorized, errors.New("username or password is incorrect"))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|