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