本站源代码
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

465 lines
13KB

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