api_user.go 9.7 KB

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