You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.3 KiB

  1. package Auth
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "time"
  6. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
  7. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  8. "github.com/gofrs/uuid"
  9. )
  10. type Credentials struct {
  11. Email string `json:"email"`
  12. Password string `json:"password"`
  13. }
  14. func Login(w http.ResponseWriter, r *http.Request) {
  15. var (
  16. creds Credentials
  17. userData Models.User
  18. sessionToken uuid.UUID
  19. expiresAt time.Time
  20. err error
  21. )
  22. err = json.NewDecoder(r.Body).Decode(&creds)
  23. if err != nil {
  24. w.WriteHeader(http.StatusBadRequest)
  25. return
  26. }
  27. userData, err = Database.GetUserByEmail(creds.Email)
  28. if err != nil {
  29. w.WriteHeader(http.StatusUnauthorized)
  30. return
  31. }
  32. if !CheckPasswordHash(creds.Password, userData.Password) {
  33. w.WriteHeader(http.StatusUnauthorized)
  34. return
  35. }
  36. sessionToken, err = uuid.NewV4()
  37. if err != nil {
  38. w.WriteHeader(http.StatusInternalServerError)
  39. return
  40. }
  41. expiresAt = time.Now().Add(1 * time.Hour)
  42. Sessions[sessionToken.String()] = Session{
  43. UserID: userData.ID.String(),
  44. Email: userData.Email,
  45. Expiry: expiresAt,
  46. }
  47. http.SetCookie(w, &http.Cookie{
  48. Name: "session_token",
  49. Value: sessionToken.String(),
  50. Expires: expiresAt,
  51. })
  52. w.WriteHeader(http.StatusOK)
  53. }