api_utils.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 getCompressedFileName(username string, files []string) string {
  202. if len(files) == 1 {
  203. name := path.Base(files[0])
  204. return fmt.Sprintf("%s-%s.zip", username, strings.TrimSuffix(name, path.Ext(name)))
  205. }
  206. return fmt.Sprintf("%s-download.zip", username)
  207. }
  208. func renderCompressedFiles(w http.ResponseWriter, conn *Connection, baseDir string, files []string,
  209. share *dataprovider.Share,
  210. ) {
  211. conn.User.CheckFsRoot(conn.ID) //nolint:errcheck
  212. w.Header().Set("Content-Type", "application/zip")
  213. w.Header().Set("Accept-Ranges", "none")
  214. w.Header().Set("Content-Transfer-Encoding", "binary")
  215. w.WriteHeader(http.StatusOK)
  216. wr := zip.NewWriter(w)
  217. for _, file := range files {
  218. fullPath := util.CleanPath(path.Join(baseDir, file))
  219. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  220. if share != nil {
  221. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  222. }
  223. panic(http.ErrAbortHandler)
  224. }
  225. }
  226. if err := wr.Close(); err != nil {
  227. conn.Log(logger.LevelError, "unable to close zip file: %v", err)
  228. if share != nil {
  229. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  230. }
  231. panic(http.ErrAbortHandler)
  232. }
  233. }
  234. func addZipEntry(wr *zip.Writer, conn *Connection, entryPath, baseDir string) error {
  235. info, err := conn.Stat(entryPath, 1)
  236. if err != nil {
  237. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, stat error: %v", entryPath, err)
  238. return err
  239. }
  240. if info.IsDir() {
  241. _, err := wr.CreateHeader(&zip.FileHeader{
  242. Name: getZipEntryName(entryPath, baseDir) + "/",
  243. Method: zip.Deflate,
  244. Modified: info.ModTime(),
  245. })
  246. if err != nil {
  247. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  248. return err
  249. }
  250. contents, err := conn.ReadDir(entryPath)
  251. if err != nil {
  252. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, read dir error: %v", entryPath, err)
  253. return err
  254. }
  255. for _, info := range contents {
  256. fullPath := util.CleanPath(path.Join(entryPath, info.Name()))
  257. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  258. return err
  259. }
  260. }
  261. return nil
  262. }
  263. if !info.Mode().IsRegular() {
  264. // we only allow regular files
  265. conn.Log(logger.LevelDebug, "skipping zip entry for non regular file %#v", entryPath)
  266. return nil
  267. }
  268. reader, err := conn.getFileReader(entryPath, 0, http.MethodGet)
  269. if err != nil {
  270. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, cannot open file: %v", entryPath, err)
  271. return err
  272. }
  273. defer reader.Close()
  274. f, err := wr.CreateHeader(&zip.FileHeader{
  275. Name: getZipEntryName(entryPath, baseDir),
  276. Method: zip.Deflate,
  277. Modified: info.ModTime(),
  278. })
  279. if err != nil {
  280. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  281. return err
  282. }
  283. _, err = io.Copy(f, reader)
  284. return err
  285. }
  286. func getZipEntryName(entryPath, baseDir string) string {
  287. entryPath = strings.TrimPrefix(entryPath, baseDir)
  288. return strings.TrimPrefix(entryPath, "/")
  289. }
  290. func checkDownloadFileFromShare(share *dataprovider.Share, info os.FileInfo) error {
  291. if share != nil && !info.Mode().IsRegular() {
  292. return util.NewValidationError("non regular files are not supported for shares")
  293. }
  294. return nil
  295. }
  296. func downloadFile(w http.ResponseWriter, r *http.Request, connection *Connection, name string,
  297. info os.FileInfo, inline bool, share *dataprovider.Share,
  298. ) (int, error) {
  299. connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
  300. err := checkDownloadFileFromShare(share, info)
  301. if err != nil {
  302. return http.StatusBadRequest, err
  303. }
  304. rangeHeader := r.Header.Get("Range")
  305. if rangeHeader != "" && checkIfRange(r, info.ModTime()) == condFalse {
  306. rangeHeader = ""
  307. }
  308. offset := int64(0)
  309. size := info.Size()
  310. responseStatus := http.StatusOK
  311. if strings.HasPrefix(rangeHeader, "bytes=") {
  312. if strings.Contains(rangeHeader, ",") {
  313. return http.StatusRequestedRangeNotSatisfiable, fmt.Errorf("unsupported range %#v", rangeHeader)
  314. }
  315. offset, size, err = parseRangeRequest(rangeHeader[6:], size)
  316. if err != nil {
  317. return http.StatusRequestedRangeNotSatisfiable, err
  318. }
  319. responseStatus = http.StatusPartialContent
  320. }
  321. reader, err := connection.getFileReader(name, offset, r.Method)
  322. if err != nil {
  323. return getMappedStatusCode(err), fmt.Errorf("unable to read file %#v: %v", name, err)
  324. }
  325. defer reader.Close()
  326. w.Header().Set("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
  327. if checkPreconditions(w, r, info.ModTime()) {
  328. return 0, fmt.Errorf("%v", http.StatusText(http.StatusPreconditionFailed))
  329. }
  330. ctype := mime.TypeByExtension(path.Ext(name))
  331. if ctype == "" {
  332. ctype = "application/octet-stream"
  333. }
  334. if responseStatus == http.StatusPartialContent {
  335. w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, info.Size()))
  336. }
  337. w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
  338. w.Header().Set("Content-Type", ctype)
  339. if !inline {
  340. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%#v", path.Base(name)))
  341. }
  342. w.Header().Set("Accept-Ranges", "bytes")
  343. w.WriteHeader(responseStatus)
  344. if r.Method != http.MethodHead {
  345. _, err = io.CopyN(w, reader, size)
  346. if err != nil {
  347. if share != nil {
  348. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  349. }
  350. connection.Log(logger.LevelDebug, "error reading file to download: %v", err)
  351. panic(http.ErrAbortHandler)
  352. }
  353. }
  354. return http.StatusOK, nil
  355. }
  356. func checkPreconditions(w http.ResponseWriter, r *http.Request, modtime time.Time) bool {
  357. if checkIfUnmodifiedSince(r, modtime) == condFalse {
  358. w.WriteHeader(http.StatusPreconditionFailed)
  359. return true
  360. }
  361. if checkIfModifiedSince(r, modtime) == condFalse {
  362. w.WriteHeader(http.StatusNotModified)
  363. return true
  364. }
  365. return false
  366. }
  367. func checkIfUnmodifiedSince(r *http.Request, modtime time.Time) condResult {
  368. ius := r.Header.Get("If-Unmodified-Since")
  369. if ius == "" || isZeroTime(modtime) {
  370. return condNone
  371. }
  372. t, err := http.ParseTime(ius)
  373. if err != nil {
  374. return condNone
  375. }
  376. // The Last-Modified header truncates sub-second precision so
  377. // the modtime needs to be truncated too.
  378. modtime = modtime.Truncate(time.Second)
  379. if modtime.Before(t) || modtime.Equal(t) {
  380. return condTrue
  381. }
  382. return condFalse
  383. }
  384. func checkIfModifiedSince(r *http.Request, modtime time.Time) condResult {
  385. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  386. return condNone
  387. }
  388. ims := r.Header.Get("If-Modified-Since")
  389. if ims == "" || isZeroTime(modtime) {
  390. return condNone
  391. }
  392. t, err := http.ParseTime(ims)
  393. if err != nil {
  394. return condNone
  395. }
  396. // The Last-Modified header truncates sub-second precision so
  397. // the modtime needs to be truncated too.
  398. modtime = modtime.Truncate(time.Second)
  399. if modtime.Before(t) || modtime.Equal(t) {
  400. return condFalse
  401. }
  402. return condTrue
  403. }
  404. func checkIfRange(r *http.Request, modtime time.Time) condResult {
  405. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  406. return condNone
  407. }
  408. ir := r.Header.Get("If-Range")
  409. if ir == "" {
  410. return condNone
  411. }
  412. if modtime.IsZero() {
  413. return condFalse
  414. }
  415. t, err := http.ParseTime(ir)
  416. if err != nil {
  417. return condFalse
  418. }
  419. if modtime.Unix() == t.Unix() {
  420. return condTrue
  421. }
  422. return condFalse
  423. }
  424. func parseRangeRequest(bytesRange string, size int64) (int64, int64, error) {
  425. var start, end int64
  426. var err error
  427. values := strings.Split(bytesRange, "-")
  428. if values[0] == "" {
  429. start = -1
  430. } else {
  431. start, err = strconv.ParseInt(values[0], 10, 64)
  432. if err != nil {
  433. return start, size, err
  434. }
  435. }
  436. if len(values) >= 2 {
  437. if values[1] != "" {
  438. end, err = strconv.ParseInt(values[1], 10, 64)
  439. if err != nil {
  440. return start, size, err
  441. }
  442. if end >= size {
  443. end = size - 1
  444. }
  445. }
  446. }
  447. if start == -1 && end == 0 {
  448. return 0, 0, fmt.Errorf("unsupported range %#v", bytesRange)
  449. }
  450. if end > 0 {
  451. if start == -1 {
  452. // we have something like -500
  453. start = size - end
  454. size = end
  455. // start cannit be < 0 here, we did end = size -1 above
  456. } else {
  457. // we have something like 500-600
  458. size = end - start + 1
  459. if size < 0 {
  460. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  461. }
  462. }
  463. return start, size, nil
  464. }
  465. // we have something like 500-
  466. size -= start
  467. if size < 0 {
  468. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  469. }
  470. return start, size, err
  471. }
  472. func updateLoginMetrics(user *dataprovider.User, loginMethod, ip string, err error) {
  473. metric.AddLoginAttempt(loginMethod)
  474. var protocol string
  475. switch loginMethod {
  476. case dataprovider.LoginMethodIDP:
  477. protocol = common.ProtocolOIDC
  478. default:
  479. protocol = common.ProtocolHTTP
  480. }
  481. if err != nil && err != common.ErrInternalFailure && err != common.ErrNoCredentials {
  482. logger.ConnectionFailedLog(user.Username, ip, loginMethod, protocol, err.Error())
  483. event := common.HostEventLoginFailed
  484. if _, ok := err.(*util.RecordNotFoundError); ok {
  485. event = common.HostEventUserNotFound
  486. }
  487. common.AddDefenderEvent(ip, event)
  488. }
  489. metric.AddLoginResult(loginMethod, err)
  490. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, protocol, err)
  491. }
  492. func checkHTTPClientUser(user *dataprovider.User, r *http.Request, connectionID string, checkSessions bool) error {
  493. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolHTTP) {
  494. logger.Info(logSender, connectionID, "cannot login user %#v, protocol HTTP is not allowed", user.Username)
  495. return fmt.Errorf("protocol HTTP is not allowed for user %#v", user.Username)
  496. }
  497. if !isLoggedInWithOIDC(r) && !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, common.ProtocolHTTP, nil) {
  498. logger.Info(logSender, connectionID, "cannot login user %#v, password login method is not allowed", user.Username)
  499. return fmt.Errorf("login method password is not allowed for user %#v", user.Username)
  500. }
  501. if checkSessions && user.MaxSessions > 0 {
  502. activeSessions := common.Connections.GetActiveSessions(user.Username)
  503. if activeSessions >= user.MaxSessions {
  504. logger.Info(logSender, connectionID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  505. activeSessions, user.MaxSessions)
  506. return fmt.Errorf("too many open sessions: %v", activeSessions)
  507. }
  508. }
  509. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  510. logger.Info(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, r.RemoteAddr)
  511. return fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, r.RemoteAddr)
  512. }
  513. return nil
  514. }
  515. func handleForgotPassword(r *http.Request, username string, isAdmin bool) error {
  516. var email, subject string
  517. var err error
  518. var admin dataprovider.Admin
  519. var user dataprovider.User
  520. if username == "" {
  521. return util.NewValidationError("username is mandatory")
  522. }
  523. if isAdmin {
  524. admin, err = dataprovider.AdminExists(username)
  525. email = admin.Email
  526. subject = fmt.Sprintf("Email Verification Code for admin %#v", username)
  527. } else {
  528. user, err = dataprovider.GetUserWithGroupSettings(username)
  529. email = user.Email
  530. subject = fmt.Sprintf("Email Verification Code for user %#v", username)
  531. if err == nil {
  532. if !isUserAllowedToResetPassword(r, &user) {
  533. return util.NewValidationError("you are not allowed to reset your password")
  534. }
  535. }
  536. }
  537. if err != nil {
  538. if _, ok := err.(*util.RecordNotFoundError); ok {
  539. logger.Debug(logSender, middleware.GetReqID(r.Context()), "username %#v does not exists, reset password request silently ignored, is admin? %v",
  540. username, isAdmin)
  541. return nil
  542. }
  543. return util.NewGenericError("Error retrieving your account, please try again later")
  544. }
  545. if email == "" {
  546. 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")
  547. }
  548. c := newResetCode(username, isAdmin)
  549. body := new(bytes.Buffer)
  550. data := make(map[string]string)
  551. data["Code"] = c.Code
  552. if err := smtp.RenderPasswordResetTemplate(body, data); err != nil {
  553. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to render password reset template: %v", err)
  554. return util.NewGenericError("Unable to render password reset template")
  555. }
  556. startTime := time.Now()
  557. if err := smtp.SendEmail(email, subject, body.String(), smtp.EmailContentTypeTextHTML); err != nil {
  558. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to send password reset code via email: %v, elapsed: %v",
  559. err, time.Since(startTime))
  560. return util.NewGenericError(fmt.Sprintf("Unable to send confirmation code via email: %v", err))
  561. }
  562. logger.Debug(logSender, middleware.GetReqID(r.Context()), "reset code sent via email to %#v, email: %#v, is admin? %v, elapsed: %v",
  563. username, email, isAdmin, time.Since(startTime))
  564. return resetCodesMgr.Add(c)
  565. }
  566. func handleResetPassword(r *http.Request, code, newPassword string, isAdmin bool) (
  567. *dataprovider.Admin, *dataprovider.User, error,
  568. ) {
  569. var admin dataprovider.Admin
  570. var user dataprovider.User
  571. var err error
  572. if newPassword == "" {
  573. return &admin, &user, util.NewValidationError("please set a password")
  574. }
  575. if code == "" {
  576. return &admin, &user, util.NewValidationError("please set a confirmation code")
  577. }
  578. resetCode, err := resetCodesMgr.Get(code)
  579. if err != nil {
  580. return &admin, &user, util.NewValidationError("confirmation code not found")
  581. }
  582. if resetCode.IsAdmin != isAdmin {
  583. return &admin, &user, util.NewValidationError("invalid confirmation code")
  584. }
  585. if isAdmin {
  586. admin, err = dataprovider.AdminExists(resetCode.Username)
  587. if err != nil {
  588. return &admin, &user, util.NewValidationError("unable to associate the confirmation code with an existing admin")
  589. }
  590. admin.Password = newPassword
  591. err = dataprovider.UpdateAdmin(&admin, dataprovider.ActionExecutorSelf, util.GetIPFromRemoteAddress(r.RemoteAddr))
  592. if err != nil {
  593. return &admin, &user, util.NewGenericError(fmt.Sprintf("unable to set the new password: %v", err))
  594. }
  595. err = resetCodesMgr.Delete(code)
  596. return &admin, &user, err
  597. }
  598. user, err = dataprovider.GetUserWithGroupSettings(resetCode.Username)
  599. if err != nil {
  600. return &admin, &user, util.NewValidationError("Unable to associate the confirmation code with an existing user")
  601. }
  602. if err == nil {
  603. if !isUserAllowedToResetPassword(r, &user) {
  604. return &admin, &user, util.NewValidationError("you are not allowed to reset your password")
  605. }
  606. }
  607. err = dataprovider.UpdateUserPassword(user.Username, newPassword, dataprovider.ActionExecutorSelf,
  608. util.GetIPFromRemoteAddress(r.RemoteAddr))
  609. if err == nil {
  610. err = resetCodesMgr.Delete(code)
  611. }
  612. return &admin, &user, err
  613. }
  614. func isUserAllowedToResetPassword(r *http.Request, user *dataprovider.User) bool {
  615. if !user.CanResetPassword() {
  616. return false
  617. }
  618. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolHTTP) {
  619. return false
  620. }
  621. if !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, common.ProtocolHTTP, nil) {
  622. return false
  623. }
  624. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  625. return false
  626. }
  627. return true
  628. }
  629. func getProtocolFromRequest(r *http.Request) string {
  630. if isLoggedInWithOIDC(r) {
  631. return common.ProtocolOIDC
  632. }
  633. return common.ProtocolHTTP
  634. }