setting.go 15 KB

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