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.5 KiB

  1. package Auth
  2. import (
  3. "errors"
  4. "net/http"
  5. "time"
  6. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  7. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Util"
  8. )
  9. var (
  10. Sessions = map[string]Session{}
  11. )
  12. type Session struct {
  13. UserID string
  14. Email string
  15. Expiry time.Time
  16. }
  17. func (s Session) IsExpired() bool {
  18. return s.Expiry.Before(time.Now())
  19. }
  20. func CheckCookie(r *http.Request) (Session, error) {
  21. var (
  22. c *http.Cookie
  23. sessionToken string
  24. userSession Session
  25. exists bool
  26. err error
  27. )
  28. c, err = r.Cookie("session_token")
  29. if err != nil {
  30. return userSession, err
  31. }
  32. sessionToken = c.Value
  33. // We then get the session from our session map
  34. userSession, exists = Sessions[sessionToken]
  35. if !exists {
  36. return userSession, errors.New("Cookie not found")
  37. }
  38. // If the session is present, but has expired, we can delete the session, and return
  39. // an unauthorized status
  40. if userSession.IsExpired() {
  41. delete(Sessions, sessionToken)
  42. return userSession, errors.New("Cookie expired")
  43. }
  44. return userSession, nil
  45. }
  46. func CheckCookieCurrentUser(w http.ResponseWriter, r *http.Request) (Models.User, error) {
  47. var (
  48. userSession Session
  49. userData Models.User
  50. err error
  51. )
  52. userSession, err = CheckCookie(r)
  53. if err != nil {
  54. return userData, err
  55. }
  56. userData, err = Util.GetUserById(w, r)
  57. if err != nil {
  58. return userData, err
  59. }
  60. if userData.ID.String() != userSession.UserID {
  61. return userData, errors.New("Is not current user")
  62. }
  63. return userData, nil
  64. }