1
1
mirror of https://github.com/go-gitea/gitea synced 2024-12-27 02:54:27 +00:00
gitea/modules/upload/filetype.go
Lunny Xiao 2d0b90c967 Fix upload file type check (#7890)
* fix upload file type check

* make the function simple and added tests

* Update comment as per @silverwind
2019-08-17 13:10:17 +03:00

47 lines
1.1 KiB
Go

// 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)
for _, t := range allowedTypes {
t := strings.Trim(t, " ")
if t == "*/*" || t == fileType ||
// Allow directives after type, like 'text/plain; charset=utf-8'
strings.HasPrefix(fileType, t+";") {
return nil
}
}
log.Info("Attachment with type %s blocked from upload", fileType)
return ErrFileTypeForbidden{Type: fileType}
}