fix auth middleware

This commit is contained in:
divyam234 2023-12-03 13:35:32 +05:30
parent b25a4bc7ca
commit 5546b81e51
6 changed files with 163 additions and 19 deletions

38
.github/workflows/codeql.yml vendored Normal file
View file

@ -0,0 +1,38 @@
name: "CodeQL"
on:
push:
tags:
- "*"
workflow_dispatch:
jobs:
analyze:
name: Analyze
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'go' ]
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"

1
go.mod
View file

@ -14,7 +14,6 @@ require (
github.com/kelseyhightower/envconfig v1.4.0
github.com/mitchellh/mapstructure v1.5.0
github.com/pkg/errors v0.9.1
github.com/quantumsheep/range-parser v1.1.0
github.com/thoas/go-funk v0.9.3
go.etcd.io/bbolt v1.3.8
go.uber.org/zap v1.26.0

2
go.sum
View file

@ -207,8 +207,6 @@ github.com/pressly/goose/v3 v3.16.0 h1:xMJUsZdHLqSnCqESyKSqEfcYVYsUuup1nrOhaEFft
github.com/pressly/goose/v3 v3.16.0/go.mod h1:JwdKVnmCRhnF6XLQs2mHEQtucFD49cQBdRM4UiwkxsM=
github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo=
github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo=
github.com/quantumsheep/range-parser v1.1.0 h1:k4f1F58f8FF54FBYc9dYBRM+8JkAxFo11gC3IeMH4rU=
github.com/quantumsheep/range-parser v1.1.0/go.mod h1:acv4Vt2PvpGvRsvGju7Gk2ahKluZJsIUNR69W53J22I=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=

View file

@ -0,0 +1,106 @@
package http_range
import (
"errors"
"fmt"
"net/textproto"
"strconv"
"strings"
)
// Range specifies the byte range to be sent to the client.
type Range struct {
Start int64
End int64
}
// ContentRange returns Content-Range header value.
func (r Range) ContentRange(size int64) string {
return fmt.Sprintf("bytes %d-%d/%d", r.Start, r.End, size)
}
var (
// ErrNoOverlap is returned by ParseRange if first-byte-pos of
// all of the byte-range-spec values is greater than the content size.
ErrNoOverlap = errors.New("invalid range: failed to overlap")
// ErrInvalid is returned by ParseRange on invalid input.
ErrInvalid = errors.New("invalid range")
)
// ParseRange parses a Range header string as per RFC 7233.
// ErrNoOverlap is returned if none of the ranges overlap.
// ErrInvalid is returned if s is invalid range.
func ParseRange(s string, size int64) ([]Range, error) { // nolint:gocognit
if s == "" {
return nil, nil // header not present
}
const b = "bytes="
if !strings.HasPrefix(s, b) {
return nil, ErrInvalid
}
var ranges []Range
noOverlap := false
for _, ra := range strings.Split(s[len(b):], ",") {
ra = textproto.TrimString(ra)
if ra == "" {
continue
}
i := strings.Index(ra, "-")
if i < 0 {
return nil, ErrInvalid
}
start, end := textproto.TrimString(ra[:i]), textproto.TrimString(ra[i+1:])
var r Range
if start == "" {
// If no start is specified, end specifies the
// range start relative to the end of the file,
// and we are dealing with <suffix-length>
// which has to be a non-negative integer as per
// RFC 7233 Section 2.1 "Byte-Ranges".
if end == "" || end[0] == '-' {
return nil, ErrInvalid
}
i, err := strconv.ParseInt(end, 10, 64)
if i < 0 || err != nil {
return nil, ErrInvalid
}
if i > size {
i = size
}
r.Start = size - i
r.End = size - 1
} else {
i, err := strconv.ParseInt(start, 10, 64)
if err != nil || i < 0 {
return nil, ErrInvalid
}
if i >= size {
// If the range begins after the size of the content,
// then it does not overlap.
noOverlap = true
continue
}
r.Start = i
if end == "" {
// If no end is specified, range extends to end of the file.
r.End = size - 1
} else {
i, err := strconv.ParseInt(end, 10, 64)
if err != nil || r.Start > i {
return nil, ErrInvalid
}
if i >= size {
i = size - 1
}
r.End = i
}
}
ranges = append(ranges, r)
}
if noOverlap && len(ranges) == 0 {
// The specified ranges did not overlap with the content.
return nil, ErrNoOverlap
}
return ranges, nil
}

View file

@ -16,8 +16,6 @@ func Authmiddleware(c *gin.Context) {
cookie, err := c.Request.Cookie("user-session")
token = cookie.Value
if err != nil {
authHeader := c.GetHeader("Authorization")
bearerToken := strings.Split(authHeader, "Bearer ")
@ -27,6 +25,8 @@ func Authmiddleware(c *gin.Context) {
return
}
token = bearerToken[1]
} else {
token = cookie.Value
}
now := time.Now().UTC()

View file

@ -6,12 +6,14 @@ import (
"errors"
"fmt"
"io"
"mime"
"net/http"
"strconv"
"strings"
cnf "github.com/divyam234/teldrive/config"
"github.com/divyam234/teldrive/internal/cache"
"github.com/divyam234/teldrive/internal/http_range"
"github.com/divyam234/teldrive/internal/md5"
"github.com/divyam234/teldrive/internal/reader"
"github.com/divyam234/teldrive/internal/tgc"
@ -26,7 +28,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgconn"
"github.com/mitchellh/mapstructure"
range_parser "github.com/quantumsheep/range-parser"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
@ -499,11 +500,20 @@ func (fs *FileService) GetFileStream(c *gin.Context) {
end = file.Size - 1
w.WriteHeader(http.StatusOK)
} else {
ranges, err := range_parser.Parse(file.Size, r.Header.Get("Range"))
ranges, err := http_range.ParseRange(rangeHeader, file.Size)
if err == http_range.ErrNoOverlap {
w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", file.Size))
http.Error(w, http_range.ErrNoOverlap.Error(), http.StatusRequestedRangeNotSatisfiable)
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(ranges) > 1 {
http.Error(w, "multiple ranges are not supported", http.StatusRequestedRangeNotSatisfiable)
return
}
start = ranges[0].Start
end = ranges[0].End
c.Header("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, file.Size))
@ -530,7 +540,7 @@ func (fs *FileService) GetFileStream(c *gin.Context) {
disposition = "attachment"
}
c.Header("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", disposition, file.Name))
c.Header("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": file.Name}))
tokens, err := getBotsToken(c, session.UserId, file.ChannelID)
@ -605,12 +615,7 @@ func (fs *FileService) GetFileStream(c *gin.Context) {
func setOrderFilter(query *gorm.DB, pagingParams *schemas.PaginationQuery, sortingParams *schemas.SortingQuery) *gorm.DB {
if pagingParams.NextPageToken != "" {
sortColumn := sortingParams.Sort
if sortColumn == "name" {
sortColumn = "name collate numeric"
} else {
sortColumn = utils.CamelToSnake(sortingParams.Sort)
}
sortColumn := utils.CamelToSnake(sortingParams.Sort)
tokenValue, err := base64.StdEncoding.DecodeString(pagingParams.NextPageToken)
if err == nil {
@ -624,11 +629,9 @@ func setOrderFilter(query *gorm.DB, pagingParams *schemas.PaginationQuery, sorti
return query
}
func getOrder(sortingParams schemas.SortingQuery) string {
func getOrder(sortingParams schemas.SortingQuery) clause.OrderByColumn {
sortColumn := utils.CamelToSnake(sortingParams.Sort)
if sortingParams.Sort == "name" {
sortColumn = "name collate numeric"
}
return fmt.Sprintf("%s %s", sortColumn, strings.ToUpper(sortingParams.Order))
return clause.OrderByColumn{Column: clause.Column{Name: sortColumn},
Desc: sortingParams.Order == "desc"}
}