123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815 |
- // Copyright (C) 2019-2023 Nicola Murino
- //
- // This program is free software: you can redistribute it and/or modify
- // it under the terms of the GNU Affero General Public License as published
- // by the Free Software Foundation, version 3.
- //
- // This program is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU Affero General Public License for more details.
- //
- // You should have received a copy of the GNU Affero General Public License
- // along with this program. If not, see <https://www.gnu.org/licenses/>.
- package httpd
- import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "html/template"
- "io"
- "math"
- "net/http"
- "net/url"
- "os"
- "path"
- "path/filepath"
- "strconv"
- "strings"
- "time"
- "github.com/go-chi/render"
- "github.com/rs/xid"
- "github.com/sftpgo/sdk"
- "github.com/drakkan/sftpgo/v2/internal/common"
- "github.com/drakkan/sftpgo/v2/internal/dataprovider"
- "github.com/drakkan/sftpgo/v2/internal/logger"
- "github.com/drakkan/sftpgo/v2/internal/mfa"
- "github.com/drakkan/sftpgo/v2/internal/smtp"
- "github.com/drakkan/sftpgo/v2/internal/util"
- "github.com/drakkan/sftpgo/v2/internal/version"
- "github.com/drakkan/sftpgo/v2/internal/vfs"
- )
- const (
- templateClientDir = "webclient"
- templateClientBase = "base.html"
- templateClientBaseLogin = "baselogin.html"
- templateClientLogin = "login.html"
- templateClientFiles = "files.html"
- templateClientMessage = "message.html"
- templateClientProfile = "profile.html"
- templateClientChangePwd = "changepassword.html"
- templateClientTwoFactor = "twofactor.html"
- templateClientTwoFactorRecovery = "twofactor-recovery.html"
- templateClientMFA = "mfa.html"
- templateClientEditFile = "editfile.html"
- templateClientShare = "share.html"
- templateClientShares = "shares.html"
- templateClientViewPDF = "viewpdf.html"
- templateShareLogin = "sharelogin.html"
- templateUploadToShare = "shareupload.html"
- pageClientFilesTitle = "Files"
- pageClientSharesTitle = "Shares"
- pageClientProfileTitle = "My Profile"
- pageClientChangePwdTitle = "Change password"
- pageClient2FATitle = "Two-factor auth"
- pageClientEditFileTitle = "Edit file"
- pageClientForgotPwdTitle = "SFTPGo WebClient - Forgot password"
- pageClientResetPwdTitle = "SFTPGo WebClient - Reset password"
- pageExtShareTitle = "Shared files"
- pageUploadToShareTitle = "Upload to share"
- )
- // condResult is the result of an HTTP request precondition check.
- // See https://tools.ietf.org/html/rfc7232 section 3.
- type condResult int
- const (
- condNone condResult = iota
- condTrue
- condFalse
- )
- var (
- clientTemplates = make(map[string]*template.Template)
- unixEpochTime = time.Unix(0, 0)
- )
- // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
- func isZeroTime(t time.Time) bool {
- return t.IsZero() || t.Equal(unixEpochTime)
- }
- type baseClientPage struct {
- Title string
- CurrentURL string
- FilesURL string
- SharesURL string
- ShareURL string
- ProfileURL string
- ChangePwdURL string
- StaticURL string
- LogoutURL string
- LoginURL string
- EditURL string
- MFAURL string
- MFATitle string
- FilesTitle string
- SharesTitle string
- ProfileTitle string
- Version string
- CSRFToken string
- LoggedUser *dataprovider.User
- Branding UIBranding
- }
- type dirMapping struct {
- DirName string
- Href string
- }
- type viewPDFPage struct {
- Title string
- URL string
- StaticURL string
- Branding UIBranding
- }
- type editFilePage struct {
- baseClientPage
- CurrentDir string
- FileURL string
- Path string
- Name string
- ReadOnly bool
- Data string
- }
- type filesPage struct {
- baseClientPage
- CurrentDir string
- DirsURL string
- FileActionsURL string
- DownloadURL string
- ViewPDFURL string
- FileURL string
- CanAddFiles bool
- CanCreateDirs bool
- CanRename bool
- CanDelete bool
- CanDownload bool
- CanShare bool
- ShareUploadBaseURL string
- Error string
- Paths []dirMapping
- HasIntegrations bool
- QuotaUsage *userQuotaUsage
- }
- type shareLoginPage struct {
- CurrentURL string
- Version string
- Error string
- CSRFToken string
- StaticURL string
- Branding UIBranding
- }
- type shareUploadPage struct {
- baseClientPage
- Share *dataprovider.Share
- UploadBasePath string
- }
- type clientMessagePage struct {
- baseClientPage
- Error string
- Success string
- }
- type clientProfilePage struct {
- baseClientPage
- PublicKeys []string
- CanSubmit bool
- AllowAPIKeyAuth bool
- Email string
- Description string
- Error string
- }
- type changeClientPasswordPage struct {
- baseClientPage
- Error string
- }
- type clientMFAPage struct {
- baseClientPage
- TOTPConfigs []string
- TOTPConfig dataprovider.UserTOTPConfig
- GenerateTOTPURL string
- ValidateTOTPURL string
- SaveTOTPURL string
- RecCodesURL string
- Protocols []string
- }
- type clientSharesPage struct {
- baseClientPage
- Shares []dataprovider.Share
- BasePublicSharesURL string
- }
- type clientSharePage struct {
- baseClientPage
- Share *dataprovider.Share
- Error string
- IsAdd bool
- }
- type userQuotaUsage struct {
- QuotaSize int64
- QuotaFiles int
- UsedQuotaSize int64
- UsedQuotaFiles int
- UploadDataTransfer int64
- DownloadDataTransfer int64
- TotalDataTransfer int64
- UsedUploadDataTransfer int64
- UsedDownloadDataTransfer int64
- }
- func (u *userQuotaUsage) HasQuotaInfo() bool {
- if dataprovider.GetQuotaTracking() == 0 {
- return false
- }
- if u.HasDiskQuota() {
- return true
- }
- return u.HasTranferQuota()
- }
- func (u *userQuotaUsage) HasDiskQuota() bool {
- if u.QuotaSize > 0 || u.UsedQuotaSize > 0 {
- return true
- }
- return u.QuotaFiles > 0 || u.UsedQuotaFiles > 0
- }
- func (u *userQuotaUsage) HasTranferQuota() bool {
- if u.TotalDataTransfer > 0 || u.UploadDataTransfer > 0 || u.DownloadDataTransfer > 0 {
- return true
- }
- return u.UsedDownloadDataTransfer > 0 || u.UsedUploadDataTransfer > 0
- }
- func (u *userQuotaUsage) GetQuotaSize() string {
- if u.QuotaSize > 0 {
- return fmt.Sprintf("%s/%s", util.ByteCountIEC(u.UsedQuotaSize), util.ByteCountIEC(u.QuotaSize))
- }
- if u.UsedQuotaSize > 0 {
- return util.ByteCountIEC(u.UsedQuotaSize)
- }
- return ""
- }
- func (u *userQuotaUsage) GetQuotaFiles() string {
- if u.QuotaFiles > 0 {
- return fmt.Sprintf("%d/%d", u.UsedQuotaFiles, u.QuotaFiles)
- }
- if u.UsedQuotaFiles > 0 {
- return strconv.FormatInt(int64(u.UsedQuotaFiles), 10)
- }
- return ""
- }
- func (u *userQuotaUsage) GetQuotaSizePercentage() int {
- if u.QuotaSize > 0 {
- return int(math.Round(100 * float64(u.UsedQuotaSize) / float64(u.QuotaSize)))
- }
- return 0
- }
- func (u *userQuotaUsage) GetQuotaFilesPercentage() int {
- if u.QuotaFiles > 0 {
- return int(math.Round(100 * float64(u.UsedQuotaFiles) / float64(u.QuotaFiles)))
- }
- return 0
- }
- func (u *userQuotaUsage) IsQuotaSizeLow() bool {
- return u.GetQuotaSizePercentage() > 85
- }
- func (u *userQuotaUsage) IsQuotaFilesLow() bool {
- return u.GetQuotaFilesPercentage() > 85
- }
- func (u *userQuotaUsage) IsDiskQuotaLow() bool {
- return u.IsQuotaSizeLow() || u.IsQuotaFilesLow()
- }
- func (u *userQuotaUsage) GetTotalTransferQuota() string {
- total := u.UsedUploadDataTransfer + u.UsedDownloadDataTransfer
- if u.TotalDataTransfer > 0 {
- return fmt.Sprintf("%s/%s", util.ByteCountIEC(total), util.ByteCountIEC(u.TotalDataTransfer*1048576))
- }
- if total > 0 {
- return util.ByteCountIEC(total)
- }
- return ""
- }
- func (u *userQuotaUsage) GetUploadTransferQuota() string {
- if u.UploadDataTransfer > 0 {
- return fmt.Sprintf("%s/%s", util.ByteCountIEC(u.UsedUploadDataTransfer),
- util.ByteCountIEC(u.UploadDataTransfer*1048576))
- }
- if u.UsedUploadDataTransfer > 0 {
- return util.ByteCountIEC(u.UsedUploadDataTransfer)
- }
- return ""
- }
- func (u *userQuotaUsage) GetDownloadTransferQuota() string {
- if u.DownloadDataTransfer > 0 {
- return fmt.Sprintf("%s/%s", util.ByteCountIEC(u.UsedDownloadDataTransfer),
- util.ByteCountIEC(u.DownloadDataTransfer*1048576))
- }
- if u.UsedDownloadDataTransfer > 0 {
- return util.ByteCountIEC(u.UsedDownloadDataTransfer)
- }
- return ""
- }
- func (u *userQuotaUsage) GetTotalTransferQuotaPercentage() int {
- if u.TotalDataTransfer > 0 {
- return int(math.Round(100 * float64(u.UsedDownloadDataTransfer+u.UsedUploadDataTransfer) / float64(u.TotalDataTransfer*1048576)))
- }
- return 0
- }
- func (u *userQuotaUsage) GetUploadTransferQuotaPercentage() int {
- if u.UploadDataTransfer > 0 {
- return int(math.Round(100 * float64(u.UsedUploadDataTransfer) / float64(u.UploadDataTransfer*1048576)))
- }
- return 0
- }
- func (u *userQuotaUsage) GetDownloadTransferQuotaPercentage() int {
- if u.DownloadDataTransfer > 0 {
- return int(math.Round(100 * float64(u.UsedDownloadDataTransfer) / float64(u.DownloadDataTransfer*1048576)))
- }
- return 0
- }
- func (u *userQuotaUsage) IsTotalTransferQuotaLow() bool {
- if u.TotalDataTransfer > 0 {
- return u.GetTotalTransferQuotaPercentage() > 85
- }
- return false
- }
- func (u *userQuotaUsage) IsUploadTransferQuotaLow() bool {
- if u.UploadDataTransfer > 0 {
- return u.GetUploadTransferQuotaPercentage() > 85
- }
- return false
- }
- func (u *userQuotaUsage) IsDownloadTransferQuotaLow() bool {
- if u.DownloadDataTransfer > 0 {
- return u.GetDownloadTransferQuotaPercentage() > 85
- }
- return false
- }
- func (u *userQuotaUsage) IsTransferQuotaLow() bool {
- return u.IsTotalTransferQuotaLow() || u.IsUploadTransferQuotaLow() || u.IsDownloadTransferQuotaLow()
- }
- func (u *userQuotaUsage) IsQuotaLow() bool {
- return u.IsDiskQuotaLow() || u.IsTransferQuotaLow()
- }
- func newUserQuotaUsage(u *dataprovider.User) *userQuotaUsage {
- return &userQuotaUsage{
- QuotaSize: u.QuotaSize,
- QuotaFiles: u.QuotaFiles,
- UsedQuotaSize: u.UsedQuotaSize,
- UsedQuotaFiles: u.UsedQuotaFiles,
- TotalDataTransfer: u.TotalDataTransfer,
- UploadDataTransfer: u.UploadDataTransfer,
- DownloadDataTransfer: u.DownloadDataTransfer,
- UsedUploadDataTransfer: u.UsedUploadDataTransfer,
- UsedDownloadDataTransfer: u.UsedDownloadDataTransfer,
- }
- }
- func getFileObjectURL(baseDir, name, baseWebPath string) string {
- return fmt.Sprintf("%v?path=%v&_=%v", baseWebPath, url.QueryEscape(path.Join(baseDir, name)), time.Now().UTC().Unix())
- }
- func getFileObjectModTime(t time.Time) string {
- if isZeroTime(t) {
- return ""
- }
- return t.Format("2006-01-02 15:04")
- }
- func loadClientTemplates(templatesPath string) {
- filesPaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientFiles),
- }
- editFilePath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientEditFile),
- }
- sharesPaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientShares),
- }
- sharePaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientShare),
- }
- profilePaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientProfile),
- }
- changePwdPaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientChangePwd),
- }
- loginPath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBaseLogin),
- filepath.Join(templatesPath, templateClientDir, templateClientLogin),
- }
- messagePath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientMessage),
- }
- mfaPath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateClientMFA),
- }
- twoFactorPath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBaseLogin),
- filepath.Join(templatesPath, templateClientDir, templateClientTwoFactor),
- }
- twoFactorRecoveryPath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBaseLogin),
- filepath.Join(templatesPath, templateClientDir, templateClientTwoFactorRecovery),
- }
- forgotPwdPaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBaseLogin),
- filepath.Join(templatesPath, templateClientDir, templateForgotPassword),
- }
- resetPwdPaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBaseLogin),
- filepath.Join(templatesPath, templateClientDir, templateResetPassword),
- }
- viewPDFPaths := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientViewPDF),
- }
- shareLoginPath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBaseLogin),
- filepath.Join(templatesPath, templateClientDir, templateShareLogin),
- }
- shareUploadPath := []string{
- filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
- filepath.Join(templatesPath, templateClientDir, templateClientBase),
- filepath.Join(templatesPath, templateClientDir, templateUploadToShare),
- }
- filesTmpl := util.LoadTemplate(nil, filesPaths...)
- profileTmpl := util.LoadTemplate(nil, profilePaths...)
- changePwdTmpl := util.LoadTemplate(nil, changePwdPaths...)
- loginTmpl := util.LoadTemplate(nil, loginPath...)
- messageTmpl := util.LoadTemplate(nil, messagePath...)
- mfaTmpl := util.LoadTemplate(nil, mfaPath...)
- twoFactorTmpl := util.LoadTemplate(nil, twoFactorPath...)
- twoFactorRecoveryTmpl := util.LoadTemplate(nil, twoFactorRecoveryPath...)
- editFileTmpl := util.LoadTemplate(nil, editFilePath...)
- shareLoginTmpl := util.LoadTemplate(nil, shareLoginPath...)
- sharesTmpl := util.LoadTemplate(nil, sharesPaths...)
- shareTmpl := util.LoadTemplate(nil, sharePaths...)
- forgotPwdTmpl := util.LoadTemplate(nil, forgotPwdPaths...)
- resetPwdTmpl := util.LoadTemplate(nil, resetPwdPaths...)
- viewPDFTmpl := util.LoadTemplate(nil, viewPDFPaths...)
- shareUploadTmpl := util.LoadTemplate(nil, shareUploadPath...)
- clientTemplates[templateClientFiles] = filesTmpl
- clientTemplates[templateClientProfile] = profileTmpl
- clientTemplates[templateClientChangePwd] = changePwdTmpl
- clientTemplates[templateClientLogin] = loginTmpl
- clientTemplates[templateClientMessage] = messageTmpl
- clientTemplates[templateClientMFA] = mfaTmpl
- clientTemplates[templateClientTwoFactor] = twoFactorTmpl
- clientTemplates[templateClientTwoFactorRecovery] = twoFactorRecoveryTmpl
- clientTemplates[templateClientEditFile] = editFileTmpl
- clientTemplates[templateClientShares] = sharesTmpl
- clientTemplates[templateClientShare] = shareTmpl
- clientTemplates[templateForgotPassword] = forgotPwdTmpl
- clientTemplates[templateResetPassword] = resetPwdTmpl
- clientTemplates[templateClientViewPDF] = viewPDFTmpl
- clientTemplates[templateShareLogin] = shareLoginTmpl
- clientTemplates[templateUploadToShare] = shareUploadTmpl
- }
- func (s *httpdServer) getBaseClientPageData(title, currentURL string, r *http.Request) baseClientPage {
- var csrfToken string
- if currentURL != "" {
- csrfToken = createCSRFToken(util.GetIPFromRemoteAddress(r.RemoteAddr))
- }
- v := version.Get()
- data := baseClientPage{
- Title: title,
- CurrentURL: currentURL,
- FilesURL: webClientFilesPath,
- SharesURL: webClientSharesPath,
- ShareURL: webClientSharePath,
- ProfileURL: webClientProfilePath,
- ChangePwdURL: webChangeClientPwdPath,
- StaticURL: webStaticFilesPath,
- LogoutURL: webClientLogoutPath,
- EditURL: webClientEditFilePath,
- MFAURL: webClientMFAPath,
- MFATitle: pageClient2FATitle,
- FilesTitle: pageClientFilesTitle,
- SharesTitle: pageClientSharesTitle,
- ProfileTitle: pageClientProfileTitle,
- Version: fmt.Sprintf("%v-%v", v.Version, v.CommitHash),
- CSRFToken: csrfToken,
- LoggedUser: getUserFromToken(r),
- Branding: s.binding.Branding.WebClient,
- }
- if !strings.HasPrefix(r.RequestURI, webClientPubSharesPath) {
- data.LoginURL = webClientLoginPath
- }
- return data
- }
- func (s *httpdServer) renderClientForgotPwdPage(w http.ResponseWriter, error, ip string) {
- data := forgotPwdPage{
- CurrentURL: webClientForgotPwdPath,
- Error: error,
- CSRFToken: createCSRFToken(ip),
- StaticURL: webStaticFilesPath,
- LoginURL: webClientLoginPath,
- Title: pageClientForgotPwdTitle,
- Branding: s.binding.Branding.WebClient,
- }
- renderClientTemplate(w, templateForgotPassword, data)
- }
- func (s *httpdServer) renderClientResetPwdPage(w http.ResponseWriter, _ *http.Request, error, ip string) {
- data := resetPwdPage{
- CurrentURL: webClientResetPwdPath,
- Error: error,
- CSRFToken: createCSRFToken(ip),
- StaticURL: webStaticFilesPath,
- LoginURL: webClientLoginPath,
- Title: pageClientResetPwdTitle,
- Branding: s.binding.Branding.WebClient,
- }
- renderClientTemplate(w, templateResetPassword, data)
- }
- func (s *httpdServer) renderShareLoginPage(w http.ResponseWriter, currentURL, error, ip string) {
- data := shareLoginPage{
- CurrentURL: currentURL,
- Version: version.Get().Version,
- Error: error,
- CSRFToken: createCSRFToken(ip),
- StaticURL: webStaticFilesPath,
- Branding: s.binding.Branding.WebClient,
- }
- renderClientTemplate(w, templateShareLogin, data)
- }
- func renderClientTemplate(w http.ResponseWriter, tmplName string, data any) {
- err := clientTemplates[tmplName].ExecuteTemplate(w, tmplName, data)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- }
- }
- func (s *httpdServer) renderClientMessagePage(w http.ResponseWriter, r *http.Request, title, body string, statusCode int, err error, message string) {
- var errorString strings.Builder
- if body != "" {
- errorString.WriteString(body)
- errorString.WriteString(" ")
- }
- if err != nil {
- errorString.WriteString(err.Error())
- }
- data := clientMessagePage{
- baseClientPage: s.getBaseClientPageData(title, "", r),
- Error: errorString.String(),
- Success: message,
- }
- w.WriteHeader(statusCode)
- renderClientTemplate(w, templateClientMessage, data)
- }
- func (s *httpdServer) renderClientInternalServerErrorPage(w http.ResponseWriter, r *http.Request, err error) {
- s.renderClientMessagePage(w, r, page500Title, page500Body, http.StatusInternalServerError, err, "")
- }
- func (s *httpdServer) renderClientBadRequestPage(w http.ResponseWriter, r *http.Request, err error) {
- s.renderClientMessagePage(w, r, page400Title, "", http.StatusBadRequest, err, "")
- }
- func (s *httpdServer) renderClientForbiddenPage(w http.ResponseWriter, r *http.Request, body string) {
- s.renderClientMessagePage(w, r, page403Title, "", http.StatusForbidden, nil, body)
- }
- func (s *httpdServer) renderClientNotFoundPage(w http.ResponseWriter, r *http.Request, err error) {
- s.renderClientMessagePage(w, r, page404Title, page404Body, http.StatusNotFound, err, "")
- }
- func (s *httpdServer) renderClientTwoFactorPage(w http.ResponseWriter, r *http.Request, error, ip string) {
- data := twoFactorPage{
- CurrentURL: webClientTwoFactorPath,
- Version: version.Get().Version,
- Error: error,
- CSRFToken: createCSRFToken(ip),
- StaticURL: webStaticFilesPath,
- RecoveryURL: webClientTwoFactorRecoveryPath,
- Branding: s.binding.Branding.WebClient,
- }
- if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
- data.CurrentURL += "?next=" + url.QueryEscape(next)
- }
- renderClientTemplate(w, templateTwoFactor, data)
- }
- func (s *httpdServer) renderClientTwoFactorRecoveryPage(w http.ResponseWriter, _ *http.Request, error, ip string) {
- data := twoFactorPage{
- CurrentURL: webClientTwoFactorRecoveryPath,
- Version: version.Get().Version,
- Error: error,
- CSRFToken: createCSRFToken(ip),
- StaticURL: webStaticFilesPath,
- Branding: s.binding.Branding.WebClient,
- }
- renderClientTemplate(w, templateTwoFactorRecovery, data)
- }
- func (s *httpdServer) renderClientMFAPage(w http.ResponseWriter, r *http.Request) {
- data := clientMFAPage{
- baseClientPage: s.getBaseClientPageData(pageMFATitle, webClientMFAPath, r),
- TOTPConfigs: mfa.GetAvailableTOTPConfigNames(),
- GenerateTOTPURL: webClientTOTPGeneratePath,
- ValidateTOTPURL: webClientTOTPValidatePath,
- SaveTOTPURL: webClientTOTPSavePath,
- RecCodesURL: webClientRecoveryCodesPath,
- Protocols: dataprovider.MFAProtocols,
- }
- user, err := dataprovider.UserExists(data.LoggedUser.Username, "")
- if err != nil {
- s.renderInternalServerErrorPage(w, r, err)
- return
- }
- data.TOTPConfig = user.Filters.TOTPConfig
- renderClientTemplate(w, templateClientMFA, data)
- }
- func (s *httpdServer) renderEditFilePage(w http.ResponseWriter, r *http.Request, fileName, fileData string, readOnly bool) {
- data := editFilePage{
- baseClientPage: s.getBaseClientPageData(pageClientEditFileTitle, webClientEditFilePath, r),
- Path: fileName,
- Name: path.Base(fileName),
- CurrentDir: path.Dir(fileName),
- FileURL: webClientFilePath,
- ReadOnly: readOnly,
- Data: fileData,
- }
- renderClientTemplate(w, templateClientEditFile, data)
- }
- func (s *httpdServer) renderAddUpdateSharePage(w http.ResponseWriter, r *http.Request, share *dataprovider.Share,
- error string, isAdd bool) {
- currentURL := webClientSharePath
- title := "Add a new share"
- if !isAdd {
- currentURL = fmt.Sprintf("%v/%v", webClientSharePath, url.PathEscape(share.ShareID))
- title = "Update share"
- }
- data := clientSharePage{
- baseClientPage: s.getBaseClientPageData(title, currentURL, r),
- Share: share,
- Error: error,
- IsAdd: isAdd,
- }
- renderClientTemplate(w, templateClientShare, data)
- }
- func getDirMapping(dirName, baseWebPath string) []dirMapping {
- paths := []dirMapping{}
- if dirName != "/" {
- paths = append(paths, dirMapping{
- DirName: path.Base(dirName),
- Href: getFileObjectURL("/", dirName, baseWebPath),
- })
- for {
- dirName = path.Dir(dirName)
- if dirName == "/" || dirName == "." {
- break
- }
- paths = append([]dirMapping{{
- DirName: path.Base(dirName),
- Href: getFileObjectURL("/", dirName, baseWebPath)},
- }, paths...)
- }
- }
- return paths
- }
- func (s *httpdServer) renderSharedFilesPage(w http.ResponseWriter, r *http.Request, dirName, error string,
- share dataprovider.Share,
- ) {
- currentURL := path.Join(webClientPubSharesPath, share.ShareID, "browse")
- baseData := s.getBaseClientPageData(pageExtShareTitle, currentURL, r)
- baseData.FilesURL = currentURL
- data := filesPage{
- baseClientPage: baseData,
- Error: error,
- CurrentDir: url.QueryEscape(dirName),
- DownloadURL: path.Join(webClientPubSharesPath, share.ShareID, "partial"),
- ShareUploadBaseURL: path.Join(webClientPubSharesPath, share.ShareID, url.PathEscape(dirName)),
- ViewPDFURL: path.Join(webClientPubSharesPath, share.ShareID, "viewpdf"),
- DirsURL: path.Join(webClientPubSharesPath, share.ShareID, "dirs"),
- FileURL: "",
- FileActionsURL: "",
- CanAddFiles: share.Scope == dataprovider.ShareScopeReadWrite,
- CanCreateDirs: false,
- CanRename: false,
- CanDelete: false,
- CanDownload: share.Scope != dataprovider.ShareScopeWrite,
- CanShare: false,
- HasIntegrations: false,
- Paths: getDirMapping(dirName, currentURL),
- QuotaUsage: newUserQuotaUsage(&dataprovider.User{}),
- }
- renderClientTemplate(w, templateClientFiles, data)
- }
- func (s *httpdServer) renderUploadToSharePage(w http.ResponseWriter, r *http.Request, share dataprovider.Share) {
- currentURL := path.Join(webClientPubSharesPath, share.ShareID, "upload")
- data := shareUploadPage{
- baseClientPage: s.getBaseClientPageData(pageUploadToShareTitle, currentURL, r),
- Share: &share,
- UploadBasePath: path.Join(webClientPubSharesPath, share.ShareID),
- }
- renderClientTemplate(w, templateUploadToShare, data)
- }
- func (s *httpdServer) renderFilesPage(w http.ResponseWriter, r *http.Request, dirName, error string, user *dataprovider.User,
- hasIntegrations bool,
- ) {
- data := filesPage{
- baseClientPage: s.getBaseClientPageData(pageClientFilesTitle, webClientFilesPath, r),
- Error: error,
- CurrentDir: url.QueryEscape(dirName),
- DownloadURL: webClientDownloadZipPath,
- ViewPDFURL: webClientViewPDFPath,
- DirsURL: webClientDirsPath,
- FileURL: webClientFilePath,
- FileActionsURL: webClientFileActionsPath,
- CanAddFiles: user.CanAddFilesFromWeb(dirName),
- CanCreateDirs: user.CanAddDirsFromWeb(dirName),
- CanRename: user.CanRenameFromWeb(dirName, dirName),
- CanDelete: user.CanDeleteFromWeb(dirName),
- CanDownload: user.HasPerm(dataprovider.PermDownload, dirName),
- CanShare: user.CanManageShares(),
- ShareUploadBaseURL: "",
- HasIntegrations: hasIntegrations,
- Paths: getDirMapping(dirName, webClientFilesPath),
- QuotaUsage: newUserQuotaUsage(user),
- }
- renderClientTemplate(w, templateClientFiles, data)
- }
- func (s *httpdServer) renderClientProfilePage(w http.ResponseWriter, r *http.Request, error string) {
- data := clientProfilePage{
- baseClientPage: s.getBaseClientPageData(pageClientProfileTitle, webClientProfilePath, r),
- Error: error,
- }
- user, userMerged, err := dataprovider.GetUserVariants(data.LoggedUser.Username, "")
- if err != nil {
- s.renderClientInternalServerErrorPage(w, r, err)
- return
- }
- data.PublicKeys = user.PublicKeys
- data.AllowAPIKeyAuth = user.Filters.AllowAPIKeyAuth
- data.Email = user.Email
- data.Description = user.Description
- data.CanSubmit = userMerged.CanChangeAPIKeyAuth() || userMerged.CanManagePublicKeys() || userMerged.CanChangeInfo()
- renderClientTemplate(w, templateClientProfile, data)
- }
- func (s *httpdServer) renderClientChangePasswordPage(w http.ResponseWriter, r *http.Request, error string) {
- data := changeClientPasswordPage{
- baseClientPage: s.getBaseClientPageData(pageClientChangePwdTitle, webChangeClientPwdPath, r),
- Error: error,
- }
- renderClientTemplate(w, templateClientChangePwd, data)
- }
- func (s *httpdServer) handleWebClientDownloadZip(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxMultipartMem)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientMessagePage(w, r, "Invalid token claims", "", http.StatusForbidden, nil, "")
- return
- }
- if err := r.ParseForm(); err != nil {
- s.renderClientMessagePage(w, r, "Invalid request", err.Error(), getRespStatus(err), nil, "")
- return
- }
- ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
- if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to retrieve your user", "", getRespStatus(err), nil, "")
- return
- }
- connID := xid.New().String()
- protocol := getProtocolFromRequest(r)
- connectionID := fmt.Sprintf("%v_%v", protocol, connID)
- if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- connection := &Connection{
- BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
- r.RemoteAddr, user),
- request: r,
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
- files := r.Form.Get("files")
- var filesList []string
- err = json.Unmarshal([]byte(files), &filesList)
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to get files list", "", http.StatusInternalServerError, err, "")
- return
- }
- w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"",
- getCompressedFileName(connection.GetUsername(), filesList)))
- renderCompressedFiles(w, connection, name, filesList, nil)
- }
- func (s *httpdServer) handleClientSharePartialDownload(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxMultipartMem)
- if err := r.ParseForm(); err != nil {
- s.renderClientMessagePage(w, r, "Invalid request", err.Error(), getRespStatus(err), nil, "")
- return
- }
- validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
- share, connection, err := s.checkPublicShare(w, r, validScopes)
- if err != nil {
- return
- }
- if err := validateBrowsableShare(share, connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to validate share", "", getRespStatus(err), err, "")
- return
- }
- name, err := getBrowsableSharedPath(share, r)
- if err != nil {
- s.renderClientMessagePage(w, r, "Invalid share path", "", getRespStatus(err), err, "")
- return
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- transferQuota := connection.GetTransferQuota()
- if !transferQuota.HasDownloadSpace() {
- err = connection.GetReadQuotaExceededError()
- connection.Log(logger.LevelInfo, "denying share read due to quota limits")
- s.renderClientMessagePage(w, r, "Denying share read due to quota limits", "", getMappedStatusCode(err), err, "")
- return
- }
- files := r.Form.Get("files")
- var filesList []string
- err = json.Unmarshal([]byte(files), &filesList)
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to get files list", "", http.StatusInternalServerError, err, "")
- return
- }
- dataprovider.UpdateShareLastUse(&share, 1) //nolint:errcheck
- w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"",
- getCompressedFileName(fmt.Sprintf("share-%s", share.Name), filesList)))
- renderCompressedFiles(w, connection, name, filesList, &share)
- }
- func (s *httpdServer) handleShareGetDirContents(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
- share, connection, err := s.checkPublicShare(w, r, validScopes)
- if err != nil {
- return
- }
- if err := validateBrowsableShare(share, connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to validate share", "", getRespStatus(err), err, "")
- return
- }
- name, err := getBrowsableSharedPath(share, r)
- if err != nil {
- s.renderClientMessagePage(w, r, "Invalid share path", "", getRespStatus(err), err, "")
- return
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- contents, err := connection.ReadDir(name)
- if err != nil {
- sendAPIResponse(w, r, err, "Unable to get directory contents", getMappedStatusCode(err))
- return
- }
- results := make([]map[string]any, 0, len(contents))
- for _, info := range contents {
- if !info.Mode().IsDir() && !info.Mode().IsRegular() {
- continue
- }
- res := make(map[string]any)
- if info.IsDir() {
- res["type"] = "1"
- res["size"] = ""
- } else {
- res["type"] = "2"
- res["size"] = info.Size()
- }
- res["meta"] = fmt.Sprintf("%v_%v", res["type"], info.Name())
- res["name"] = info.Name()
- res["url"] = getFileObjectURL(share.GetRelativePath(name), info.Name(),
- path.Join(webClientPubSharesPath, share.ShareID, "browse"))
- res["last_modified"] = getFileObjectModTime(info.ModTime())
- results = append(results, res)
- }
- render.JSON(w, r, results)
- }
- func (s *httpdServer) handleClientUploadToShare(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeWrite, dataprovider.ShareScopeReadWrite}
- share, _, err := s.checkPublicShare(w, r, validScopes)
- if err != nil {
- return
- }
- if share.Scope == dataprovider.ShareScopeReadWrite {
- http.Redirect(w, r, path.Join(webClientPubSharesPath, share.ShareID, "browse"), http.StatusFound)
- return
- }
- s.renderUploadToSharePage(w, r, share)
- }
- func (s *httpdServer) handleShareGetFiles(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
- share, connection, err := s.checkPublicShare(w, r, validScopes)
- if err != nil {
- return
- }
- if err := validateBrowsableShare(share, connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to validate share", "", getRespStatus(err), err, "")
- return
- }
- name, err := getBrowsableSharedPath(share, r)
- if err != nil {
- s.renderClientMessagePage(w, r, "Invalid share path", "", getRespStatus(err), err, "")
- return
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- var info os.FileInfo
- if name == "/" {
- info = vfs.NewFileInfo(name, true, 0, time.Unix(0, 0), false)
- } else {
- info, err = connection.Stat(name, 1)
- }
- if err != nil {
- s.renderSharedFilesPage(w, r, path.Dir(share.GetRelativePath(name)), err.Error(), share)
- return
- }
- if info.IsDir() {
- s.renderSharedFilesPage(w, r, share.GetRelativePath(name), "", share)
- return
- }
- dataprovider.UpdateShareLastUse(&share, 1) //nolint:errcheck
- if status, err := downloadFile(w, r, connection, name, info, false, &share); err != nil {
- dataprovider.UpdateShareLastUse(&share, -1) //nolint:errcheck
- if status > 0 {
- s.renderSharedFilesPage(w, r, path.Dir(share.GetRelativePath(name)), err.Error(), share)
- }
- }
- }
- func (s *httpdServer) handleShareViewPDF(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
- validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
- share, _, err := s.checkPublicShare(w, r, validScopes)
- if err != nil {
- return
- }
- name, err := getBrowsableSharedPath(share, r)
- if err != nil {
- s.renderClientMessagePage(w, r, "Invalid share path", "", getRespStatus(err), err, "")
- return
- }
- data := viewPDFPage{
- Title: path.Base(name),
- URL: fmt.Sprintf("%s?path=%s&_=%d", path.Join(webClientPubSharesPath, share.ShareID, "getpdf"),
- url.QueryEscape(name), time.Now().UTC().Unix()),
- StaticURL: webStaticFilesPath,
- Branding: s.binding.Branding.WebClient,
- }
- renderClientTemplate(w, templateClientViewPDF, data)
- }
- func (s *httpdServer) handleShareGetPDF(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
- share, connection, err := s.checkPublicShare(w, r, validScopes)
- if err != nil {
- return
- }
- if err := validateBrowsableShare(share, connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to validate share", "", getRespStatus(err), err, "")
- return
- }
- name, err := getBrowsableSharedPath(share, r)
- if err != nil {
- s.renderClientMessagePage(w, r, "Invalid share path", "", getRespStatus(err), err, "")
- return
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- info, err := connection.Stat(name, 0)
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to get file", "", getRespStatus(err), err, "")
- return
- }
- if info.IsDir() {
- s.renderClientMessagePage(w, r, "Invalid file", fmt.Sprintf("%q is not a file", name),
- http.StatusBadRequest, nil, "")
- return
- }
- connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
- if err := s.ensurePDF(w, r, name, connection); err != nil {
- return
- }
- dataprovider.UpdateShareLastUse(&share, 1) //nolint:errcheck
- if _, err := downloadFile(w, r, connection, name, info, true, &share); err != nil {
- dataprovider.UpdateShareLastUse(&share, -1) //nolint:errcheck
- }
- }
- func (s *httpdServer) handleClientGetDirContents(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- sendAPIResponse(w, r, nil, "invalid token claims", http.StatusForbidden)
- return
- }
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- sendAPIResponse(w, r, nil, "Unable to retrieve your user", getRespStatus(err))
- return
- }
- connID := xid.New().String()
- protocol := getProtocolFromRequest(r)
- connectionID := fmt.Sprintf("%v_%v", protocol, connID)
- if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
- sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
- return
- }
- connection := &Connection{
- BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
- r.RemoteAddr, user),
- request: r,
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
- contents, err := connection.ReadDir(name)
- if err != nil {
- sendAPIResponse(w, r, err, "Unable to get directory contents", getMappedStatusCode(err))
- return
- }
- dirTree := r.URL.Query().Get("dirtree") == "1"
- results := make([]map[string]any, 0, len(contents))
- for _, info := range contents {
- res := make(map[string]any)
- res["url"] = getFileObjectURL(name, info.Name(), webClientFilesPath)
- if info.IsDir() {
- res["type"] = "1"
- res["size"] = ""
- res["dir_path"] = url.QueryEscape(path.Join(name, info.Name()))
- } else {
- if dirTree {
- continue
- }
- res["type"] = "2"
- if info.Mode()&os.ModeSymlink != 0 {
- res["size"] = ""
- } else {
- res["size"] = info.Size()
- if info.Size() < httpdMaxEditFileSize {
- res["edit_url"] = strings.Replace(res["url"].(string), webClientFilesPath, webClientEditFilePath, 1)
- }
- if len(s.binding.WebClientIntegrations) > 0 {
- extension := path.Ext(info.Name())
- for idx := range s.binding.WebClientIntegrations {
- if util.Contains(s.binding.WebClientIntegrations[idx].FileExtensions, extension) {
- res["ext_url"] = s.binding.WebClientIntegrations[idx].URL
- res["ext_link"] = fmt.Sprintf("%v?path=%v&_=%v", webClientFilePath,
- url.QueryEscape(path.Join(name, info.Name())), time.Now().UTC().Unix())
- break
- }
- }
- }
- }
- }
- res["meta"] = fmt.Sprintf("%v_%v", res["type"], info.Name())
- res["name"] = info.Name()
- res["last_modified"] = getFileObjectModTime(info.ModTime())
- results = append(results, res)
- }
- render.JSON(w, r, results)
- }
- func (s *httpdServer) handleClientGetFiles(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to retrieve your user", "", getRespStatus(err), nil, "")
- return
- }
- connID := xid.New().String()
- protocol := getProtocolFromRequest(r)
- connectionID := fmt.Sprintf("%v_%v", protocol, connID)
- if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- connection := &Connection{
- BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
- r.RemoteAddr, user),
- request: r,
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
- var info os.FileInfo
- if name == "/" {
- info = vfs.NewFileInfo(name, true, 0, time.Unix(0, 0), false)
- } else {
- info, err = connection.Stat(name, 0)
- }
- if err != nil {
- s.renderFilesPage(w, r, path.Dir(name), fmt.Sprintf("unable to stat file %q: %v", name, err),
- &user, len(s.binding.WebClientIntegrations) > 0)
- return
- }
- if info.IsDir() {
- s.renderFilesPage(w, r, name, "", &user, len(s.binding.WebClientIntegrations) > 0)
- return
- }
- if status, err := downloadFile(w, r, connection, name, info, false, nil); err != nil && status != 0 {
- if status > 0 {
- if status == http.StatusRequestedRangeNotSatisfiable {
- s.renderClientMessagePage(w, r, http.StatusText(status), "", status, err, "")
- return
- }
- s.renderFilesPage(w, r, path.Dir(name), err.Error(), &user, len(s.binding.WebClientIntegrations) > 0)
- }
- }
- }
- func (s *httpdServer) handleClientEditFile(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to retrieve your user", "", getRespStatus(err), nil, "")
- return
- }
- connID := xid.New().String()
- protocol := getProtocolFromRequest(r)
- connectionID := fmt.Sprintf("%v_%v", protocol, connID)
- if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- connection := &Connection{
- BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
- r.RemoteAddr, user),
- request: r,
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
- info, err := connection.Stat(name, 0)
- if err != nil {
- s.renderClientMessagePage(w, r, fmt.Sprintf("Unable to stat file %q", name), "",
- getRespStatus(err), nil, "")
- return
- }
- if info.IsDir() {
- s.renderClientMessagePage(w, r, fmt.Sprintf("The path %q does not point to a file", name), "",
- http.StatusBadRequest, nil, "")
- return
- }
- if info.Size() > httpdMaxEditFileSize {
- s.renderClientMessagePage(w, r, fmt.Sprintf("The file size %v for %q exceeds the maximum allowed size",
- util.ByteCountIEC(info.Size()), name), "", http.StatusBadRequest, nil, "")
- return
- }
- connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
- reader, err := connection.getFileReader(name, 0, r.Method)
- if err != nil {
- s.renderClientMessagePage(w, r, fmt.Sprintf("Unable to get a reader for the file %q", name), "",
- getRespStatus(err), nil, "")
- return
- }
- defer reader.Close()
- var b bytes.Buffer
- _, err = io.Copy(&b, reader)
- if err != nil {
- s.renderClientMessagePage(w, r, fmt.Sprintf("Unable to read the file %q", name), "", http.StatusInternalServerError,
- nil, "")
- return
- }
- s.renderEditFilePage(w, r, name, b.String(), !user.CanAddFilesFromWeb(path.Dir(name)))
- }
- func (s *httpdServer) handleClientAddShareGet(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to retrieve your user", "", getRespStatus(err), nil, "")
- return
- }
- share := &dataprovider.Share{Scope: dataprovider.ShareScopeRead}
- if user.Filters.DefaultSharesExpiration > 0 {
- share.ExpiresAt = util.GetTimeAsMsSinceEpoch(time.Now().Add(24 * time.Hour * time.Duration(user.Filters.DefaultSharesExpiration)))
- }
- dirName := "/"
- if _, ok := r.URL.Query()["path"]; ok {
- dirName = util.CleanPath(r.URL.Query().Get("path"))
- }
- if _, ok := r.URL.Query()["files"]; ok {
- files := r.URL.Query().Get("files")
- var filesList []string
- err := json.Unmarshal([]byte(files), &filesList)
- if err != nil {
- s.renderClientMessagePage(w, r, "Invalid share list", "", http.StatusBadRequest, err, "")
- return
- }
- for _, f := range filesList {
- if f != "" {
- share.Paths = append(share.Paths, path.Join(dirName, f))
- }
- }
- }
- s.renderAddUpdateSharePage(w, r, share, "", true)
- }
- func (s *httpdServer) handleClientUpdateShareGet(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- shareID := getURLParam(r, "id")
- share, err := dataprovider.ShareExists(shareID, claims.Username)
- if err == nil {
- share.HideConfidentialData()
- s.renderAddUpdateSharePage(w, r, &share, "", false)
- } else if errors.Is(err, util.ErrNotFound) {
- s.renderClientNotFoundPage(w, r, err)
- } else {
- s.renderClientInternalServerErrorPage(w, r, err)
- }
- }
- func (s *httpdServer) handleClientAddSharePost(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- share, err := getShareFromPostFields(r)
- if err != nil {
- s.renderAddUpdateSharePage(w, r, share, err.Error(), true)
- return
- }
- ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
- if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- share.ID = 0
- share.ShareID = util.GenerateUniqueID()
- share.LastUseAt = 0
- share.Username = claims.Username
- if share.Password == "" {
- if util.Contains(claims.Permissions, sdk.WebClientShareNoPasswordDisabled) {
- s.renderClientForbiddenPage(w, r, "You are not authorized to share files/folders without a password")
- return
- }
- }
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- s.renderAddUpdateSharePage(w, r, share, "Unable to retrieve your user", true)
- return
- }
- if err := user.CheckMaxShareExpiration(util.GetTimeFromMsecSinceEpoch(share.ExpiresAt)); err != nil {
- s.renderAddUpdateSharePage(w, r, share, err.Error(), true)
- return
- }
- err = dataprovider.AddShare(share, claims.Username, ipAddr, claims.Role)
- if err == nil {
- http.Redirect(w, r, webClientSharesPath, http.StatusSeeOther)
- } else {
- s.renderAddUpdateSharePage(w, r, share, err.Error(), true)
- }
- }
- func (s *httpdServer) handleClientUpdateSharePost(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- shareID := getURLParam(r, "id")
- share, err := dataprovider.ShareExists(shareID, claims.Username)
- if errors.Is(err, util.ErrNotFound) {
- s.renderClientNotFoundPage(w, r, err)
- return
- } else if err != nil {
- s.renderClientInternalServerErrorPage(w, r, err)
- return
- }
- updatedShare, err := getShareFromPostFields(r)
- if err != nil {
- s.renderAddUpdateSharePage(w, r, updatedShare, err.Error(), false)
- return
- }
- ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
- if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- updatedShare.ShareID = shareID
- updatedShare.Username = claims.Username
- if updatedShare.Password == redactedSecret {
- updatedShare.Password = share.Password
- }
- if updatedShare.Password == "" {
- if util.Contains(claims.Permissions, sdk.WebClientShareNoPasswordDisabled) {
- s.renderClientForbiddenPage(w, r, "You are not authorized to share files/folders without a password")
- return
- }
- }
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- s.renderAddUpdateSharePage(w, r, updatedShare, "Unable to retrieve your user", false)
- return
- }
- if err := user.CheckMaxShareExpiration(util.GetTimeFromMsecSinceEpoch(updatedShare.ExpiresAt)); err != nil {
- s.renderAddUpdateSharePage(w, r, updatedShare, err.Error(), false)
- return
- }
- err = dataprovider.UpdateShare(updatedShare, claims.Username, ipAddr, claims.Role)
- if err == nil {
- http.Redirect(w, r, webClientSharesPath, http.StatusSeeOther)
- } else {
- s.renderAddUpdateSharePage(w, r, updatedShare, err.Error(), false)
- }
- }
- func (s *httpdServer) handleClientGetShares(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- limit := defaultQueryLimit
- if _, ok := r.URL.Query()["qlimit"]; ok {
- var err error
- limit, err = strconv.Atoi(r.URL.Query().Get("qlimit"))
- if err != nil {
- limit = defaultQueryLimit
- }
- }
- shares := make([]dataprovider.Share, 0, limit)
- for {
- sh, err := dataprovider.GetShares(limit, len(shares), dataprovider.OrderASC, claims.Username)
- if err != nil {
- s.renderInternalServerErrorPage(w, r, err)
- return
- }
- shares = append(shares, sh...)
- if len(sh) < limit {
- break
- }
- }
- data := clientSharesPage{
- baseClientPage: s.getBaseClientPageData(pageClientSharesTitle, webClientSharesPath, r),
- Shares: shares,
- BasePublicSharesURL: webClientPubSharesPath,
- }
- renderClientTemplate(w, templateClientShares, data)
- }
- func (s *httpdServer) handleClientGetProfile(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- s.renderClientProfilePage(w, r, "")
- }
- func (s *httpdServer) handleWebClientChangePwd(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- s.renderClientChangePasswordPage(w, r, "")
- }
- func (s *httpdServer) handleWebClientProfilePost(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- err := r.ParseForm()
- if err != nil {
- s.renderClientProfilePage(w, r, err.Error())
- return
- }
- ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
- if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- user, userMerged, err := dataprovider.GetUserVariants(claims.Username, "")
- if err != nil {
- s.renderClientProfilePage(w, r, err.Error())
- return
- }
- if !userMerged.CanManagePublicKeys() && !userMerged.CanChangeAPIKeyAuth() && !userMerged.CanChangeInfo() {
- s.renderClientForbiddenPage(w, r, "You are not allowed to change anything")
- return
- }
- if userMerged.CanManagePublicKeys() {
- for k := range r.Form {
- if strings.HasPrefix(k, "public_keys[") {
- r.Form.Add("public_keys", r.Form.Get(k))
- }
- }
- user.PublicKeys = r.Form["public_keys"]
- }
- if userMerged.CanChangeAPIKeyAuth() {
- user.Filters.AllowAPIKeyAuth = r.Form.Get("allow_api_key_auth") != ""
- }
- if userMerged.CanChangeInfo() {
- user.Email = strings.TrimSpace(r.Form.Get("email"))
- user.Description = r.Form.Get("description")
- }
- err = dataprovider.UpdateUser(&user, dataprovider.ActionExecutorSelf, ipAddr, user.Role)
- if err != nil {
- s.renderClientProfilePage(w, r, err.Error())
- return
- }
- s.renderClientMessagePage(w, r, "Profile updated", "", http.StatusOK, nil,
- "Your profile has been successfully updated")
- }
- func (s *httpdServer) handleWebClientMFA(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- s.renderClientMFAPage(w, r)
- }
- func (s *httpdServer) handleWebClientTwoFactor(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- s.renderClientTwoFactorPage(w, r, "", util.GetIPFromRemoteAddress(r.RemoteAddr))
- }
- func (s *httpdServer) handleWebClientTwoFactorRecovery(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- s.renderClientTwoFactorRecoveryPage(w, r, "", util.GetIPFromRemoteAddress(r.RemoteAddr))
- }
- func getShareFromPostFields(r *http.Request) (*dataprovider.Share, error) {
- share := &dataprovider.Share{}
- if err := r.ParseForm(); err != nil {
- return share, err
- }
- for k := range r.Form {
- if strings.HasPrefix(k, "paths[") {
- r.Form.Add("paths", r.Form.Get(k))
- }
- }
- share.Name = strings.TrimSpace(r.Form.Get("name"))
- share.Description = r.Form.Get("description")
- for _, p := range r.Form["paths"] {
- if strings.TrimSpace(p) != "" {
- share.Paths = append(share.Paths, p)
- }
- }
- share.Password = strings.TrimSpace(r.Form.Get("password"))
- share.AllowFrom = getSliceFromDelimitedValues(r.Form.Get("allowed_ip"), ",")
- scope, err := strconv.Atoi(r.Form.Get("scope"))
- if err != nil {
- return share, err
- }
- share.Scope = dataprovider.ShareScope(scope)
- maxTokens, err := strconv.Atoi(r.Form.Get("max_tokens"))
- if err != nil {
- return share, err
- }
- share.MaxTokens = maxTokens
- expirationDateMillis := int64(0)
- expirationDateString := strings.TrimSpace(r.Form.Get("expiration_date"))
- if expirationDateString != "" {
- expirationDate, err := time.Parse(webDateTimeFormat, expirationDateString)
- if err != nil {
- return share, err
- }
- expirationDateMillis = util.GetTimeAsMsSinceEpoch(expirationDate)
- }
- share.ExpiresAt = expirationDateMillis
- return share, nil
- }
- func (s *httpdServer) handleWebClientForgotPwd(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- if !smtp.IsEnabled() {
- s.renderClientNotFoundPage(w, r, errors.New("this page does not exist"))
- return
- }
- s.renderClientForgotPwdPage(w, "", util.GetIPFromRemoteAddress(r.RemoteAddr))
- }
- func (s *httpdServer) handleWebClientForgotPwdPost(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
- ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
- err := r.ParseForm()
- if err != nil {
- s.renderClientForgotPwdPage(w, err.Error(), ipAddr)
- return
- }
- if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- username := strings.TrimSpace(r.Form.Get("username"))
- err = handleForgotPassword(r, username, false)
- if err != nil {
- if e, ok := err.(*util.ValidationError); ok {
- s.renderClientForgotPwdPage(w, e.GetErrorString(), ipAddr)
- return
- }
- s.renderClientForgotPwdPage(w, err.Error(), ipAddr)
- return
- }
- http.Redirect(w, r, webClientResetPwdPath, http.StatusFound)
- }
- func (s *httpdServer) handleWebClientPasswordReset(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
- if !smtp.IsEnabled() {
- s.renderClientNotFoundPage(w, r, errors.New("this page does not exist"))
- return
- }
- s.renderClientResetPwdPage(w, r, "", util.GetIPFromRemoteAddress(r.RemoteAddr))
- }
- func (s *httpdServer) handleClientViewPDF(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
- name := r.URL.Query().Get("path")
- if name == "" {
- s.renderClientBadRequestPage(w, r, errors.New("no file specified"))
- return
- }
- name = util.CleanPath(name)
- data := viewPDFPage{
- Title: path.Base(name),
- URL: fmt.Sprintf("%s?path=%s&_=%d", webClientGetPDFPath, url.QueryEscape(name), time.Now().UTC().Unix()),
- StaticURL: webStaticFilesPath,
- Branding: s.binding.Branding.WebClient,
- }
- renderClientTemplate(w, templateClientViewPDF, data)
- }
- func (s *httpdServer) handleClientGetPDF(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
- claims, err := getTokenClaims(r)
- if err != nil || claims.Username == "" {
- s.renderClientForbiddenPage(w, r, "Invalid token claims")
- return
- }
- name := r.URL.Query().Get("path")
- if name == "" {
- s.renderClientBadRequestPage(w, r, errors.New("no file specified"))
- return
- }
- name = util.CleanPath(name)
- user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to retrieve your user", "", getRespStatus(err), nil, "")
- return
- }
- connID := xid.New().String()
- protocol := getProtocolFromRequest(r)
- connectionID := fmt.Sprintf("%v_%v", protocol, connID)
- if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
- s.renderClientForbiddenPage(w, r, err.Error())
- return
- }
- connection := &Connection{
- BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
- r.RemoteAddr, user),
- request: r,
- }
- if err = common.Connections.Add(connection); err != nil {
- s.renderClientMessagePage(w, r, "Unable to add connection", "", http.StatusTooManyRequests, err, "")
- return
- }
- defer common.Connections.Remove(connection.GetID())
- info, err := connection.Stat(name, 0)
- if err != nil {
- s.renderClientMessagePage(w, r, "Unable to get file", "", getRespStatus(err), err, "")
- return
- }
- if info.IsDir() {
- s.renderClientMessagePage(w, r, "Invalid file", fmt.Sprintf("%q is not a file", name),
- http.StatusBadRequest, nil, "")
- return
- }
- connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
- if err := s.ensurePDF(w, r, name, connection); err != nil {
- return
- }
- downloadFile(w, r, connection, name, info, true, nil) //nolint:errcheck
- }
- func (s *httpdServer) ensurePDF(w http.ResponseWriter, r *http.Request, name string, connection *Connection) error {
- reader, err := connection.getFileReader(name, 0, r.Method)
- if err != nil {
- s.renderClientMessagePage(w, r, fmt.Sprintf("Unable to get a reader for the file %q", name), "",
- getRespStatus(err), err, "")
- return err
- }
- defer reader.Close()
- var b bytes.Buffer
- _, err = io.CopyN(&b, reader, 128)
- if err != nil {
- s.renderClientMessagePage(w, r, "Invalid PDF file", fmt.Sprintf("Unable to validate the file %q as PDF", name),
- http.StatusBadRequest, nil, "")
- return err
- }
- if ctype := http.DetectContentType(b.Bytes()); ctype != "application/pdf" {
- connection.Log(logger.LevelDebug, "detected %q content type, expected PDF, file %q", ctype, name)
- s.renderClientBadRequestPage(w, r, fmt.Errorf("the file %q does not look like a PDF", name))
- return errors.New("invalid PDF")
- }
- return nil
- }
- func (s *httpdServer) handleClientShareLoginGet(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
- s.renderShareLoginPage(w, r.RequestURI, "", util.GetIPFromRemoteAddress(r.RemoteAddr))
- }
- func (s *httpdServer) handleClientShareLoginPost(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
- ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
- if err := r.ParseForm(); err != nil {
- s.renderShareLoginPage(w, r.RequestURI, err.Error(), ipAddr)
- return
- }
- if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
- s.renderShareLoginPage(w, r.RequestURI, err.Error(), ipAddr)
- return
- }
- shareID := getURLParam(r, "id")
- share, err := dataprovider.ShareExists(shareID, "")
- if err != nil {
- s.renderShareLoginPage(w, r.RequestURI, dataprovider.ErrInvalidCredentials.Error(), ipAddr)
- return
- }
- match, err := share.CheckCredentials(strings.TrimSpace(r.Form.Get("share_password")))
- if !match || err != nil {
- s.renderShareLoginPage(w, r.RequestURI, dataprovider.ErrInvalidCredentials.Error(), ipAddr)
- return
- }
- c := jwtTokenClaims{
- Username: shareID,
- }
- err = c.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebShare, ipAddr)
- if err != nil {
- s.renderShareLoginPage(w, r.RequestURI, common.ErrInternalFailure.Error(), ipAddr)
- return
- }
- next := path.Clean(r.URL.Query().Get("next"))
- if strings.HasPrefix(next, path.Join(webClientPubSharesPath, share.ShareID)) {
- http.Redirect(w, r, next, http.StatusFound)
- return
- }
- s.renderClientMessagePage(w, r, "Share Login OK", "Share login successful, you can now use your link",
- http.StatusOK, nil, "")
- }
|