You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

linkaccount.go 11KB

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