setting.go 13 KB

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