api_utils.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. "bytes"
  17. "context"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "io/fs"
  22. "mime"
  23. "net/http"
  24. "net/url"
  25. "os"
  26. "path"
  27. "strconv"
  28. "strings"
  29. "time"
  30. "github.com/go-chi/chi/v5"
  31. "github.com/go-chi/chi/v5/middleware"
  32. "github.com/go-chi/render"
  33. "github.com/klauspost/compress/zip"
  34. "github.com/drakkan/sftpgo/v2/common"
  35. "github.com/drakkan/sftpgo/v2/dataprovider"
  36. "github.com/drakkan/sftpgo/v2/logger"
  37. "github.com/drakkan/sftpgo/v2/metric"
  38. "github.com/drakkan/sftpgo/v2/plugin"
  39. "github.com/drakkan/sftpgo/v2/smtp"
  40. "github.com/drakkan/sftpgo/v2/util"
  41. )
  42. type pwdChange struct {
  43. CurrentPassword string `json:"current_password"`
  44. NewPassword string `json:"new_password"`
  45. }
  46. type pwdReset struct {
  47. Code string `json:"code"`
  48. Password string `json:"password"`
  49. }
  50. type baseProfile struct {
  51. Email string `json:"email,omitempty"`
  52. Description string `json:"description,omitempty"`
  53. AllowAPIKeyAuth bool `json:"allow_api_key_auth"`
  54. }
  55. type adminProfile struct {
  56. baseProfile
  57. }
  58. type userProfile struct {
  59. baseProfile
  60. PublicKeys []string `json:"public_keys,omitempty"`
  61. }
  62. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  63. var errorString string
  64. if _, ok := err.(*util.RecordNotFoundError); ok {
  65. errorString = http.StatusText(http.StatusNotFound)
  66. } else if err != nil {
  67. errorString = err.Error()
  68. }
  69. resp := apiResponse{
  70. Error: errorString,
  71. Message: message,
  72. }
  73. ctx := context.WithValue(r.Context(), render.StatusCtxKey, code)
  74. render.JSON(w, r.WithContext(ctx), resp)
  75. }
  76. func getRespStatus(err error) int {
  77. if _, ok := err.(*util.ValidationError); ok {
  78. return http.StatusBadRequest
  79. }
  80. if _, ok := err.(*util.MethodDisabledError); ok {
  81. return http.StatusForbidden
  82. }
  83. if _, ok := err.(*util.RecordNotFoundError); ok {
  84. return http.StatusNotFound
  85. }
  86. if errors.Is(err, fs.ErrNotExist) {
  87. return http.StatusBadRequest
  88. }
  89. if errors.Is(err, fs.ErrPermission) || errors.Is(err, dataprovider.ErrLoginNotAllowedFromIP) {
  90. return http.StatusForbidden
  91. }
  92. if errors.Is(err, plugin.ErrNoSearcher) || errors.Is(err, dataprovider.ErrNotImplemented) {
  93. return http.StatusNotImplemented
  94. }
  95. return http.StatusInternalServerError
  96. }
  97. // mappig between fs errors for HTTP protocol and HTTP response status codes
  98. func getMappedStatusCode(err error) int {
  99. var statusCode int
  100. switch {
  101. case errors.Is(err, os.ErrPermission):
  102. statusCode = http.StatusForbidden
  103. case errors.Is(err, common.ErrReadQuotaExceeded):
  104. statusCode = http.StatusForbidden
  105. case errors.Is(err, os.ErrNotExist):
  106. statusCode = http.StatusNotFound
  107. case errors.Is(err, common.ErrQuotaExceeded):
  108. statusCode = http.StatusRequestEntityTooLarge
  109. case errors.Is(err, common.ErrOpUnsupported):
  110. statusCode = http.StatusBadRequest
  111. default:
  112. statusCode = http.StatusInternalServerError
  113. }
  114. return statusCode
  115. }
  116. func getURLParam(r *http.Request, key string) string {
  117. v := chi.URLParam(r, key)
  118. unescaped, err := url.PathUnescape(v)
  119. if err != nil {
  120. return v
  121. }
  122. return unescaped
  123. }
  124. func getCommaSeparatedQueryParam(r *http.Request, key string) []string {
  125. var result []string
  126. for _, val := range strings.Split(r.URL.Query().Get(key), ",") {
  127. val = strings.TrimSpace(val)
  128. if val != "" {
  129. result = append(result, val)
  130. }
  131. }
  132. return util.RemoveDuplicates(result, false)
  133. }
  134. func getBoolQueryParam(r *http.Request, param string) bool {
  135. return r.URL.Query().Get(param) == "true"
  136. }
  137. func handleCloseConnection(w http.ResponseWriter, r *http.Request) {
  138. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  139. connectionID := getURLParam(r, "connectionID")
  140. if connectionID == "" {
  141. sendAPIResponse(w, r, nil, "connectionID is mandatory", http.StatusBadRequest)
  142. return
  143. }
  144. if common.Connections.Close(connectionID) {
  145. sendAPIResponse(w, r, nil, "Connection closed", http.StatusOK)
  146. } else {
  147. sendAPIResponse(w, r, nil, "Not Found", http.StatusNotFound)
  148. }
  149. }
  150. func getSearchFilters(w http.ResponseWriter, r *http.Request) (int, int, string, error) {
  151. var err error
  152. limit := 100
  153. offset := 0
  154. order := dataprovider.OrderASC
  155. if _, ok := r.URL.Query()["limit"]; ok {
  156. limit, err = strconv.Atoi(r.URL.Query().Get("limit"))
  157. if err != nil {
  158. err = errors.New("invalid limit")
  159. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  160. return limit, offset, order, err
  161. }
  162. if limit > 500 {
  163. limit = 500
  164. }
  165. }
  166. if _, ok := r.URL.Query()["offset"]; ok {
  167. offset, err = strconv.Atoi(r.URL.Query().Get("offset"))
  168. if err != nil {
  169. err = errors.New("invalid offset")
  170. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  171. return limit, offset, order, err
  172. }
  173. }
  174. if _, ok := r.URL.Query()["order"]; ok {
  175. order = r.URL.Query().Get("order")
  176. if order != dataprovider.OrderASC && order != dataprovider.OrderDESC {
  177. err = errors.New("invalid order")
  178. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  179. return limit, offset, order, err
  180. }
  181. }
  182. return limit, offset, order, err
  183. }
  184. func renderAPIDirContents(w http.ResponseWriter, r *http.Request, contents []os.FileInfo, omitNonRegularFiles bool) {
  185. results := make([]map[string]any, 0, len(contents))
  186. for _, info := range contents {
  187. if omitNonRegularFiles && !info.Mode().IsDir() && !info.Mode().IsRegular() {
  188. continue
  189. }
  190. res := make(map[string]any)
  191. res["name"] = info.Name()
  192. if info.Mode().IsRegular() {
  193. res["size"] = info.Size()
  194. }
  195. res["mode"] = info.Mode()
  196. res["last_modified"] = info.ModTime().UTC().Format(time.RFC3339)
  197. results = append(results, res)
  198. }
  199. render.JSON(w, r, results)
  200. }
  201. func renderCompressedFiles(w http.ResponseWriter, conn *Connection, baseDir string, files []string,
  202. share *dataprovider.Share,
  203. ) {
  204. w.Header().Set("Content-Type", "application/zip")
  205. w.Header().Set("Accept-Ranges", "none")
  206. w.Header().Set("Content-Transfer-Encoding", "binary")
  207. w.WriteHeader(http.StatusOK)
  208. wr := zip.NewWriter(w)
  209. for _, file := range files {
  210. fullPath := util.CleanPath(path.Join(baseDir, file))
  211. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  212. if share != nil {
  213. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  214. }
  215. panic(http.ErrAbortHandler)
  216. }
  217. }
  218. if err := wr.Close(); err != nil {
  219. conn.Log(logger.LevelError, "unable to close zip file: %v", err)
  220. if share != nil {
  221. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  222. }
  223. panic(http.ErrAbortHandler)
  224. }
  225. }
  226. func addZipEntry(wr *zip.Writer, conn *Connection, entryPath, baseDir string) error {
  227. info, err := conn.Stat(entryPath, 1)
  228. if err != nil {
  229. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, stat error: %v", entryPath, err)
  230. return err
  231. }
  232. if info.IsDir() {
  233. _, err := wr.CreateHeader(&zip.FileHeader{
  234. Name: getZipEntryName(entryPath, baseDir) + "/",
  235. Method: zip.Deflate,
  236. Modified: info.ModTime(),
  237. })
  238. if err != nil {
  239. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  240. return err
  241. }
  242. contents, err := conn.ReadDir(entryPath)
  243. if err != nil {
  244. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, read dir error: %v", entryPath, err)
  245. return err
  246. }
  247. for _, info := range contents {
  248. fullPath := util.CleanPath(path.Join(entryPath, info.Name()))
  249. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  250. return err
  251. }
  252. }
  253. return nil
  254. }
  255. if !info.Mode().IsRegular() {
  256. // we only allow regular files
  257. conn.Log(logger.LevelDebug, "skipping zip entry for non regular file %#v", entryPath)
  258. return nil
  259. }
  260. reader, err := conn.getFileReader(entryPath, 0, http.MethodGet)
  261. if err != nil {
  262. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, cannot open file: %v", entryPath, err)
  263. return err
  264. }
  265. defer reader.Close()
  266. f, err := wr.CreateHeader(&zip.FileHeader{
  267. Name: getZipEntryName(entryPath, baseDir),
  268. Method: zip.Deflate,
  269. Modified: info.ModTime(),
  270. })
  271. if err != nil {
  272. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  273. return err
  274. }
  275. _, err = io.Copy(f, reader)
  276. return err
  277. }
  278. func getZipEntryName(entryPath, baseDir string) string {
  279. entryPath = strings.TrimPrefix(entryPath, baseDir)
  280. return strings.TrimPrefix(entryPath, "/")
  281. }
  282. func checkDownloadFileFromShare(share *dataprovider.Share, info os.FileInfo) error {
  283. if share != nil && !info.Mode().IsRegular() {
  284. return util.NewValidationError("non regular files are not supported for shares")
  285. }
  286. return nil
  287. }
  288. func downloadFile(w http.ResponseWriter, r *http.Request, connection *Connection, name string,
  289. info os.FileInfo, inline bool, share *dataprovider.Share,
  290. ) (int, error) {
  291. err := checkDownloadFileFromShare(share, info)
  292. if err != nil {
  293. return http.StatusBadRequest, err
  294. }
  295. rangeHeader := r.Header.Get("Range")
  296. if rangeHeader != "" && checkIfRange(r, info.ModTime()) == condFalse {
  297. rangeHeader = ""
  298. }
  299. offset := int64(0)
  300. size := info.Size()
  301. responseStatus := http.StatusOK
  302. if strings.HasPrefix(rangeHeader, "bytes=") {
  303. if strings.Contains(rangeHeader, ",") {
  304. return http.StatusRequestedRangeNotSatisfiable, fmt.Errorf("unsupported range %#v", rangeHeader)
  305. }
  306. offset, size, err = parseRangeRequest(rangeHeader[6:], size)
  307. if err != nil {
  308. return http.StatusRequestedRangeNotSatisfiable, err
  309. }
  310. responseStatus = http.StatusPartialContent
  311. }
  312. reader, err := connection.getFileReader(name, offset, r.Method)
  313. if err != nil {
  314. return getMappedStatusCode(err), fmt.Errorf("unable to read file %#v: %v", name, err)
  315. }
  316. defer reader.Close()
  317. w.Header().Set("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
  318. if checkPreconditions(w, r, info.ModTime()) {
  319. return 0, fmt.Errorf("%v", http.StatusText(http.StatusPreconditionFailed))
  320. }
  321. ctype := mime.TypeByExtension(path.Ext(name))
  322. if ctype == "" {
  323. ctype = "application/octet-stream"
  324. }
  325. if responseStatus == http.StatusPartialContent {
  326. w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, info.Size()))
  327. }
  328. w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
  329. w.Header().Set("Content-Type", ctype)
  330. if !inline {
  331. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%#v", path.Base(name)))
  332. }
  333. w.Header().Set("Accept-Ranges", "bytes")
  334. w.WriteHeader(responseStatus)
  335. if r.Method != http.MethodHead {
  336. _, err = io.CopyN(w, reader, size)
  337. if err != nil {
  338. if share != nil {
  339. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  340. }
  341. connection.Log(logger.LevelDebug, "error reading file to download: %v", err)
  342. panic(http.ErrAbortHandler)
  343. }
  344. }
  345. return http.StatusOK, nil
  346. }
  347. func checkPreconditions(w http.ResponseWriter, r *http.Request, modtime time.Time) bool {
  348. if checkIfUnmodifiedSince(r, modtime) == condFalse {
  349. w.WriteHeader(http.StatusPreconditionFailed)
  350. return true
  351. }
  352. if checkIfModifiedSince(r, modtime) == condFalse {
  353. w.WriteHeader(http.StatusNotModified)
  354. return true
  355. }
  356. return false
  357. }
  358. func checkIfUnmodifiedSince(r *http.Request, modtime time.Time) condResult {
  359. ius := r.Header.Get("If-Unmodified-Since")
  360. if ius == "" || isZeroTime(modtime) {
  361. return condNone
  362. }
  363. t, err := http.ParseTime(ius)
  364. if err != nil {
  365. return condNone
  366. }
  367. // The Last-Modified header truncates sub-second precision so
  368. // the modtime needs to be truncated too.
  369. modtime = modtime.Truncate(time.Second)
  370. if modtime.Before(t) || modtime.Equal(t) {
  371. return condTrue
  372. }
  373. return condFalse
  374. }
  375. func checkIfModifiedSince(r *http.Request, modtime time.Time) condResult {
  376. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  377. return condNone
  378. }
  379. ims := r.Header.Get("If-Modified-Since")
  380. if ims == "" || isZeroTime(modtime) {
  381. return condNone
  382. }
  383. t, err := http.ParseTime(ims)
  384. if err != nil {
  385. return condNone
  386. }
  387. // The Last-Modified header truncates sub-second precision so
  388. // the modtime needs to be truncated too.
  389. modtime = modtime.Truncate(time.Second)
  390. if modtime.Before(t) || modtime.Equal(t) {
  391. return condFalse
  392. }
  393. return condTrue
  394. }
  395. func checkIfRange(r *http.Request, modtime time.Time) condResult {
  396. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  397. return condNone
  398. }
  399. ir := r.Header.Get("If-Range")
  400. if ir == "" {
  401. return condNone
  402. }
  403. if modtime.IsZero() {
  404. return condFalse
  405. }
  406. t, err := http.ParseTime(ir)
  407. if err != nil {
  408. return condFalse
  409. }
  410. if modtime.Unix() == t.Unix() {
  411. return condTrue
  412. }
  413. return condFalse
  414. }
  415. func parseRangeRequest(bytesRange string, size int64) (int64, int64, error) {
  416. var start, end int64
  417. var err error
  418. values := strings.Split(bytesRange, "-")
  419. if values[0] == "" {
  420. start = -1
  421. } else {
  422. start, err = strconv.ParseInt(values[0], 10, 64)
  423. if err != nil {
  424. return start, size, err
  425. }
  426. }
  427. if len(values) >= 2 {
  428. if values[1] != "" {
  429. end, err = strconv.ParseInt(values[1], 10, 64)
  430. if err != nil {
  431. return start, size, err
  432. }
  433. if end >= size {
  434. end = size - 1
  435. }
  436. }
  437. }
  438. if start == -1 && end == 0 {
  439. return 0, 0, fmt.Errorf("unsupported range %#v", bytesRange)
  440. }
  441. if end > 0 {
  442. if start == -1 {
  443. // we have something like -500
  444. start = size - end
  445. size = end
  446. // start cannot be < 0 here, we did end = size -1 above
  447. } else {
  448. // we have something like 500-600
  449. size = end - start + 1
  450. if size < 0 {
  451. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  452. }
  453. }
  454. return start, size, nil
  455. }
  456. // we have something like 500-
  457. size -= start
  458. if size < 0 {
  459. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  460. }
  461. return start, size, err
  462. }
  463. func updateLoginMetrics(user *dataprovider.User, loginMethod, ip string, err error) {
  464. metric.AddLoginAttempt(loginMethod)
  465. var protocol string
  466. switch loginMethod {
  467. case dataprovider.LoginMethodIDP:
  468. protocol = common.ProtocolOIDC
  469. default:
  470. protocol = common.ProtocolHTTP
  471. }
  472. if err != nil && err != common.ErrInternalFailure && err != common.ErrNoCredentials {
  473. logger.ConnectionFailedLog(user.Username, ip, loginMethod, protocol, err.Error())
  474. event := common.HostEventLoginFailed
  475. if _, ok := err.(*util.RecordNotFoundError); ok {
  476. event = common.HostEventUserNotFound
  477. }
  478. common.AddDefenderEvent(ip, event)
  479. }
  480. metric.AddLoginResult(loginMethod, err)
  481. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, protocol, err)
  482. }
  483. func checkHTTPClientUser(user *dataprovider.User, r *http.Request, connectionID string, checkSessions bool) error {
  484. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolHTTP) {
  485. logger.Info(logSender, connectionID, "cannot login user %#v, protocol HTTP is not allowed", user.Username)
  486. return fmt.Errorf("protocol HTTP is not allowed for user %#v", user.Username)
  487. }
  488. if !isLoggedInWithOIDC(r) && !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, common.ProtocolHTTP, nil) {
  489. logger.Info(logSender, connectionID, "cannot login user %#v, password login method is not allowed", user.Username)
  490. return fmt.Errorf("login method password is not allowed for user %#v", user.Username)
  491. }
  492. if checkSessions && user.MaxSessions > 0 {
  493. activeSessions := common.Connections.GetActiveSessions(user.Username)
  494. if activeSessions >= user.MaxSessions {
  495. logger.Info(logSender, connectionID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  496. activeSessions, user.MaxSessions)
  497. return fmt.Errorf("too many open sessions: %v", activeSessions)
  498. }
  499. }
  500. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  501. logger.Info(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, r.RemoteAddr)
  502. return fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, r.RemoteAddr)
  503. }
  504. return nil
  505. }
  506. func handleForgotPassword(r *http.Request, username string, isAdmin bool) error {
  507. var email, subject string
  508. var err error
  509. var admin dataprovider.Admin
  510. var user dataprovider.User
  511. if username == "" {
  512. return util.NewValidationError("username is mandatory")
  513. }
  514. if isAdmin {
  515. admin, err = dataprovider.AdminExists(username)
  516. email = admin.Email
  517. subject = fmt.Sprintf("Email Verification Code for admin %#v", username)
  518. } else {
  519. user, err = dataprovider.GetUserWithGroupSettings(username)
  520. email = user.Email
  521. subject = fmt.Sprintf("Email Verification Code for user %#v", username)
  522. if err == nil {
  523. if !isUserAllowedToResetPassword(r, &user) {
  524. return util.NewValidationError("you are not allowed to reset your password")
  525. }
  526. }
  527. }
  528. if err != nil {
  529. if _, ok := err.(*util.RecordNotFoundError); ok {
  530. logger.Debug(logSender, middleware.GetReqID(r.Context()), "username %#v does not exists, reset password request silently ignored, is admin? %v",
  531. username, isAdmin)
  532. return nil
  533. }
  534. return util.NewGenericError("Error retrieving your account, please try again later")
  535. }
  536. if email == "" {
  537. return util.NewValidationError("Your account does not have an email address, it is not possible to reset your password by sending an email verification code")
  538. }
  539. c := newResetCode(username, isAdmin)
  540. body := new(bytes.Buffer)
  541. data := make(map[string]string)
  542. data["Code"] = c.Code
  543. if err := smtp.RenderPasswordResetTemplate(body, data); err != nil {
  544. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to render password reset template: %v", err)
  545. return util.NewGenericError("Unable to render password reset template")
  546. }
  547. startTime := time.Now()
  548. if err := smtp.SendEmail([]string{email}, subject, body.String(), smtp.EmailContentTypeTextHTML); err != nil {
  549. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to send password reset code via email: %v, elapsed: %v",
  550. err, time.Since(startTime))
  551. return util.NewGenericError(fmt.Sprintf("Unable to send confirmation code via email: %v", err))
  552. }
  553. logger.Debug(logSender, middleware.GetReqID(r.Context()), "reset code sent via email to %#v, email: %#v, is admin? %v, elapsed: %v",
  554. username, email, isAdmin, time.Since(startTime))
  555. return resetCodesMgr.Add(c)
  556. }
  557. func handleResetPassword(r *http.Request, code, newPassword string, isAdmin bool) (
  558. *dataprovider.Admin, *dataprovider.User, error,
  559. ) {
  560. var admin dataprovider.Admin
  561. var user dataprovider.User
  562. var err error
  563. if newPassword == "" {
  564. return &admin, &user, util.NewValidationError("please set a password")
  565. }
  566. if code == "" {
  567. return &admin, &user, util.NewValidationError("please set a confirmation code")
  568. }
  569. resetCode, err := resetCodesMgr.Get(code)
  570. if err != nil {
  571. return &admin, &user, util.NewValidationError("confirmation code not found")
  572. }
  573. if resetCode.IsAdmin != isAdmin {
  574. return &admin, &user, util.NewValidationError("invalid confirmation code")
  575. }
  576. if isAdmin {
  577. admin, err = dataprovider.AdminExists(resetCode.Username)
  578. if err != nil {
  579. return &admin, &user, util.NewValidationError("unable to associate the confirmation code with an existing admin")
  580. }
  581. admin.Password = newPassword
  582. err = dataprovider.UpdateAdmin(&admin, dataprovider.ActionExecutorSelf, util.GetIPFromRemoteAddress(r.RemoteAddr))
  583. if err != nil {
  584. return &admin, &user, util.NewGenericError(fmt.Sprintf("unable to set the new password: %v", err))
  585. }
  586. err = resetCodesMgr.Delete(code)
  587. return &admin, &user, err
  588. }
  589. user, err = dataprovider.GetUserWithGroupSettings(resetCode.Username)
  590. if err != nil {
  591. return &admin, &user, util.NewValidationError("Unable to associate the confirmation code with an existing user")
  592. }
  593. if err == nil {
  594. if !isUserAllowedToResetPassword(r, &user) {
  595. return &admin, &user, util.NewValidationError("you are not allowed to reset your password")
  596. }
  597. }
  598. err = dataprovider.UpdateUserPassword(user.Username, newPassword, dataprovider.ActionExecutorSelf,
  599. util.GetIPFromRemoteAddress(r.RemoteAddr))
  600. if err == nil {
  601. err = resetCodesMgr.Delete(code)
  602. }
  603. return &admin, &user, err
  604. }
  605. func isUserAllowedToResetPassword(r *http.Request, user *dataprovider.User) bool {
  606. if !user.CanResetPassword() {
  607. return false
  608. }
  609. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolHTTP) {
  610. return false
  611. }
  612. if !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, common.ProtocolHTTP, nil) {
  613. return false
  614. }
  615. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  616. return false
  617. }
  618. return true
  619. }
  620. func getProtocolFromRequest(r *http.Request) string {
  621. if isLoggedInWithOIDC(r) {
  622. return common.ProtocolOIDC
  623. }
  624. return common.ProtocolHTTP
  625. }