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.

436 lines
13 KiB

  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import (
  6. "fmt"
  7. "net/url"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/auth"
  10. "code.gitea.io/gitea/modules/auth/openid"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/generate"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/recaptcha"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/go-macaron/captcha"
  18. )
  19. const (
  20. tplSignInOpenID base.TplName = "user/auth/signin_openid"
  21. tplConnectOID base.TplName = "user/auth/signup_openid_connect"
  22. tplSignUpOID base.TplName = "user/auth/signup_openid_register"
  23. )
  24. // SignInOpenID render sign in page
  25. func SignInOpenID(ctx *context.Context) {
  26. ctx.Data["Title"] = ctx.Tr("sign_in")
  27. if ctx.Query("openid.return_to") != "" {
  28. signInOpenIDVerify(ctx)
  29. return
  30. }
  31. // Check auto-login.
  32. isSucceed, err := AutoSignIn(ctx)
  33. if err != nil {
  34. ctx.ServerError("AutoSignIn", err)
  35. return
  36. }
  37. redirectTo := ctx.Query("redirect_to")
  38. if len(redirectTo) > 0 {
  39. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  40. } else {
  41. redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to"))
  42. }
  43. if isSucceed {
  44. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  45. ctx.RedirectToFirst(redirectTo)
  46. return
  47. }
  48. ctx.Data["PageIsSignIn"] = true
  49. ctx.Data["PageIsLoginOpenID"] = true
  50. ctx.HTML(200, tplSignInOpenID)
  51. }
  52. // Check if the given OpenID URI is allowed by blacklist/whitelist
  53. func allowedOpenIDURI(uri string) (err error) {
  54. // In case a Whitelist is present, URI must be in it
  55. // in order to be accepted
  56. if len(setting.Service.OpenIDWhitelist) != 0 {
  57. for _, pat := range setting.Service.OpenIDWhitelist {
  58. if pat.MatchString(uri) {
  59. return nil // pass
  60. }
  61. }
  62. // must match one of this or be refused
  63. return fmt.Errorf("URI not allowed by whitelist")
  64. }
  65. // A blacklist match expliclty forbids
  66. for _, pat := range setting.Service.OpenIDBlacklist {
  67. if pat.MatchString(uri) {
  68. return fmt.Errorf("URI forbidden by blacklist")
  69. }
  70. }
  71. return nil
  72. }
  73. // SignInOpenIDPost response for openid sign in request
  74. func SignInOpenIDPost(ctx *context.Context, form auth.SignInOpenIDForm) {
  75. ctx.Data["Title"] = ctx.Tr("sign_in")
  76. ctx.Data["PageIsSignIn"] = true
  77. ctx.Data["PageIsLoginOpenID"] = true
  78. if ctx.HasError() {
  79. ctx.HTML(200, tplSignInOpenID)
  80. return
  81. }
  82. id, err := openid.Normalize(form.Openid)
  83. if err != nil {
  84. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &form)
  85. return
  86. }
  87. form.Openid = id
  88. log.Trace("OpenID uri: " + id)
  89. err = allowedOpenIDURI(id)
  90. if err != nil {
  91. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &form)
  92. return
  93. }
  94. redirectTo := setting.AppURL + "user/login/openid"
  95. url, err := openid.RedirectURL(id, redirectTo, setting.AppURL)
  96. if err != nil {
  97. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &form)
  98. return
  99. }
  100. // Request optional nickname and email info
  101. // NOTE: change to `openid.sreg.required` to require it
  102. url += "&openid.ns.sreg=http%3A%2F%2Fopenid.net%2Fextensions%2Fsreg%2F1.1"
  103. url += "&openid.sreg.optional=nickname%2Cemail"
  104. log.Trace("Form-passed openid-remember: %s", form.Remember)
  105. ctx.Session.Set("openid_signin_remember", form.Remember)
  106. ctx.Redirect(url)
  107. }
  108. // signInOpenIDVerify handles response from OpenID provider
  109. func signInOpenIDVerify(ctx *context.Context) {
  110. log.Trace("Incoming call to: " + ctx.Req.Request.URL.String())
  111. fullURL := setting.AppURL + ctx.Req.Request.URL.String()[1:]
  112. log.Trace("Full URL: " + fullURL)
  113. var id, err = openid.Verify(fullURL)
  114. if err != nil {
  115. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  116. Openid: id,
  117. })
  118. return
  119. }
  120. log.Trace("Verified ID: " + id)
  121. /* Now we should seek for the user and log him in, or prompt
  122. * to register if not found */
  123. u, _ := models.GetUserByOpenID(id)
  124. if err != nil {
  125. if !models.IsErrUserNotExist(err) {
  126. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  127. Openid: id,
  128. })
  129. return
  130. }
  131. }
  132. if u != nil {
  133. log.Trace("User exists, logging in")
  134. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  135. log.Trace("Session stored openid-remember: %s", remember)
  136. handleSignIn(ctx, u, remember)
  137. return
  138. }
  139. log.Trace("User with openid " + id + " does not exist, should connect or register")
  140. parsedURL, err := url.Parse(fullURL)
  141. if err != nil {
  142. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  143. Openid: id,
  144. })
  145. return
  146. }
  147. values, err := url.ParseQuery(parsedURL.RawQuery)
  148. if err != nil {
  149. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  150. Openid: id,
  151. })
  152. return
  153. }
  154. email := values.Get("openid.sreg.email")
  155. nickname := values.Get("openid.sreg.nickname")
  156. log.Trace("User has email=" + email + " and nickname=" + nickname)
  157. if email != "" {
  158. u, _ = models.GetUserByEmail(email)
  159. if err != nil {
  160. if !models.IsErrUserNotExist(err) {
  161. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  162. Openid: id,
  163. })
  164. return
  165. }
  166. }
  167. if u != nil {
  168. log.Trace("Local user " + u.LowerName + " has OpenID provided email " + email)
  169. }
  170. }
  171. if u == nil && nickname != "" {
  172. u, _ = models.GetUserByName(nickname)
  173. if err != nil {
  174. if !models.IsErrUserNotExist(err) {
  175. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  176. Openid: id,
  177. })
  178. return
  179. }
  180. }
  181. if u != nil {
  182. log.Trace("Local user " + u.LowerName + " has OpenID provided nickname " + nickname)
  183. }
  184. }
  185. ctx.Session.Set("openid_verified_uri", id)
  186. ctx.Session.Set("openid_determined_email", email)
  187. if u != nil {
  188. nickname = u.LowerName
  189. }
  190. ctx.Session.Set("openid_determined_username", nickname)
  191. if u != nil || !setting.Service.EnableOpenIDSignUp {
  192. ctx.Redirect(setting.AppSubURL + "/user/openid/connect")
  193. } else {
  194. ctx.Redirect(setting.AppSubURL + "/user/openid/register")
  195. }
  196. }
  197. // ConnectOpenID shows a form to connect an OpenID URI to an existing account
  198. func ConnectOpenID(ctx *context.Context) {
  199. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  200. if oid == "" {
  201. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  202. return
  203. }
  204. ctx.Data["Title"] = "OpenID connect"
  205. ctx.Data["PageIsSignIn"] = true
  206. ctx.Data["PageIsOpenIDConnect"] = true
  207. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  208. ctx.Data["OpenID"] = oid
  209. userName, _ := ctx.Session.Get("openid_determined_username").(string)
  210. if userName != "" {
  211. ctx.Data["user_name"] = userName
  212. }
  213. ctx.HTML(200, tplConnectOID)
  214. }
  215. // ConnectOpenIDPost handles submission of a form to connect an OpenID URI to an existing account
  216. func ConnectOpenIDPost(ctx *context.Context, form auth.ConnectOpenIDForm) {
  217. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  218. if oid == "" {
  219. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  220. return
  221. }
  222. ctx.Data["Title"] = "OpenID connect"
  223. ctx.Data["PageIsSignIn"] = true
  224. ctx.Data["PageIsOpenIDConnect"] = true
  225. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  226. ctx.Data["OpenID"] = oid
  227. u, err := models.UserSignIn(form.UserName, form.Password)
  228. if err != nil {
  229. if models.IsErrUserNotExist(err) {
  230. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplConnectOID, &form)
  231. } else {
  232. ctx.ServerError("ConnectOpenIDPost", err)
  233. }
  234. return
  235. }
  236. // add OpenID for the user
  237. userOID := &models.UserOpenID{UID: u.ID, URI: oid}
  238. if err = models.AddUserOpenID(userOID); err != nil {
  239. if models.IsErrOpenIDAlreadyUsed(err) {
  240. ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplConnectOID, &form)
  241. return
  242. }
  243. ctx.ServerError("AddUserOpenID", err)
  244. return
  245. }
  246. ctx.Flash.Success(ctx.Tr("settings.add_openid_success"))
  247. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  248. log.Trace("Session stored openid-remember: %s", remember)
  249. handleSignIn(ctx, u, remember)
  250. }
  251. // RegisterOpenID shows a form to create a new user authenticated via an OpenID URI
  252. func RegisterOpenID(ctx *context.Context) {
  253. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  254. if oid == "" {
  255. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  256. return
  257. }
  258. ctx.Data["Title"] = "OpenID signup"
  259. ctx.Data["PageIsSignIn"] = true
  260. ctx.Data["PageIsOpenIDRegister"] = true
  261. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  262. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  263. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  264. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  265. ctx.Data["OpenID"] = oid
  266. userName, _ := ctx.Session.Get("openid_determined_username").(string)
  267. if userName != "" {
  268. ctx.Data["user_name"] = userName
  269. }
  270. email, _ := ctx.Session.Get("openid_determined_email").(string)
  271. if email != "" {
  272. ctx.Data["email"] = email
  273. }
  274. ctx.HTML(200, tplSignUpOID)
  275. }
  276. // RegisterOpenIDPost handles submission of a form to create a new user authenticated via an OpenID URI
  277. func RegisterOpenIDPost(ctx *context.Context, cpt *captcha.Captcha, form auth.SignUpOpenIDForm) {
  278. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  279. if oid == "" {
  280. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  281. return
  282. }
  283. ctx.Data["Title"] = "OpenID signup"
  284. ctx.Data["PageIsSignIn"] = true
  285. ctx.Data["PageIsOpenIDRegister"] = true
  286. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  287. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  288. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  289. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  290. ctx.Data["OpenID"] = oid
  291. if setting.Service.EnableCaptcha && setting.Service.CaptchaType == setting.ImageCaptcha && !cpt.VerifyReq(ctx.Req) {
  292. ctx.Data["Err_Captcha"] = true
  293. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form)
  294. return
  295. }
  296. if setting.Service.EnableCaptcha && setting.Service.CaptchaType == setting.ReCaptcha {
  297. ctx.Req.ParseForm()
  298. valid, _ := recaptcha.Verify(form.GRecaptchaResponse)
  299. if !valid {
  300. ctx.Data["Err_Captcha"] = true
  301. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form)
  302. return
  303. }
  304. }
  305. len := setting.MinPasswordLength
  306. if len < 256 {
  307. len = 256
  308. }
  309. password, err := generate.GetRandomString(len)
  310. if err != nil {
  311. ctx.RenderWithErr(err.Error(), tplSignUpOID, form)
  312. return
  313. }
  314. // TODO: abstract a finalizeSignUp function ?
  315. u := &models.User{
  316. Name: form.UserName,
  317. Email: form.Email,
  318. Passwd: password,
  319. IsActive: !setting.Service.RegisterEmailConfirm,
  320. }
  321. if err := models.CreateUser(u); err != nil {
  322. switch {
  323. case models.IsErrUserAlreadyExist(err):
  324. ctx.Data["Err_UserName"] = true
  325. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUpOID, &form)
  326. case models.IsErrEmailAlreadyUsed(err):
  327. ctx.Data["Err_Email"] = true
  328. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUpOID, &form)
  329. case models.IsErrNameReserved(err):
  330. ctx.Data["Err_UserName"] = true
  331. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUpOID, &form)
  332. case models.IsErrNamePatternNotAllowed(err):
  333. ctx.Data["Err_UserName"] = true
  334. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUpOID, &form)
  335. default:
  336. ctx.ServerError("CreateUser", err)
  337. }
  338. return
  339. }
  340. log.Trace("Account created: %s", u.Name)
  341. // add OpenID for the user
  342. userOID := &models.UserOpenID{UID: u.ID, URI: oid}
  343. if err = models.AddUserOpenID(userOID); err != nil {
  344. if models.IsErrOpenIDAlreadyUsed(err) {
  345. ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplSignUpOID, &form)
  346. return
  347. }
  348. ctx.ServerError("AddUserOpenID", err)
  349. return
  350. }
  351. // Auto-set admin for the only user.
  352. if models.CountUsers() == 1 {
  353. u.IsAdmin = true
  354. u.IsActive = true
  355. u.SetLastLogin()
  356. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  357. ctx.ServerError("UpdateUser", err)
  358. return
  359. }
  360. }
  361. // Send confirmation email, no need for social account.
  362. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  363. models.SendActivateAccountMail(ctx.Context, u)
  364. ctx.Data["IsSendRegisterMail"] = true
  365. ctx.Data["Email"] = u.Email
  366. ctx.Data["ActiveCodeLives"] = base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  367. ctx.HTML(200, TplActivate)
  368. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  369. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  370. }
  371. return
  372. }
  373. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  374. log.Trace("Session stored openid-remember: %s", remember)
  375. handleSignIn(ctx, u, remember)
  376. }