auth.go 11 KB

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