setting.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. "os"
  10. "strconv"
  11. "strings"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/modules/auth"
  14. "github.com/gogits/gogs/modules/base"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/gogs/modules/middleware"
  17. "github.com/gogits/gogs/modules/process"
  18. )
  19. const (
  20. SETTING base.TplName = "user/setting"
  21. SOCIAL base.TplName = "user/social"
  22. PASSWORD base.TplName = "user/password"
  23. PUBLICKEY base.TplName = "user/publickey"
  24. NOTIFICATION base.TplName = "user/notification"
  25. SECURITY base.TplName = "user/security"
  26. )
  27. var (
  28. MinimumKeySize = map[string]int{
  29. "(ED25519)": 256,
  30. "(ECDSA)": 256,
  31. "(NTRU)": 1087,
  32. "(MCE)": 1702,
  33. "(McE)": 1702,
  34. "(RSA)": 2048,
  35. }
  36. )
  37. func Setting(ctx *middleware.Context) {
  38. ctx.Data["Title"] = "Setting"
  39. ctx.Data["PageIsUserSetting"] = true
  40. ctx.Data["IsUserPageSetting"] = true
  41. ctx.Data["Owner"] = ctx.User
  42. ctx.HTML(200, SETTING)
  43. }
  44. func SettingPost(ctx *middleware.Context, form auth.UpdateProfileForm) {
  45. ctx.Data["Title"] = "Setting"
  46. ctx.Data["PageIsUserSetting"] = true
  47. ctx.Data["IsUserPageSetting"] = true
  48. if ctx.HasError() {
  49. ctx.HTML(200, SETTING)
  50. return
  51. }
  52. ctx.Data["Owner"] = ctx.User
  53. // Check if user name has been changed.
  54. if ctx.User.Name != form.UserName {
  55. isExist, err := models.IsUserExist(form.UserName)
  56. if err != nil {
  57. ctx.Handle(500, "user.SettingPost(update: check existence)", err)
  58. return
  59. } else if isExist {
  60. ctx.RenderWithErr("User name has been taken.", SETTING, &form)
  61. return
  62. } else if err = models.ChangeUserName(ctx.User, form.UserName); err != nil {
  63. ctx.Handle(500, "user.SettingPost(change user name)", err)
  64. return
  65. }
  66. log.Trace("%s User name changed: %s -> %s", ctx.Req.RequestURI, ctx.User.Name, form.UserName)
  67. ctx.User.Name = form.UserName
  68. }
  69. ctx.User.FullName = form.FullName
  70. ctx.User.Email = form.Email
  71. ctx.User.Website = form.Website
  72. ctx.User.Location = form.Location
  73. ctx.User.Avatar = base.EncodeMd5(form.Avatar)
  74. ctx.User.AvatarEmail = form.Avatar
  75. if err := models.UpdateUser(ctx.User); err != nil {
  76. ctx.Handle(500, "setting.SettingPost(UpdateUser)", err)
  77. return
  78. }
  79. log.Trace("%s User setting updated: %s", ctx.Req.RequestURI, ctx.User.LowerName)
  80. ctx.Flash.Success("Your profile has been successfully updated.")
  81. ctx.Redirect("/user/settings")
  82. }
  83. func SettingSocial(ctx *middleware.Context) {
  84. ctx.Data["Title"] = "Social Account"
  85. ctx.Data["PageIsUserSetting"] = true
  86. ctx.Data["IsUserPageSettingSocial"] = true
  87. // Unbind social account.
  88. remove, _ := base.StrTo(ctx.Query("remove")).Int64()
  89. if remove > 0 {
  90. if err := models.DeleteOauth2ById(remove); err != nil {
  91. ctx.Handle(500, "user.SettingSocial(DeleteOauth2ById)", err)
  92. return
  93. }
  94. ctx.Flash.Success("OAuth2 has been unbinded.")
  95. ctx.Redirect("/user/settings/social")
  96. return
  97. }
  98. var err error
  99. ctx.Data["Socials"], err = models.GetOauthByUserId(ctx.User.Id)
  100. if err != nil {
  101. ctx.Handle(500, "user.SettingSocial(GetOauthByUserId)", err)
  102. return
  103. }
  104. ctx.HTML(200, SOCIAL)
  105. }
  106. func SettingPassword(ctx *middleware.Context) {
  107. ctx.Data["Title"] = "Password"
  108. ctx.Data["PageIsUserSetting"] = true
  109. ctx.Data["IsUserPageSettingPasswd"] = true
  110. ctx.HTML(200, PASSWORD)
  111. }
  112. func SettingPasswordPost(ctx *middleware.Context, form auth.UpdatePasswdForm) {
  113. ctx.Data["Title"] = "Password"
  114. ctx.Data["PageIsUserSetting"] = true
  115. ctx.Data["IsUserPageSettingPasswd"] = true
  116. if ctx.HasError() {
  117. ctx.HTML(200, PASSWORD)
  118. return
  119. }
  120. tmpUser := &models.User{
  121. Passwd: form.OldPasswd,
  122. Salt: ctx.User.Salt,
  123. }
  124. tmpUser.EncodePasswd()
  125. if ctx.User.Passwd != tmpUser.Passwd {
  126. ctx.Flash.Error("Old password is not correct.")
  127. } else if form.NewPasswd != form.RetypePasswd {
  128. ctx.Flash.Error("New password and re-type password are not same.")
  129. } else {
  130. ctx.User.Passwd = form.NewPasswd
  131. ctx.User.Salt = models.GetUserSalt()
  132. ctx.User.EncodePasswd()
  133. if err := models.UpdateUser(ctx.User); err != nil {
  134. ctx.Handle(200, "setting.SettingPassword", err)
  135. return
  136. }
  137. log.Trace("%s User password updated: %s", ctx.Req.RequestURI, ctx.User.LowerName)
  138. ctx.Flash.Success("Password is changed successfully. You can now sign in via new password.")
  139. }
  140. ctx.Redirect("/user/settings/password")
  141. }
  142. // Checks if the given public key string is recognized by SSH.
  143. func CheckPublicKeyString(keyContent string) (ok bool, err error) {
  144. if strings.ContainsAny(keyContent, "\n\r") {
  145. return false, errors.New("Only a single line with a single key please")
  146. }
  147. // write the key to a file…
  148. tmpFile, err := ioutil.TempFile(os.TempDir(), "keytest")
  149. if err != nil {
  150. return false, err
  151. }
  152. tmpPath := tmpFile.Name()
  153. defer os.Remove(tmpPath)
  154. tmpFile.WriteString(keyContent)
  155. tmpFile.Close()
  156. // … see if ssh-keygen recognizes its contents
  157. stdout, stderr, err := process.Exec("CheckPublicKeyString", "ssh-keygen", "-l", "-f", tmpPath)
  158. if err != nil {
  159. return false, errors.New("ssh-keygen -l -f: " + stderr)
  160. } else if len(stdout) < 2 {
  161. return false, errors.New("ssh-keygen returned not enough output to evaluate the key")
  162. }
  163. sshKeygenOutput := strings.Split(stdout, " ")
  164. if len(sshKeygenOutput) < 4 {
  165. return false, errors.New("Not enough fields returned by ssh-keygen -l -f")
  166. }
  167. keySize, err := strconv.Atoi(sshKeygenOutput[0])
  168. if err != nil {
  169. return false, errors.New("Cannot get key size of the given key")
  170. }
  171. keyType := strings.TrimSpace(sshKeygenOutput[len(sshKeygenOutput)-1])
  172. if minimumKeySize := MinimumKeySize[keyType]; minimumKeySize == 0 {
  173. return false, errors.New("Sorry, unrecognized public key type")
  174. } else {
  175. if keySize < minimumKeySize {
  176. return false, fmt.Errorf("The minimum accepted size of a public key %s is %d", keyType, minimumKeySize)
  177. }
  178. }
  179. return true, nil
  180. }
  181. func SettingSSHKeys(ctx *middleware.Context, form auth.AddSSHKeyForm) {
  182. ctx.Data["Title"] = "SSH Keys"
  183. ctx.Data["PageIsUserSetting"] = true
  184. ctx.Data["IsUserPageSettingSSH"] = true
  185. // Delete SSH key.
  186. if ctx.Req.Method == "DELETE" || ctx.Query("_method") == "DELETE" {
  187. id, err := base.StrTo(ctx.Query("id")).Int64()
  188. if err != nil {
  189. log.Error("ssh.DelPublicKey: %v", err)
  190. ctx.JSON(200, map[string]interface{}{
  191. "ok": false,
  192. "err": err.Error(),
  193. })
  194. return
  195. }
  196. if err = models.DeletePublicKey(&models.PublicKey{Id: id}); err != nil {
  197. log.Error("ssh.DelPublicKey: %v", err)
  198. ctx.JSON(200, map[string]interface{}{
  199. "ok": false,
  200. "err": err.Error(),
  201. })
  202. } else {
  203. log.Trace("%s User SSH key deleted: %s", ctx.Req.RequestURI, ctx.User.LowerName)
  204. ctx.JSON(200, map[string]interface{}{
  205. "ok": true,
  206. })
  207. }
  208. return
  209. }
  210. var err error
  211. // List existed SSH keys.
  212. ctx.Data["Keys"], err = models.ListPublicKey(ctx.User.Id)
  213. if err != nil {
  214. ctx.Handle(500, "ssh.ListPublicKey", err)
  215. return
  216. }
  217. // Add new SSH key.
  218. if ctx.Req.Method == "POST" {
  219. if ctx.HasError() {
  220. ctx.HTML(200, "user/publickey")
  221. return
  222. }
  223. if ok, err := CheckPublicKeyString(form.KeyContent); !ok {
  224. ctx.Flash.Error(err.Error())
  225. ctx.Redirect("/user/settings/ssh")
  226. return
  227. }
  228. k := &models.PublicKey{
  229. OwnerId: ctx.User.Id,
  230. Name: form.KeyName,
  231. Content: form.KeyContent,
  232. }
  233. if err := models.AddPublicKey(k); err != nil {
  234. if err.Error() == models.ErrKeyAlreadyExist.Error() {
  235. ctx.RenderWithErr("Public key name has been used", "user/publickey", &form)
  236. return
  237. }
  238. ctx.Handle(500, "ssh.AddPublicKey", err)
  239. return
  240. } else {
  241. log.Trace("%s User SSH key added: %s", ctx.Req.RequestURI, ctx.User.LowerName)
  242. ctx.Flash.Success("New SSH Key has been added!")
  243. ctx.Redirect("/user/settings/ssh")
  244. return
  245. }
  246. }
  247. ctx.HTML(200, PUBLICKEY)
  248. }
  249. func SettingNotification(ctx *middleware.Context) {
  250. // TODO: user setting notification
  251. ctx.Data["Title"] = "Notification"
  252. ctx.Data["PageIsUserSetting"] = true
  253. ctx.Data["IsUserPageSettingNotify"] = true
  254. ctx.HTML(200, NOTIFICATION)
  255. }
  256. func SettingSecurity(ctx *middleware.Context) {
  257. // TODO: user setting security
  258. ctx.Data["Title"] = "Security"
  259. ctx.Data["PageIsUserSetting"] = true
  260. ctx.Data["IsUserPageSettingSecurity"] = true
  261. ctx.HTML(200, SECURITY)
  262. }