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.

setting.go 19 kB

11 years ago
12 years ago
10 years ago
12 years ago
12 years ago
12 years ago
12 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
11 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
11 years ago
11 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
11 years ago
11 years ago
12 years ago
9 years ago
12 years ago
12 years ago
10 years ago
10 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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. "bytes"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "strings"
  11. "github.com/Unknwon/com"
  12. "github.com/pquerna/otp"
  13. "github.com/pquerna/otp/totp"
  14. "encoding/base64"
  15. "html/template"
  16. "image/png"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/auth"
  19. "code.gitea.io/gitea/modules/base"
  20. "code.gitea.io/gitea/modules/context"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/setting"
  23. )
  24. const (
  25. tplSettingsProfile base.TplName = "user/settings/profile"
  26. tplSettingsAvatar base.TplName = "user/settings/avatar"
  27. tplSettingsPassword base.TplName = "user/settings/password"
  28. tplSettingsEmails base.TplName = "user/settings/email"
  29. tplSettingsSSHKeys base.TplName = "user/settings/sshkeys"
  30. tplSettingsSocial base.TplName = "user/settings/social"
  31. tplSettingsApplications base.TplName = "user/settings/applications"
  32. tplSettingsTwofa base.TplName = "user/settings/twofa"
  33. tplSettingsTwofaEnroll base.TplName = "user/settings/twofa_enroll"
  34. tplSettingsDelete base.TplName = "user/settings/delete"
  35. tplSecurity base.TplName = "user/security"
  36. )
  37. // Settings render user's profile page
  38. func Settings(ctx *context.Context) {
  39. ctx.Data["Title"] = ctx.Tr("settings")
  40. ctx.Data["PageIsSettingsProfile"] = true
  41. ctx.HTML(200, tplSettingsProfile)
  42. }
  43. func handleUsernameChange(ctx *context.Context, newName string) {
  44. // Non-local users are not allowed to change their username.
  45. if len(newName) == 0 || !ctx.User.IsLocal() {
  46. return
  47. }
  48. // Check if user name has been changed
  49. if ctx.User.LowerName != strings.ToLower(newName) {
  50. if err := models.ChangeUserName(ctx.User, newName); err != nil {
  51. switch {
  52. case models.IsErrUserAlreadyExist(err):
  53. ctx.Flash.Error(ctx.Tr("newName_been_taken"))
  54. ctx.Redirect(setting.AppSubURL + "/user/settings")
  55. case models.IsErrEmailAlreadyUsed(err):
  56. ctx.Flash.Error(ctx.Tr("form.email_been_used"))
  57. ctx.Redirect(setting.AppSubURL + "/user/settings")
  58. case models.IsErrNameReserved(err):
  59. ctx.Flash.Error(ctx.Tr("user.newName_reserved"))
  60. ctx.Redirect(setting.AppSubURL + "/user/settings")
  61. case models.IsErrNamePatternNotAllowed(err):
  62. ctx.Flash.Error(ctx.Tr("user.newName_pattern_not_allowed"))
  63. ctx.Redirect(setting.AppSubURL + "/user/settings")
  64. default:
  65. ctx.Handle(500, "ChangeUserName", err)
  66. }
  67. return
  68. }
  69. log.Trace("User name changed: %s -> %s", ctx.User.Name, newName)
  70. }
  71. // In case it's just a case change
  72. ctx.User.Name = newName
  73. ctx.User.LowerName = strings.ToLower(newName)
  74. }
  75. // SettingsPost response for change user's profile
  76. func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) {
  77. ctx.Data["Title"] = ctx.Tr("settings")
  78. ctx.Data["PageIsSettingsProfile"] = true
  79. if ctx.HasError() {
  80. ctx.HTML(200, tplSettingsProfile)
  81. return
  82. }
  83. handleUsernameChange(ctx, form.Name)
  84. if ctx.Written() {
  85. return
  86. }
  87. ctx.User.FullName = form.FullName
  88. ctx.User.Email = form.Email
  89. ctx.User.KeepEmailPrivate = form.KeepEmailPrivate
  90. ctx.User.Website = form.Website
  91. ctx.User.Location = form.Location
  92. if err := models.UpdateUser(ctx.User); err != nil {
  93. ctx.Handle(500, "UpdateUser", err)
  94. return
  95. }
  96. log.Trace("User settings updated: %s", ctx.User.Name)
  97. ctx.Flash.Success(ctx.Tr("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 {
  109. fr, err := form.Avatar.Open()
  110. if err != nil {
  111. return fmt.Errorf("Avatar.Open: %v", err)
  112. }
  113. defer fr.Close()
  114. data, err := ioutil.ReadAll(fr)
  115. if err != nil {
  116. return fmt.Errorf("ioutil.ReadAll: %v", err)
  117. }
  118. if !base.IsImageFile(data) {
  119. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  120. }
  121. if err = ctxUser.UploadAvatar(data); err != nil {
  122. return fmt.Errorf("UploadAvatar: %v", err)
  123. }
  124. } else {
  125. // No avatar is uploaded but setting has been changed to enable,
  126. // generate a random one when needed.
  127. if ctxUser.UseCustomAvatar && !com.IsFile(ctxUser.CustomAvatarPath()) {
  128. if err := ctxUser.GenerateRandomAvatar(); err != nil {
  129. log.Error(4, "GenerateRandomAvatar[%d]: %v", ctxUser.ID, err)
  130. }
  131. }
  132. }
  133. if err := models.UpdateUser(ctxUser); err != nil {
  134. return fmt.Errorf("UpdateUser: %v", err)
  135. }
  136. return nil
  137. }
  138. // SettingsAvatar render user avatar page
  139. func SettingsAvatar(ctx *context.Context) {
  140. ctx.Data["Title"] = ctx.Tr("settings")
  141. ctx.Data["PageIsSettingsAvatar"] = true
  142. ctx.HTML(200, tplSettingsAvatar)
  143. }
  144. // SettingsAvatarPost response for change user's avatar request
  145. func SettingsAvatarPost(ctx *context.Context, form auth.AvatarForm) {
  146. if err := UpdateAvatarSetting(ctx, form, ctx.User); err != nil {
  147. ctx.Flash.Error(err.Error())
  148. } else {
  149. ctx.Flash.Success(ctx.Tr("settings.update_avatar_success"))
  150. }
  151. ctx.Redirect(setting.AppSubURL + "/user/settings/avatar")
  152. }
  153. // SettingsDeleteAvatar render delete avatar page
  154. func SettingsDeleteAvatar(ctx *context.Context) {
  155. if err := ctx.User.DeleteAvatar(); err != nil {
  156. ctx.Flash.Error(err.Error())
  157. }
  158. ctx.Redirect(setting.AppSubURL + "/user/settings/avatar")
  159. }
  160. // SettingsPassword render change user's password page
  161. func SettingsPassword(ctx *context.Context) {
  162. ctx.Data["Title"] = ctx.Tr("settings")
  163. ctx.Data["PageIsSettingsPassword"] = true
  164. ctx.HTML(200, tplSettingsPassword)
  165. }
  166. // SettingsPasswordPost response for change user's password
  167. func SettingsPasswordPost(ctx *context.Context, form auth.ChangePasswordForm) {
  168. ctx.Data["Title"] = ctx.Tr("settings")
  169. ctx.Data["PageIsSettingsPassword"] = true
  170. if ctx.HasError() {
  171. ctx.HTML(200, tplSettingsPassword)
  172. return
  173. }
  174. if !ctx.User.ValidatePassword(form.OldPassword) {
  175. ctx.Flash.Error(ctx.Tr("settings.password_incorrect"))
  176. } else if form.Password != form.Retype {
  177. ctx.Flash.Error(ctx.Tr("form.password_not_match"))
  178. } else {
  179. ctx.User.Passwd = form.Password
  180. var err error
  181. if ctx.User.Salt, err = models.GetUserSalt(); err != nil {
  182. ctx.Handle(500, "UpdateUser", err)
  183. return
  184. }
  185. ctx.User.EncodePasswd()
  186. if err := models.UpdateUser(ctx.User); err != nil {
  187. ctx.Handle(500, "UpdateUser", err)
  188. return
  189. }
  190. log.Trace("User password updated: %s", ctx.User.Name)
  191. ctx.Flash.Success(ctx.Tr("settings.change_password_success"))
  192. }
  193. ctx.Redirect(setting.AppSubURL + "/user/settings/password")
  194. }
  195. // SettingsEmails render user's emails page
  196. func SettingsEmails(ctx *context.Context) {
  197. ctx.Data["Title"] = ctx.Tr("settings")
  198. ctx.Data["PageIsSettingsEmails"] = true
  199. emails, err := models.GetEmailAddresses(ctx.User.ID)
  200. if err != nil {
  201. ctx.Handle(500, "GetEmailAddresses", err)
  202. return
  203. }
  204. ctx.Data["Emails"] = emails
  205. ctx.HTML(200, tplSettingsEmails)
  206. }
  207. // SettingsEmailPost response for change user's email
  208. func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) {
  209. ctx.Data["Title"] = ctx.Tr("settings")
  210. ctx.Data["PageIsSettingsEmails"] = true
  211. // Make emailaddress primary.
  212. if ctx.Query("_method") == "PRIMARY" {
  213. if err := models.MakeEmailPrimary(&models.EmailAddress{ID: ctx.QueryInt64("id")}); err != nil {
  214. ctx.Handle(500, "MakeEmailPrimary", err)
  215. return
  216. }
  217. log.Trace("Email made primary: %s", ctx.User.Name)
  218. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  219. return
  220. }
  221. // Add Email address.
  222. emails, err := models.GetEmailAddresses(ctx.User.ID)
  223. if err != nil {
  224. ctx.Handle(500, "GetEmailAddresses", err)
  225. return
  226. }
  227. ctx.Data["Emails"] = emails
  228. if ctx.HasError() {
  229. ctx.HTML(200, tplSettingsEmails)
  230. return
  231. }
  232. email := &models.EmailAddress{
  233. UID: ctx.User.ID,
  234. Email: form.Email,
  235. IsActivated: !setting.Service.RegisterEmailConfirm,
  236. }
  237. if err := models.AddEmailAddress(email); err != nil {
  238. if models.IsErrEmailAlreadyUsed(err) {
  239. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSettingsEmails, &form)
  240. return
  241. }
  242. ctx.Handle(500, "AddEmailAddress", err)
  243. return
  244. }
  245. // Send confirmation email
  246. if setting.Service.RegisterEmailConfirm {
  247. models.SendActivateEmailMail(ctx.Context, ctx.User, email)
  248. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  249. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  250. }
  251. ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, setting.Service.ActiveCodeLives/60))
  252. } else {
  253. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  254. }
  255. log.Trace("Email address added: %s", email.Email)
  256. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  257. }
  258. // DeleteEmail response for delete user's email
  259. func DeleteEmail(ctx *context.Context) {
  260. if err := models.DeleteEmailAddress(&models.EmailAddress{ID: ctx.QueryInt64("id"), UID: ctx.User.ID}); err != nil {
  261. ctx.Handle(500, "DeleteEmail", err)
  262. return
  263. }
  264. log.Trace("Email address deleted: %s", ctx.User.Name)
  265. ctx.Flash.Success(ctx.Tr("settings.email_deletion_success"))
  266. ctx.JSON(200, map[string]interface{}{
  267. "redirect": setting.AppSubURL + "/user/settings/email",
  268. })
  269. }
  270. // SettingsSSHKeys render user's SSH public keys page
  271. func SettingsSSHKeys(ctx *context.Context) {
  272. ctx.Data["Title"] = ctx.Tr("settings")
  273. ctx.Data["PageIsSettingsSSHKeys"] = true
  274. keys, err := models.ListPublicKeys(ctx.User.ID)
  275. if err != nil {
  276. ctx.Handle(500, "ListPublicKeys", err)
  277. return
  278. }
  279. ctx.Data["Keys"] = keys
  280. ctx.HTML(200, tplSettingsSSHKeys)
  281. }
  282. // SettingsSSHKeysPost response for change user's SSH keys
  283. func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) {
  284. ctx.Data["Title"] = ctx.Tr("settings")
  285. ctx.Data["PageIsSettingsSSHKeys"] = true
  286. keys, err := models.ListPublicKeys(ctx.User.ID)
  287. if err != nil {
  288. ctx.Handle(500, "ListPublicKeys", err)
  289. return
  290. }
  291. ctx.Data["Keys"] = keys
  292. if ctx.HasError() {
  293. ctx.HTML(200, tplSettingsSSHKeys)
  294. return
  295. }
  296. content, err := models.CheckPublicKeyString(form.Content)
  297. if err != nil {
  298. if models.IsErrKeyUnableVerify(err) {
  299. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  300. } else {
  301. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  302. ctx.Redirect(setting.AppSubURL + "/user/settings/ssh")
  303. return
  304. }
  305. }
  306. if _, err = models.AddPublicKey(ctx.User.ID, form.Title, content); err != nil {
  307. ctx.Data["HasError"] = true
  308. switch {
  309. case models.IsErrKeyAlreadyExist(err):
  310. ctx.Data["Err_Content"] = true
  311. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplSettingsSSHKeys, &form)
  312. case models.IsErrKeyNameAlreadyUsed(err):
  313. ctx.Data["Err_Title"] = true
  314. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_name_used"), tplSettingsSSHKeys, &form)
  315. default:
  316. ctx.Handle(500, "AddPublicKey", err)
  317. }
  318. return
  319. }
  320. ctx.Flash.Success(ctx.Tr("settings.add_key_success", form.Title))
  321. ctx.Redirect(setting.AppSubURL + "/user/settings/ssh")
  322. }
  323. // DeleteSSHKey response for delete user's SSH key
  324. func DeleteSSHKey(ctx *context.Context) {
  325. if err := models.DeletePublicKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  326. ctx.Flash.Error("DeletePublicKey: " + err.Error())
  327. } else {
  328. ctx.Flash.Success(ctx.Tr("settings.ssh_key_deletion_success"))
  329. }
  330. ctx.JSON(200, map[string]interface{}{
  331. "redirect": setting.AppSubURL + "/user/settings/ssh",
  332. })
  333. }
  334. // SettingsApplications render user's access tokens page
  335. func SettingsApplications(ctx *context.Context) {
  336. ctx.Data["Title"] = ctx.Tr("settings")
  337. ctx.Data["PageIsSettingsApplications"] = true
  338. tokens, err := models.ListAccessTokens(ctx.User.ID)
  339. if err != nil {
  340. ctx.Handle(500, "ListAccessTokens", err)
  341. return
  342. }
  343. ctx.Data["Tokens"] = tokens
  344. ctx.HTML(200, tplSettingsApplications)
  345. }
  346. // SettingsApplicationsPost response for add user's access token
  347. func SettingsApplicationsPost(ctx *context.Context, form auth.NewAccessTokenForm) {
  348. ctx.Data["Title"] = ctx.Tr("settings")
  349. ctx.Data["PageIsSettingsApplications"] = true
  350. if ctx.HasError() {
  351. tokens, err := models.ListAccessTokens(ctx.User.ID)
  352. if err != nil {
  353. ctx.Handle(500, "ListAccessTokens", err)
  354. return
  355. }
  356. ctx.Data["Tokens"] = tokens
  357. ctx.HTML(200, tplSettingsApplications)
  358. return
  359. }
  360. t := &models.AccessToken{
  361. UID: ctx.User.ID,
  362. Name: form.Name,
  363. }
  364. if err := models.NewAccessToken(t); err != nil {
  365. ctx.Handle(500, "NewAccessToken", err)
  366. return
  367. }
  368. ctx.Flash.Success(ctx.Tr("settings.generate_token_succees"))
  369. ctx.Flash.Info(t.Sha1)
  370. ctx.Redirect(setting.AppSubURL + "/user/settings/applications")
  371. }
  372. // SettingsDeleteApplication response for delete user access token
  373. func SettingsDeleteApplication(ctx *context.Context) {
  374. if err := models.DeleteAccessTokenByID(ctx.QueryInt64("id"), ctx.User.ID); err != nil {
  375. ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error())
  376. } else {
  377. ctx.Flash.Success(ctx.Tr("settings.delete_token_success"))
  378. }
  379. ctx.JSON(200, map[string]interface{}{
  380. "redirect": setting.AppSubURL + "/user/settings/applications",
  381. })
  382. }
  383. // SettingsTwoFactor renders the 2FA page.
  384. func SettingsTwoFactor(ctx *context.Context) {
  385. ctx.Data["Title"] = ctx.Tr("settings")
  386. ctx.Data["PageIsSettingsTwofa"] = true
  387. enrolled := true
  388. _, err := models.GetTwoFactorByUID(ctx.User.ID)
  389. if err != nil {
  390. if models.IsErrTwoFactorNotEnrolled(err) {
  391. enrolled = false
  392. } else {
  393. ctx.Handle(500, "SettingsTwoFactor", err)
  394. return
  395. }
  396. }
  397. ctx.Data["TwofaEnrolled"] = enrolled
  398. ctx.HTML(200, tplSettingsTwofa)
  399. }
  400. // SettingsTwoFactorRegenerateScratch regenerates the user's 2FA scratch code.
  401. func SettingsTwoFactorRegenerateScratch(ctx *context.Context) {
  402. ctx.Data["Title"] = ctx.Tr("settings")
  403. ctx.Data["PageIsSettingsTwofa"] = true
  404. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  405. if err != nil {
  406. ctx.Handle(500, "SettingsTwoFactor", err)
  407. return
  408. }
  409. if err = t.GenerateScratchToken(); err != nil {
  410. ctx.Handle(500, "SettingsTwoFactor", err)
  411. return
  412. }
  413. if err = models.UpdateTwoFactor(t); err != nil {
  414. ctx.Handle(500, "SettingsTwoFactor", err)
  415. return
  416. }
  417. ctx.Flash.Success(ctx.Tr("settings.twofa_scratch_token_regenerated", t.ScratchToken))
  418. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  419. }
  420. // SettingsTwoFactorDisable deletes the user's 2FA settings.
  421. func SettingsTwoFactorDisable(ctx *context.Context) {
  422. ctx.Data["Title"] = ctx.Tr("settings")
  423. ctx.Data["PageIsSettingsTwofa"] = true
  424. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  425. if err != nil {
  426. ctx.Handle(500, "SettingsTwoFactor", err)
  427. return
  428. }
  429. if err = models.DeleteTwoFactorByID(t.ID, ctx.User.ID); err != nil {
  430. ctx.Handle(500, "SettingsTwoFactor", err)
  431. return
  432. }
  433. ctx.Flash.Success(ctx.Tr("settings.twofa_disabled"))
  434. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  435. }
  436. func twofaGenerateSecretAndQr(ctx *context.Context) bool {
  437. var otpKey *otp.Key
  438. var err error
  439. uri := ctx.Session.Get("twofaUri")
  440. if uri != nil {
  441. otpKey, err = otp.NewKeyFromURL(uri.(string))
  442. }
  443. if otpKey == nil {
  444. err = nil // clear the error, in case the URL was invalid
  445. otpKey, err = totp.Generate(totp.GenerateOpts{
  446. Issuer: setting.AppName,
  447. AccountName: ctx.User.Name,
  448. })
  449. if err != nil {
  450. ctx.Handle(500, "SettingsTwoFactor", err)
  451. return false
  452. }
  453. }
  454. ctx.Data["TwofaSecret"] = otpKey.Secret()
  455. img, err := otpKey.Image(320, 240)
  456. if err != nil {
  457. ctx.Handle(500, "SettingsTwoFactor", err)
  458. return false
  459. }
  460. var imgBytes bytes.Buffer
  461. if err = png.Encode(&imgBytes, img); err != nil {
  462. ctx.Handle(500, "SettingsTwoFactor", err)
  463. return false
  464. }
  465. ctx.Data["QrUri"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(imgBytes.Bytes()))
  466. ctx.Session.Set("twofaSecret", otpKey.Secret())
  467. ctx.Session.Set("twofaUri", otpKey.String())
  468. return true
  469. }
  470. // SettingsTwoFactorEnroll shows the page where the user can enroll into 2FA.
  471. func SettingsTwoFactorEnroll(ctx *context.Context) {
  472. ctx.Data["Title"] = ctx.Tr("settings")
  473. ctx.Data["PageIsSettingsTwofa"] = true
  474. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  475. if t != nil {
  476. // already enrolled
  477. ctx.Handle(500, "SettingsTwoFactor", err)
  478. return
  479. }
  480. if err != nil && !models.IsErrTwoFactorNotEnrolled(err) {
  481. ctx.Handle(500, "SettingsTwoFactor", err)
  482. return
  483. }
  484. if !twofaGenerateSecretAndQr(ctx) {
  485. return
  486. }
  487. ctx.HTML(200, tplSettingsTwofaEnroll)
  488. }
  489. // SettingsTwoFactorEnrollPost handles enrolling the user into 2FA.
  490. func SettingsTwoFactorEnrollPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  491. ctx.Data["Title"] = ctx.Tr("settings")
  492. ctx.Data["PageIsSettingsTwofa"] = true
  493. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  494. if t != nil {
  495. // already enrolled
  496. ctx.Handle(500, "SettingsTwoFactor", err)
  497. return
  498. }
  499. if err != nil && !models.IsErrTwoFactorNotEnrolled(err) {
  500. ctx.Handle(500, "SettingsTwoFactor", err)
  501. return
  502. }
  503. if ctx.HasError() {
  504. if !twofaGenerateSecretAndQr(ctx) {
  505. return
  506. }
  507. ctx.HTML(200, tplSettingsTwofaEnroll)
  508. return
  509. }
  510. secret := ctx.Session.Get("twofaSecret").(string)
  511. if !totp.Validate(form.Passcode, secret) {
  512. if !twofaGenerateSecretAndQr(ctx) {
  513. return
  514. }
  515. ctx.Flash.Error(ctx.Tr("settings.passcode_invalid"))
  516. ctx.HTML(200, tplSettingsTwofaEnroll)
  517. return
  518. }
  519. t = &models.TwoFactor{
  520. UID: ctx.User.ID,
  521. }
  522. err = t.SetSecret(secret)
  523. if err != nil {
  524. ctx.Handle(500, "SettingsTwoFactor", err)
  525. return
  526. }
  527. err = t.GenerateScratchToken()
  528. if err != nil {
  529. ctx.Handle(500, "SettingsTwoFactor", err)
  530. return
  531. }
  532. if err = models.NewTwoFactor(t); err != nil {
  533. ctx.Handle(500, "SettingsTwoFactor", err)
  534. return
  535. }
  536. ctx.Session.Delete("twofaSecret")
  537. ctx.Session.Delete("twofaUri")
  538. ctx.Flash.Success(ctx.Tr("settings.twofa_enrolled", t.ScratchToken))
  539. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  540. }
  541. // SettingsDelete render user suicide page and response for delete user himself
  542. func SettingsDelete(ctx *context.Context) {
  543. ctx.Data["Title"] = ctx.Tr("settings")
  544. ctx.Data["PageIsSettingsDelete"] = true
  545. if ctx.Req.Method == "POST" {
  546. if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil {
  547. if models.IsErrUserNotExist(err) {
  548. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), tplSettingsDelete, nil)
  549. } else {
  550. ctx.Handle(500, "UserSignIn", err)
  551. }
  552. return
  553. }
  554. if err := models.DeleteUser(ctx.User); err != nil {
  555. switch {
  556. case models.IsErrUserOwnRepos(err):
  557. ctx.Flash.Error(ctx.Tr("form.still_own_repo"))
  558. ctx.Redirect(setting.AppSubURL + "/user/settings/delete")
  559. case models.IsErrUserHasOrgs(err):
  560. ctx.Flash.Error(ctx.Tr("form.still_has_org"))
  561. ctx.Redirect(setting.AppSubURL + "/user/settings/delete")
  562. default:
  563. ctx.Handle(500, "DeleteUser", err)
  564. }
  565. } else {
  566. log.Trace("Account deleted: %s", ctx.User.Name)
  567. ctx.Redirect(setting.AppSubURL + "/")
  568. }
  569. return
  570. }
  571. ctx.HTML(200, tplSettingsDelete)
  572. }