auth.go 12 KB

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