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.2 kB

3 years ago
11 years ago
3 years ago
11 years ago
11 years ago
11 years ago
3 years ago
3 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. } else if setting.PhoneService.Enabled && ctx.User.IsActive && ctx.User.PhoneNumber == "" && ctx.Req.URL.Path != "/bindPhone" {
  49. ctx.Data["Title"] = ctx.Tr("phone.bind_phone")
  50. ctx.HTML(200, "user/auth/bind_phone")
  51. return
  52. }
  53. if ctx.User.MustChangePassword {
  54. if ctx.Req.URL.Path != "/user/settings/change_password" {
  55. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  56. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"
  57. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  58. ctx.Redirect(setting.AppSubURL + "/user/settings/change_password")
  59. return
  60. }
  61. } else if ctx.Req.URL.Path == "/user/settings/change_password" {
  62. // make sure that the form cannot be accessed by users who don't need this
  63. ctx.Redirect(setting.AppSubURL + "/")
  64. return
  65. }
  66. if ctx.QueryBool("course") {
  67. ctx.Redirect(setting.AppSubURL + "/" + setting.Course.OrgName)
  68. return
  69. }
  70. }
  71. // Redirect to dashboard if user tries to visit any non-login page.
  72. if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" {
  73. ctx.Redirect(setting.AppSubURL + "/")
  74. return
  75. }
  76. if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) {
  77. csrf.Validate(ctx.Context, ctx.csrf)
  78. if ctx.Written() {
  79. return
  80. }
  81. }
  82. if options.SignInRequired {
  83. if !ctx.IsSigned {
  84. // Restrict API calls with error message.
  85. if auth.IsAPIPath(ctx.Req.URL.Path) {
  86. ctx.JSON(403, map[string]string{
  87. "message": "Only signed in user is allowed to call APIs.",
  88. })
  89. return
  90. }
  91. tempUrl := ctx.Req.URL.RequestURI()
  92. if strings.Contains(tempUrl, "action/star?") || strings.Contains(tempUrl, "action/watch?") {
  93. redirectForStarAndWatch(ctx, tempUrl)
  94. } else {
  95. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  96. }
  97. ctx.Redirect(setting.AppSubURL + "/user/login")
  98. return
  99. } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  100. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  101. ctx.HTML(200, "user/auth/activate")
  102. return
  103. }
  104. if ctx.IsSigned && auth.IsAPIPath(ctx.Req.URL.Path) && ctx.IsBasicAuth {
  105. twofa, err := models.GetTwoFactorByUID(ctx.User.ID)
  106. if err != nil {
  107. if models.IsErrTwoFactorNotEnrolled(err) {
  108. return // No 2FA enrollment for this user
  109. }
  110. ctx.Error(500)
  111. return
  112. }
  113. otpHeader := ctx.Req.Header.Get("X-Gitea-OTP")
  114. ok, err := twofa.ValidateTOTP(otpHeader)
  115. if err != nil {
  116. ctx.Error(500)
  117. return
  118. }
  119. if !ok {
  120. ctx.JSON(403, map[string]string{
  121. "message": "Only signed in user is allowed to call APIs.",
  122. })
  123. return
  124. }
  125. }
  126. }
  127. if setting.WechatAuthSwitch && options.WechatAuthRequired {
  128. if !ctx.IsSigned {
  129. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  130. ctx.Redirect(setting.AppSubURL + "/user/login")
  131. return
  132. }
  133. if ctx.User.WechatOpenId == "" {
  134. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  135. ctx.Redirect(setting.AppSubURL + "/authentication/wechat/bind")
  136. }
  137. }
  138. if setting.WechatAuthSwitch && options.WechatAuthRequiredForAPI {
  139. if !ctx.IsSigned {
  140. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  141. ctx.Redirect(setting.AppSubURL + "/user/login")
  142. return
  143. }
  144. if ctx.User.WechatOpenId == "" {
  145. redirectUrl := ctx.Query("redirect_to")
  146. if redirectUrl == "" {
  147. redirectUrl = ctx.Req.URL.RequestURI()
  148. }
  149. ctx.SetCookie("redirect_to", setting.AppSubURL+redirectUrl, 0, setting.AppSubURL)
  150. ctx.JSON(200, map[string]string{
  151. "WechatRedirectUrl": setting.AppSubURL + "/authentication/wechat/bind",
  152. })
  153. }
  154. }
  155. // Redirect to log in page if auto-signin info is provided and has not signed in.
  156. if !options.SignOutRequired && !ctx.IsSigned && !auth.IsAPIPath(ctx.Req.URL.Path) &&
  157. len(ctx.GetCookie(setting.CookieUserName)) > 0 {
  158. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  159. ctx.Redirect(setting.AppSubURL + "/user/login")
  160. return
  161. }
  162. if options.AdminRequired {
  163. if !ctx.User.IsAdmin {
  164. ctx.Error(403)
  165. return
  166. }
  167. ctx.Data["PageIsAdmin"] = true
  168. }
  169. if options.BasicAuthRequired {
  170. if !basicAuth(ctx) {
  171. basicUnauthorized(ctx.Resp)
  172. return
  173. }
  174. }
  175. if options.OperationRequired {
  176. if !ctx.User.IsOperator {
  177. ctx.Error(403)
  178. return
  179. }
  180. ctx.Data["PageIsOperation"] = true
  181. }
  182. }
  183. }
  184. func redirectForStarAndWatch(ctx *Context, tempUrl string) {
  185. splits := strings.Split(tempUrl, "?")
  186. if len(splits) > 1 {
  187. redirectArguments := strings.Split(splits[1], "=")
  188. if len(redirectArguments) > 0 && redirectArguments[0] == "redirect_to" {
  189. ctx.SetCookie("redirect_to", setting.AppSubURL+strings.Replace(redirectArguments[1], "%2f", "/", -1), 0, setting.AppSubURL)
  190. }
  191. }
  192. }
  193. func basicAuth(ctx *Context) bool {
  194. var siteAuth = base64.StdEncoding.EncodeToString([]byte(setting.CBAuthUser + ":" + setting.CBAuthPassword))
  195. auth := ctx.Req.Header.Get("Authorization")
  196. if !marc_auth.SecureCompare(auth, "Basic "+siteAuth) {
  197. return false
  198. }
  199. return true
  200. }
  201. func basicUnauthorized(res http.ResponseWriter) {
  202. res.Header().Set("WWW-Authenticate", "Basic realm=\""+marc_auth.BasicRealm+"\"")
  203. http.Error(res, "Not Authorized", http.StatusUnauthorized)
  204. }