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.

account.go 9.9 kB

3 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package setting
  6. import (
  7. "errors"
  8. "code.gitea.io/gitea/routers/repo"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/auth"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/password"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "code.gitea.io/gitea/services/mailer"
  18. )
  19. const (
  20. tplSettingsAccount base.TplName = "user/settings/account"
  21. )
  22. // Account renders change user's password, user's email and user suicide page
  23. func Account(ctx *context.Context) {
  24. ctx.Data["Title"] = ctx.Tr("settings")
  25. ctx.Data["PageIsSettingsAccount"] = true
  26. ctx.Data["Email"] = ctx.User.Email
  27. loadAccountData(ctx)
  28. ctx.HTML(200, tplSettingsAccount)
  29. }
  30. // AccountPost response for change user's password
  31. func AccountPost(ctx *context.Context, form auth.ChangePasswordForm) {
  32. ctx.Data["Title"] = ctx.Tr("settings")
  33. ctx.Data["PageIsSettingsAccount"] = true
  34. if ctx.HasError() {
  35. loadAccountData(ctx)
  36. ctx.HTML(200, tplSettingsAccount)
  37. return
  38. }
  39. if len(form.Password) < setting.MinPasswordLength {
  40. ctx.Flash.Error(ctx.Tr("auth.password_too_short", setting.MinPasswordLength))
  41. } else if ctx.User.IsPasswordSet() && !ctx.User.ValidatePassword(form.OldPassword) {
  42. ctx.Flash.Error(ctx.Tr("settings.password_incorrect"))
  43. } else if form.Password != form.Retype {
  44. ctx.Flash.Error(ctx.Tr("form.password_not_match"))
  45. } else if !password.IsComplexEnough(form.Password) {
  46. ctx.Flash.Error(password.BuildComplexityError(ctx))
  47. } else {
  48. var err error
  49. if ctx.User.Salt, err = models.GetUserSalt(); err != nil {
  50. ctx.ServerError("UpdateUser", err)
  51. return
  52. }
  53. ctx.User.HashPassword(form.Password)
  54. if err := models.UpdateUserCols(ctx.User, "salt", "passwd"); err != nil {
  55. ctx.ServerError("UpdateUser", err)
  56. return
  57. }
  58. log.Trace("User password updated: %s", ctx.User.Name)
  59. ctx.Flash.Success(ctx.Tr("settings.change_password_success"))
  60. }
  61. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  62. }
  63. // EmailPost response for change user's email
  64. func EmailPost(ctx *context.Context, form auth.AddEmailForm) {
  65. ctx.Data["Title"] = ctx.Tr("settings")
  66. ctx.Data["PageIsSettingsAccount"] = true
  67. // Make emailaddress primary.
  68. if ctx.Query("_method") == "PRIMARY" {
  69. if err := models.MakeEmailPrimary(&models.EmailAddress{ID: ctx.QueryInt64("id")}); err != nil {
  70. if _, ok := err.(models.ErrEmailAlreadyUsed); ok {
  71. ctx.Flash.Error(ctx.Tr("form.email_been_used"))
  72. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  73. return
  74. }
  75. ctx.ServerError("MakeEmailPrimary", err)
  76. return
  77. }
  78. log.Trace("Email made primary: %s", ctx.User.Name)
  79. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  80. return
  81. }
  82. // Send activation Email
  83. if ctx.Query("_method") == "SENDACTIVATION" {
  84. var address string
  85. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  86. log.Error("Send activation: activation still pending")
  87. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  88. return
  89. }
  90. if ctx.Query("id") == "PRIMARY" {
  91. if ctx.User.IsActive {
  92. log.Error("Send activation: email not set for activation")
  93. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  94. return
  95. }
  96. mailer.SendActivateAccountMail(ctx.Locale, ctx.User)
  97. address = ctx.User.Email
  98. } else {
  99. id := ctx.QueryInt64("id")
  100. email, err := models.GetEmailAddressByID(ctx.User.ID, id)
  101. if err != nil {
  102. log.Error("GetEmailAddressByID(%d,%d) error: %v", ctx.User.ID, id, err)
  103. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  104. return
  105. }
  106. if email == nil {
  107. log.Error("Send activation: EmailAddress not found; user:%d, id: %d", ctx.User.ID, id)
  108. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  109. return
  110. }
  111. if email.IsActivated {
  112. log.Error("Send activation: email not set for activation")
  113. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  114. return
  115. }
  116. mailer.SendActivateEmailMail(ctx.Locale, ctx.User, email)
  117. address = email.Email
  118. }
  119. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  120. log.Error("Set cache(MailResendLimit) fail: %v", err)
  121. }
  122. ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", address, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())))
  123. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  124. return
  125. }
  126. // Set Email Notification Preference
  127. if ctx.Query("_method") == "NOTIFICATION" {
  128. preference := ctx.Query("preference")
  129. if !(preference == models.EmailNotificationsEnabled ||
  130. preference == models.EmailNotificationsOnMention ||
  131. preference == models.EmailNotificationsDisabled) {
  132. log.Error("Email notifications preference change returned unrecognized option %s: %s", preference, ctx.User.Name)
  133. ctx.ServerError("SetEmailPreference", errors.New("option unrecognized"))
  134. return
  135. }
  136. if err := ctx.User.SetEmailNotifications(preference); err != nil {
  137. log.Error("Set Email Notifications failed: %v", err)
  138. ctx.ServerError("SetEmailNotifications", err)
  139. return
  140. }
  141. log.Trace("Email notifications preference made %s: %s", preference, ctx.User.Name)
  142. ctx.Flash.Success(ctx.Tr("settings.email_preference_set_success"))
  143. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  144. return
  145. }
  146. if ctx.HasError() {
  147. loadAccountData(ctx)
  148. ctx.HTML(200, tplSettingsAccount)
  149. return
  150. }
  151. email := &models.EmailAddress{
  152. UID: ctx.User.ID,
  153. Email: form.Email,
  154. IsActivated: !setting.Service.RegisterEmailConfirm,
  155. }
  156. if err := models.AddEmailAddress(email); err != nil {
  157. if models.IsErrEmailAlreadyUsed(err) {
  158. loadAccountData(ctx)
  159. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSettingsAccount, &form)
  160. return
  161. }
  162. ctx.ServerError("AddEmailAddress", err)
  163. return
  164. }
  165. // Send confirmation email
  166. if setting.Service.RegisterEmailConfirm {
  167. mailer.SendActivateEmailMail(ctx.Locale, ctx.User, email)
  168. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  169. log.Error("Set cache(MailResendLimit) fail: %v", err)
  170. }
  171. ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())))
  172. } else {
  173. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  174. }
  175. log.Trace("Email address added: %s", email.Email)
  176. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  177. }
  178. // DeleteEmail response for delete user's email
  179. func DeleteEmail(ctx *context.Context) {
  180. if err := models.DeleteEmailAddress(&models.EmailAddress{ID: ctx.QueryInt64("id"), UID: ctx.User.ID}); err != nil {
  181. ctx.ServerError("DeleteEmail", err)
  182. return
  183. }
  184. log.Trace("Email address deleted: %s", ctx.User.Name)
  185. ctx.Flash.Success(ctx.Tr("settings.email_deletion_success"))
  186. ctx.JSON(200, map[string]interface{}{
  187. "redirect": setting.AppSubURL + "/user/settings/account",
  188. })
  189. }
  190. // DeleteAccount render user suicide page and response for delete user himself
  191. func DeleteAccount(ctx *context.Context) {
  192. ctx.Data["Title"] = ctx.Tr("settings")
  193. ctx.Data["PageIsSettingsAccount"] = true
  194. if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil {
  195. if models.IsErrUserNotExist(err) {
  196. loadAccountData(ctx)
  197. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), tplSettingsAccount, nil)
  198. } else {
  199. ctx.ServerError("UserSignIn", err)
  200. }
  201. return
  202. }
  203. if err := models.DeleteUser(ctx.User); err != nil {
  204. switch {
  205. case models.IsErrUserOwnRepos(err):
  206. ctx.Flash.Error(ctx.Tr("form.still_own_repo"))
  207. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  208. case models.IsErrUserHasOrgs(err):
  209. ctx.Flash.Error(ctx.Tr("form.still_has_org"))
  210. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  211. default:
  212. ctx.ServerError("DeleteUser", err)
  213. }
  214. } else {
  215. go repo.StopJobsByUserID(ctx.User.ID)
  216. log.Trace("Account deleted: %s", ctx.User.Name)
  217. ctx.Redirect(setting.AppSubURL + "/")
  218. }
  219. }
  220. // UpdateUIThemePost is used to update users' specific theme
  221. func UpdateUIThemePost(ctx *context.Context, form auth.UpdateThemeForm) {
  222. ctx.Data["Title"] = ctx.Tr("settings")
  223. ctx.Data["PageIsSettingsAccount"] = true
  224. if ctx.HasError() {
  225. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  226. return
  227. }
  228. if !form.IsThemeExists() {
  229. ctx.Flash.Error(ctx.Tr("settings.theme_update_error"))
  230. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  231. return
  232. }
  233. if err := ctx.User.UpdateTheme(form.Theme); err != nil {
  234. ctx.Flash.Error(ctx.Tr("settings.theme_update_error"))
  235. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  236. return
  237. }
  238. log.Trace("Update user theme: %s", ctx.User.Name)
  239. ctx.Flash.Success(ctx.Tr("settings.theme_update_success"))
  240. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  241. }
  242. func loadAccountData(ctx *context.Context) {
  243. emlist, err := models.GetEmailAddresses(ctx.User.ID)
  244. if err != nil {
  245. ctx.ServerError("GetEmailAddresses", err)
  246. return
  247. }
  248. type UserEmail struct {
  249. models.EmailAddress
  250. CanBePrimary bool
  251. }
  252. pendingActivation := ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName)
  253. emails := make([]*UserEmail, len(emlist))
  254. for i, em := range emlist {
  255. var email UserEmail
  256. email.EmailAddress = *em
  257. email.CanBePrimary = em.IsActivated
  258. emails[i] = &email
  259. }
  260. ctx.Data["Emails"] = emails
  261. ctx.Data["EmailNotificationsPreference"] = ctx.User.EmailNotifications()
  262. ctx.Data["ActivationsPending"] = pendingActivation
  263. ctx.Data["CanAddEmails"] = !pendingActivation || !setting.Service.RegisterEmailConfirm
  264. }