You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

787 lines
23 KiB

10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 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
8 years ago
8 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
8 years ago
10 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
8 years ago
10 years ago
10 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
8 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
8 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
8 years ago
10 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
10 years ago
8 years ago
10 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
10 years ago
  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. tplSettingsKeys base.TplName = "user/settings/keys"
  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. tplSettingsAccountLink base.TplName = "user/settings/account_link"
  35. tplSettingsOrganization base.TplName = "user/settings/organization"
  36. tplSettingsDelete base.TplName = "user/settings/delete"
  37. tplSecurity base.TplName = "user/security"
  38. )
  39. // Settings render user's profile page
  40. func Settings(ctx *context.Context) {
  41. ctx.Data["Title"] = ctx.Tr("settings")
  42. ctx.Data["PageIsSettingsProfile"] = true
  43. ctx.HTML(200, tplSettingsProfile)
  44. }
  45. func handleUsernameChange(ctx *context.Context, newName string) {
  46. // Non-local users are not allowed to change their username.
  47. if len(newName) == 0 || !ctx.User.IsLocal() {
  48. return
  49. }
  50. // Check if user name has been changed
  51. if ctx.User.LowerName != strings.ToLower(newName) {
  52. if err := models.ChangeUserName(ctx.User, newName); err != nil {
  53. switch {
  54. case models.IsErrUserAlreadyExist(err):
  55. ctx.Flash.Error(ctx.Tr("newName_been_taken"))
  56. ctx.Redirect(setting.AppSubURL + "/user/settings")
  57. case models.IsErrEmailAlreadyUsed(err):
  58. ctx.Flash.Error(ctx.Tr("form.email_been_used"))
  59. ctx.Redirect(setting.AppSubURL + "/user/settings")
  60. case models.IsErrNameReserved(err):
  61. ctx.Flash.Error(ctx.Tr("user.newName_reserved"))
  62. ctx.Redirect(setting.AppSubURL + "/user/settings")
  63. case models.IsErrNamePatternNotAllowed(err):
  64. ctx.Flash.Error(ctx.Tr("user.newName_pattern_not_allowed"))
  65. ctx.Redirect(setting.AppSubURL + "/user/settings")
  66. default:
  67. ctx.Handle(500, "ChangeUserName", err)
  68. }
  69. return
  70. }
  71. log.Trace("User name changed: %s -> %s", ctx.User.Name, newName)
  72. }
  73. // In case it's just a case change
  74. ctx.User.Name = newName
  75. ctx.User.LowerName = strings.ToLower(newName)
  76. }
  77. // SettingsPost response for change user's profile
  78. func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) {
  79. ctx.Data["Title"] = ctx.Tr("settings")
  80. ctx.Data["PageIsSettingsProfile"] = true
  81. if ctx.HasError() {
  82. ctx.HTML(200, tplSettingsProfile)
  83. return
  84. }
  85. handleUsernameChange(ctx, form.Name)
  86. if ctx.Written() {
  87. return
  88. }
  89. ctx.User.FullName = form.FullName
  90. ctx.User.Email = form.Email
  91. ctx.User.KeepEmailPrivate = form.KeepEmailPrivate
  92. ctx.User.Website = form.Website
  93. ctx.User.Location = form.Location
  94. if err := models.UpdateUserSetting(ctx.User); err != nil {
  95. if _, ok := err.(models.ErrEmailAlreadyUsed); ok {
  96. ctx.Flash.Error(ctx.Tr("form.email_been_used"))
  97. ctx.Redirect(setting.AppSubURL + "/user/settings")
  98. return
  99. }
  100. ctx.Handle(500, "UpdateUser", err)
  101. return
  102. }
  103. log.Trace("User settings updated: %s", ctx.User.Name)
  104. ctx.Flash.Success(ctx.Tr("settings.update_profile_success"))
  105. ctx.Redirect(setting.AppSubURL + "/user/settings")
  106. }
  107. // UpdateAvatarSetting update user's avatar
  108. // FIXME: limit size.
  109. func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm, ctxUser *models.User) error {
  110. ctxUser.UseCustomAvatar = form.Source == auth.AvatarLocal
  111. if len(form.Gravatar) > 0 {
  112. ctxUser.Avatar = base.EncodeMD5(form.Gravatar)
  113. ctxUser.AvatarEmail = form.Gravatar
  114. }
  115. if form.Avatar != nil {
  116. fr, err := form.Avatar.Open()
  117. if err != nil {
  118. return fmt.Errorf("Avatar.Open: %v", err)
  119. }
  120. defer fr.Close()
  121. data, err := ioutil.ReadAll(fr)
  122. if err != nil {
  123. return fmt.Errorf("ioutil.ReadAll: %v", err)
  124. }
  125. if !base.IsImageFile(data) {
  126. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  127. }
  128. if err = ctxUser.UploadAvatar(data); err != nil {
  129. return fmt.Errorf("UploadAvatar: %v", err)
  130. }
  131. } else {
  132. // No avatar is uploaded but setting has been changed to enable,
  133. // generate a random one when needed.
  134. if ctxUser.UseCustomAvatar && !com.IsFile(ctxUser.CustomAvatarPath()) {
  135. if err := ctxUser.GenerateRandomAvatar(); err != nil {
  136. log.Error(4, "GenerateRandomAvatar[%d]: %v", ctxUser.ID, err)
  137. }
  138. }
  139. }
  140. if err := models.UpdateUser(ctxUser); err != nil {
  141. return fmt.Errorf("UpdateUser: %v", err)
  142. }
  143. return nil
  144. }
  145. // SettingsAvatar render user avatar page
  146. func SettingsAvatar(ctx *context.Context) {
  147. ctx.Data["Title"] = ctx.Tr("settings")
  148. ctx.Data["PageIsSettingsAvatar"] = true
  149. ctx.HTML(200, tplSettingsAvatar)
  150. }
  151. // SettingsAvatarPost response for change user's avatar request
  152. func SettingsAvatarPost(ctx *context.Context, form auth.AvatarForm) {
  153. if err := UpdateAvatarSetting(ctx, form, ctx.User); err != nil {
  154. ctx.Flash.Error(err.Error())
  155. } else {
  156. ctx.Flash.Success(ctx.Tr("settings.update_avatar_success"))
  157. }
  158. ctx.Redirect(setting.AppSubURL + "/user/settings/avatar")
  159. }
  160. // SettingsDeleteAvatar render delete avatar page
  161. func SettingsDeleteAvatar(ctx *context.Context) {
  162. if err := ctx.User.DeleteAvatar(); err != nil {
  163. ctx.Flash.Error(err.Error())
  164. }
  165. ctx.Redirect(setting.AppSubURL + "/user/settings/avatar")
  166. }
  167. // SettingsPassword render change user's password page
  168. func SettingsPassword(ctx *context.Context) {
  169. ctx.Data["Title"] = ctx.Tr("settings")
  170. ctx.Data["PageIsSettingsPassword"] = true
  171. ctx.Data["Email"] = ctx.User.Email
  172. ctx.HTML(200, tplSettingsPassword)
  173. }
  174. // SettingsPasswordPost response for change user's password
  175. func SettingsPasswordPost(ctx *context.Context, form auth.ChangePasswordForm) {
  176. ctx.Data["Title"] = ctx.Tr("settings")
  177. ctx.Data["PageIsSettingsPassword"] = true
  178. ctx.Data["PageIsSettingsDelete"] = true
  179. if ctx.HasError() {
  180. ctx.HTML(200, tplSettingsPassword)
  181. return
  182. }
  183. if ctx.User.IsPasswordSet() && !ctx.User.ValidatePassword(form.OldPassword) {
  184. ctx.Flash.Error(ctx.Tr("settings.password_incorrect"))
  185. } else if form.Password != form.Retype {
  186. ctx.Flash.Error(ctx.Tr("form.password_not_match"))
  187. } else {
  188. ctx.User.Passwd = form.Password
  189. var err error
  190. if ctx.User.Salt, err = models.GetUserSalt(); err != nil {
  191. ctx.Handle(500, "UpdateUser", err)
  192. return
  193. }
  194. ctx.User.EncodePasswd()
  195. if err := models.UpdateUser(ctx.User); err != nil {
  196. ctx.Handle(500, "UpdateUser", err)
  197. return
  198. }
  199. log.Trace("User password updated: %s", ctx.User.Name)
  200. ctx.Flash.Success(ctx.Tr("settings.change_password_success"))
  201. }
  202. ctx.Redirect(setting.AppSubURL + "/user/settings/password")
  203. }
  204. // SettingsEmails render user's emails page
  205. func SettingsEmails(ctx *context.Context) {
  206. ctx.Data["Title"] = ctx.Tr("settings")
  207. ctx.Data["PageIsSettingsEmails"] = true
  208. emails, err := models.GetEmailAddresses(ctx.User.ID)
  209. if err != nil {
  210. ctx.Handle(500, "GetEmailAddresses", err)
  211. return
  212. }
  213. ctx.Data["Emails"] = emails
  214. ctx.HTML(200, tplSettingsEmails)
  215. }
  216. // SettingsEmailPost response for change user's email
  217. func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) {
  218. ctx.Data["Title"] = ctx.Tr("settings")
  219. ctx.Data["PageIsSettingsEmails"] = true
  220. // Make emailaddress primary.
  221. if ctx.Query("_method") == "PRIMARY" {
  222. if err := models.MakeEmailPrimary(&models.EmailAddress{ID: ctx.QueryInt64("id")}); err != nil {
  223. ctx.Handle(500, "MakeEmailPrimary", err)
  224. return
  225. }
  226. log.Trace("Email made primary: %s", ctx.User.Name)
  227. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  228. return
  229. }
  230. // Add Email address.
  231. emails, err := models.GetEmailAddresses(ctx.User.ID)
  232. if err != nil {
  233. ctx.Handle(500, "GetEmailAddresses", err)
  234. return
  235. }
  236. ctx.Data["Emails"] = emails
  237. if ctx.HasError() {
  238. ctx.HTML(200, tplSettingsEmails)
  239. return
  240. }
  241. email := &models.EmailAddress{
  242. UID: ctx.User.ID,
  243. Email: form.Email,
  244. IsActivated: !setting.Service.RegisterEmailConfirm,
  245. }
  246. if err := models.AddEmailAddress(email); err != nil {
  247. if models.IsErrEmailAlreadyUsed(err) {
  248. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSettingsEmails, &form)
  249. return
  250. }
  251. ctx.Handle(500, "AddEmailAddress", err)
  252. return
  253. }
  254. // Send confirmation email
  255. if setting.Service.RegisterEmailConfirm {
  256. models.SendActivateEmailMail(ctx.Context, ctx.User, email)
  257. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  258. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  259. }
  260. ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())))
  261. } else {
  262. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  263. }
  264. log.Trace("Email address added: %s", email.Email)
  265. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  266. }
  267. // DeleteEmail response for delete user's email
  268. func DeleteEmail(ctx *context.Context) {
  269. if err := models.DeleteEmailAddress(&models.EmailAddress{ID: ctx.QueryInt64("id"), UID: ctx.User.ID}); err != nil {
  270. ctx.Handle(500, "DeleteEmail", err)
  271. return
  272. }
  273. log.Trace("Email address deleted: %s", ctx.User.Name)
  274. ctx.Flash.Success(ctx.Tr("settings.email_deletion_success"))
  275. ctx.JSON(200, map[string]interface{}{
  276. "redirect": setting.AppSubURL + "/user/settings/email",
  277. })
  278. }
  279. // SettingsKeys render user's SSH/GPG public keys page
  280. func SettingsKeys(ctx *context.Context) {
  281. ctx.Data["Title"] = ctx.Tr("settings")
  282. ctx.Data["PageIsSettingsKeys"] = true
  283. keys, err := models.ListPublicKeys(ctx.User.ID)
  284. if err != nil {
  285. ctx.Handle(500, "ListPublicKeys", err)
  286. return
  287. }
  288. ctx.Data["Keys"] = keys
  289. gpgkeys, err := models.ListGPGKeys(ctx.User.ID)
  290. if err != nil {
  291. ctx.Handle(500, "ListGPGKeys", err)
  292. return
  293. }
  294. ctx.Data["GPGKeys"] = gpgkeys
  295. ctx.HTML(200, tplSettingsKeys)
  296. }
  297. // SettingsKeysPost response for change user's SSH/GPG keys
  298. func SettingsKeysPost(ctx *context.Context, form auth.AddKeyForm) {
  299. ctx.Data["Title"] = ctx.Tr("settings")
  300. ctx.Data["PageIsSettingsKeys"] = true
  301. keys, err := models.ListPublicKeys(ctx.User.ID)
  302. if err != nil {
  303. ctx.Handle(500, "ListPublicKeys", err)
  304. return
  305. }
  306. ctx.Data["Keys"] = keys
  307. gpgkeys, err := models.ListGPGKeys(ctx.User.ID)
  308. if err != nil {
  309. ctx.Handle(500, "ListGPGKeys", err)
  310. return
  311. }
  312. ctx.Data["GPGKeys"] = gpgkeys
  313. if ctx.HasError() {
  314. ctx.HTML(200, tplSettingsKeys)
  315. return
  316. }
  317. switch form.Type {
  318. case "gpg":
  319. key, err := models.AddGPGKey(ctx.User.ID, form.Content)
  320. if err != nil {
  321. ctx.Data["HasGPGError"] = true
  322. switch {
  323. case models.IsErrGPGKeyParsing(err):
  324. ctx.Flash.Error(ctx.Tr("form.invalid_gpg_key", err.Error()))
  325. ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
  326. case models.IsErrGPGKeyIDAlreadyUsed(err):
  327. ctx.Data["Err_Content"] = true
  328. ctx.RenderWithErr(ctx.Tr("settings.gpg_key_id_used"), tplSettingsKeys, &form)
  329. case models.IsErrGPGEmailNotFound(err):
  330. ctx.Data["Err_Content"] = true
  331. ctx.RenderWithErr(ctx.Tr("settings.gpg_key_email_not_found", err.(models.ErrGPGEmailNotFound).Email), tplSettingsKeys, &form)
  332. default:
  333. ctx.Handle(500, "AddPublicKey", err)
  334. }
  335. return
  336. }
  337. ctx.Flash.Success(ctx.Tr("settings.add_gpg_key_success", key.KeyID))
  338. ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
  339. case "ssh":
  340. content, err := models.CheckPublicKeyString(form.Content)
  341. if err != nil {
  342. if models.IsErrKeyUnableVerify(err) {
  343. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  344. } else {
  345. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  346. ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
  347. return
  348. }
  349. }
  350. if _, err = models.AddPublicKey(ctx.User.ID, form.Title, content); err != nil {
  351. ctx.Data["HasSSHError"] = true
  352. switch {
  353. case models.IsErrKeyAlreadyExist(err):
  354. ctx.Data["Err_Content"] = true
  355. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplSettingsKeys, &form)
  356. case models.IsErrKeyNameAlreadyUsed(err):
  357. ctx.Data["Err_Title"] = true
  358. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_name_used"), tplSettingsKeys, &form)
  359. default:
  360. ctx.Handle(500, "AddPublicKey", err)
  361. }
  362. return
  363. }
  364. ctx.Flash.Success(ctx.Tr("settings.add_key_success", form.Title))
  365. ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
  366. default:
  367. ctx.Flash.Warning("Function not implemented")
  368. ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
  369. }
  370. }
  371. // DeleteKey response for delete user's SSH/GPG key
  372. func DeleteKey(ctx *context.Context) {
  373. switch ctx.Query("type") {
  374. case "gpg":
  375. if err := models.DeleteGPGKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  376. ctx.Flash.Error("DeleteGPGKey: " + err.Error())
  377. } else {
  378. ctx.Flash.Success(ctx.Tr("settings.gpg_key_deletion_success"))
  379. }
  380. case "ssh":
  381. if err := models.DeletePublicKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  382. ctx.Flash.Error("DeletePublicKey: " + err.Error())
  383. } else {
  384. ctx.Flash.Success(ctx.Tr("settings.ssh_key_deletion_success"))
  385. }
  386. default:
  387. ctx.Flash.Warning("Function not implemented")
  388. ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
  389. }
  390. ctx.JSON(200, map[string]interface{}{
  391. "redirect": setting.AppSubURL + "/user/settings/keys",
  392. })
  393. }
  394. // SettingsApplications render user's access tokens page
  395. func SettingsApplications(ctx *context.Context) {
  396. ctx.Data["Title"] = ctx.Tr("settings")
  397. ctx.Data["PageIsSettingsApplications"] = true
  398. tokens, err := models.ListAccessTokens(ctx.User.ID)
  399. if err != nil {
  400. ctx.Handle(500, "ListAccessTokens", err)
  401. return
  402. }
  403. ctx.Data["Tokens"] = tokens
  404. ctx.HTML(200, tplSettingsApplications)
  405. }
  406. // SettingsApplicationsPost response for add user's access token
  407. func SettingsApplicationsPost(ctx *context.Context, form auth.NewAccessTokenForm) {
  408. ctx.Data["Title"] = ctx.Tr("settings")
  409. ctx.Data["PageIsSettingsApplications"] = true
  410. if ctx.HasError() {
  411. tokens, err := models.ListAccessTokens(ctx.User.ID)
  412. if err != nil {
  413. ctx.Handle(500, "ListAccessTokens", err)
  414. return
  415. }
  416. ctx.Data["Tokens"] = tokens
  417. ctx.HTML(200, tplSettingsApplications)
  418. return
  419. }
  420. t := &models.AccessToken{
  421. UID: ctx.User.ID,
  422. Name: form.Name,
  423. }
  424. if err := models.NewAccessToken(t); err != nil {
  425. ctx.Handle(500, "NewAccessToken", err)
  426. return
  427. }
  428. ctx.Flash.Success(ctx.Tr("settings.generate_token_success"))
  429. ctx.Flash.Info(t.Sha1)
  430. ctx.Redirect(setting.AppSubURL + "/user/settings/applications")
  431. }
  432. // SettingsDeleteApplication response for delete user access token
  433. func SettingsDeleteApplication(ctx *context.Context) {
  434. if err := models.DeleteAccessTokenByID(ctx.QueryInt64("id"), ctx.User.ID); err != nil {
  435. ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error())
  436. } else {
  437. ctx.Flash.Success(ctx.Tr("settings.delete_token_success"))
  438. }
  439. ctx.JSON(200, map[string]interface{}{
  440. "redirect": setting.AppSubURL + "/user/settings/applications",
  441. })
  442. }
  443. // SettingsTwoFactor renders the 2FA page.
  444. func SettingsTwoFactor(ctx *context.Context) {
  445. ctx.Data["Title"] = ctx.Tr("settings")
  446. ctx.Data["PageIsSettingsTwofa"] = true
  447. enrolled := true
  448. _, err := models.GetTwoFactorByUID(ctx.User.ID)
  449. if err != nil {
  450. if models.IsErrTwoFactorNotEnrolled(err) {
  451. enrolled = false
  452. } else {
  453. ctx.Handle(500, "SettingsTwoFactor", err)
  454. return
  455. }
  456. }
  457. ctx.Data["TwofaEnrolled"] = enrolled
  458. ctx.HTML(200, tplSettingsTwofa)
  459. }
  460. // SettingsTwoFactorRegenerateScratch regenerates the user's 2FA scratch code.
  461. func SettingsTwoFactorRegenerateScratch(ctx *context.Context) {
  462. ctx.Data["Title"] = ctx.Tr("settings")
  463. ctx.Data["PageIsSettingsTwofa"] = true
  464. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  465. if err != nil {
  466. ctx.Handle(500, "SettingsTwoFactor", err)
  467. return
  468. }
  469. if err = t.GenerateScratchToken(); err != nil {
  470. ctx.Handle(500, "SettingsTwoFactor", err)
  471. return
  472. }
  473. if err = models.UpdateTwoFactor(t); err != nil {
  474. ctx.Handle(500, "SettingsTwoFactor", err)
  475. return
  476. }
  477. ctx.Flash.Success(ctx.Tr("settings.twofa_scratch_token_regenerated", t.ScratchToken))
  478. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  479. }
  480. // SettingsTwoFactorDisable deletes the user's 2FA settings.
  481. func SettingsTwoFactorDisable(ctx *context.Context) {
  482. ctx.Data["Title"] = ctx.Tr("settings")
  483. ctx.Data["PageIsSettingsTwofa"] = true
  484. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  485. if err != nil {
  486. ctx.Handle(500, "SettingsTwoFactor", err)
  487. return
  488. }
  489. if err = models.DeleteTwoFactorByID(t.ID, ctx.User.ID); err != nil {
  490. ctx.Handle(500, "SettingsTwoFactor", err)
  491. return
  492. }
  493. ctx.Flash.Success(ctx.Tr("settings.twofa_disabled"))
  494. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  495. }
  496. func twofaGenerateSecretAndQr(ctx *context.Context) bool {
  497. var otpKey *otp.Key
  498. var err error
  499. uri := ctx.Session.Get("twofaUri")
  500. if uri != nil {
  501. otpKey, err = otp.NewKeyFromURL(uri.(string))
  502. }
  503. if otpKey == nil {
  504. err = nil // clear the error, in case the URL was invalid
  505. otpKey, err = totp.Generate(totp.GenerateOpts{
  506. Issuer: setting.AppName,
  507. AccountName: ctx.User.Name,
  508. })
  509. if err != nil {
  510. ctx.Handle(500, "SettingsTwoFactor", err)
  511. return false
  512. }
  513. }
  514. ctx.Data["TwofaSecret"] = otpKey.Secret()
  515. img, err := otpKey.Image(320, 240)
  516. if err != nil {
  517. ctx.Handle(500, "SettingsTwoFactor", err)
  518. return false
  519. }
  520. var imgBytes bytes.Buffer
  521. if err = png.Encode(&imgBytes, img); err != nil {
  522. ctx.Handle(500, "SettingsTwoFactor", err)
  523. return false
  524. }
  525. ctx.Data["QrUri"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(imgBytes.Bytes()))
  526. ctx.Session.Set("twofaSecret", otpKey.Secret())
  527. ctx.Session.Set("twofaUri", otpKey.String())
  528. return true
  529. }
  530. // SettingsTwoFactorEnroll shows the page where the user can enroll into 2FA.
  531. func SettingsTwoFactorEnroll(ctx *context.Context) {
  532. ctx.Data["Title"] = ctx.Tr("settings")
  533. ctx.Data["PageIsSettingsTwofa"] = true
  534. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  535. if t != nil {
  536. // already enrolled
  537. ctx.Handle(500, "SettingsTwoFactor", err)
  538. return
  539. }
  540. if err != nil && !models.IsErrTwoFactorNotEnrolled(err) {
  541. ctx.Handle(500, "SettingsTwoFactor", err)
  542. return
  543. }
  544. if !twofaGenerateSecretAndQr(ctx) {
  545. return
  546. }
  547. ctx.HTML(200, tplSettingsTwofaEnroll)
  548. }
  549. // SettingsTwoFactorEnrollPost handles enrolling the user into 2FA.
  550. func SettingsTwoFactorEnrollPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  551. ctx.Data["Title"] = ctx.Tr("settings")
  552. ctx.Data["PageIsSettingsTwofa"] = true
  553. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  554. if t != nil {
  555. // already enrolled
  556. ctx.Handle(500, "SettingsTwoFactor", err)
  557. return
  558. }
  559. if err != nil && !models.IsErrTwoFactorNotEnrolled(err) {
  560. ctx.Handle(500, "SettingsTwoFactor", err)
  561. return
  562. }
  563. if ctx.HasError() {
  564. if !twofaGenerateSecretAndQr(ctx) {
  565. return
  566. }
  567. ctx.HTML(200, tplSettingsTwofaEnroll)
  568. return
  569. }
  570. secret := ctx.Session.Get("twofaSecret").(string)
  571. if !totp.Validate(form.Passcode, secret) {
  572. if !twofaGenerateSecretAndQr(ctx) {
  573. return
  574. }
  575. ctx.Flash.Error(ctx.Tr("settings.passcode_invalid"))
  576. ctx.HTML(200, tplSettingsTwofaEnroll)
  577. return
  578. }
  579. t = &models.TwoFactor{
  580. UID: ctx.User.ID,
  581. }
  582. err = t.SetSecret(secret)
  583. if err != nil {
  584. ctx.Handle(500, "SettingsTwoFactor", err)
  585. return
  586. }
  587. err = t.GenerateScratchToken()
  588. if err != nil {
  589. ctx.Handle(500, "SettingsTwoFactor", err)
  590. return
  591. }
  592. if err = models.NewTwoFactor(t); err != nil {
  593. ctx.Handle(500, "SettingsTwoFactor", err)
  594. return
  595. }
  596. ctx.Session.Delete("twofaSecret")
  597. ctx.Session.Delete("twofaUri")
  598. ctx.Flash.Success(ctx.Tr("settings.twofa_enrolled", t.ScratchToken))
  599. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  600. }
  601. // SettingsAccountLinks render the account links settings page
  602. func SettingsAccountLinks(ctx *context.Context) {
  603. ctx.Data["Title"] = ctx.Tr("settings")
  604. ctx.Data["PageIsSettingsAccountLink"] = true
  605. accountLinks, err := models.ListAccountLinks(ctx.User)
  606. if err != nil {
  607. ctx.Handle(500, "ListAccountLinks", err)
  608. return
  609. }
  610. // map the provider display name with the LoginSource
  611. sources := make(map[*models.LoginSource]string)
  612. for _, externalAccount := range accountLinks {
  613. if loginSource, err := models.GetLoginSourceByID(externalAccount.LoginSourceID); err == nil {
  614. var providerDisplayName string
  615. if loginSource.IsOAuth2() {
  616. providerTechnicalName := loginSource.OAuth2().Provider
  617. providerDisplayName = models.OAuth2Providers[providerTechnicalName].DisplayName
  618. } else {
  619. providerDisplayName = loginSource.Name
  620. }
  621. sources[loginSource] = providerDisplayName
  622. }
  623. }
  624. ctx.Data["AccountLinks"] = sources
  625. ctx.HTML(200, tplSettingsAccountLink)
  626. }
  627. // SettingsDeleteAccountLink delete a single account link
  628. func SettingsDeleteAccountLink(ctx *context.Context) {
  629. if _, err := models.RemoveAccountLink(ctx.User, ctx.QueryInt64("loginSourceID")); err != nil {
  630. ctx.Flash.Error("RemoveAccountLink: " + err.Error())
  631. } else {
  632. ctx.Flash.Success(ctx.Tr("settings.remove_account_link_success"))
  633. }
  634. ctx.JSON(200, map[string]interface{}{
  635. "redirect": setting.AppSubURL + "/user/settings/account_link",
  636. })
  637. }
  638. // SettingsDelete render user suicide page and response for delete user himself
  639. func SettingsDelete(ctx *context.Context) {
  640. ctx.Data["Title"] = ctx.Tr("settings")
  641. ctx.Data["PageIsSettingsDelete"] = true
  642. ctx.Data["Email"] = ctx.User.Email
  643. if ctx.Req.Method == "POST" {
  644. if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil {
  645. if models.IsErrUserNotExist(err) {
  646. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), tplSettingsDelete, nil)
  647. } else {
  648. ctx.Handle(500, "UserSignIn", err)
  649. }
  650. return
  651. }
  652. if err := models.DeleteUser(ctx.User); err != nil {
  653. switch {
  654. case models.IsErrUserOwnRepos(err):
  655. ctx.Flash.Error(ctx.Tr("form.still_own_repo"))
  656. ctx.Redirect(setting.AppSubURL + "/user/settings/delete")
  657. case models.IsErrUserHasOrgs(err):
  658. ctx.Flash.Error(ctx.Tr("form.still_has_org"))
  659. ctx.Redirect(setting.AppSubURL + "/user/settings/delete")
  660. default:
  661. ctx.Handle(500, "DeleteUser", err)
  662. }
  663. } else {
  664. log.Trace("Account deleted: %s", ctx.User.Name)
  665. ctx.Redirect(setting.AppSubURL + "/")
  666. }
  667. return
  668. }
  669. ctx.HTML(200, tplSettingsDelete)
  670. }
  671. // SettingsOrganization render all the organization of the user
  672. func SettingsOrganization(ctx *context.Context) {
  673. ctx.Data["Title"] = ctx.Tr("settings")
  674. ctx.Data["PageIsSettingsOrganization"] = true
  675. orgs, err := models.GetOrgsByUserID(ctx.User.ID, ctx.IsSigned)
  676. if err != nil {
  677. ctx.Handle(500, "GetOrgsByUserID", err)
  678. return
  679. }
  680. ctx.Data["Orgs"] = orgs
  681. ctx.HTML(200, tplSettingsOrganization)
  682. }