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