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.

437 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. log.Error(1, "Error in OpenID redirect URL: %s, %v", redirectTo, err.Error())
  98. ctx.RenderWithErr(fmt.Sprintf("Unable to find OpenID provider in %s", redirectTo), tplSignInOpenID, &form)
  99. return
  100. }
  101. // Request optional nickname and email info
  102. // NOTE: change to `openid.sreg.required` to require it
  103. url += "&openid.ns.sreg=http%3A%2F%2Fopenid.net%2Fextensions%2Fsreg%2F1.1"
  104. url += "&openid.sreg.optional=nickname%2Cemail"
  105. log.Trace("Form-passed openid-remember: %s", form.Remember)
  106. ctx.Session.Set("openid_signin_remember", form.Remember)
  107. ctx.Redirect(url)
  108. }
  109. // signInOpenIDVerify handles response from OpenID provider
  110. func signInOpenIDVerify(ctx *context.Context) {
  111. log.Trace("Incoming call to: " + ctx.Req.Request.URL.String())
  112. fullURL := setting.AppURL + ctx.Req.Request.URL.String()[1:]
  113. log.Trace("Full URL: " + fullURL)
  114. var id, err = openid.Verify(fullURL)
  115. if err != nil {
  116. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  117. Openid: id,
  118. })
  119. return
  120. }
  121. log.Trace("Verified ID: " + id)
  122. /* Now we should seek for the user and log him in, or prompt
  123. * to register if not found */
  124. u, _ := models.GetUserByOpenID(id)
  125. if err != nil {
  126. if !models.IsErrUserNotExist(err) {
  127. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  128. Openid: id,
  129. })
  130. return
  131. }
  132. }
  133. if u != nil {
  134. log.Trace("User exists, logging in")
  135. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  136. log.Trace("Session stored openid-remember: %s", remember)
  137. handleSignIn(ctx, u, remember)
  138. return
  139. }
  140. log.Trace("User with openid " + id + " does not exist, should connect or register")
  141. parsedURL, err := url.Parse(fullURL)
  142. if err != nil {
  143. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  144. Openid: id,
  145. })
  146. return
  147. }
  148. values, err := url.ParseQuery(parsedURL.RawQuery)
  149. if err != nil {
  150. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  151. Openid: id,
  152. })
  153. return
  154. }
  155. email := values.Get("openid.sreg.email")
  156. nickname := values.Get("openid.sreg.nickname")
  157. log.Trace("User has email=" + email + " and nickname=" + nickname)
  158. if email != "" {
  159. u, _ = models.GetUserByEmail(email)
  160. if err != nil {
  161. if !models.IsErrUserNotExist(err) {
  162. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  163. Openid: id,
  164. })
  165. return
  166. }
  167. }
  168. if u != nil {
  169. log.Trace("Local user " + u.LowerName + " has OpenID provided email " + email)
  170. }
  171. }
  172. if u == nil && nickname != "" {
  173. u, _ = models.GetUserByName(nickname)
  174. if err != nil {
  175. if !models.IsErrUserNotExist(err) {
  176. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  177. Openid: id,
  178. })
  179. return
  180. }
  181. }
  182. if u != nil {
  183. log.Trace("Local user " + u.LowerName + " has OpenID provided nickname " + nickname)
  184. }
  185. }
  186. ctx.Session.Set("openid_verified_uri", id)
  187. ctx.Session.Set("openid_determined_email", email)
  188. if u != nil {
  189. nickname = u.LowerName
  190. }
  191. ctx.Session.Set("openid_determined_username", nickname)
  192. if u != nil || !setting.Service.EnableOpenIDSignUp {
  193. ctx.Redirect(setting.AppSubURL + "/user/openid/connect")
  194. } else {
  195. ctx.Redirect(setting.AppSubURL + "/user/openid/register")
  196. }
  197. }
  198. // ConnectOpenID shows a form to connect an OpenID URI to an existing account
  199. func ConnectOpenID(ctx *context.Context) {
  200. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  201. if oid == "" {
  202. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  203. return
  204. }
  205. ctx.Data["Title"] = "OpenID connect"
  206. ctx.Data["PageIsSignIn"] = true
  207. ctx.Data["PageIsOpenIDConnect"] = true
  208. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  209. ctx.Data["OpenID"] = oid
  210. userName, _ := ctx.Session.Get("openid_determined_username").(string)
  211. if userName != "" {
  212. ctx.Data["user_name"] = userName
  213. }
  214. ctx.HTML(200, tplConnectOID)
  215. }
  216. // ConnectOpenIDPost handles submission of a form to connect an OpenID URI to an existing account
  217. func ConnectOpenIDPost(ctx *context.Context, form auth.ConnectOpenIDForm) {
  218. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  219. if oid == "" {
  220. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  221. return
  222. }
  223. ctx.Data["Title"] = "OpenID connect"
  224. ctx.Data["PageIsSignIn"] = true
  225. ctx.Data["PageIsOpenIDConnect"] = true
  226. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  227. ctx.Data["OpenID"] = oid
  228. u, err := models.UserSignIn(form.UserName, form.Password)
  229. if err != nil {
  230. if models.IsErrUserNotExist(err) {
  231. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplConnectOID, &form)
  232. } else {
  233. ctx.ServerError("ConnectOpenIDPost", err)
  234. }
  235. return
  236. }
  237. // add OpenID for the user
  238. userOID := &models.UserOpenID{UID: u.ID, URI: oid}
  239. if err = models.AddUserOpenID(userOID); err != nil {
  240. if models.IsErrOpenIDAlreadyUsed(err) {
  241. ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplConnectOID, &form)
  242. return
  243. }
  244. ctx.ServerError("AddUserOpenID", err)
  245. return
  246. }
  247. ctx.Flash.Success(ctx.Tr("settings.add_openid_success"))
  248. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  249. log.Trace("Session stored openid-remember: %s", remember)
  250. handleSignIn(ctx, u, remember)
  251. }
  252. // RegisterOpenID shows a form to create a new user authenticated via an OpenID URI
  253. func RegisterOpenID(ctx *context.Context) {
  254. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  255. if oid == "" {
  256. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  257. return
  258. }
  259. ctx.Data["Title"] = "OpenID signup"
  260. ctx.Data["PageIsSignIn"] = true
  261. ctx.Data["PageIsOpenIDRegister"] = true
  262. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  263. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  264. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  265. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  266. ctx.Data["OpenID"] = oid
  267. userName, _ := ctx.Session.Get("openid_determined_username").(string)
  268. if userName != "" {
  269. ctx.Data["user_name"] = userName
  270. }
  271. email, _ := ctx.Session.Get("openid_determined_email").(string)
  272. if email != "" {
  273. ctx.Data["email"] = email
  274. }
  275. ctx.HTML(200, tplSignUpOID)
  276. }
  277. // RegisterOpenIDPost handles submission of a form to create a new user authenticated via an OpenID URI
  278. func RegisterOpenIDPost(ctx *context.Context, cpt *captcha.Captcha, form auth.SignUpOpenIDForm) {
  279. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  280. if oid == "" {
  281. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  282. return
  283. }
  284. ctx.Data["Title"] = "OpenID signup"
  285. ctx.Data["PageIsSignIn"] = true
  286. ctx.Data["PageIsOpenIDRegister"] = true
  287. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  288. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  289. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  290. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  291. ctx.Data["OpenID"] = oid
  292. if setting.Service.EnableCaptcha && setting.Service.CaptchaType == setting.ImageCaptcha && !cpt.VerifyReq(ctx.Req) {
  293. ctx.Data["Err_Captcha"] = true
  294. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form)
  295. return
  296. }
  297. if setting.Service.EnableCaptcha && setting.Service.CaptchaType == setting.ReCaptcha {
  298. ctx.Req.ParseForm()
  299. valid, _ := recaptcha.Verify(form.GRecaptchaResponse)
  300. if !valid {
  301. ctx.Data["Err_Captcha"] = true
  302. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form)
  303. return
  304. }
  305. }
  306. len := setting.MinPasswordLength
  307. if len < 256 {
  308. len = 256
  309. }
  310. password, err := generate.GetRandomString(len)
  311. if err != nil {
  312. ctx.RenderWithErr(err.Error(), tplSignUpOID, form)
  313. return
  314. }
  315. // TODO: abstract a finalizeSignUp function ?
  316. u := &models.User{
  317. Name: form.UserName,
  318. Email: form.Email,
  319. Passwd: password,
  320. IsActive: !setting.Service.RegisterEmailConfirm,
  321. }
  322. if err := models.CreateUser(u); err != nil {
  323. switch {
  324. case models.IsErrUserAlreadyExist(err):
  325. ctx.Data["Err_UserName"] = true
  326. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUpOID, &form)
  327. case models.IsErrEmailAlreadyUsed(err):
  328. ctx.Data["Err_Email"] = true
  329. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUpOID, &form)
  330. case models.IsErrNameReserved(err):
  331. ctx.Data["Err_UserName"] = true
  332. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUpOID, &form)
  333. case models.IsErrNamePatternNotAllowed(err):
  334. ctx.Data["Err_UserName"] = true
  335. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUpOID, &form)
  336. default:
  337. ctx.ServerError("CreateUser", err)
  338. }
  339. return
  340. }
  341. log.Trace("Account created: %s", u.Name)
  342. // add OpenID for the user
  343. userOID := &models.UserOpenID{UID: u.ID, URI: oid}
  344. if err = models.AddUserOpenID(userOID); err != nil {
  345. if models.IsErrOpenIDAlreadyUsed(err) {
  346. ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplSignUpOID, &form)
  347. return
  348. }
  349. ctx.ServerError("AddUserOpenID", err)
  350. return
  351. }
  352. // Auto-set admin for the only user.
  353. if models.CountUsers() == 1 {
  354. u.IsAdmin = true
  355. u.IsActive = true
  356. u.SetLastLogin()
  357. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  358. ctx.ServerError("UpdateUser", err)
  359. return
  360. }
  361. }
  362. // Send confirmation email, no need for social account.
  363. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  364. models.SendActivateAccountMail(ctx.Context, u)
  365. ctx.Data["IsSendRegisterMail"] = true
  366. ctx.Data["Email"] = u.Email
  367. ctx.Data["ActiveCodeLives"] = base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  368. ctx.HTML(200, TplActivate)
  369. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  370. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  371. }
  372. return
  373. }
  374. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  375. log.Trace("Session stored openid-remember: %s", remember)
  376. handleSignIn(ctx, u, remember)
  377. }