You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth.go 28 kB

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)
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)
9 years ago
10 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)
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)
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)
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)
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)
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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. handleSignIn(ctx, u, remember)
  190. return
  191. }
  192. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, auth.TwoFactorAuthForm{})
  193. }
  194. // TwoFactorScratch shows the scratch code form for two-factor authentication.
  195. func TwoFactorScratch(ctx *context.Context) {
  196. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  197. // Check auto-login.
  198. if checkAutoLogin(ctx) {
  199. return
  200. }
  201. // Ensure user is in a 2FA session.
  202. if ctx.Session.Get("twofaUid") == nil {
  203. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  204. return
  205. }
  206. ctx.HTML(200, tplTwofaScratch)
  207. }
  208. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
  209. func TwoFactorScratchPost(ctx *context.Context, form auth.TwoFactorScratchAuthForm) {
  210. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  211. // Ensure user is in a 2FA session.
  212. idSess := ctx.Session.Get("twofaUid")
  213. if idSess == nil {
  214. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  215. return
  216. }
  217. id := idSess.(int64)
  218. twofa, err := models.GetTwoFactorByUID(id)
  219. if err != nil {
  220. ctx.Handle(500, "UserSignIn", err)
  221. return
  222. }
  223. // Validate the passcode with the stored TOTP secret.
  224. if twofa.VerifyScratchToken(form.Token) {
  225. // Invalidate the scratch token.
  226. twofa.ScratchToken = ""
  227. if err = models.UpdateTwoFactor(twofa); err != nil {
  228. ctx.Handle(500, "UserSignIn", err)
  229. return
  230. }
  231. remember := ctx.Session.Get("twofaRemember").(bool)
  232. u, err := models.GetUserByID(id)
  233. if err != nil {
  234. ctx.Handle(500, "UserSignIn", err)
  235. return
  236. }
  237. handleSignInFull(ctx, u, remember, false)
  238. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  239. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  240. return
  241. }
  242. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, auth.TwoFactorScratchAuthForm{})
  243. }
  244. // This handles the final part of the sign-in process of the user.
  245. func handleSignIn(ctx *context.Context, u *models.User, remember bool) {
  246. handleSignInFull(ctx, u, remember, true)
  247. }
  248. func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) {
  249. if remember {
  250. days := 86400 * setting.LogInRememberDays
  251. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL)
  252. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  253. setting.CookieRememberName, u.Name, days, setting.AppSubURL)
  254. }
  255. ctx.Session.Delete("twofaUid")
  256. ctx.Session.Delete("twofaRemember")
  257. ctx.Session.Set("uid", u.ID)
  258. ctx.Session.Set("uname", u.Name)
  259. // Clear whatever CSRF has right now, force to generate a new one
  260. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  261. // Register last login
  262. u.SetLastLogin()
  263. if err := models.UpdateUser(u); err != nil {
  264. ctx.Handle(500, "UpdateUser", err)
  265. return
  266. }
  267. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  268. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  269. if obeyRedirect {
  270. ctx.Redirect(redirectTo)
  271. }
  272. return
  273. }
  274. if obeyRedirect {
  275. ctx.Redirect(setting.AppSubURL + "/")
  276. }
  277. }
  278. // SignInOAuth handles the OAuth2 login buttons
  279. func SignInOAuth(ctx *context.Context) {
  280. provider := ctx.Params(":provider")
  281. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  282. if err != nil {
  283. ctx.Handle(500, "SignIn", err)
  284. return
  285. }
  286. // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user
  287. user, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  288. if err == nil && user != nil {
  289. // we got the user without going through the whole OAuth2 authentication flow again
  290. handleOAuth2SignIn(user, gothUser, ctx, err)
  291. return
  292. }
  293. err = oauth2.Auth(loginSource.Name, ctx.Req.Request, ctx.Resp)
  294. if err != nil {
  295. ctx.Handle(500, "SignIn", err)
  296. }
  297. // redirect is done in oauth2.Auth
  298. }
  299. // SignInOAuthCallback handles the callback from the given provider
  300. func SignInOAuthCallback(ctx *context.Context) {
  301. provider := ctx.Params(":provider")
  302. // first look if the provider is still active
  303. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  304. if err != nil {
  305. ctx.Handle(500, "SignIn", err)
  306. return
  307. }
  308. if loginSource == nil {
  309. ctx.Handle(500, "SignIn", errors.New("No valid provider found, check configured callback url in provider"))
  310. return
  311. }
  312. u, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  313. handleOAuth2SignIn(u, gothUser, ctx, err)
  314. }
  315. func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context, err error) {
  316. if err != nil {
  317. ctx.Handle(500, "UserSignIn", err)
  318. return
  319. }
  320. if u == nil {
  321. // no existing user is found, request attach or new account
  322. ctx.Session.Set("linkAccountGothUser", gothUser)
  323. ctx.Redirect(setting.AppSubURL + "/user/link_account")
  324. return
  325. }
  326. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  327. // Instead, redirect them to the 2FA authentication page.
  328. _, err = models.GetTwoFactorByUID(u.ID)
  329. if err != nil {
  330. if models.IsErrTwoFactorNotEnrolled(err) {
  331. ctx.Session.Set("uid", u.ID)
  332. ctx.Session.Set("uname", u.Name)
  333. // Clear whatever CSRF has right now, force to generate a new one
  334. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  335. // Register last login
  336. u.SetLastLogin()
  337. if err := models.UpdateUser(u); err != nil {
  338. ctx.Handle(500, "UpdateUser", err)
  339. return
  340. }
  341. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  342. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  343. ctx.Redirect(redirectTo)
  344. return
  345. }
  346. ctx.Redirect(setting.AppSubURL + "/")
  347. } else {
  348. ctx.Handle(500, "UserSignIn", err)
  349. }
  350. return
  351. }
  352. // User needs to use 2FA, save data and redirect to 2FA page.
  353. ctx.Session.Set("twofaUid", u.ID)
  354. ctx.Session.Set("twofaRemember", false)
  355. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  356. }
  357. // OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful
  358. // login the user
  359. func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
  360. gothUser, err := oauth2.ProviderCallback(loginSource.Name, request, response)
  361. if err != nil {
  362. return nil, goth.User{}, err
  363. }
  364. user := &models.User{
  365. LoginName: gothUser.UserID,
  366. LoginType: models.LoginOAuth2,
  367. LoginSource: loginSource.ID,
  368. }
  369. hasUser, err := models.GetUser(user)
  370. if err != nil {
  371. return nil, goth.User{}, err
  372. }
  373. if hasUser {
  374. return user, goth.User{}, nil
  375. }
  376. // search in external linked users
  377. externalLoginUser := &models.ExternalLoginUser{
  378. ExternalID: gothUser.UserID,
  379. LoginSourceID: loginSource.ID,
  380. }
  381. hasUser, err = models.GetExternalLogin(externalLoginUser)
  382. if err != nil {
  383. return nil, goth.User{}, err
  384. }
  385. if hasUser {
  386. user, err = models.GetUserByID(externalLoginUser.UserID)
  387. return user, goth.User{}, err
  388. }
  389. // no user found to login
  390. return nil, gothUser, nil
  391. }
  392. // LinkAccount shows the page where the user can decide to login or create a new account
  393. func LinkAccount(ctx *context.Context) {
  394. ctx.Data["Title"] = ctx.Tr("link_account")
  395. ctx.Data["LinkAccountMode"] = true
  396. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  397. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  398. ctx.Data["ShowRegistrationButton"] = false
  399. // use this to set the right link into the signIn and signUp templates in the link_account template
  400. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  401. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  402. gothUser := ctx.Session.Get("linkAccountGothUser")
  403. if gothUser == nil {
  404. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  405. return
  406. }
  407. ctx.Data["user_name"] = gothUser.(goth.User).NickName
  408. ctx.Data["email"] = gothUser.(goth.User).Email
  409. ctx.HTML(200, tplLinkAccount)
  410. }
  411. // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
  412. func LinkAccountPostSignIn(ctx *context.Context, signInForm auth.SignInForm) {
  413. ctx.Data["Title"] = ctx.Tr("link_account")
  414. ctx.Data["LinkAccountMode"] = true
  415. ctx.Data["LinkAccountModeSignIn"] = true
  416. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  417. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  418. ctx.Data["ShowRegistrationButton"] = false
  419. // use this to set the right link into the signIn and signUp templates in the link_account template
  420. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  421. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  422. gothUser := ctx.Session.Get("linkAccountGothUser")
  423. if gothUser == nil {
  424. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  425. return
  426. }
  427. if ctx.HasError() {
  428. ctx.HTML(200, tplLinkAccount)
  429. return
  430. }
  431. u, err := models.UserSignIn(signInForm.UserName, signInForm.Password)
  432. if err != nil {
  433. if models.IsErrUserNotExist(err) {
  434. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm)
  435. } else {
  436. ctx.Handle(500, "UserLinkAccount", err)
  437. }
  438. return
  439. }
  440. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  441. // Instead, redirect them to the 2FA authentication page.
  442. _, err = models.GetTwoFactorByUID(u.ID)
  443. if err != nil {
  444. if models.IsErrTwoFactorNotEnrolled(err) {
  445. models.LinkAccountToUser(u, gothUser.(goth.User))
  446. handleSignIn(ctx, u, signInForm.Remember)
  447. } else {
  448. ctx.Handle(500, "UserLinkAccount", err)
  449. }
  450. return
  451. }
  452. // User needs to use 2FA, save data and redirect to 2FA page.
  453. ctx.Session.Set("twofaUid", u.ID)
  454. ctx.Session.Set("twofaRemember", signInForm.Remember)
  455. ctx.Session.Set("linkAccount", true)
  456. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  457. }
  458. // LinkAccountPostRegister handle the creation of a new account for an external account using signUp
  459. func LinkAccountPostRegister(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  460. ctx.Data["Title"] = ctx.Tr("link_account")
  461. ctx.Data["LinkAccountMode"] = true
  462. ctx.Data["LinkAccountModeRegister"] = true
  463. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  464. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  465. ctx.Data["ShowRegistrationButton"] = false
  466. // use this to set the right link into the signIn and signUp templates in the link_account template
  467. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  468. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  469. gothUser := ctx.Session.Get("linkAccountGothUser")
  470. if gothUser == nil {
  471. ctx.Handle(500, "UserSignUp", errors.New("not in LinkAccount session"))
  472. return
  473. }
  474. if ctx.HasError() {
  475. ctx.HTML(200, tplLinkAccount)
  476. return
  477. }
  478. if setting.Service.DisableRegistration {
  479. ctx.Error(403)
  480. return
  481. }
  482. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  483. ctx.Data["Err_Captcha"] = true
  484. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form)
  485. return
  486. }
  487. if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype {
  488. ctx.Data["Err_Password"] = true
  489. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form)
  490. return
  491. }
  492. if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength {
  493. ctx.Data["Err_Password"] = true
  494. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form)
  495. return
  496. }
  497. loginSource, err := models.GetActiveOAuth2LoginSourceByName(gothUser.(goth.User).Provider)
  498. if err != nil {
  499. ctx.Handle(500, "CreateUser", err)
  500. }
  501. u := &models.User{
  502. Name: form.UserName,
  503. Email: form.Email,
  504. Passwd: form.Password,
  505. IsActive: !setting.Service.RegisterEmailConfirm,
  506. LoginType: models.LoginOAuth2,
  507. LoginSource: loginSource.ID,
  508. LoginName: gothUser.(goth.User).UserID,
  509. }
  510. if err := models.CreateUser(u); err != nil {
  511. switch {
  512. case models.IsErrUserAlreadyExist(err):
  513. ctx.Data["Err_UserName"] = true
  514. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplLinkAccount, &form)
  515. case models.IsErrEmailAlreadyUsed(err):
  516. ctx.Data["Err_Email"] = true
  517. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplLinkAccount, &form)
  518. case models.IsErrNameReserved(err):
  519. ctx.Data["Err_UserName"] = true
  520. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplLinkAccount, &form)
  521. case models.IsErrNamePatternNotAllowed(err):
  522. ctx.Data["Err_UserName"] = true
  523. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplLinkAccount, &form)
  524. default:
  525. ctx.Handle(500, "CreateUser", err)
  526. }
  527. return
  528. }
  529. log.Trace("Account created: %s", u.Name)
  530. // Auto-set admin for the only user.
  531. if models.CountUsers() == 1 {
  532. u.IsAdmin = true
  533. u.IsActive = true
  534. if err := models.UpdateUser(u); err != nil {
  535. ctx.Handle(500, "UpdateUser", err)
  536. return
  537. }
  538. }
  539. // Send confirmation email
  540. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  541. models.SendActivateAccountMail(ctx.Context, u)
  542. ctx.Data["IsSendRegisterMail"] = true
  543. ctx.Data["Email"] = u.Email
  544. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  545. ctx.HTML(200, TplActivate)
  546. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  547. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  548. }
  549. return
  550. }
  551. ctx.Redirect(setting.AppSubURL + "/user/login")
  552. }
  553. // SignOut sign out from login status
  554. func SignOut(ctx *context.Context) {
  555. ctx.Session.Delete("uid")
  556. ctx.Session.Delete("uname")
  557. ctx.Session.Delete("socialId")
  558. ctx.Session.Delete("socialName")
  559. ctx.Session.Delete("socialEmail")
  560. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  561. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  562. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  563. ctx.Redirect(setting.AppSubURL + "/")
  564. }
  565. // SignUp render the register page
  566. func SignUp(ctx *context.Context) {
  567. ctx.Data["Title"] = ctx.Tr("sign_up")
  568. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  569. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  570. ctx.HTML(200, tplSignUp)
  571. }
  572. // SignUpPost response for sign up information submission
  573. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  574. ctx.Data["Title"] = ctx.Tr("sign_up")
  575. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  576. if setting.Service.DisableRegistration {
  577. ctx.Error(403)
  578. return
  579. }
  580. if ctx.HasError() {
  581. ctx.HTML(200, tplSignUp)
  582. return
  583. }
  584. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  585. ctx.Data["Err_Captcha"] = true
  586. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  587. return
  588. }
  589. if form.Password != form.Retype {
  590. ctx.Data["Err_Password"] = true
  591. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  592. return
  593. }
  594. if len(form.Password) < setting.MinPasswordLength {
  595. ctx.Data["Err_Password"] = true
  596. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  597. return
  598. }
  599. u := &models.User{
  600. Name: form.UserName,
  601. Email: form.Email,
  602. Passwd: form.Password,
  603. IsActive: !setting.Service.RegisterEmailConfirm,
  604. }
  605. if err := models.CreateUser(u); err != nil {
  606. switch {
  607. case models.IsErrUserAlreadyExist(err):
  608. ctx.Data["Err_UserName"] = true
  609. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  610. case models.IsErrEmailAlreadyUsed(err):
  611. ctx.Data["Err_Email"] = true
  612. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  613. case models.IsErrNameReserved(err):
  614. ctx.Data["Err_UserName"] = true
  615. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  616. case models.IsErrNamePatternNotAllowed(err):
  617. ctx.Data["Err_UserName"] = true
  618. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  619. default:
  620. ctx.Handle(500, "CreateUser", err)
  621. }
  622. return
  623. }
  624. log.Trace("Account created: %s", u.Name)
  625. // Auto-set admin for the only user.
  626. if models.CountUsers() == 1 {
  627. u.IsAdmin = true
  628. u.IsActive = true
  629. if err := models.UpdateUser(u); err != nil {
  630. ctx.Handle(500, "UpdateUser", err)
  631. return
  632. }
  633. }
  634. // Send confirmation email, no need for social account.
  635. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  636. models.SendActivateAccountMail(ctx.Context, u)
  637. ctx.Data["IsSendRegisterMail"] = true
  638. ctx.Data["Email"] = u.Email
  639. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  640. ctx.HTML(200, TplActivate)
  641. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  642. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  643. }
  644. return
  645. }
  646. ctx.Redirect(setting.AppSubURL + "/user/login")
  647. }
  648. // Activate render activate user page
  649. func Activate(ctx *context.Context) {
  650. code := ctx.Query("code")
  651. if len(code) == 0 {
  652. ctx.Data["IsActivatePage"] = true
  653. if ctx.User.IsActive {
  654. ctx.Error(404)
  655. return
  656. }
  657. // Resend confirmation email.
  658. if setting.Service.RegisterEmailConfirm {
  659. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  660. ctx.Data["ResendLimited"] = true
  661. } else {
  662. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  663. models.SendActivateAccountMail(ctx.Context, ctx.User)
  664. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  665. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  666. }
  667. }
  668. } else {
  669. ctx.Data["ServiceNotEnabled"] = true
  670. }
  671. ctx.HTML(200, TplActivate)
  672. return
  673. }
  674. // Verify code.
  675. if user := models.VerifyUserActiveCode(code); user != nil {
  676. user.IsActive = true
  677. var err error
  678. if user.Rands, err = models.GetUserSalt(); err != nil {
  679. ctx.Handle(500, "UpdateUser", err)
  680. return
  681. }
  682. if err := models.UpdateUser(user); err != nil {
  683. if models.IsErrUserNotExist(err) {
  684. ctx.Error(404)
  685. } else {
  686. ctx.Handle(500, "UpdateUser", err)
  687. }
  688. return
  689. }
  690. log.Trace("User activated: %s", user.Name)
  691. ctx.Session.Set("uid", user.ID)
  692. ctx.Session.Set("uname", user.Name)
  693. ctx.Redirect(setting.AppSubURL + "/")
  694. return
  695. }
  696. ctx.Data["IsActivateFailed"] = true
  697. ctx.HTML(200, TplActivate)
  698. }
  699. // ActivateEmail render the activate email page
  700. func ActivateEmail(ctx *context.Context) {
  701. code := ctx.Query("code")
  702. emailStr := ctx.Query("email")
  703. // Verify code.
  704. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  705. if err := email.Activate(); err != nil {
  706. ctx.Handle(500, "ActivateEmail", err)
  707. }
  708. log.Trace("Email activated: %s", email.Email)
  709. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  710. }
  711. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  712. return
  713. }
  714. // ForgotPasswd render the forget pasword page
  715. func ForgotPasswd(ctx *context.Context) {
  716. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  717. if setting.MailService == nil {
  718. ctx.Data["IsResetDisable"] = true
  719. ctx.HTML(200, tplForgotPassword)
  720. return
  721. }
  722. ctx.Data["IsResetRequest"] = true
  723. ctx.HTML(200, tplForgotPassword)
  724. }
  725. // ForgotPasswdPost response for forget password request
  726. func ForgotPasswdPost(ctx *context.Context) {
  727. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  728. if setting.MailService == nil {
  729. ctx.Handle(403, "ForgotPasswdPost", nil)
  730. return
  731. }
  732. ctx.Data["IsResetRequest"] = true
  733. email := ctx.Query("email")
  734. ctx.Data["Email"] = email
  735. u, err := models.GetUserByEmail(email)
  736. if err != nil {
  737. if models.IsErrUserNotExist(err) {
  738. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  739. ctx.Data["IsResetSent"] = true
  740. ctx.HTML(200, tplForgotPassword)
  741. return
  742. }
  743. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  744. return
  745. }
  746. if !u.IsLocal() && !u.IsOAuth2() {
  747. ctx.Data["Err_Email"] = true
  748. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  749. return
  750. }
  751. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  752. ctx.Data["ResendLimited"] = true
  753. ctx.HTML(200, tplForgotPassword)
  754. return
  755. }
  756. models.SendResetPasswordMail(ctx.Context, u)
  757. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  758. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  759. }
  760. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  761. ctx.Data["IsResetSent"] = true
  762. ctx.HTML(200, tplForgotPassword)
  763. }
  764. // ResetPasswd render the reset password page
  765. func ResetPasswd(ctx *context.Context) {
  766. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  767. code := ctx.Query("code")
  768. if len(code) == 0 {
  769. ctx.Error(404)
  770. return
  771. }
  772. ctx.Data["Code"] = code
  773. ctx.Data["IsResetForm"] = true
  774. ctx.HTML(200, tplResetPassword)
  775. }
  776. // ResetPasswdPost response from reset password request
  777. func ResetPasswdPost(ctx *context.Context) {
  778. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  779. code := ctx.Query("code")
  780. if len(code) == 0 {
  781. ctx.Error(404)
  782. return
  783. }
  784. ctx.Data["Code"] = code
  785. if u := models.VerifyUserActiveCode(code); u != nil {
  786. // Validate password length.
  787. passwd := ctx.Query("password")
  788. if len(passwd) < setting.MinPasswordLength {
  789. ctx.Data["IsResetForm"] = true
  790. ctx.Data["Err_Password"] = true
  791. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  792. return
  793. }
  794. u.Passwd = passwd
  795. var err error
  796. if u.Rands, err = models.GetUserSalt(); err != nil {
  797. ctx.Handle(500, "UpdateUser", err)
  798. return
  799. }
  800. if u.Salt, err = models.GetUserSalt(); err != nil {
  801. ctx.Handle(500, "UpdateUser", err)
  802. return
  803. }
  804. u.EncodePasswd()
  805. if err := models.UpdateUser(u); err != nil {
  806. ctx.Handle(500, "UpdateUser", err)
  807. return
  808. }
  809. log.Trace("User password reset: %s", u.Name)
  810. ctx.Redirect(setting.AppSubURL + "/user/login")
  811. return
  812. }
  813. ctx.Data["IsResetFailed"] = true
  814. ctx.HTML(200, tplResetPassword)
  815. }