setting.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "strings"
  10. "github.com/Unknwon/com"
  11. "github.com/gogits/gogs/models"
  12. "github.com/gogits/gogs/modules/auth"
  13. "github.com/gogits/gogs/modules/base"
  14. "github.com/gogits/gogs/modules/context"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/gogs/modules/setting"
  17. )
  18. const (
  19. SETTINGS_PROFILE base.TplName = "user/settings/profile"
  20. SETTINGS_PASSWORD base.TplName = "user/settings/password"
  21. SETTINGS_EMAILS base.TplName = "user/settings/email"
  22. SETTINGS_SSH_KEYS base.TplName = "user/settings/sshkeys"
  23. SETTINGS_SOCIAL base.TplName = "user/settings/social"
  24. SETTINGS_APPLICATIONS base.TplName = "user/settings/applications"
  25. SETTINGS_DELETE base.TplName = "user/settings/delete"
  26. NOTIFICATION base.TplName = "user/notification"
  27. SECURITY base.TplName = "user/security"
  28. )
  29. func Settings(ctx *context.Context) {
  30. ctx.Data["Title"] = ctx.Tr("settings")
  31. ctx.Data["PageIsSettingsProfile"] = true
  32. ctx.HTML(200, SETTINGS_PROFILE)
  33. }
  34. func handleUsernameChange(ctx *context.Context, newName string) {
  35. // Non-local users are not allowed to change their username.
  36. if len(newName) == 0 || !ctx.User.IsLocal() {
  37. return
  38. }
  39. // Check if user name has been changed
  40. if ctx.User.LowerName != strings.ToLower(newName) {
  41. if err := models.ChangeUserName(ctx.User, newName); err != nil {
  42. switch {
  43. case models.IsErrUserAlreadyExist(err):
  44. ctx.Flash.Error(ctx.Tr("newName_been_taken"))
  45. ctx.Redirect(setting.AppSubUrl + "/user/settings")
  46. case models.IsErrEmailAlreadyUsed(err):
  47. ctx.Flash.Error(ctx.Tr("form.email_been_used"))
  48. ctx.Redirect(setting.AppSubUrl + "/user/settings")
  49. case models.IsErrNameReserved(err):
  50. ctx.Flash.Error(ctx.Tr("user.newName_reserved"))
  51. ctx.Redirect(setting.AppSubUrl + "/user/settings")
  52. case models.IsErrNamePatternNotAllowed(err):
  53. ctx.Flash.Error(ctx.Tr("user.newName_pattern_not_allowed"))
  54. ctx.Redirect(setting.AppSubUrl + "/user/settings")
  55. default:
  56. ctx.Handle(500, "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. func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) {
  67. ctx.Data["Title"] = ctx.Tr("settings")
  68. ctx.Data["PageIsSettingsProfile"] = true
  69. if ctx.HasError() {
  70. ctx.HTML(200, SETTINGS_PROFILE)
  71. return
  72. }
  73. handleUsernameChange(ctx, form.Name)
  74. if ctx.Written() {
  75. return
  76. }
  77. ctx.User.FullName = form.FullName
  78. ctx.User.Email = form.Email
  79. ctx.User.Website = form.Website
  80. ctx.User.Location = form.Location
  81. if len(form.Gravatar) > 0 {
  82. ctx.User.Avatar = base.EncodeMD5(form.Gravatar)
  83. ctx.User.AvatarEmail = form.Gravatar
  84. }
  85. if err := models.UpdateUser(ctx.User); err != nil {
  86. ctx.Handle(500, "UpdateUser", err)
  87. return
  88. }
  89. log.Trace("User settings updated: %s", ctx.User.Name)
  90. ctx.Flash.Success(ctx.Tr("settings.update_profile_success"))
  91. ctx.Redirect(setting.AppSubUrl + "/user/settings")
  92. }
  93. // FIXME: limit size.
  94. func UpdateAvatarSetting(ctx *context.Context, form auth.UploadAvatarForm, ctxUser *models.User) error {
  95. ctxUser.UseCustomAvatar = form.Enable
  96. if form.Avatar != nil {
  97. fr, err := form.Avatar.Open()
  98. if err != nil {
  99. return fmt.Errorf("Avatar.Open: %v", err)
  100. }
  101. defer fr.Close()
  102. data, err := ioutil.ReadAll(fr)
  103. if err != nil {
  104. return fmt.Errorf("ioutil.ReadAll: %v", err)
  105. }
  106. if _, ok := base.IsImageFile(data); !ok {
  107. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  108. }
  109. if err = ctxUser.UploadAvatar(data); err != nil {
  110. return fmt.Errorf("UploadAvatar: %v", err)
  111. }
  112. } else {
  113. // No avatar is uploaded but setting has been changed to enable,
  114. // generate a random one when needed.
  115. if form.Enable && !com.IsFile(ctxUser.CustomAvatarPath()) {
  116. if err := ctxUser.GenerateRandomAvatar(); err != nil {
  117. log.Error(4, "GenerateRandomAvatar[%d]: %v", ctxUser.ID, err)
  118. }
  119. }
  120. }
  121. if err := models.UpdateUser(ctxUser); err != nil {
  122. return fmt.Errorf("UpdateUser: %v", err)
  123. }
  124. return nil
  125. }
  126. func SettingsAvatar(ctx *context.Context, form auth.UploadAvatarForm) {
  127. if err := UpdateAvatarSetting(ctx, form, ctx.User); err != nil {
  128. ctx.Flash.Error(err.Error())
  129. } else {
  130. ctx.Flash.Success(ctx.Tr("settings.update_avatar_success"))
  131. }
  132. ctx.Redirect(setting.AppSubUrl + "/user/settings")
  133. }
  134. func SettingsDeleteAvatar(ctx *context.Context) {
  135. if err := ctx.User.DeleteAvatar(); err != nil {
  136. ctx.Flash.Error(err.Error())
  137. }
  138. ctx.Redirect(setting.AppSubUrl + "/user/settings")
  139. }
  140. func SettingsPassword(ctx *context.Context) {
  141. ctx.Data["Title"] = ctx.Tr("settings")
  142. ctx.Data["PageIsSettingsPassword"] = true
  143. ctx.HTML(200, SETTINGS_PASSWORD)
  144. }
  145. func SettingsPasswordPost(ctx *context.Context, form auth.ChangePasswordForm) {
  146. ctx.Data["Title"] = ctx.Tr("settings")
  147. ctx.Data["PageIsSettingsPassword"] = true
  148. if ctx.HasError() {
  149. ctx.HTML(200, SETTINGS_PASSWORD)
  150. return
  151. }
  152. if !ctx.User.ValidatePassword(form.OldPassword) {
  153. ctx.Flash.Error(ctx.Tr("settings.password_incorrect"))
  154. } else if form.Password != form.Retype {
  155. ctx.Flash.Error(ctx.Tr("form.password_not_match"))
  156. } else {
  157. ctx.User.Passwd = form.Password
  158. ctx.User.Salt = models.GetUserSalt()
  159. ctx.User.EncodePasswd()
  160. if err := models.UpdateUser(ctx.User); err != nil {
  161. ctx.Handle(500, "UpdateUser", err)
  162. return
  163. }
  164. log.Trace("User password updated: %s", ctx.User.Name)
  165. ctx.Flash.Success(ctx.Tr("settings.change_password_success"))
  166. }
  167. ctx.Redirect(setting.AppSubUrl + "/user/settings/password")
  168. }
  169. func SettingsEmails(ctx *context.Context) {
  170. ctx.Data["Title"] = ctx.Tr("settings")
  171. ctx.Data["PageIsSettingsEmails"] = true
  172. emails, err := models.GetEmailAddresses(ctx.User.ID)
  173. if err != nil {
  174. ctx.Handle(500, "GetEmailAddresses", err)
  175. return
  176. }
  177. ctx.Data["Emails"] = emails
  178. ctx.HTML(200, SETTINGS_EMAILS)
  179. }
  180. func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) {
  181. ctx.Data["Title"] = ctx.Tr("settings")
  182. ctx.Data["PageIsSettingsEmails"] = true
  183. // Make emailaddress primary.
  184. if ctx.Query("_method") == "PRIMARY" {
  185. if err := models.MakeEmailPrimary(&models.EmailAddress{ID: ctx.QueryInt64("id")}); err != nil {
  186. ctx.Handle(500, "MakeEmailPrimary", err)
  187. return
  188. }
  189. log.Trace("Email made primary: %s", ctx.User.Name)
  190. ctx.Redirect(setting.AppSubUrl + "/user/settings/email")
  191. return
  192. }
  193. // Add Email address.
  194. emails, err := models.GetEmailAddresses(ctx.User.ID)
  195. if err != nil {
  196. ctx.Handle(500, "GetEmailAddresses", err)
  197. return
  198. }
  199. ctx.Data["Emails"] = emails
  200. if ctx.HasError() {
  201. ctx.HTML(200, SETTINGS_EMAILS)
  202. return
  203. }
  204. email := &models.EmailAddress{
  205. UID: ctx.User.ID,
  206. Email: form.Email,
  207. IsActivated: !setting.Service.RegisterEmailConfirm,
  208. }
  209. if err := models.AddEmailAddress(email); err != nil {
  210. if models.IsErrEmailAlreadyUsed(err) {
  211. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SETTINGS_EMAILS, &form)
  212. return
  213. }
  214. ctx.Handle(500, "AddEmailAddress", err)
  215. return
  216. }
  217. // Send confirmation email
  218. if setting.Service.RegisterEmailConfirm {
  219. models.SendActivateEmailMail(ctx.Context, ctx.User, email)
  220. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  221. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  222. }
  223. ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, setting.Service.ActiveCodeLives/60))
  224. } else {
  225. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  226. }
  227. log.Trace("Email address added: %s", email.Email)
  228. ctx.Redirect(setting.AppSubUrl + "/user/settings/email")
  229. }
  230. func DeleteEmail(ctx *context.Context) {
  231. if err := models.DeleteEmailAddress(&models.EmailAddress{ID: ctx.QueryInt64("id")}); err != nil {
  232. ctx.Handle(500, "DeleteEmail", err)
  233. return
  234. }
  235. log.Trace("Email address deleted: %s", ctx.User.Name)
  236. ctx.Flash.Success(ctx.Tr("settings.email_deletion_success"))
  237. ctx.JSON(200, map[string]interface{}{
  238. "redirect": setting.AppSubUrl + "/user/settings/email",
  239. })
  240. }
  241. func SettingsSSHKeys(ctx *context.Context) {
  242. ctx.Data["Title"] = ctx.Tr("settings")
  243. ctx.Data["PageIsSettingsSSHKeys"] = true
  244. keys, err := models.ListPublicKeys(ctx.User.ID)
  245. if err != nil {
  246. ctx.Handle(500, "ListPublicKeys", err)
  247. return
  248. }
  249. ctx.Data["Keys"] = keys
  250. ctx.HTML(200, SETTINGS_SSH_KEYS)
  251. }
  252. func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) {
  253. ctx.Data["Title"] = ctx.Tr("settings")
  254. ctx.Data["PageIsSettingsSSHKeys"] = true
  255. keys, err := models.ListPublicKeys(ctx.User.ID)
  256. if err != nil {
  257. ctx.Handle(500, "ListPublicKeys", err)
  258. return
  259. }
  260. ctx.Data["Keys"] = keys
  261. if ctx.HasError() {
  262. ctx.HTML(200, SETTINGS_SSH_KEYS)
  263. return
  264. }
  265. content, err := models.CheckPublicKeyString(form.Content)
  266. if err != nil {
  267. if models.IsErrKeyUnableVerify(err) {
  268. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  269. } else {
  270. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  271. ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh")
  272. return
  273. }
  274. }
  275. if _, err = models.AddPublicKey(ctx.User.ID, form.Title, content); err != nil {
  276. ctx.Data["HasError"] = true
  277. switch {
  278. case models.IsErrKeyAlreadyExist(err):
  279. ctx.Data["Err_Content"] = true
  280. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), SETTINGS_SSH_KEYS, &form)
  281. case models.IsErrKeyNameAlreadyUsed(err):
  282. ctx.Data["Err_Title"] = true
  283. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_name_used"), SETTINGS_SSH_KEYS, &form)
  284. default:
  285. ctx.Handle(500, "AddPublicKey", err)
  286. }
  287. return
  288. }
  289. ctx.Flash.Success(ctx.Tr("settings.add_key_success", form.Title))
  290. ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh")
  291. }
  292. func DeleteSSHKey(ctx *context.Context) {
  293. if err := models.DeletePublicKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  294. ctx.Flash.Error("DeletePublicKey: " + err.Error())
  295. } else {
  296. ctx.Flash.Success(ctx.Tr("settings.ssh_key_deletion_success"))
  297. }
  298. ctx.JSON(200, map[string]interface{}{
  299. "redirect": setting.AppSubUrl + "/user/settings/ssh",
  300. })
  301. }
  302. func SettingsApplications(ctx *context.Context) {
  303. ctx.Data["Title"] = ctx.Tr("settings")
  304. ctx.Data["PageIsSettingsApplications"] = true
  305. tokens, err := models.ListAccessTokens(ctx.User.ID)
  306. if err != nil {
  307. ctx.Handle(500, "ListAccessTokens", err)
  308. return
  309. }
  310. ctx.Data["Tokens"] = tokens
  311. ctx.HTML(200, SETTINGS_APPLICATIONS)
  312. }
  313. func SettingsApplicationsPost(ctx *context.Context, form auth.NewAccessTokenForm) {
  314. ctx.Data["Title"] = ctx.Tr("settings")
  315. ctx.Data["PageIsSettingsApplications"] = true
  316. if ctx.HasError() {
  317. tokens, err := models.ListAccessTokens(ctx.User.ID)
  318. if err != nil {
  319. ctx.Handle(500, "ListAccessTokens", err)
  320. return
  321. }
  322. ctx.Data["Tokens"] = tokens
  323. ctx.HTML(200, SETTINGS_APPLICATIONS)
  324. return
  325. }
  326. t := &models.AccessToken{
  327. UID: ctx.User.ID,
  328. Name: form.Name,
  329. }
  330. if err := models.NewAccessToken(t); err != nil {
  331. ctx.Handle(500, "NewAccessToken", err)
  332. return
  333. }
  334. ctx.Flash.Success(ctx.Tr("settings.generate_token_succees"))
  335. ctx.Flash.Info(t.Sha1)
  336. ctx.Redirect(setting.AppSubUrl + "/user/settings/applications")
  337. }
  338. func SettingsDeleteApplication(ctx *context.Context) {
  339. if err := models.DeleteAccessTokenByID(ctx.QueryInt64("id")); err != nil {
  340. ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error())
  341. } else {
  342. ctx.Flash.Success(ctx.Tr("settings.delete_token_success"))
  343. }
  344. ctx.JSON(200, map[string]interface{}{
  345. "redirect": setting.AppSubUrl + "/user/settings/applications",
  346. })
  347. }
  348. func SettingsDelete(ctx *context.Context) {
  349. ctx.Data["Title"] = ctx.Tr("settings")
  350. ctx.Data["PageIsSettingsDelete"] = true
  351. if ctx.Req.Method == "POST" {
  352. if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil {
  353. if models.IsErrUserNotExist(err) {
  354. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil)
  355. } else {
  356. ctx.Handle(500, "UserSignIn", err)
  357. }
  358. return
  359. }
  360. if err := models.DeleteUser(ctx.User); err != nil {
  361. switch {
  362. case models.IsErrUserOwnRepos(err):
  363. ctx.Flash.Error(ctx.Tr("form.still_own_repo"))
  364. ctx.Redirect(setting.AppSubUrl + "/user/settings/delete")
  365. case models.IsErrUserHasOrgs(err):
  366. ctx.Flash.Error(ctx.Tr("form.still_has_org"))
  367. ctx.Redirect(setting.AppSubUrl + "/user/settings/delete")
  368. default:
  369. ctx.Handle(500, "DeleteUser", err)
  370. }
  371. } else {
  372. log.Trace("Account deleted: %s", ctx.User.Name)
  373. ctx.Redirect(setting.AppSubUrl + "/")
  374. }
  375. return
  376. }
  377. ctx.HTML(200, SETTINGS_DELETE)
  378. }