diff options
author | Antoine GIRARD <sapk@users.noreply.github.com> | 2019-07-07 04:25:05 +0200 |
---|---|---|
committer | techknowlogick <techknowlogick@gitea.io> | 2019-07-06 22:25:05 -0400 |
commit | f369788347167a47a8fc162e086b92048ff0a43f (patch) | |
tree | f959bd40d1a33761b0fa8a25bb956b4e24d3b044 /modules/upload | |
parent | 75d44143863e90a7aeff30a3f40128f144df94dd (diff) | |
download | gitea-f369788347167a47a8fc162e086b92048ff0a43f.tar.gz gitea-f369788347167a47a8fc162e086b92048ff0a43f.zip |
Refactor filetype is not allowed errors (#7309)
Diffstat (limited to 'modules/upload')
-rw-r--r-- | modules/upload/filetype.go | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/modules/upload/filetype.go b/modules/upload/filetype.go new file mode 100644 index 0000000000..1ec7324ed3 --- /dev/null +++ b/modules/upload/filetype.go @@ -0,0 +1,49 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package upload + +import ( + "fmt" + "net/http" + "strings" + + "code.gitea.io/gitea/modules/log" +) + +// ErrFileTypeForbidden not allowed file type error +type ErrFileTypeForbidden struct { + Type string +} + +// IsErrFileTypeForbidden checks if an error is a ErrFileTypeForbidden. +func IsErrFileTypeForbidden(err error) bool { + _, ok := err.(ErrFileTypeForbidden) + return ok +} + +func (err ErrFileTypeForbidden) Error() string { + return fmt.Sprintf("File type is not allowed: %s", err.Type) +} + +// VerifyAllowedContentType validates a file is allowed to be uploaded. +func VerifyAllowedContentType(buf []byte, allowedTypes []string) error { + fileType := http.DetectContentType(buf) + + allowed := false + for _, t := range allowedTypes { + t := strings.Trim(t, " ") + if t == "*/*" || t == fileType { + allowed = true + break + } + } + + if !allowed { + log.Info("Attachment with type %s blocked from upload", fileType) + return ErrFileTypeForbidden{Type: fileType} + } + + return nil +} |