api_utils.go 20 KB

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