gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package auth
  4. import (
  5. "errors"
  6. "net/http"
  7. "strings"
  8. "code.gitea.io/gitea/models/auth"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/templates"
  13. "code.gitea.io/gitea/modules/util"
  14. "code.gitea.io/gitea/modules/web"
  15. auth_service "code.gitea.io/gitea/services/auth"
  16. "code.gitea.io/gitea/services/auth/source/oauth2"
  17. "code.gitea.io/gitea/services/context"
  18. "code.gitea.io/gitea/services/externalaccount"
  19. "code.gitea.io/gitea/services/forms"
  20. )
  21. var tplLinkAccount templates.TplName = "user/auth/link_account"
  22. // LinkAccount shows the page where the user can decide to login or create a new account
  23. func LinkAccount(ctx *context.Context) {
  24. // FIXME: these common template variables should be prepared in one common function, but not just copy-paste again and again.
  25. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration
  26. ctx.Data["Title"] = ctx.Tr("link_account")
  27. ctx.Data["LinkAccountMode"] = true
  28. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  29. ctx.Data["Captcha"] = context.GetImageCaptcha()
  30. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  31. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  32. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  33. ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey
  34. ctx.Data["McaptchaSitekey"] = setting.Service.McaptchaSitekey
  35. ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL
  36. ctx.Data["CfTurnstileSitekey"] = setting.Service.CfTurnstileSitekey
  37. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  38. ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration
  39. ctx.Data["EnablePasswordSignInForm"] = setting.Service.EnablePasswordSignInForm
  40. ctx.Data["ShowRegistrationButton"] = false
  41. ctx.Data["EnablePasskeyAuth"] = setting.Service.EnablePasskeyAuth
  42. // use this to set the right link into the signIn and signUp templates in the link_account template
  43. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  44. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  45. linkAccountData := oauth2GetLinkAccountData(ctx)
  46. // If you'd like to quickly debug the "link account" page layout, just uncomment the blow line
  47. // Don't worry, when the below line exists, the lint won't pass: ineffectual assignment to gothUser (ineffassign)
  48. // linkAccountData = &LinkAccountData{authSource, gothUser} // intentionally use invalid data to avoid pass the registration check
  49. if linkAccountData == nil {
  50. // no account in session, so just redirect to the login page, then the user could restart the process
  51. ctx.Redirect(setting.AppSubURL + "/user/login")
  52. return
  53. }
  54. if missingFields, ok := linkAccountData.GothUser.RawData["__giteaAutoRegMissingFields"].([]string); ok {
  55. ctx.Data["AutoRegistrationFailedPrompt"] = ctx.Tr("auth.oauth_callback_unable_auto_reg", linkAccountData.GothUser.Provider, strings.Join(missingFields, ","))
  56. }
  57. uname, err := extractUserNameFromOAuth2(&linkAccountData.GothUser)
  58. if err != nil {
  59. ctx.ServerError("UserSignIn", err)
  60. return
  61. }
  62. email := linkAccountData.GothUser.Email
  63. ctx.Data["user_name"] = uname
  64. ctx.Data["email"] = email
  65. if email != "" {
  66. u, err := user_model.GetUserByEmail(ctx, email)
  67. if err != nil && !user_model.IsErrUserNotExist(err) {
  68. ctx.ServerError("UserSignIn", err)
  69. return
  70. }
  71. if u != nil {
  72. ctx.Data["user_exists"] = true
  73. }
  74. } else if uname != "" {
  75. u, err := user_model.GetUserByName(ctx, uname)
  76. if err != nil && !user_model.IsErrUserNotExist(err) {
  77. ctx.ServerError("UserSignIn", err)
  78. return
  79. }
  80. if u != nil {
  81. ctx.Data["user_exists"] = true
  82. }
  83. }
  84. ctx.HTML(http.StatusOK, tplLinkAccount)
  85. }
  86. func handleSignInError(ctx *context.Context, userName string, ptrForm any, tmpl templates.TplName, invoker string, err error) {
  87. if errors.Is(err, util.ErrNotExist) {
  88. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tmpl, ptrForm)
  89. } else if errors.Is(err, util.ErrInvalidArgument) {
  90. ctx.Data["user_exists"] = true
  91. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tmpl, ptrForm)
  92. } else if user_model.IsErrUserProhibitLogin(err) {
  93. ctx.Data["user_exists"] = true
  94. log.Info("Failed authentication attempt for %s from %s: %v", userName, ctx.RemoteAddr(), err)
  95. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  96. ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
  97. } else if user_model.IsErrUserInactive(err) {
  98. ctx.Data["user_exists"] = true
  99. if setting.Service.RegisterEmailConfirm {
  100. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  101. ctx.HTML(http.StatusOK, TplActivate)
  102. } else {
  103. log.Info("Failed authentication attempt for %s from %s: %v", userName, ctx.RemoteAddr(), err)
  104. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  105. ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
  106. }
  107. } else {
  108. ctx.ServerError(invoker, err)
  109. }
  110. }
  111. // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
  112. func LinkAccountPostSignIn(ctx *context.Context) {
  113. signInForm := web.GetForm(ctx).(*forms.SignInForm)
  114. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration
  115. ctx.Data["Title"] = ctx.Tr("link_account")
  116. ctx.Data["LinkAccountMode"] = true
  117. ctx.Data["LinkAccountModeSignIn"] = true
  118. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  119. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  120. ctx.Data["Captcha"] = context.GetImageCaptcha()
  121. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  122. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  123. ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey
  124. ctx.Data["McaptchaSitekey"] = setting.Service.McaptchaSitekey
  125. ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL
  126. ctx.Data["CfTurnstileSitekey"] = setting.Service.CfTurnstileSitekey
  127. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  128. ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration
  129. ctx.Data["EnablePasswordSignInForm"] = setting.Service.EnablePasswordSignInForm
  130. ctx.Data["ShowRegistrationButton"] = false
  131. ctx.Data["EnablePasskeyAuth"] = setting.Service.EnablePasskeyAuth
  132. // use this to set the right link into the signIn and signUp templates in the link_account template
  133. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  134. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  135. linkAccountData := oauth2GetLinkAccountData(ctx)
  136. if linkAccountData == nil {
  137. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  138. return
  139. }
  140. if ctx.HasError() {
  141. ctx.HTML(http.StatusOK, tplLinkAccount)
  142. return
  143. }
  144. u, _, err := auth_service.UserSignIn(ctx, signInForm.UserName, signInForm.Password)
  145. if err != nil {
  146. handleSignInError(ctx, signInForm.UserName, &signInForm, tplLinkAccount, "UserLinkAccount", err)
  147. return
  148. }
  149. oauth2LinkAccount(ctx, u, linkAccountData, signInForm.Remember)
  150. }
  151. func oauth2LinkAccount(ctx *context.Context, u *user_model.User, linkAccountData *LinkAccountData, remember bool) {
  152. oauth2SignInSync(ctx, linkAccountData.AuthSourceID, u, linkAccountData.GothUser)
  153. if ctx.Written() {
  154. return
  155. }
  156. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  157. // Instead, redirect them to the 2FA authentication page.
  158. // We deliberately ignore the skip local 2fa setting here because we are linking to a previous user here
  159. _, err := auth.GetTwoFactorByUID(ctx, u.ID)
  160. if err != nil {
  161. if !auth.IsErrTwoFactorNotEnrolled(err) {
  162. ctx.ServerError("UserLinkAccount", err)
  163. return
  164. }
  165. err = externalaccount.LinkAccountToUser(ctx, linkAccountData.AuthSourceID, u, linkAccountData.GothUser)
  166. if err != nil {
  167. ctx.ServerError("UserLinkAccount", err)
  168. return
  169. }
  170. handleSignIn(ctx, u, remember)
  171. return
  172. }
  173. if err := updateSession(ctx, nil, map[string]any{
  174. // User needs to use 2FA, save data and redirect to 2FA page.
  175. "twofaUid": u.ID,
  176. "twofaRemember": remember,
  177. "linkAccount": true,
  178. }); err != nil {
  179. ctx.ServerError("RegenerateSession", err)
  180. return
  181. }
  182. // If WebAuthn is enrolled -> Redirect to WebAuthn instead
  183. regs, err := auth.GetWebAuthnCredentialsByUID(ctx, u.ID)
  184. if err == nil && len(regs) > 0 {
  185. ctx.Redirect(setting.AppSubURL + "/user/webauthn")
  186. return
  187. }
  188. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  189. }
  190. // LinkAccountPostRegister handle the creation of a new account for an external account using signUp
  191. func LinkAccountPostRegister(ctx *context.Context) {
  192. form := web.GetForm(ctx).(*forms.RegisterForm)
  193. // TODO Make insecure passwords optional for local accounts also,
  194. // once email-based Second-Factor Auth is available
  195. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration
  196. ctx.Data["Title"] = ctx.Tr("link_account")
  197. ctx.Data["LinkAccountMode"] = true
  198. ctx.Data["LinkAccountModeRegister"] = true
  199. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  200. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  201. ctx.Data["Captcha"] = context.GetImageCaptcha()
  202. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  203. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  204. ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey
  205. ctx.Data["McaptchaSitekey"] = setting.Service.McaptchaSitekey
  206. ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL
  207. ctx.Data["CfTurnstileSitekey"] = setting.Service.CfTurnstileSitekey
  208. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  209. ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration
  210. ctx.Data["EnablePasswordSignInForm"] = setting.Service.EnablePasswordSignInForm
  211. ctx.Data["ShowRegistrationButton"] = false
  212. ctx.Data["EnablePasskeyAuth"] = setting.Service.EnablePasskeyAuth
  213. // use this to set the right link into the signIn and signUp templates in the link_account template
  214. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  215. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  216. linkAccountData := oauth2GetLinkAccountData(ctx)
  217. if linkAccountData == nil {
  218. ctx.ServerError("UserSignUp", errors.New("not in LinkAccount session"))
  219. return
  220. }
  221. if ctx.HasError() {
  222. ctx.HTML(http.StatusOK, tplLinkAccount)
  223. return
  224. }
  225. if setting.Service.DisableRegistration || setting.Service.AllowOnlyInternalRegistration {
  226. ctx.HTTPError(http.StatusForbidden)
  227. return
  228. }
  229. if setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha {
  230. context.VerifyCaptcha(ctx, tplLinkAccount, form)
  231. if ctx.Written() {
  232. return
  233. }
  234. }
  235. if !form.IsEmailDomainAllowed() {
  236. ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplLinkAccount, &form)
  237. return
  238. }
  239. if setting.Service.AllowOnlyExternalRegistration || !setting.Service.RequireExternalRegistrationPassword {
  240. // In user_model.User an empty password is classed as not set, so we set form.Password to empty.
  241. // Eventually the database should be changed to indicate "Second Factor"-enabled accounts
  242. // (accounts that do not introduce the security vulnerabilities of a password).
  243. // If a user decides to circumvent second-factor security, and purposefully create a password,
  244. // they can still do so using the "Recover Account" option.
  245. form.Password = ""
  246. } else {
  247. if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype {
  248. ctx.Data["Err_Password"] = true
  249. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form)
  250. return
  251. }
  252. if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength {
  253. ctx.Data["Err_Password"] = true
  254. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form)
  255. return
  256. }
  257. }
  258. u := &user_model.User{
  259. Name: form.UserName,
  260. Email: form.Email,
  261. Passwd: form.Password,
  262. LoginType: auth.OAuth2,
  263. LoginSource: linkAccountData.AuthSourceID,
  264. LoginName: linkAccountData.GothUser.UserID,
  265. }
  266. if !createAndHandleCreatedUser(ctx, tplLinkAccount, form, u, nil, linkAccountData) {
  267. // error already handled
  268. return
  269. }
  270. authSource, err := auth.GetSourceByID(ctx, linkAccountData.AuthSourceID)
  271. if err != nil {
  272. ctx.ServerError("GetSourceByID", err)
  273. return
  274. }
  275. source := authSource.Cfg.(*oauth2.Source)
  276. if err := syncGroupsToTeams(ctx, source, &linkAccountData.GothUser, u); err != nil {
  277. ctx.ServerError("SyncGroupsToTeams", err)
  278. return
  279. }
  280. handleSignIn(ctx, u, false)
  281. }
  282. func linkAccountFromContext(ctx *context.Context, user *user_model.User) error {
  283. linkAccountData := oauth2GetLinkAccountData(ctx)
  284. if linkAccountData == nil {
  285. return errors.New("not in LinkAccount session")
  286. }
  287. return externalaccount.LinkAccountToUser(ctx, linkAccountData.AuthSourceID, user, linkAccountData.GothUser)
  288. }