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.

session.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package auth
  4. import (
  5. "context"
  6. "net/http"
  7. user_model "code.gitea.io/gitea/models/user"
  8. "code.gitea.io/gitea/modules/log"
  9. )
  10. // Ensure the struct implements the interface.
  11. var (
  12. _ Method = &Session{}
  13. )
  14. // Session checks if there is a user uid stored in the session and returns the user
  15. // object for that uid.
  16. type Session struct{}
  17. // Name represents the name of auth method
  18. func (s *Session) Name() string {
  19. return "session"
  20. }
  21. // Verify checks if there is a user uid stored in the session and returns the user
  22. // object for that uid.
  23. // Returns nil if there is no user uid stored in the session.
  24. func (s *Session) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
  25. user := SessionUser(req.Context(), sess)
  26. if user != nil {
  27. return user, nil
  28. }
  29. return nil, nil
  30. }
  31. // SessionUser returns the user object corresponding to the "uid" session variable.
  32. func SessionUser(ctx context.Context, sess SessionStore) *user_model.User {
  33. if sess == nil {
  34. return nil
  35. }
  36. // Get user ID
  37. uid := sess.Get("uid")
  38. if uid == nil {
  39. return nil
  40. }
  41. log.Trace("Session Authorization: Found user[%d]", uid)
  42. id, ok := uid.(int64)
  43. if !ok {
  44. return nil
  45. }
  46. // Get user object
  47. user, err := user_model.GetUserByID(ctx, id)
  48. if err != nil {
  49. if !user_model.IsErrUserNotExist(err) {
  50. log.Error("GetUserById: %v", err)
  51. }
  52. return nil
  53. }
  54. log.Trace("Session Authorization: Logged in user %-v", user)
  55. return user
  56. }