auth.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. "fmt"
  7. "net/url"
  8. "github.com/go-macaron/captcha"
  9. log "gopkg.in/clog.v1"
  10. "github.com/gogits/gogs/models"
  11. "github.com/gogits/gogs/modules/base"
  12. "github.com/gogits/gogs/modules/context"
  13. "github.com/gogits/gogs/modules/form"
  14. "github.com/gogits/gogs/modules/mailer"
  15. "github.com/gogits/gogs/modules/setting"
  16. )
  17. const (
  18. SIGNIN base.TplName = "user/auth/signin"
  19. SIGNUP base.TplName = "user/auth/signup"
  20. ACTIVATE base.TplName = "user/auth/activate"
  21. FORGOT_PASSWORD base.TplName = "user/auth/forgot_passwd"
  22. RESET_PASSWORD base.TplName = "user/auth/reset_passwd"
  23. )
  24. // AutoSignIn reads cookie and try to auto-login.
  25. func AutoSignIn(ctx *context.Context) (bool, error) {
  26. if !models.HasEngine {
  27. return false, nil
  28. }
  29. uname := ctx.GetCookie(setting.CookieUserName)
  30. if len(uname) == 0 {
  31. return false, nil
  32. }
  33. isSucceed := false
  34. defer func() {
  35. if !isSucceed {
  36. log.Trace("auto-login cookie cleared: %s", uname)
  37. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl)
  38. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl)
  39. }
  40. }()
  41. u, err := models.GetUserByName(uname)
  42. if err != nil {
  43. if !models.IsErrUserNotExist(err) {
  44. return false, fmt.Errorf("GetUserByName: %v", err)
  45. }
  46. return false, nil
  47. }
  48. if val, ok := ctx.GetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName); !ok || val != u.Name {
  49. return false, nil
  50. }
  51. isSucceed = true
  52. ctx.Session.Set("uid", u.ID)
  53. ctx.Session.Set("uname", u.Name)
  54. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl)
  55. return true, nil
  56. }
  57. // isValidRedirect returns false if the URL does not redirect to same site.
  58. // False: //url, http://url
  59. // True: /url
  60. func isValidRedirect(url string) bool {
  61. return len(url) >= 2 && url[0] == '/' && url[1] != '/'
  62. }
  63. func SignIn(ctx *context.Context) {
  64. ctx.Data["Title"] = ctx.Tr("sign_in")
  65. // Check auto-login.
  66. isSucceed, err := AutoSignIn(ctx)
  67. if err != nil {
  68. ctx.Handle(500, "AutoSignIn", err)
  69. return
  70. }
  71. redirectTo := ctx.Query("redirect_to")
  72. if len(redirectTo) > 0 {
  73. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubUrl)
  74. } else {
  75. redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to"))
  76. }
  77. ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl)
  78. if isSucceed {
  79. if isValidRedirect(redirectTo) {
  80. ctx.Redirect(redirectTo)
  81. } else {
  82. ctx.Redirect(setting.AppSubUrl + "/")
  83. }
  84. return
  85. }
  86. ctx.HTML(200, SIGNIN)
  87. }
  88. func SignInPost(ctx *context.Context, f form.SignIn) {
  89. ctx.Data["Title"] = ctx.Tr("sign_in")
  90. if ctx.HasError() {
  91. ctx.HTML(200, SIGNIN)
  92. return
  93. }
  94. u, err := models.UserSignIn(f.UserName, f.Password)
  95. if err != nil {
  96. if models.IsErrUserNotExist(err) {
  97. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), SIGNIN, &f)
  98. } else {
  99. ctx.Handle(500, "UserSignIn", err)
  100. }
  101. return
  102. }
  103. if f.Remember {
  104. days := 86400 * setting.LogInRememberDays
  105. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubUrl, "", setting.CookieSecure, true)
  106. ctx.SetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName, u.Name, days, setting.AppSubUrl, "", setting.CookieSecure, true)
  107. }
  108. ctx.Session.Set("uid", u.ID)
  109. ctx.Session.Set("uname", u.Name)
  110. // Clear whatever CSRF has right now, force to generate a new one
  111. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl)
  112. redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to"))
  113. ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl)
  114. if isValidRedirect(redirectTo) {
  115. ctx.Redirect(redirectTo)
  116. return
  117. }
  118. ctx.Redirect(setting.AppSubUrl + "/")
  119. }
  120. func SignOut(ctx *context.Context) {
  121. ctx.Session.Delete("uid")
  122. ctx.Session.Delete("uname")
  123. ctx.Session.Delete("socialId")
  124. ctx.Session.Delete("socialName")
  125. ctx.Session.Delete("socialEmail")
  126. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl)
  127. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl)
  128. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl)
  129. ctx.Redirect(setting.AppSubUrl + "/")
  130. }
  131. func SignUp(ctx *context.Context) {
  132. ctx.Data["Title"] = ctx.Tr("sign_up")
  133. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  134. if setting.Service.DisableRegistration {
  135. ctx.Data["DisableRegistration"] = true
  136. ctx.HTML(200, SIGNUP)
  137. return
  138. }
  139. ctx.HTML(200, SIGNUP)
  140. }
  141. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
  142. ctx.Data["Title"] = ctx.Tr("sign_up")
  143. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  144. if setting.Service.DisableRegistration {
  145. ctx.Error(403)
  146. return
  147. }
  148. if ctx.HasError() {
  149. ctx.HTML(200, SIGNUP)
  150. return
  151. }
  152. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  153. ctx.Data["Err_Captcha"] = true
  154. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &f)
  155. return
  156. }
  157. if f.Password != f.Retype {
  158. ctx.Data["Err_Password"] = true
  159. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &f)
  160. return
  161. }
  162. u := &models.User{
  163. Name: f.UserName,
  164. Email: f.Email,
  165. Passwd: f.Password,
  166. IsActive: !setting.Service.RegisterEmailConfirm,
  167. }
  168. if err := models.CreateUser(u); err != nil {
  169. switch {
  170. case models.IsErrUserAlreadyExist(err):
  171. ctx.Data["Err_UserName"] = true
  172. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SIGNUP, &f)
  173. case models.IsErrEmailAlreadyUsed(err):
  174. ctx.Data["Err_Email"] = true
  175. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &f)
  176. case models.IsErrNameReserved(err):
  177. ctx.Data["Err_UserName"] = true
  178. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
  179. case models.IsErrNamePatternNotAllowed(err):
  180. ctx.Data["Err_UserName"] = true
  181. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f)
  182. default:
  183. ctx.Handle(500, "CreateUser", err)
  184. }
  185. return
  186. }
  187. log.Trace("Account created: %s", u.Name)
  188. // Auto-set admin for the only user.
  189. if models.CountUsers() == 1 {
  190. u.IsAdmin = true
  191. u.IsActive = true
  192. if err := models.UpdateUser(u); err != nil {
  193. ctx.Handle(500, "UpdateUser", err)
  194. return
  195. }
  196. }
  197. // Send confirmation email, no need for social account.
  198. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  199. mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(u))
  200. ctx.Data["IsSendRegisterMail"] = true
  201. ctx.Data["Email"] = u.Email
  202. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  203. ctx.HTML(200, ACTIVATE)
  204. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  205. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  206. }
  207. return
  208. }
  209. ctx.Redirect(setting.AppSubUrl + "/user/login")
  210. }
  211. func Activate(ctx *context.Context) {
  212. code := ctx.Query("code")
  213. if len(code) == 0 {
  214. ctx.Data["IsActivatePage"] = true
  215. if ctx.User.IsActive {
  216. ctx.Error(404)
  217. return
  218. }
  219. // Resend confirmation email.
  220. if setting.Service.RegisterEmailConfirm {
  221. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  222. ctx.Data["ResendLimited"] = true
  223. } else {
  224. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  225. mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(ctx.User))
  226. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  227. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  228. }
  229. }
  230. } else {
  231. ctx.Data["ServiceNotEnabled"] = true
  232. }
  233. ctx.HTML(200, ACTIVATE)
  234. return
  235. }
  236. // Verify code.
  237. if user := models.VerifyUserActiveCode(code); user != nil {
  238. user.IsActive = true
  239. var err error
  240. if user.Rands, err = models.GetUserSalt(); err != nil {
  241. ctx.Handle(500, "UpdateUser", err)
  242. return
  243. }
  244. if err := models.UpdateUser(user); err != nil {
  245. if models.IsErrUserNotExist(err) {
  246. ctx.Error(404)
  247. } else {
  248. ctx.Handle(500, "UpdateUser", err)
  249. }
  250. return
  251. }
  252. log.Trace("User activated: %s", user.Name)
  253. ctx.Session.Set("uid", user.ID)
  254. ctx.Session.Set("uname", user.Name)
  255. ctx.Redirect(setting.AppSubUrl + "/")
  256. return
  257. }
  258. ctx.Data["IsActivateFailed"] = true
  259. ctx.HTML(200, ACTIVATE)
  260. }
  261. func ActivateEmail(ctx *context.Context) {
  262. code := ctx.Query("code")
  263. email_string := ctx.Query("email")
  264. // Verify code.
  265. if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
  266. if err := email.Activate(); err != nil {
  267. ctx.Handle(500, "ActivateEmail", err)
  268. }
  269. log.Trace("Email activated: %s", email.Email)
  270. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  271. }
  272. ctx.Redirect(setting.AppSubUrl + "/user/settings/email")
  273. return
  274. }
  275. func ForgotPasswd(ctx *context.Context) {
  276. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  277. if setting.MailService == nil {
  278. ctx.Data["IsResetDisable"] = true
  279. ctx.HTML(200, FORGOT_PASSWORD)
  280. return
  281. }
  282. ctx.Data["IsResetRequest"] = true
  283. ctx.HTML(200, FORGOT_PASSWORD)
  284. }
  285. func ForgotPasswdPost(ctx *context.Context) {
  286. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  287. if setting.MailService == nil {
  288. ctx.Handle(403, "ForgotPasswdPost", nil)
  289. return
  290. }
  291. ctx.Data["IsResetRequest"] = true
  292. email := ctx.Query("email")
  293. ctx.Data["Email"] = email
  294. u, err := models.GetUserByEmail(email)
  295. if err != nil {
  296. if models.IsErrUserNotExist(err) {
  297. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  298. ctx.Data["IsResetSent"] = true
  299. ctx.HTML(200, FORGOT_PASSWORD)
  300. return
  301. } else {
  302. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  303. }
  304. return
  305. }
  306. if !u.IsLocal() {
  307. ctx.Data["Err_Email"] = true
  308. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
  309. return
  310. }
  311. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  312. ctx.Data["ResendLimited"] = true
  313. ctx.HTML(200, FORGOT_PASSWORD)
  314. return
  315. }
  316. mailer.SendResetPasswordMail(ctx.Context, models.NewMailerUser(u))
  317. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  318. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  319. }
  320. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  321. ctx.Data["IsResetSent"] = true
  322. ctx.HTML(200, FORGOT_PASSWORD)
  323. }
  324. func ResetPasswd(ctx *context.Context) {
  325. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  326. code := ctx.Query("code")
  327. if len(code) == 0 {
  328. ctx.Error(404)
  329. return
  330. }
  331. ctx.Data["Code"] = code
  332. ctx.Data["IsResetForm"] = true
  333. ctx.HTML(200, RESET_PASSWORD)
  334. }
  335. func ResetPasswdPost(ctx *context.Context) {
  336. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  337. code := ctx.Query("code")
  338. if len(code) == 0 {
  339. ctx.Error(404)
  340. return
  341. }
  342. ctx.Data["Code"] = code
  343. if u := models.VerifyUserActiveCode(code); u != nil {
  344. // Validate password length.
  345. passwd := ctx.Query("password")
  346. if len(passwd) < 6 {
  347. ctx.Data["IsResetForm"] = true
  348. ctx.Data["Err_Password"] = true
  349. ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  350. return
  351. }
  352. u.Passwd = passwd
  353. var err error
  354. if u.Rands, err = models.GetUserSalt(); err != nil {
  355. ctx.Handle(500, "UpdateUser", err)
  356. return
  357. }
  358. if u.Salt, err = models.GetUserSalt(); err != nil {
  359. ctx.Handle(500, "UpdateUser", err)
  360. return
  361. }
  362. u.EncodePasswd()
  363. if err := models.UpdateUser(u); err != nil {
  364. ctx.Handle(500, "UpdateUser", err)
  365. return
  366. }
  367. log.Trace("User password reset: %s", u.Name)
  368. ctx.Redirect(setting.AppSubUrl + "/user/login")
  369. return
  370. }
  371. ctx.Data["IsResetFailed"] = true
  372. ctx.HTML(200, RESET_PASSWORD)
  373. }