api_user.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. err = dataprovider.AddUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  75. if err != nil {
  76. sendAPIResponse(w, r, err, "", getRespStatus(err))
  77. return
  78. }
  79. renderUser(w, r, user.Username, http.StatusCreated)
  80. }
  81. func disableUser2FA(w http.ResponseWriter, r *http.Request) {
  82. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  83. claims, err := getTokenClaims(r)
  84. if err != nil || claims.Username == "" {
  85. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  86. return
  87. }
  88. username := getURLParam(r, "username")
  89. user, err := dataprovider.UserExists(username)
  90. if err != nil {
  91. sendAPIResponse(w, r, err, "", getRespStatus(err))
  92. return
  93. }
  94. user.Filters.RecoveryCodes = nil
  95. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{
  96. Enabled: false,
  97. }
  98. if err := dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr)); err != nil {
  99. sendAPIResponse(w, r, err, "", getRespStatus(err))
  100. return
  101. }
  102. sendAPIResponse(w, r, nil, "2FA disabled", http.StatusOK)
  103. }
  104. func updateUser(w http.ResponseWriter, r *http.Request) {
  105. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  106. claims, err := getTokenClaims(r)
  107. if err != nil || claims.Username == "" {
  108. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  109. return
  110. }
  111. username := getURLParam(r, "username")
  112. disconnect := 0
  113. if _, ok := r.URL.Query()["disconnect"]; ok {
  114. disconnect, err = strconv.Atoi(r.URL.Query().Get("disconnect"))
  115. if err != nil {
  116. err = fmt.Errorf("invalid disconnect parameter: %v", err)
  117. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  118. return
  119. }
  120. }
  121. user, err := dataprovider.UserExists(username)
  122. if err != nil {
  123. sendAPIResponse(w, r, err, "", getRespStatus(err))
  124. return
  125. }
  126. userID := user.ID
  127. username = user.Username
  128. totpConfig := user.Filters.TOTPConfig
  129. recoveryCodes := user.Filters.RecoveryCodes
  130. currentPermissions := user.Permissions
  131. currentS3AccessSecret := user.FsConfig.S3Config.AccessSecret
  132. currentAzAccountKey := user.FsConfig.AzBlobConfig.AccountKey
  133. currentAzSASUrl := user.FsConfig.AzBlobConfig.SASURL
  134. currentGCSCredentials := user.FsConfig.GCSConfig.Credentials
  135. currentCryptoPassphrase := user.FsConfig.CryptConfig.Passphrase
  136. currentSFTPPassword := user.FsConfig.SFTPConfig.Password
  137. currentSFTPKey := user.FsConfig.SFTPConfig.PrivateKey
  138. currentSFTPKeyPassphrase := user.FsConfig.SFTPConfig.KeyPassphrase
  139. currentHTTPPassword := user.FsConfig.HTTPConfig.Password
  140. currentHTTPAPIKey := user.FsConfig.HTTPConfig.APIKey
  141. user.Permissions = make(map[string][]string)
  142. user.FsConfig.S3Config = vfs.S3FsConfig{}
  143. user.FsConfig.AzBlobConfig = vfs.AzBlobFsConfig{}
  144. user.FsConfig.GCSConfig = vfs.GCSFsConfig{}
  145. user.FsConfig.CryptConfig = vfs.CryptFsConfig{}
  146. user.FsConfig.SFTPConfig = vfs.SFTPFsConfig{}
  147. user.FsConfig.HTTPConfig = vfs.HTTPFsConfig{}
  148. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{}
  149. user.Filters.RecoveryCodes = nil
  150. user.VirtualFolders = nil
  151. err = render.DecodeJSON(r.Body, &user)
  152. if err != nil {
  153. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  154. return
  155. }
  156. user.ID = userID
  157. user.Username = username
  158. user.Filters.TOTPConfig = totpConfig
  159. user.Filters.RecoveryCodes = recoveryCodes
  160. user.SetEmptySecretsIfNil()
  161. // we use new Permissions if passed otherwise the old ones
  162. if len(user.Permissions) == 0 {
  163. user.Permissions = currentPermissions
  164. }
  165. updateEncryptedSecrets(&user.FsConfig, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  166. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  167. currentHTTPPassword, currentHTTPAPIKey)
  168. err = dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  169. if err != nil {
  170. sendAPIResponse(w, r, err, "", getRespStatus(err))
  171. return
  172. }
  173. sendAPIResponse(w, r, err, "User updated", http.StatusOK)
  174. if disconnect == 1 {
  175. disconnectUser(user.Username)
  176. }
  177. }
  178. func deleteUser(w http.ResponseWriter, r *http.Request) {
  179. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  180. claims, err := getTokenClaims(r)
  181. if err != nil || claims.Username == "" {
  182. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  183. return
  184. }
  185. username := getURLParam(r, "username")
  186. err = dataprovider.DeleteUser(username, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  187. if err != nil {
  188. sendAPIResponse(w, r, err, "", getRespStatus(err))
  189. return
  190. }
  191. sendAPIResponse(w, r, err, "User deleted", http.StatusOK)
  192. disconnectUser(dataprovider.ConvertName(username))
  193. }
  194. func forgotUserPassword(w http.ResponseWriter, r *http.Request) {
  195. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  196. if !smtp.IsEnabled() {
  197. sendAPIResponse(w, r, nil, "No SMTP configuration", http.StatusBadRequest)
  198. return
  199. }
  200. err := handleForgotPassword(r, getURLParam(r, "username"), false)
  201. if err != nil {
  202. sendAPIResponse(w, r, err, "", getRespStatus(err))
  203. return
  204. }
  205. sendAPIResponse(w, r, err, "Check your email for the confirmation code", http.StatusOK)
  206. }
  207. func resetUserPassword(w http.ResponseWriter, r *http.Request) {
  208. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  209. var req pwdReset
  210. err := render.DecodeJSON(r.Body, &req)
  211. if err != nil {
  212. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  213. return
  214. }
  215. _, _, err = handleResetPassword(r, req.Code, req.Password, false)
  216. if err != nil {
  217. sendAPIResponse(w, r, err, "", getRespStatus(err))
  218. return
  219. }
  220. sendAPIResponse(w, r, err, "Password reset successful", http.StatusOK)
  221. }
  222. func disconnectUser(username string) {
  223. for _, stat := range common.Connections.GetStats() {
  224. if stat.Username == username {
  225. common.Connections.Close(stat.ConnectionID)
  226. }
  227. }
  228. }
  229. func updateEncryptedSecrets(fsConfig *vfs.Filesystem, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  230. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  231. currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  232. // we use the new access secret if plain or empty, otherwise the old value
  233. switch fsConfig.Provider {
  234. case sdk.S3FilesystemProvider:
  235. if fsConfig.S3Config.AccessSecret.IsNotPlainAndNotEmpty() {
  236. fsConfig.S3Config.AccessSecret = currentS3AccessSecret
  237. }
  238. case sdk.AzureBlobFilesystemProvider:
  239. if fsConfig.AzBlobConfig.AccountKey.IsNotPlainAndNotEmpty() {
  240. fsConfig.AzBlobConfig.AccountKey = currentAzAccountKey
  241. }
  242. if fsConfig.AzBlobConfig.SASURL.IsNotPlainAndNotEmpty() {
  243. fsConfig.AzBlobConfig.SASURL = currentAzSASUrl
  244. }
  245. case sdk.GCSFilesystemProvider:
  246. // for GCS credentials will be cleared if we enable automatic credentials
  247. // so keep the old credentials here if no new credentials are provided
  248. if !fsConfig.GCSConfig.Credentials.IsPlain() {
  249. fsConfig.GCSConfig.Credentials = currentGCSCredentials
  250. }
  251. case sdk.CryptedFilesystemProvider:
  252. if fsConfig.CryptConfig.Passphrase.IsNotPlainAndNotEmpty() {
  253. fsConfig.CryptConfig.Passphrase = currentCryptoPassphrase
  254. }
  255. case sdk.SFTPFilesystemProvider:
  256. updateSFTPFsEncryptedSecrets(fsConfig, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase)
  257. case sdk.HTTPFilesystemProvider:
  258. updateHTTPFsEncryptedSecrets(fsConfig, currentHTTPPassword, currentHTTPAPIKey)
  259. }
  260. }
  261. func updateSFTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentSFTPPassword, currentSFTPKey,
  262. currentSFTPKeyPassphrase *kms.Secret,
  263. ) {
  264. if fsConfig.SFTPConfig.Password.IsNotPlainAndNotEmpty() {
  265. fsConfig.SFTPConfig.Password = currentSFTPPassword
  266. }
  267. if fsConfig.SFTPConfig.PrivateKey.IsNotPlainAndNotEmpty() {
  268. fsConfig.SFTPConfig.PrivateKey = currentSFTPKey
  269. }
  270. if fsConfig.SFTPConfig.KeyPassphrase.IsNotPlainAndNotEmpty() {
  271. fsConfig.SFTPConfig.KeyPassphrase = currentSFTPKeyPassphrase
  272. }
  273. }
  274. func updateHTTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  275. if fsConfig.HTTPConfig.Password.IsNotPlainAndNotEmpty() {
  276. fsConfig.HTTPConfig.Password = currentHTTPPassword
  277. }
  278. if fsConfig.HTTPConfig.APIKey.IsNotPlainAndNotEmpty() {
  279. fsConfig.HTTPConfig.APIKey = currentHTTPAPIKey
  280. }
  281. }