You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

227 lines
6.7 KiB

Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
  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. "fmt"
  9. "io/ioutil"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/unknwon/com"
  18. "github.com/unknwon/i18n"
  19. )
  20. const (
  21. tplSettingsProfile base.TplName = "user/settings/profile"
  22. tplSettingsOrganization base.TplName = "user/settings/organization"
  23. tplSettingsRepositories base.TplName = "user/settings/repos"
  24. )
  25. // Profile render user's profile page
  26. func Profile(ctx *context.Context) {
  27. ctx.Data["Title"] = ctx.Tr("settings")
  28. ctx.Data["PageIsSettingsProfile"] = true
  29. ctx.HTML(200, tplSettingsProfile)
  30. }
  31. func handleUsernameChange(ctx *context.Context, newName string) {
  32. // Non-local users are not allowed to change their username.
  33. if len(newName) == 0 || !ctx.User.IsLocal() {
  34. return
  35. }
  36. // Check if user name has been changed
  37. if ctx.User.LowerName != strings.ToLower(newName) {
  38. if err := models.ChangeUserName(ctx.User, newName); err != nil {
  39. switch {
  40. case models.IsErrUserAlreadyExist(err):
  41. ctx.Flash.Error(ctx.Tr("form.username_been_taken"))
  42. ctx.Redirect(setting.AppSubURL + "/user/settings")
  43. case models.IsErrEmailAlreadyUsed(err):
  44. ctx.Flash.Error(ctx.Tr("form.email_been_used"))
  45. ctx.Redirect(setting.AppSubURL + "/user/settings")
  46. case models.IsErrNameReserved(err):
  47. ctx.Flash.Error(ctx.Tr("user.form.name_reserved", newName))
  48. ctx.Redirect(setting.AppSubURL + "/user/settings")
  49. case models.IsErrNamePatternNotAllowed(err):
  50. ctx.Flash.Error(ctx.Tr("user.form.name_pattern_not_allowed", newName))
  51. ctx.Redirect(setting.AppSubURL + "/user/settings")
  52. case models.IsErrNameCharsNotAllowed(err):
  53. ctx.Flash.Error(ctx.Tr("user.form.name_chars_not_allowed", newName))
  54. ctx.Redirect(setting.AppSubURL + "/user/settings")
  55. default:
  56. ctx.ServerError("ChangeUserName", err)
  57. }
  58. return
  59. }
  60. log.Trace("User name changed: %s -> %s", ctx.User.Name, newName)
  61. }
  62. // In case it's just a case change
  63. ctx.User.Name = newName
  64. ctx.User.LowerName = strings.ToLower(newName)
  65. }
  66. // ProfilePost response for change user's profile
  67. func ProfilePost(ctx *context.Context, form auth.UpdateProfileForm) {
  68. ctx.Data["Title"] = ctx.Tr("settings")
  69. ctx.Data["PageIsSettingsProfile"] = true
  70. if ctx.HasError() {
  71. ctx.HTML(200, tplSettingsProfile)
  72. return
  73. }
  74. handleUsernameChange(ctx, form.Name)
  75. if ctx.Written() {
  76. return
  77. }
  78. ctx.User.FullName = form.FullName
  79. ctx.User.Email = form.Email
  80. ctx.User.KeepEmailPrivate = form.KeepEmailPrivate
  81. ctx.User.Website = form.Website
  82. ctx.User.Location = form.Location
  83. ctx.User.Language = form.Language
  84. ctx.User.Description = form.Description
  85. if err := models.UpdateUserSetting(ctx.User); err != nil {
  86. if _, ok := err.(models.ErrEmailAlreadyUsed); ok {
  87. ctx.Flash.Error(ctx.Tr("form.email_been_used"))
  88. ctx.Redirect(setting.AppSubURL + "/user/settings")
  89. return
  90. }
  91. ctx.ServerError("UpdateUser", err)
  92. return
  93. }
  94. // Update the language to the one we just set
  95. ctx.SetCookie("lang", ctx.User.Language, nil, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  96. log.Trace("User settings updated: %s", ctx.User.Name)
  97. ctx.Flash.Success(i18n.Tr(ctx.User.Language, "settings.update_profile_success"))
  98. ctx.Redirect(setting.AppSubURL + "/user/settings")
  99. }
  100. // UpdateAvatarSetting update user's avatar
  101. // FIXME: limit size.
  102. func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm, ctxUser *models.User) error {
  103. ctxUser.UseCustomAvatar = form.Source == auth.AvatarLocal
  104. if len(form.Gravatar) > 0 {
  105. ctxUser.Avatar = base.EncodeMD5(form.Gravatar)
  106. ctxUser.AvatarEmail = form.Gravatar
  107. }
  108. if form.Avatar != nil && form.Avatar.Filename != "" {
  109. fr, err := form.Avatar.Open()
  110. if err != nil {
  111. return fmt.Errorf("Avatar.Open: %v", err)
  112. }
  113. defer fr.Close()
  114. if form.Avatar.Size > setting.AvatarMaxFileSize {
  115. return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big"))
  116. }
  117. data, err := ioutil.ReadAll(fr)
  118. if err != nil {
  119. return fmt.Errorf("ioutil.ReadAll: %v", err)
  120. }
  121. if !base.IsImageFile(data) {
  122. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  123. }
  124. if err = ctxUser.UploadAvatar(data); err != nil {
  125. return fmt.Errorf("UploadAvatar: %v", err)
  126. }
  127. } else if ctxUser.UseCustomAvatar && !com.IsFile(ctxUser.CustomAvatarPath()) {
  128. // No avatar is uploaded but setting has been changed to enable,
  129. // generate a random one when needed.
  130. if err := ctxUser.GenerateRandomAvatar(); err != nil {
  131. log.Error("GenerateRandomAvatar[%d]: %v", ctxUser.ID, err)
  132. }
  133. }
  134. if err := models.UpdateUserCols(ctxUser, "avatar", "avatar_email", "use_custom_avatar"); err != nil {
  135. return fmt.Errorf("UpdateUser: %v", err)
  136. }
  137. return nil
  138. }
  139. // AvatarPost response for change user's avatar request
  140. func AvatarPost(ctx *context.Context, form auth.AvatarForm) {
  141. if err := UpdateAvatarSetting(ctx, form, ctx.User); err != nil {
  142. ctx.Flash.Error(err.Error())
  143. } else {
  144. ctx.Flash.Success(ctx.Tr("settings.update_avatar_success"))
  145. }
  146. ctx.Redirect(setting.AppSubURL + "/user/settings")
  147. }
  148. // DeleteAvatar render delete avatar page
  149. func DeleteAvatar(ctx *context.Context) {
  150. if err := ctx.User.DeleteAvatar(); err != nil {
  151. ctx.Flash.Error(err.Error())
  152. }
  153. ctx.Redirect(setting.AppSubURL + "/user/settings")
  154. }
  155. // Organization render all the organization of the user
  156. func Organization(ctx *context.Context) {
  157. ctx.Data["Title"] = ctx.Tr("settings")
  158. ctx.Data["PageIsSettingsOrganization"] = true
  159. orgs, err := models.GetOrgsByUserID(ctx.User.ID, ctx.IsSigned)
  160. if err != nil {
  161. ctx.ServerError("GetOrgsByUserID", err)
  162. return
  163. }
  164. ctx.Data["Orgs"] = orgs
  165. ctx.HTML(200, tplSettingsOrganization)
  166. }
  167. // Repos display a list of all repositories of the user
  168. func Repos(ctx *context.Context) {
  169. ctx.Data["Title"] = ctx.Tr("settings")
  170. ctx.Data["PageIsSettingsRepos"] = true
  171. ctxUser := ctx.User
  172. var err error
  173. if err = ctxUser.GetRepositories(models.ListOptions{Page: 1, PageSize: setting.UI.User.RepoPagingNum}); err != nil {
  174. ctx.ServerError("GetRepositories", err)
  175. return
  176. }
  177. repos := ctxUser.Repos
  178. for i := range repos {
  179. if repos[i].IsFork {
  180. err := repos[i].GetBaseRepo()
  181. if err != nil {
  182. ctx.ServerError("GetBaseRepo", err)
  183. return
  184. }
  185. err = repos[i].BaseRepo.GetOwner()
  186. if err != nil {
  187. ctx.ServerError("GetOwner", err)
  188. return
  189. }
  190. }
  191. }
  192. ctx.Data["Owner"] = ctxUser
  193. ctx.Data["Repos"] = repos
  194. ctx.HTML(200, tplSettingsRepositories)
  195. }