package Auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
|
|
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
|
|
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Util"
|
|
|
|
"github.com/gofrs/uuid"
|
|
)
|
|
|
|
type Credentials struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
func Login(w http.ResponseWriter, r *http.Request) {
|
|
var (
|
|
creds Credentials
|
|
userData Models.User
|
|
sessionToken uuid.UUID
|
|
expiresAt time.Time
|
|
returnJson []byte
|
|
err error
|
|
)
|
|
|
|
err = json.NewDecoder(r.Body).Decode(&creds)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
userData, err = Database.GetUserByEmail(creds.Email)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
if !CheckPasswordHash(creds.Password, userData.Password) {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
sessionToken, err = uuid.NewV4()
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
expiresAt = time.Now().Add(1 * time.Hour)
|
|
|
|
Sessions[sessionToken.String()] = Session{
|
|
UserID: userData.ID.String(),
|
|
Email: userData.Email,
|
|
Expiry: expiresAt,
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "session_token",
|
|
Value: sessionToken.String(),
|
|
Expires: expiresAt,
|
|
})
|
|
|
|
userData.Password = ""
|
|
|
|
returnJson, err = json.MarshalIndent(userData, "", " ")
|
|
if err != nil {
|
|
log.Printf("An error occured: %s\n", err.Error())
|
|
Util.JsonReturn(w, 500, "An error occured")
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write(returnJson)
|
|
}
|