api_user.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package httpd
  15. import (
  16. "context"
  17. "fmt"
  18. "net/http"
  19. "strconv"
  20. "github.com/go-chi/render"
  21. "github.com/sftpgo/sdk"
  22. "github.com/drakkan/sftpgo/v2/internal/common"
  23. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  24. "github.com/drakkan/sftpgo/v2/internal/kms"
  25. "github.com/drakkan/sftpgo/v2/internal/smtp"
  26. "github.com/drakkan/sftpgo/v2/internal/util"
  27. "github.com/drakkan/sftpgo/v2/internal/vfs"
  28. )
  29. func getUsers(w http.ResponseWriter, r *http.Request) {
  30. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  31. limit, offset, order, err := getSearchFilters(w, r)
  32. if err != nil {
  33. return
  34. }
  35. users, err := dataprovider.GetUsers(limit, offset, order)
  36. if err == nil {
  37. render.JSON(w, r, users)
  38. } else {
  39. sendAPIResponse(w, r, err, "", http.StatusInternalServerError)
  40. }
  41. }
  42. func getUserByUsername(w http.ResponseWriter, r *http.Request) {
  43. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  44. username := getURLParam(r, "username")
  45. renderUser(w, r, username, http.StatusOK)
  46. }
  47. func renderUser(w http.ResponseWriter, r *http.Request, username string, status int) {
  48. user, err := dataprovider.UserExists(username)
  49. if err != nil {
  50. sendAPIResponse(w, r, err, "", getRespStatus(err))
  51. return
  52. }
  53. user.PrepareForRendering()
  54. if status != http.StatusOK {
  55. ctx := context.WithValue(r.Context(), render.StatusCtxKey, status)
  56. render.JSON(w, r.WithContext(ctx), user)
  57. } else {
  58. render.JSON(w, r, user)
  59. }
  60. }
  61. func addUser(w http.ResponseWriter, r *http.Request) {
  62. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  63. claims, err := getTokenClaims(r)
  64. if err != nil || claims.Username == "" {
  65. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  66. return
  67. }
  68. var user dataprovider.User
  69. err = render.DecodeJSON(r.Body, &user)
  70. if err != nil {
  71. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  72. return
  73. }
  74. user.Filters.RecoveryCodes = nil
  75. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{
  76. Enabled: false,
  77. }
  78. err = dataprovider.AddUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  79. if err != nil {
  80. sendAPIResponse(w, r, err, "", getRespStatus(err))
  81. return
  82. }
  83. renderUser(w, r, user.Username, http.StatusCreated)
  84. }
  85. func disableUser2FA(w http.ResponseWriter, r *http.Request) {
  86. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  87. claims, err := getTokenClaims(r)
  88. if err != nil || claims.Username == "" {
  89. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  90. return
  91. }
  92. username := getURLParam(r, "username")
  93. user, err := dataprovider.UserExists(username)
  94. if err != nil {
  95. sendAPIResponse(w, r, err, "", getRespStatus(err))
  96. return
  97. }
  98. user.Filters.RecoveryCodes = nil
  99. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{
  100. Enabled: false,
  101. }
  102. if err := dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr)); err != nil {
  103. sendAPIResponse(w, r, err, "", getRespStatus(err))
  104. return
  105. }
  106. sendAPIResponse(w, r, nil, "2FA disabled", http.StatusOK)
  107. }
  108. func updateUser(w http.ResponseWriter, r *http.Request) {
  109. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  110. claims, err := getTokenClaims(r)
  111. if err != nil || claims.Username == "" {
  112. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  113. return
  114. }
  115. username := getURLParam(r, "username")
  116. disconnect := 0
  117. if _, ok := r.URL.Query()["disconnect"]; ok {
  118. disconnect, err = strconv.Atoi(r.URL.Query().Get("disconnect"))
  119. if err != nil {
  120. err = fmt.Errorf("invalid disconnect parameter: %v", err)
  121. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  122. return
  123. }
  124. }
  125. user, err := dataprovider.UserExists(username)
  126. if err != nil {
  127. sendAPIResponse(w, r, err, "", getRespStatus(err))
  128. return
  129. }
  130. userID := user.ID
  131. username = user.Username
  132. totpConfig := user.Filters.TOTPConfig
  133. recoveryCodes := user.Filters.RecoveryCodes
  134. currentPermissions := user.Permissions
  135. currentS3AccessSecret := user.FsConfig.S3Config.AccessSecret
  136. currentAzAccountKey := user.FsConfig.AzBlobConfig.AccountKey
  137. currentAzSASUrl := user.FsConfig.AzBlobConfig.SASURL
  138. currentGCSCredentials := user.FsConfig.GCSConfig.Credentials
  139. currentCryptoPassphrase := user.FsConfig.CryptConfig.Passphrase
  140. currentSFTPPassword := user.FsConfig.SFTPConfig.Password
  141. currentSFTPKey := user.FsConfig.SFTPConfig.PrivateKey
  142. currentSFTPKeyPassphrase := user.FsConfig.SFTPConfig.KeyPassphrase
  143. currentHTTPPassword := user.FsConfig.HTTPConfig.Password
  144. currentHTTPAPIKey := user.FsConfig.HTTPConfig.APIKey
  145. user.Permissions = make(map[string][]string)
  146. user.FsConfig.S3Config = vfs.S3FsConfig{}
  147. user.FsConfig.AzBlobConfig = vfs.AzBlobFsConfig{}
  148. user.FsConfig.GCSConfig = vfs.GCSFsConfig{}
  149. user.FsConfig.CryptConfig = vfs.CryptFsConfig{}
  150. user.FsConfig.SFTPConfig = vfs.SFTPFsConfig{}
  151. user.FsConfig.HTTPConfig = vfs.HTTPFsConfig{}
  152. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{}
  153. user.Filters.RecoveryCodes = nil
  154. user.VirtualFolders = nil
  155. err = render.DecodeJSON(r.Body, &user)
  156. if err != nil {
  157. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  158. return
  159. }
  160. user.ID = userID
  161. user.Username = username
  162. user.Filters.TOTPConfig = totpConfig
  163. user.Filters.RecoveryCodes = recoveryCodes
  164. user.SetEmptySecretsIfNil()
  165. // we use new Permissions if passed otherwise the old ones
  166. if len(user.Permissions) == 0 {
  167. user.Permissions = currentPermissions
  168. }
  169. updateEncryptedSecrets(&user.FsConfig, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  170. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  171. currentHTTPPassword, currentHTTPAPIKey)
  172. err = dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  173. if err != nil {
  174. sendAPIResponse(w, r, err, "", getRespStatus(err))
  175. return
  176. }
  177. sendAPIResponse(w, r, err, "User updated", http.StatusOK)
  178. if disconnect == 1 {
  179. disconnectUser(user.Username)
  180. }
  181. }
  182. func deleteUser(w http.ResponseWriter, r *http.Request) {
  183. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  184. claims, err := getTokenClaims(r)
  185. if err != nil || claims.Username == "" {
  186. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  187. return
  188. }
  189. username := getURLParam(r, "username")
  190. err = dataprovider.DeleteUser(username, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  191. if err != nil {
  192. sendAPIResponse(w, r, err, "", getRespStatus(err))
  193. return
  194. }
  195. sendAPIResponse(w, r, err, "User deleted", http.StatusOK)
  196. disconnectUser(dataprovider.ConvertName(username))
  197. }
  198. func forgotUserPassword(w http.ResponseWriter, r *http.Request) {
  199. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  200. if !smtp.IsEnabled() {
  201. sendAPIResponse(w, r, nil, "No SMTP configuration", http.StatusBadRequest)
  202. return
  203. }
  204. err := handleForgotPassword(r, getURLParam(r, "username"), false)
  205. if err != nil {
  206. sendAPIResponse(w, r, err, "", getRespStatus(err))
  207. return
  208. }
  209. sendAPIResponse(w, r, err, "Check your email for the confirmation code", http.StatusOK)
  210. }
  211. func resetUserPassword(w http.ResponseWriter, r *http.Request) {
  212. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  213. var req pwdReset
  214. err := render.DecodeJSON(r.Body, &req)
  215. if err != nil {
  216. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  217. return
  218. }
  219. _, _, err = handleResetPassword(r, req.Code, req.Password, false)
  220. if err != nil {
  221. sendAPIResponse(w, r, err, "", getRespStatus(err))
  222. return
  223. }
  224. sendAPIResponse(w, r, err, "Password reset successful", http.StatusOK)
  225. }
  226. func disconnectUser(username string) {
  227. for _, stat := range common.Connections.GetStats() {
  228. if stat.Username == username {
  229. common.Connections.Close(stat.ConnectionID)
  230. }
  231. }
  232. }
  233. func updateEncryptedSecrets(fsConfig *vfs.Filesystem, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  234. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  235. currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  236. // we use the new access secret if plain or empty, otherwise the old value
  237. switch fsConfig.Provider {
  238. case sdk.S3FilesystemProvider:
  239. if fsConfig.S3Config.AccessSecret.IsNotPlainAndNotEmpty() {
  240. fsConfig.S3Config.AccessSecret = currentS3AccessSecret
  241. }
  242. case sdk.AzureBlobFilesystemProvider:
  243. if fsConfig.AzBlobConfig.AccountKey.IsNotPlainAndNotEmpty() {
  244. fsConfig.AzBlobConfig.AccountKey = currentAzAccountKey
  245. }
  246. if fsConfig.AzBlobConfig.SASURL.IsNotPlainAndNotEmpty() {
  247. fsConfig.AzBlobConfig.SASURL = currentAzSASUrl
  248. }
  249. case sdk.GCSFilesystemProvider:
  250. // for GCS credentials will be cleared if we enable automatic credentials
  251. // so keep the old credentials here if no new credentials are provided
  252. if !fsConfig.GCSConfig.Credentials.IsPlain() {
  253. fsConfig.GCSConfig.Credentials = currentGCSCredentials
  254. }
  255. case sdk.CryptedFilesystemProvider:
  256. if fsConfig.CryptConfig.Passphrase.IsNotPlainAndNotEmpty() {
  257. fsConfig.CryptConfig.Passphrase = currentCryptoPassphrase
  258. }
  259. case sdk.SFTPFilesystemProvider:
  260. updateSFTPFsEncryptedSecrets(fsConfig, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase)
  261. case sdk.HTTPFilesystemProvider:
  262. updateHTTPFsEncryptedSecrets(fsConfig, currentHTTPPassword, currentHTTPAPIKey)
  263. }
  264. }
  265. func updateSFTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentSFTPPassword, currentSFTPKey,
  266. currentSFTPKeyPassphrase *kms.Secret,
  267. ) {
  268. if fsConfig.SFTPConfig.Password.IsNotPlainAndNotEmpty() {
  269. fsConfig.SFTPConfig.Password = currentSFTPPassword
  270. }
  271. if fsConfig.SFTPConfig.PrivateKey.IsNotPlainAndNotEmpty() {
  272. fsConfig.SFTPConfig.PrivateKey = currentSFTPKey
  273. }
  274. if fsConfig.SFTPConfig.KeyPassphrase.IsNotPlainAndNotEmpty() {
  275. fsConfig.SFTPConfig.KeyPassphrase = currentSFTPKeyPassphrase
  276. }
  277. }
  278. func updateHTTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  279. if fsConfig.HTTPConfig.Password.IsNotPlainAndNotEmpty() {
  280. fsConfig.HTTPConfig.Password = currentHTTPPassword
  281. }
  282. if fsConfig.HTTPConfig.APIKey.IsNotPlainAndNotEmpty() {
  283. fsConfig.HTTPConfig.APIKey = currentHTTPAPIKey
  284. }
  285. }