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.

82 lines
1.7 KiB

  1. // Copyright 2014 The Gogs 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. "github.com/codegangsta/martini"
  7. "github.com/martini-contrib/render"
  8. "github.com/martini-contrib/sessions"
  9. "github.com/gogits/gogs/models"
  10. "github.com/gogits/gogs/modules/base"
  11. "github.com/gogits/gogs/modules/log"
  12. )
  13. func SignedInId(session sessions.Session) int64 {
  14. userId := session.Get("userId")
  15. if userId == nil {
  16. return 0
  17. }
  18. if s, ok := userId.(int64); ok {
  19. return s
  20. }
  21. return 0
  22. }
  23. func SignedInName(session sessions.Session) string {
  24. userName := session.Get("userName")
  25. if userName == nil {
  26. return ""
  27. }
  28. if s, ok := userName.(string); ok {
  29. return s
  30. }
  31. return ""
  32. }
  33. func SignedInUser(session sessions.Session) *models.User {
  34. id := SignedInId(session)
  35. if id <= 0 {
  36. return nil
  37. }
  38. user, err := models.GetUserById(id)
  39. if err != nil {
  40. log.Error("user.SignedInUser: %v", err)
  41. return nil
  42. }
  43. return user
  44. }
  45. func IsSignedIn(session sessions.Session) bool {
  46. return SignedInId(session) > 0
  47. }
  48. // SignInRequire checks user status from session.
  49. // It will assign correspoding values to
  50. // template data map if user has signed in.
  51. func SignInRequire(redirect bool) martini.Handler {
  52. return func(r render.Render, data base.TmplData, session sessions.Session) {
  53. if !IsSignedIn(session) {
  54. if redirect {
  55. r.Redirect("/")
  56. }
  57. return
  58. }
  59. data["IsSigned"] = true
  60. data["SignedUserId"] = SignedInId(session)
  61. data["SignedUserName"] = SignedInName(session)
  62. data["SignedAvatar"] = SignedInUser(session).Avatar
  63. }
  64. }
  65. func SignOutRequire() martini.Handler {
  66. return func(r render.Render, session sessions.Session) {
  67. if IsSignedIn(session) {
  68. r.Redirect("/")
  69. }
  70. }
  71. }