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