setting.go 15 KB

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