auth.go 12 KB

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