You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth.go 7.0 kB

3 years ago
11 years ago
3 years ago
11 years ago
11 years ago
11 years ago
3 years ago
11 years ago
11 years ago
11 years ago
11 years ago
3 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
9 years ago
11 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package context
  6. import (
  7. "encoding/base64"
  8. "net/http"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/auth"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "gitea.com/macaron/csrf"
  15. "gitea.com/macaron/macaron"
  16. marc_auth "github.com/go-macaron/auth"
  17. )
  18. // ToggleOptions contains required or check options
  19. type ToggleOptions struct {
  20. SignInRequired bool
  21. SignOutRequired bool
  22. AdminRequired bool
  23. DisableCSRF bool
  24. BasicAuthRequired bool
  25. OperationRequired bool
  26. WechatAuthRequired bool
  27. WechatAuthRequiredForAPI bool
  28. }
  29. // Toggle returns toggle options as middleware
  30. func Toggle(options *ToggleOptions) macaron.Handler {
  31. return func(ctx *Context) {
  32. // Cannot view any page before installation.
  33. if !setting.InstallLock {
  34. ctx.Redirect(setting.AppSubURL + "/install")
  35. return
  36. }
  37. // Check prohibit login users.
  38. if ctx.IsSigned {
  39. if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  40. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  41. ctx.HTML(200, "user/auth/activate")
  42. return
  43. } else if !ctx.User.IsActive || ctx.User.ProhibitLogin {
  44. log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr())
  45. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  46. ctx.HTML(200, "user/auth/prohibit_login")
  47. return
  48. }
  49. if ctx.User.MustChangePassword {
  50. if ctx.Req.URL.Path != "/user/settings/change_password" {
  51. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  52. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"
  53. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  54. ctx.Redirect(setting.AppSubURL + "/user/settings/change_password")
  55. return
  56. }
  57. } else if ctx.Req.URL.Path == "/user/settings/change_password" {
  58. // make sure that the form cannot be accessed by users who don't need this
  59. ctx.Redirect(setting.AppSubURL + "/")
  60. return
  61. }
  62. if ctx.QueryBool("course") {
  63. ctx.Redirect(setting.AppSubURL + "/" + setting.Course.OrgName)
  64. return
  65. }
  66. }
  67. // Redirect to dashboard if user tries to visit any non-login page.
  68. if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" {
  69. ctx.Redirect(setting.AppSubURL + "/")
  70. return
  71. }
  72. if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) {
  73. csrf.Validate(ctx.Context, ctx.csrf)
  74. if ctx.Written() {
  75. return
  76. }
  77. }
  78. if options.SignInRequired {
  79. if !ctx.IsSigned {
  80. // Restrict API calls with error message.
  81. if auth.IsAPIPath(ctx.Req.URL.Path) {
  82. ctx.JSON(403, map[string]string{
  83. "message": "Only signed in user is allowed to call APIs.",
  84. })
  85. return
  86. }
  87. tempUrl := ctx.Req.URL.RequestURI()
  88. if strings.Contains(tempUrl, "action/star?") || strings.Contains(tempUrl, "action/watch?") {
  89. redirectForStarAndWatch(ctx, tempUrl)
  90. } else {
  91. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  92. }
  93. ctx.Redirect(setting.AppSubURL + "/user/login")
  94. return
  95. } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  96. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  97. ctx.HTML(200, "user/auth/activate")
  98. return
  99. }
  100. if ctx.IsSigned && auth.IsAPIPath(ctx.Req.URL.Path) && ctx.IsBasicAuth {
  101. twofa, err := models.GetTwoFactorByUID(ctx.User.ID)
  102. if err != nil {
  103. if models.IsErrTwoFactorNotEnrolled(err) {
  104. return // No 2FA enrollment for this user
  105. }
  106. ctx.Error(500)
  107. return
  108. }
  109. otpHeader := ctx.Req.Header.Get("X-Gitea-OTP")
  110. ok, err := twofa.ValidateTOTP(otpHeader)
  111. if err != nil {
  112. ctx.Error(500)
  113. return
  114. }
  115. if !ok {
  116. ctx.JSON(403, map[string]string{
  117. "message": "Only signed in user is allowed to call APIs.",
  118. })
  119. return
  120. }
  121. }
  122. }
  123. if setting.WechatAuthSwitch && options.WechatAuthRequired {
  124. if !ctx.IsSigned {
  125. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  126. ctx.Redirect(setting.AppSubURL + "/user/login")
  127. return
  128. }
  129. if ctx.User.WechatOpenId == "" {
  130. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  131. ctx.Redirect(setting.AppSubURL + "/authentication/wechat/bind")
  132. }
  133. }
  134. if setting.WechatAuthSwitch && options.WechatAuthRequiredForAPI {
  135. if !ctx.IsSigned {
  136. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  137. ctx.Redirect(setting.AppSubURL + "/user/login")
  138. return
  139. }
  140. if ctx.User.WechatOpenId == "" {
  141. redirectUrl := ctx.Query("redirect_to")
  142. if redirectUrl == "" {
  143. redirectUrl = ctx.Req.URL.RequestURI()
  144. }
  145. ctx.SetCookie("redirect_to", setting.AppSubURL+redirectUrl, 0, setting.AppSubURL)
  146. ctx.JSON(200, map[string]string{
  147. "WechatRedirectUrl": setting.AppSubURL + "/authentication/wechat/bind",
  148. })
  149. }
  150. }
  151. // Redirect to log in page if auto-signin info is provided and has not signed in.
  152. if !options.SignOutRequired && !ctx.IsSigned && !auth.IsAPIPath(ctx.Req.URL.Path) &&
  153. len(ctx.GetCookie(setting.CookieUserName)) > 0 {
  154. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  155. ctx.Redirect(setting.AppSubURL + "/user/login")
  156. return
  157. }
  158. if options.AdminRequired {
  159. if !ctx.User.IsAdmin {
  160. ctx.Error(403)
  161. return
  162. }
  163. ctx.Data["PageIsAdmin"] = true
  164. }
  165. if options.BasicAuthRequired {
  166. if !basicAuth(ctx) {
  167. basicUnauthorized(ctx.Resp)
  168. return
  169. }
  170. }
  171. if options.OperationRequired {
  172. if !ctx.User.IsOperator {
  173. ctx.Error(403)
  174. return
  175. }
  176. ctx.Data["PageIsOperation"] = true
  177. }
  178. }
  179. }
  180. func redirectForStarAndWatch(ctx *Context, tempUrl string) {
  181. splits := strings.Split(tempUrl, "?")
  182. if len(splits) > 1 {
  183. redirectArguments := strings.Split(splits[1], "=")
  184. if len(redirectArguments) > 0 && redirectArguments[0] == "redirect_to" {
  185. ctx.SetCookie("redirect_to", setting.AppSubURL+strings.Replace(redirectArguments[1], "%2f", "/", -1), 0, setting.AppSubURL)
  186. }
  187. }
  188. }
  189. func basicAuth(ctx *Context) bool {
  190. var siteAuth = base64.StdEncoding.EncodeToString([]byte(setting.CBAuthUser + ":" + setting.CBAuthPassword))
  191. auth := ctx.Req.Header.Get("Authorization")
  192. if !marc_auth.SecureCompare(auth, "Basic "+siteAuth) {
  193. return false
  194. }
  195. return true
  196. }
  197. func basicUnauthorized(res http.ResponseWriter) {
  198. res.Header().Set("WWW-Authenticate", "Basic realm=\""+marc_auth.BasicRealm+"\"")
  199. http.Error(res, "Not Authorized", http.StatusUnauthorized)
  200. }