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.

79 lines
1.6 KiB

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