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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package auth
  5. import (
  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. _ Named = &Session{}
  14. )
  15. // Session checks if there is a user uid stored in the session and returns the user
  16. // object for that uid.
  17. type Session struct {
  18. }
  19. // Name represents the name of auth method
  20. func (s *Session) Name() string {
  21. return "session"
  22. }
  23. // Verify checks if there is a user uid stored in the session and returns the user
  24. // object for that uid.
  25. // Returns nil if there is no user uid stored in the session.
  26. func (s *Session) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *user_model.User {
  27. user := SessionUser(sess)
  28. if user != nil {
  29. return user
  30. }
  31. return nil
  32. }
  33. // SessionUser returns the user object corresponding to the "uid" session variable.
  34. func SessionUser(sess SessionStore) *user_model.User {
  35. // Get user ID
  36. uid := sess.Get("uid")
  37. if uid == nil {
  38. return nil
  39. }
  40. log.Trace("Session Authorization: Found user[%d]", uid)
  41. id, ok := uid.(int64)
  42. if !ok {
  43. return nil
  44. }
  45. // Get user object
  46. user, err := user_model.GetUserByID(id)
  47. if err != nil {
  48. if !user_model.IsErrUserNotExist(err) {
  49. log.Error("GetUserById: %v", err)
  50. }
  51. return nil
  52. }
  53. log.Trace("Session Authorization: Logged in user %-v", user)
  54. return user
  55. }