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.

424 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. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  256. if oid == "" {
  257. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  258. return
  259. }
  260. ctx.Data["Title"] = "OpenID signup"
  261. ctx.Data["PageIsSignIn"] = true
  262. ctx.Data["PageIsOpenIDRegister"] = true
  263. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  264. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  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["OpenID"] = oid
  289. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  290. ctx.Data["Err_Captcha"] = true
  291. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form)
  292. return
  293. }
  294. len := setting.MinPasswordLength
  295. if len < 256 {
  296. len = 256
  297. }
  298. password, err := base.GetRandomString(len)
  299. if err != nil {
  300. ctx.RenderWithErr(err.Error(), tplSignUpOID, form)
  301. return
  302. }
  303. // TODO: abstract a finalizeSignUp function ?
  304. u := &models.User{
  305. Name: form.UserName,
  306. Email: form.Email,
  307. Passwd: password,
  308. IsActive: !setting.Service.RegisterEmailConfirm,
  309. }
  310. if err := models.CreateUser(u); err != nil {
  311. switch {
  312. case models.IsErrUserAlreadyExist(err):
  313. ctx.Data["Err_UserName"] = true
  314. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUpOID, &form)
  315. case models.IsErrEmailAlreadyUsed(err):
  316. ctx.Data["Err_Email"] = true
  317. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUpOID, &form)
  318. case models.IsErrNameReserved(err):
  319. ctx.Data["Err_UserName"] = true
  320. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUpOID, &form)
  321. case models.IsErrNamePatternNotAllowed(err):
  322. ctx.Data["Err_UserName"] = true
  323. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUpOID, &form)
  324. default:
  325. ctx.Handle(500, "CreateUser", err)
  326. }
  327. return
  328. }
  329. log.Trace("Account created: %s", u.Name)
  330. // add OpenID for the user
  331. userOID := &models.UserOpenID{UID: u.ID, URI: oid}
  332. if err = models.AddUserOpenID(userOID); err != nil {
  333. if models.IsErrOpenIDAlreadyUsed(err) {
  334. ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplSignUpOID, &form)
  335. return
  336. }
  337. ctx.Handle(500, "AddUserOpenID", err)
  338. return
  339. }
  340. // Auto-set admin for the only user.
  341. if models.CountUsers() == 1 {
  342. u.IsAdmin = true
  343. u.IsActive = true
  344. u.SetLastLogin()
  345. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  346. ctx.Handle(500, "UpdateUser", err)
  347. return
  348. }
  349. }
  350. // Send confirmation email, no need for social account.
  351. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  352. models.SendActivateAccountMail(ctx.Context, u)
  353. ctx.Data["IsSendRegisterMail"] = true
  354. ctx.Data["Email"] = u.Email
  355. ctx.Data["ActiveCodeLives"] = base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  356. ctx.HTML(200, TplActivate)
  357. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  358. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  359. }
  360. return
  361. }
  362. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  363. log.Trace("Session stored openid-remember: %s", remember)
  364. handleSignIn(ctx, u, remember)
  365. }