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.

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