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.

985 lines
28 KiB

Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
  1. // Copyright 2014 The Gogs 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. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/auth/oauth2"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "github.com/go-macaron/captcha"
  19. "github.com/markbates/goth"
  20. )
  21. const (
  22. // tplSignIn template for sign in page
  23. tplSignIn base.TplName = "user/auth/signin"
  24. // tplSignUp template path for sign up page
  25. tplSignUp base.TplName = "user/auth/signup"
  26. // TplActivate template path for activate user
  27. TplActivate base.TplName = "user/auth/activate"
  28. tplForgotPassword base.TplName = "user/auth/forgot_passwd"
  29. tplResetPassword base.TplName = "user/auth/reset_passwd"
  30. tplTwofa base.TplName = "user/auth/twofa"
  31. tplTwofaScratch base.TplName = "user/auth/twofa_scratch"
  32. tplLinkAccount base.TplName = "user/auth/link_account"
  33. )
  34. // AutoSignIn reads cookie and try to auto-login.
  35. func AutoSignIn(ctx *context.Context) (bool, error) {
  36. if !models.HasEngine {
  37. return false, nil
  38. }
  39. uname := ctx.GetCookie(setting.CookieUserName)
  40. if len(uname) == 0 {
  41. return false, nil
  42. }
  43. isSucceed := false
  44. defer func() {
  45. if !isSucceed {
  46. log.Trace("auto-login cookie cleared: %s", uname)
  47. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  48. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  49. }
  50. }()
  51. u, err := models.GetUserByName(uname)
  52. if err != nil {
  53. if !models.IsErrUserNotExist(err) {
  54. return false, fmt.Errorf("GetUserByName: %v", err)
  55. }
  56. return false, nil
  57. }
  58. if val, _ := ctx.GetSuperSecureCookie(
  59. base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
  60. return false, nil
  61. }
  62. isSucceed = true
  63. ctx.Session.Set("uid", u.ID)
  64. ctx.Session.Set("uname", u.Name)
  65. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  66. return true, nil
  67. }
  68. func checkAutoLogin(ctx *context.Context) bool {
  69. // Check auto-login.
  70. isSucceed, err := AutoSignIn(ctx)
  71. if err != nil {
  72. ctx.Handle(500, "AutoSignIn", err)
  73. return true
  74. }
  75. redirectTo := ctx.Query("redirect_to")
  76. if len(redirectTo) > 0 {
  77. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL)
  78. } else {
  79. redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to"))
  80. }
  81. if isSucceed {
  82. if len(redirectTo) > 0 {
  83. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  84. ctx.Redirect(redirectTo)
  85. } else {
  86. ctx.Redirect(setting.AppSubURL + "/")
  87. }
  88. return true
  89. }
  90. return false
  91. }
  92. // SignIn render sign in page
  93. func SignIn(ctx *context.Context) {
  94. ctx.Data["Title"] = ctx.Tr("sign_in")
  95. // Check auto-login.
  96. if checkAutoLogin(ctx) {
  97. return
  98. }
  99. oauth2Providers, err := models.GetActiveOAuth2Providers()
  100. if err != nil {
  101. ctx.Handle(500, "UserSignIn", err)
  102. return
  103. }
  104. ctx.Data["OAuth2Providers"] = oauth2Providers
  105. ctx.HTML(200, tplSignIn)
  106. }
  107. // SignInPost response for sign in request
  108. func SignInPost(ctx *context.Context, form auth.SignInForm) {
  109. ctx.Data["Title"] = ctx.Tr("sign_in")
  110. oauth2Providers, err := models.GetActiveOAuth2Providers()
  111. if err != nil {
  112. ctx.Handle(500, "UserSignIn", err)
  113. return
  114. }
  115. ctx.Data["OAuth2Providers"] = oauth2Providers
  116. if ctx.HasError() {
  117. ctx.HTML(200, tplSignIn)
  118. return
  119. }
  120. u, err := models.UserSignIn(form.UserName, form.Password)
  121. if err != nil {
  122. if models.IsErrUserNotExist(err) {
  123. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
  124. } else if models.IsErrEmailAlreadyUsed(err) {
  125. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form)
  126. } else {
  127. ctx.Handle(500, "UserSignIn", err)
  128. }
  129. return
  130. }
  131. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  132. // Instead, redirect them to the 2FA authentication page.
  133. _, err = models.GetTwoFactorByUID(u.ID)
  134. if err != nil {
  135. if models.IsErrTwoFactorNotEnrolled(err) {
  136. handleSignIn(ctx, u, form.Remember)
  137. } else {
  138. ctx.Handle(500, "UserSignIn", err)
  139. }
  140. return
  141. }
  142. // User needs to use 2FA, save data and redirect to 2FA page.
  143. ctx.Session.Set("twofaUid", u.ID)
  144. ctx.Session.Set("twofaRemember", form.Remember)
  145. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  146. }
  147. // TwoFactor shows the user a two-factor authentication page.
  148. func TwoFactor(ctx *context.Context) {
  149. ctx.Data["Title"] = ctx.Tr("twofa")
  150. // Check auto-login.
  151. if checkAutoLogin(ctx) {
  152. return
  153. }
  154. // Ensure user is in a 2FA session.
  155. if ctx.Session.Get("twofaUid") == nil {
  156. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  157. return
  158. }
  159. ctx.HTML(200, tplTwofa)
  160. }
  161. // TwoFactorPost validates a user's two-factor authentication token.
  162. func TwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  163. ctx.Data["Title"] = ctx.Tr("twofa")
  164. // Ensure user is in a 2FA session.
  165. idSess := ctx.Session.Get("twofaUid")
  166. if idSess == nil {
  167. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  168. return
  169. }
  170. id := idSess.(int64)
  171. twofa, err := models.GetTwoFactorByUID(id)
  172. if err != nil {
  173. ctx.Handle(500, "UserSignIn", err)
  174. return
  175. }
  176. // Validate the passcode with the stored TOTP secret.
  177. ok, err := twofa.ValidateTOTP(form.Passcode)
  178. if err != nil {
  179. ctx.Handle(500, "UserSignIn", err)
  180. return
  181. }
  182. if ok {
  183. remember := ctx.Session.Get("twofaRemember").(bool)
  184. u, err := models.GetUserByID(id)
  185. if err != nil {
  186. ctx.Handle(500, "UserSignIn", err)
  187. return
  188. }
  189. if ctx.Session.Get("linkAccount") != nil {
  190. gothUser := ctx.Session.Get("linkAccountGothUser")
  191. if gothUser == nil {
  192. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  193. return
  194. }
  195. err = models.LinkAccountToUser(u, gothUser.(goth.User))
  196. if err != nil {
  197. ctx.Handle(500, "UserSignIn", err)
  198. return
  199. }
  200. }
  201. handleSignIn(ctx, u, remember)
  202. return
  203. }
  204. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, auth.TwoFactorAuthForm{})
  205. }
  206. // TwoFactorScratch shows the scratch code form for two-factor authentication.
  207. func TwoFactorScratch(ctx *context.Context) {
  208. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  209. // Check auto-login.
  210. if checkAutoLogin(ctx) {
  211. return
  212. }
  213. // Ensure user is in a 2FA session.
  214. if ctx.Session.Get("twofaUid") == nil {
  215. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  216. return
  217. }
  218. ctx.HTML(200, tplTwofaScratch)
  219. }
  220. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
  221. func TwoFactorScratchPost(ctx *context.Context, form auth.TwoFactorScratchAuthForm) {
  222. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  223. // Ensure user is in a 2FA session.
  224. idSess := ctx.Session.Get("twofaUid")
  225. if idSess == nil {
  226. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  227. return
  228. }
  229. id := idSess.(int64)
  230. twofa, err := models.GetTwoFactorByUID(id)
  231. if err != nil {
  232. ctx.Handle(500, "UserSignIn", err)
  233. return
  234. }
  235. // Validate the passcode with the stored TOTP secret.
  236. if twofa.VerifyScratchToken(form.Token) {
  237. // Invalidate the scratch token.
  238. twofa.ScratchToken = ""
  239. if err = models.UpdateTwoFactor(twofa); err != nil {
  240. ctx.Handle(500, "UserSignIn", err)
  241. return
  242. }
  243. remember := ctx.Session.Get("twofaRemember").(bool)
  244. u, err := models.GetUserByID(id)
  245. if err != nil {
  246. ctx.Handle(500, "UserSignIn", err)
  247. return
  248. }
  249. handleSignInFull(ctx, u, remember, false)
  250. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  251. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  252. return
  253. }
  254. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, auth.TwoFactorScratchAuthForm{})
  255. }
  256. // This handles the final part of the sign-in process of the user.
  257. func handleSignIn(ctx *context.Context, u *models.User, remember bool) {
  258. handleSignInFull(ctx, u, remember, true)
  259. }
  260. func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) {
  261. if remember {
  262. days := 86400 * setting.LogInRememberDays
  263. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL)
  264. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  265. setting.CookieRememberName, u.Name, days, setting.AppSubURL)
  266. }
  267. ctx.Session.Delete("twofaUid")
  268. ctx.Session.Delete("twofaRemember")
  269. ctx.Session.Set("uid", u.ID)
  270. ctx.Session.Set("uname", u.Name)
  271. // Clear whatever CSRF has right now, force to generate a new one
  272. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  273. // Register last login
  274. u.SetLastLogin()
  275. if err := models.UpdateUser(u); err != nil {
  276. ctx.Handle(500, "UpdateUser", err)
  277. return
  278. }
  279. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  280. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  281. if obeyRedirect {
  282. ctx.Redirect(redirectTo)
  283. }
  284. return
  285. }
  286. if obeyRedirect {
  287. ctx.Redirect(setting.AppSubURL + "/")
  288. }
  289. }
  290. // SignInOAuth handles the OAuth2 login buttons
  291. func SignInOAuth(ctx *context.Context) {
  292. provider := ctx.Params(":provider")
  293. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  294. if err != nil {
  295. ctx.Handle(500, "SignIn", err)
  296. return
  297. }
  298. // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user
  299. user, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  300. if err == nil && user != nil {
  301. // we got the user without going through the whole OAuth2 authentication flow again
  302. handleOAuth2SignIn(user, gothUser, ctx, err)
  303. return
  304. }
  305. err = oauth2.Auth(loginSource.Name, ctx.Req.Request, ctx.Resp)
  306. if err != nil {
  307. ctx.Handle(500, "SignIn", err)
  308. }
  309. // redirect is done in oauth2.Auth
  310. }
  311. // SignInOAuthCallback handles the callback from the given provider
  312. func SignInOAuthCallback(ctx *context.Context) {
  313. provider := ctx.Params(":provider")
  314. // first look if the provider is still active
  315. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  316. if err != nil {
  317. ctx.Handle(500, "SignIn", err)
  318. return
  319. }
  320. if loginSource == nil {
  321. ctx.Handle(500, "SignIn", errors.New("No valid provider found, check configured callback url in provider"))
  322. return
  323. }
  324. u, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  325. handleOAuth2SignIn(u, gothUser, ctx, err)
  326. }
  327. func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context, err error) {
  328. if err != nil {
  329. ctx.Handle(500, "UserSignIn", err)
  330. return
  331. }
  332. if u == nil {
  333. // no existing user is found, request attach or new account
  334. ctx.Session.Set("linkAccountGothUser", gothUser)
  335. ctx.Redirect(setting.AppSubURL + "/user/link_account")
  336. return
  337. }
  338. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  339. // Instead, redirect them to the 2FA authentication page.
  340. _, err = models.GetTwoFactorByUID(u.ID)
  341. if err != nil {
  342. if models.IsErrTwoFactorNotEnrolled(err) {
  343. ctx.Session.Set("uid", u.ID)
  344. ctx.Session.Set("uname", u.Name)
  345. // Clear whatever CSRF has right now, force to generate a new one
  346. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  347. // Register last login
  348. u.SetLastLogin()
  349. if err := models.UpdateUser(u); err != nil {
  350. ctx.Handle(500, "UpdateUser", err)
  351. return
  352. }
  353. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  354. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  355. ctx.Redirect(redirectTo)
  356. return
  357. }
  358. ctx.Redirect(setting.AppSubURL + "/")
  359. } else {
  360. ctx.Handle(500, "UserSignIn", err)
  361. }
  362. return
  363. }
  364. // User needs to use 2FA, save data and redirect to 2FA page.
  365. ctx.Session.Set("twofaUid", u.ID)
  366. ctx.Session.Set("twofaRemember", false)
  367. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  368. }
  369. // OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful
  370. // login the user
  371. func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
  372. gothUser, err := oauth2.ProviderCallback(loginSource.Name, request, response)
  373. if err != nil {
  374. return nil, goth.User{}, err
  375. }
  376. user := &models.User{
  377. LoginName: gothUser.UserID,
  378. LoginType: models.LoginOAuth2,
  379. LoginSource: loginSource.ID,
  380. }
  381. hasUser, err := models.GetUser(user)
  382. if err != nil {
  383. return nil, goth.User{}, err
  384. }
  385. if hasUser {
  386. return user, goth.User{}, nil
  387. }
  388. // search in external linked users
  389. externalLoginUser := &models.ExternalLoginUser{
  390. ExternalID: gothUser.UserID,
  391. LoginSourceID: loginSource.ID,
  392. }
  393. hasUser, err = models.GetExternalLogin(externalLoginUser)
  394. if err != nil {
  395. return nil, goth.User{}, err
  396. }
  397. if hasUser {
  398. user, err = models.GetUserByID(externalLoginUser.UserID)
  399. return user, goth.User{}, err
  400. }
  401. // no user found to login
  402. return nil, gothUser, nil
  403. }
  404. // LinkAccount shows the page where the user can decide to login or create a new account
  405. func LinkAccount(ctx *context.Context) {
  406. ctx.Data["Title"] = ctx.Tr("link_account")
  407. ctx.Data["LinkAccountMode"] = true
  408. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  409. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  410. ctx.Data["ShowRegistrationButton"] = false
  411. // use this to set the right link into the signIn and signUp templates in the link_account template
  412. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  413. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  414. gothUser := ctx.Session.Get("linkAccountGothUser")
  415. if gothUser == nil {
  416. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  417. return
  418. }
  419. ctx.Data["user_name"] = gothUser.(goth.User).NickName
  420. ctx.Data["email"] = gothUser.(goth.User).Email
  421. ctx.HTML(200, tplLinkAccount)
  422. }
  423. // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
  424. func LinkAccountPostSignIn(ctx *context.Context, signInForm auth.SignInForm) {
  425. ctx.Data["Title"] = ctx.Tr("link_account")
  426. ctx.Data["LinkAccountMode"] = true
  427. ctx.Data["LinkAccountModeSignIn"] = true
  428. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  429. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  430. ctx.Data["ShowRegistrationButton"] = false
  431. // use this to set the right link into the signIn and signUp templates in the link_account template
  432. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  433. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  434. gothUser := ctx.Session.Get("linkAccountGothUser")
  435. if gothUser == nil {
  436. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  437. return
  438. }
  439. if ctx.HasError() {
  440. ctx.HTML(200, tplLinkAccount)
  441. return
  442. }
  443. u, err := models.UserSignIn(signInForm.UserName, signInForm.Password)
  444. if err != nil {
  445. if models.IsErrUserNotExist(err) {
  446. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm)
  447. } else {
  448. ctx.Handle(500, "UserLinkAccount", err)
  449. }
  450. return
  451. }
  452. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  453. // Instead, redirect them to the 2FA authentication page.
  454. _, err = models.GetTwoFactorByUID(u.ID)
  455. if err != nil {
  456. if models.IsErrTwoFactorNotEnrolled(err) {
  457. err = models.LinkAccountToUser(u, gothUser.(goth.User))
  458. if err != nil {
  459. ctx.Handle(500, "UserLinkAccount", err)
  460. } else {
  461. handleSignIn(ctx, u, signInForm.Remember)
  462. }
  463. } else {
  464. ctx.Handle(500, "UserLinkAccount", err)
  465. }
  466. return
  467. }
  468. // User needs to use 2FA, save data and redirect to 2FA page.
  469. ctx.Session.Set("twofaUid", u.ID)
  470. ctx.Session.Set("twofaRemember", signInForm.Remember)
  471. ctx.Session.Set("linkAccount", true)
  472. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  473. }
  474. // LinkAccountPostRegister handle the creation of a new account for an external account using signUp
  475. func LinkAccountPostRegister(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  476. ctx.Data["Title"] = ctx.Tr("link_account")
  477. ctx.Data["LinkAccountMode"] = true
  478. ctx.Data["LinkAccountModeRegister"] = true
  479. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  480. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  481. ctx.Data["ShowRegistrationButton"] = false
  482. // use this to set the right link into the signIn and signUp templates in the link_account template
  483. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  484. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  485. gothUser := ctx.Session.Get("linkAccountGothUser")
  486. if gothUser == nil {
  487. ctx.Handle(500, "UserSignUp", errors.New("not in LinkAccount session"))
  488. return
  489. }
  490. if ctx.HasError() {
  491. ctx.HTML(200, tplLinkAccount)
  492. return
  493. }
  494. if setting.Service.DisableRegistration {
  495. ctx.Error(403)
  496. return
  497. }
  498. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  499. ctx.Data["Err_Captcha"] = true
  500. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form)
  501. return
  502. }
  503. if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype {
  504. ctx.Data["Err_Password"] = true
  505. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form)
  506. return
  507. }
  508. if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength {
  509. ctx.Data["Err_Password"] = true
  510. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form)
  511. return
  512. }
  513. loginSource, err := models.GetActiveOAuth2LoginSourceByName(gothUser.(goth.User).Provider)
  514. if err != nil {
  515. ctx.Handle(500, "CreateUser", err)
  516. }
  517. u := &models.User{
  518. Name: form.UserName,
  519. Email: form.Email,
  520. Passwd: form.Password,
  521. IsActive: !setting.Service.RegisterEmailConfirm,
  522. LoginType: models.LoginOAuth2,
  523. LoginSource: loginSource.ID,
  524. LoginName: gothUser.(goth.User).UserID,
  525. }
  526. if err := models.CreateUser(u); err != nil {
  527. switch {
  528. case models.IsErrUserAlreadyExist(err):
  529. ctx.Data["Err_UserName"] = true
  530. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplLinkAccount, &form)
  531. case models.IsErrEmailAlreadyUsed(err):
  532. ctx.Data["Err_Email"] = true
  533. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplLinkAccount, &form)
  534. case models.IsErrNameReserved(err):
  535. ctx.Data["Err_UserName"] = true
  536. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplLinkAccount, &form)
  537. case models.IsErrNamePatternNotAllowed(err):
  538. ctx.Data["Err_UserName"] = true
  539. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplLinkAccount, &form)
  540. default:
  541. ctx.Handle(500, "CreateUser", err)
  542. }
  543. return
  544. }
  545. log.Trace("Account created: %s", u.Name)
  546. // Auto-set admin for the only user.
  547. if models.CountUsers() == 1 {
  548. u.IsAdmin = true
  549. u.IsActive = true
  550. if err := models.UpdateUser(u); err != nil {
  551. ctx.Handle(500, "UpdateUser", err)
  552. return
  553. }
  554. }
  555. // Send confirmation email
  556. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  557. models.SendActivateAccountMail(ctx.Context, u)
  558. ctx.Data["IsSendRegisterMail"] = true
  559. ctx.Data["Email"] = u.Email
  560. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  561. ctx.HTML(200, TplActivate)
  562. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  563. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  564. }
  565. return
  566. }
  567. ctx.Redirect(setting.AppSubURL + "/user/login")
  568. }
  569. // SignOut sign out from login status
  570. func SignOut(ctx *context.Context) {
  571. ctx.Session.Delete("uid")
  572. ctx.Session.Delete("uname")
  573. ctx.Session.Delete("socialId")
  574. ctx.Session.Delete("socialName")
  575. ctx.Session.Delete("socialEmail")
  576. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  577. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  578. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  579. ctx.Redirect(setting.AppSubURL + "/")
  580. }
  581. // SignUp render the register page
  582. func SignUp(ctx *context.Context) {
  583. ctx.Data["Title"] = ctx.Tr("sign_up")
  584. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  585. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  586. ctx.HTML(200, tplSignUp)
  587. }
  588. // SignUpPost response for sign up information submission
  589. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  590. ctx.Data["Title"] = ctx.Tr("sign_up")
  591. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  592. if setting.Service.DisableRegistration {
  593. ctx.Error(403)
  594. return
  595. }
  596. if ctx.HasError() {
  597. ctx.HTML(200, tplSignUp)
  598. return
  599. }
  600. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  601. ctx.Data["Err_Captcha"] = true
  602. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  603. return
  604. }
  605. if form.Password != form.Retype {
  606. ctx.Data["Err_Password"] = true
  607. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  608. return
  609. }
  610. if len(form.Password) < setting.MinPasswordLength {
  611. ctx.Data["Err_Password"] = true
  612. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  613. return
  614. }
  615. u := &models.User{
  616. Name: form.UserName,
  617. Email: form.Email,
  618. Passwd: form.Password,
  619. IsActive: !setting.Service.RegisterEmailConfirm,
  620. }
  621. if err := models.CreateUser(u); err != nil {
  622. switch {
  623. case models.IsErrUserAlreadyExist(err):
  624. ctx.Data["Err_UserName"] = true
  625. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  626. case models.IsErrEmailAlreadyUsed(err):
  627. ctx.Data["Err_Email"] = true
  628. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  629. case models.IsErrNameReserved(err):
  630. ctx.Data["Err_UserName"] = true
  631. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  632. case models.IsErrNamePatternNotAllowed(err):
  633. ctx.Data["Err_UserName"] = true
  634. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  635. default:
  636. ctx.Handle(500, "CreateUser", err)
  637. }
  638. return
  639. }
  640. log.Trace("Account created: %s", u.Name)
  641. // Auto-set admin for the only user.
  642. if models.CountUsers() == 1 {
  643. u.IsAdmin = true
  644. u.IsActive = true
  645. if err := models.UpdateUser(u); err != nil {
  646. ctx.Handle(500, "UpdateUser", err)
  647. return
  648. }
  649. }
  650. // Send confirmation email, no need for social account.
  651. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  652. models.SendActivateAccountMail(ctx.Context, u)
  653. ctx.Data["IsSendRegisterMail"] = true
  654. ctx.Data["Email"] = u.Email
  655. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  656. ctx.HTML(200, TplActivate)
  657. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  658. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  659. }
  660. return
  661. }
  662. ctx.Redirect(setting.AppSubURL + "/user/login")
  663. }
  664. // Activate render activate user page
  665. func Activate(ctx *context.Context) {
  666. code := ctx.Query("code")
  667. if len(code) == 0 {
  668. ctx.Data["IsActivatePage"] = true
  669. if ctx.User.IsActive {
  670. ctx.Error(404)
  671. return
  672. }
  673. // Resend confirmation email.
  674. if setting.Service.RegisterEmailConfirm {
  675. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  676. ctx.Data["ResendLimited"] = true
  677. } else {
  678. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  679. models.SendActivateAccountMail(ctx.Context, ctx.User)
  680. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  681. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  682. }
  683. }
  684. } else {
  685. ctx.Data["ServiceNotEnabled"] = true
  686. }
  687. ctx.HTML(200, TplActivate)
  688. return
  689. }
  690. // Verify code.
  691. if user := models.VerifyUserActiveCode(code); user != nil {
  692. user.IsActive = true
  693. var err error
  694. if user.Rands, err = models.GetUserSalt(); err != nil {
  695. ctx.Handle(500, "UpdateUser", err)
  696. return
  697. }
  698. if err := models.UpdateUser(user); err != nil {
  699. if models.IsErrUserNotExist(err) {
  700. ctx.Error(404)
  701. } else {
  702. ctx.Handle(500, "UpdateUser", err)
  703. }
  704. return
  705. }
  706. log.Trace("User activated: %s", user.Name)
  707. ctx.Session.Set("uid", user.ID)
  708. ctx.Session.Set("uname", user.Name)
  709. ctx.Redirect(setting.AppSubURL + "/")
  710. return
  711. }
  712. ctx.Data["IsActivateFailed"] = true
  713. ctx.HTML(200, TplActivate)
  714. }
  715. // ActivateEmail render the activate email page
  716. func ActivateEmail(ctx *context.Context) {
  717. code := ctx.Query("code")
  718. emailStr := ctx.Query("email")
  719. // Verify code.
  720. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  721. if err := email.Activate(); err != nil {
  722. ctx.Handle(500, "ActivateEmail", err)
  723. }
  724. log.Trace("Email activated: %s", email.Email)
  725. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  726. }
  727. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  728. return
  729. }
  730. // ForgotPasswd render the forget pasword page
  731. func ForgotPasswd(ctx *context.Context) {
  732. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  733. if setting.MailService == nil {
  734. ctx.Data["IsResetDisable"] = true
  735. ctx.HTML(200, tplForgotPassword)
  736. return
  737. }
  738. ctx.Data["IsResetRequest"] = true
  739. ctx.HTML(200, tplForgotPassword)
  740. }
  741. // ForgotPasswdPost response for forget password request
  742. func ForgotPasswdPost(ctx *context.Context) {
  743. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  744. if setting.MailService == nil {
  745. ctx.Handle(403, "ForgotPasswdPost", nil)
  746. return
  747. }
  748. ctx.Data["IsResetRequest"] = true
  749. email := ctx.Query("email")
  750. ctx.Data["Email"] = email
  751. u, err := models.GetUserByEmail(email)
  752. if err != nil {
  753. if models.IsErrUserNotExist(err) {
  754. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  755. ctx.Data["IsResetSent"] = true
  756. ctx.HTML(200, tplForgotPassword)
  757. return
  758. }
  759. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  760. return
  761. }
  762. if !u.IsLocal() && !u.IsOAuth2() {
  763. ctx.Data["Err_Email"] = true
  764. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  765. return
  766. }
  767. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  768. ctx.Data["ResendLimited"] = true
  769. ctx.HTML(200, tplForgotPassword)
  770. return
  771. }
  772. models.SendResetPasswordMail(ctx.Context, u)
  773. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  774. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  775. }
  776. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  777. ctx.Data["IsResetSent"] = true
  778. ctx.HTML(200, tplForgotPassword)
  779. }
  780. // ResetPasswd render the reset password page
  781. func ResetPasswd(ctx *context.Context) {
  782. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  783. code := ctx.Query("code")
  784. if len(code) == 0 {
  785. ctx.Error(404)
  786. return
  787. }
  788. ctx.Data["Code"] = code
  789. ctx.Data["IsResetForm"] = true
  790. ctx.HTML(200, tplResetPassword)
  791. }
  792. // ResetPasswdPost response from reset password request
  793. func ResetPasswdPost(ctx *context.Context) {
  794. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  795. code := ctx.Query("code")
  796. if len(code) == 0 {
  797. ctx.Error(404)
  798. return
  799. }
  800. ctx.Data["Code"] = code
  801. if u := models.VerifyUserActiveCode(code); u != nil {
  802. // Validate password length.
  803. passwd := ctx.Query("password")
  804. if len(passwd) < setting.MinPasswordLength {
  805. ctx.Data["IsResetForm"] = true
  806. ctx.Data["Err_Password"] = true
  807. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  808. return
  809. }
  810. u.Passwd = passwd
  811. var err error
  812. if u.Rands, err = models.GetUserSalt(); err != nil {
  813. ctx.Handle(500, "UpdateUser", err)
  814. return
  815. }
  816. if u.Salt, err = models.GetUserSalt(); err != nil {
  817. ctx.Handle(500, "UpdateUser", err)
  818. return
  819. }
  820. u.EncodePasswd()
  821. if err := models.UpdateUser(u); err != nil {
  822. ctx.Handle(500, "UpdateUser", err)
  823. return
  824. }
  825. log.Trace("User password reset: %s", u.Name)
  826. ctx.Redirect(setting.AppSubURL + "/user/login")
  827. return
  828. }
  829. ctx.Data["IsResetFailed"] = true
  830. ctx.HTML(200, tplResetPassword)
  831. }