This commit is contained in:
Henrique Dias 2018-08-16 04:26:57 +00:00 committed by GitHub
commit 3d6b6338cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 164 additions and 142 deletions

View File

@ -2,9 +2,11 @@
"port": 80, "port": 80,
"address": "", "address": "",
"database": "/database.db", "database": "/database.db",
"defaults": {
"scope": "/srv", "scope": "/srv",
"allowCommands": true, "allowCommands": true,
"allowEdit": true, "allowEdit": true,
"allowNew": true, "allowNew": true,
"commands": [] "commands": []
}
} }

View File

@ -2,6 +2,14 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/asdine/storm" "github.com/asdine/storm"
"github.com/filebrowser/filebrowser" "github.com/filebrowser/filebrowser"
"github.com/filebrowser/filebrowser/bolt" "github.com/filebrowser/filebrowser/bolt"
@ -11,13 +19,7 @@ import (
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
"github.com/spf13/viper" "github.com/spf13/viper"
"gopkg.in/natefinch/lumberjack.v2" "gopkg.in/natefinch/lumberjack.v2"
"io/ioutil" )
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings")
var ( var (
addr string addr string
@ -31,20 +33,21 @@ var (
baseurl string baseurl string
prefixurl string prefixurl string
viewMode string viewMode string
recaptchakey string
recaptchasecret string
port int port int
recaptcha struct {
host string
key string
secret string
}
auth struct { auth struct {
method string method string
loginHeader string header string
} }
noAuth bool
allowCommands bool allowCommands bool
allowEdit bool allowEdit bool
allowNew bool allowNew bool
allowPublish bool allowPublish bool
showVer bool showVer bool
alterRecaptcha bool
) )
func init() { func init() {
@ -53,70 +56,82 @@ func init() {
flag.StringVarP(&addr, "address", "a", "", "Address to listen to (default is all of them)") flag.StringVarP(&addr, "address", "a", "", "Address to listen to (default is all of them)")
flag.StringVarP(&database, "database", "d", "./filebrowser.db", "Database file") flag.StringVarP(&database, "database", "d", "./filebrowser.db", "Database file")
flag.StringVarP(&logfile, "log", "l", "stdout", "Errors logger; can use 'stdout', 'stderr' or file") flag.StringVarP(&logfile, "log", "l", "stdout", "Errors logger; can use 'stdout', 'stderr' or file")
flag.StringVarP(&scope, "scope", "s", ".", "Default scope option for new users")
flag.StringVarP(&baseurl, "baseurl", "b", "", "Base URL") flag.StringVarP(&baseurl, "baseurl", "b", "", "Base URL")
flag.StringVar(&commands, "commands", "git svn hg", "Default commands option for new users")
flag.StringVar(&prefixurl, "prefixurl", "", "Prefix URL") flag.StringVar(&prefixurl, "prefixurl", "", "Prefix URL")
flag.StringVar(&viewMode, "view-mode", "mosaic", "Default view mode for new users")
flag.StringVar(&recaptchakey, "recaptcha-key", "", "ReCaptcha site key")
flag.StringVar(&recaptchasecret, "recaptcha-secret", "", "ReCaptcha secret")
flag.BoolVar(&allowCommands, "allow-commands", true, "Default allow commands option for new users")
flag.BoolVar(&allowEdit, "allow-edit", true, "Default allow edit option for new users")
flag.BoolVar(&allowPublish, "allow-publish", true, "Default allow publish option for new users")
flag.StringVar(&auth.method, "auth.method", "default", "Switch between 'none', 'default' and 'proxy' authentication.")
flag.StringVar(&auth.loginHeader, "auth.loginHeader", "X-Forwarded-User", "The header name used for proxy authentication.")
flag.BoolVar(&allowNew, "allow-new", true, "Default allow new option for new users")
flag.BoolVar(&noAuth, "no-auth", false, "Disables authentication")
flag.BoolVar(&alterRecaptcha, "alternative-recaptcha", false, "Use recaptcha.net for serving and handling, useful in China")
flag.StringVar(&locale, "locale", "", "Default locale for new users, set it empty to enable auto detect from browser")
flag.StringVar(&staticg, "staticgen", "", "Static Generator you want to enable") flag.StringVar(&staticg, "staticgen", "", "Static Generator you want to enable")
flag.BoolVarP(&showVer, "version", "v", false, "Show version") flag.BoolVarP(&showVer, "version", "v", false, "Show version")
// User default values
flag.StringVar(&commands, "defaults.commands", "git svn hg", "Default commands option for new users")
flag.StringVarP(&scope, "defaults.scope", "s", ".", "Default scope option for new users")
flag.StringVar(&viewMode, "defaults.viewMode", "mosaic", "Default view mode for new users")
flag.BoolVar(&allowCommands, "defaults.allowCommands", true, "Default allow commands option for new users")
flag.BoolVar(&allowEdit, "defaults.allowEdit", true, "Default allow edit option for new users")
flag.BoolVar(&allowPublish, "defaults.allowPublish", true, "Default allow publish option for new users")
flag.BoolVar(&allowNew, "defaults.allowNew", true, "Default allow new option for new users")
flag.StringVar(&locale, "defaults.locale", "", "Default locale for new users, set it empty to enable auto detect from browser")
// Recaptcha settings
flag.StringVar(&recaptcha.host, "recaptcha.host", "https://www.google.com", "Use another host for ReCAPTCHA. recaptcha.net might be useful in China")
flag.StringVar(&recaptcha.key, "recaptcha.key", "", "ReCaptcha site key")
flag.StringVar(&recaptcha.secret, "recaptcha.secret", "", "ReCaptcha secret")
// Auth settings
flag.StringVar(&auth.method, "auth.method", "default", "Switch between 'none', 'default' and 'proxy' authentication")
flag.StringVar(&auth.header, "auth.header", "X-Forwarded-User", "The header name used for proxy authentication")
} }
func setupViper() { func setupViper() {
viper.SetDefault("Address", "")
viper.SetDefault("Port", "0") viper.SetDefault("Port", "0")
viper.SetDefault("Address", "")
viper.SetDefault("Database", "./filebrowser.db") viper.SetDefault("Database", "./filebrowser.db")
viper.SetDefault("Scope", ".")
viper.SetDefault("Logger", "stdout") viper.SetDefault("Logger", "stdout")
viper.SetDefault("Commands", []string{"git", "svn", "hg"})
viper.SetDefault("AllowCommmands", true)
viper.SetDefault("AllowEdit", true)
viper.SetDefault("AllowNew", true)
viper.SetDefault("AllowPublish", true)
viper.SetDefault("StaticGen", "")
viper.SetDefault("Locale", "")
viper.SetDefault("AuthMethod", "default")
viper.SetDefault("LoginHeader", "X-Fowarded-User")
viper.SetDefault("NoAuth", false)
viper.SetDefault("BaseURL", "") viper.SetDefault("BaseURL", "")
viper.SetDefault("PrefixURL", "") viper.SetDefault("PrefixURL", "")
viper.SetDefault("ViewMode", filebrowser.MosaicViewMode) viper.SetDefault("StaticGen", "")
viper.SetDefault("AlternativeRecaptcha", false)
viper.SetDefault("ReCaptchaKey", "")
viper.SetDefault("ReCaptchaSecret", "")
viper.BindPFlag("Port", flag.Lookup("port")) viper.BindPFlag("Port", flag.Lookup("port"))
viper.BindPFlag("Address", flag.Lookup("address")) viper.BindPFlag("Address", flag.Lookup("address"))
viper.BindPFlag("Database", flag.Lookup("database")) viper.BindPFlag("Database", flag.Lookup("database"))
viper.BindPFlag("Scope", flag.Lookup("scope"))
viper.BindPFlag("Logger", flag.Lookup("log")) viper.BindPFlag("Logger", flag.Lookup("log"))
viper.BindPFlag("Commands", flag.Lookup("commands"))
viper.BindPFlag("AllowCommands", flag.Lookup("allow-commands"))
viper.BindPFlag("AllowEdit", flag.Lookup("allow-edit"))
viper.BindPFlag("AllowNew", flag.Lookup("allow-new"))
viper.BindPFlag("AllowPublish", flag.Lookup("allow-publish"))
viper.BindPFlag("Locale", flag.Lookup("locale"))
viper.BindPFlag("StaticGen", flag.Lookup("staticgen"))
viper.BindPFlag("AuthMethod", flag.Lookup("auth.method"))
viper.BindPFlag("LoginHeader", flag.Lookup("auth.loginHeader"))
viper.BindPFlag("NoAuth", flag.Lookup("no-auth"))
viper.BindPFlag("BaseURL", flag.Lookup("baseurl")) viper.BindPFlag("BaseURL", flag.Lookup("baseurl"))
viper.BindPFlag("PrefixURL", flag.Lookup("prefixurl")) viper.BindPFlag("PrefixURL", flag.Lookup("prefixurl"))
viper.BindPFlag("ViewMode", flag.Lookup("view-mode")) viper.BindPFlag("StaticGen", flag.Lookup("staticgen"))
viper.BindPFlag("AlternativeRecaptcha", flag.Lookup("alternative-recaptcha"))
viper.BindPFlag("ReCaptchaKey", flag.Lookup("recaptcha-key")) // User default values
viper.BindPFlag("ReCaptchaSecret", flag.Lookup("recaptcha-secret")) viper.SetDefault("Defaults.Scope", ".")
viper.SetDefault("Defaults.Commands", []string{"git", "svn", "hg"})
viper.SetDefault("Defaults.ViewMode", filebrowser.MosaicViewMode)
viper.SetDefault("Defaults.AllowCommmands", true)
viper.SetDefault("Defaults.AllowEdit", true)
viper.SetDefault("Defaults.AllowNew", true)
viper.SetDefault("Defaults.AllowPublish", true)
viper.SetDefault("Defaults.Locale", "")
viper.BindPFlag("Defaults.Scope", flag.Lookup("defaults.scope"))
viper.BindPFlag("Defaults.Commands", flag.Lookup("defaults.commands"))
viper.BindPFlag("Defaults.ViewMode", flag.Lookup("defaults.viewMode"))
viper.BindPFlag("Defaults.AllowCommands", flag.Lookup("defaults.allowCommands"))
viper.BindPFlag("Defaults.AllowEdit", flag.Lookup("defaults.allowEdit"))
viper.BindPFlag("Defaults.AllowNew", flag.Lookup("defaults.allowNew"))
viper.BindPFlag("Defaults.AllowPublish", flag.Lookup("defaults.allowPublish"))
viper.BindPFlag("Defaults.Locale", flag.Lookup("defaults.locale"))
// Recaptcha settings
viper.SetDefault("Recaptcha.Host", "https://www.google.com")
viper.SetDefault("Recaptcha.Key", "")
viper.SetDefault("Recaptcha.Secret", "")
viper.BindPFlag("Recaptcha.Host", flag.Lookup("recaptcha.host"))
viper.BindPFlag("Recaptcha.Key", flag.Lookup("recaptcha.key"))
viper.BindPFlag("Recaptcha.Secret", flag.Lookup("recaptcha.secret"))
// Auth settings
viper.SetDefault("Auth.Method", "default")
viper.SetDefault("Auth.Header", "X-Fowarded-User")
viper.BindPFlag("Auth.Method", flag.Lookup("auth.method"))
viper.BindPFlag("Auth.Header", flag.Lookup("auth.header"))
viper.SetConfigName("filebrowser") viper.SetConfigName("filebrowser")
viper.AddConfigPath(".") viper.AddConfigPath(".")
@ -175,13 +190,13 @@ func main() {
} }
// Validate the provided config before moving forward // Validate the provided config before moving forward
if viper.GetString("AuthMethod") != "none" && viper.GetString("AuthMethod") != "default" && viper.GetString("AuthMethod") != "proxy" { if viper.GetString("Auth.Method") != "none" && viper.GetString("Auth.Method") != "default" && viper.GetString("Auth.Method") != "proxy" {
log.Fatal("The property 'auth.method' needs to be set to 'default' or 'proxy'.") log.Fatal("The property 'auth.method' needs to be set to 'default' or 'proxy'.")
} }
if viper.GetString("AuthMethod") == "proxy" { if viper.GetString("Auth.Method") == "proxy" {
if viper.GetString("LoginHeader") == "" { if viper.GetString("Auth.Header") == "" {
log.Fatal("The 'loginHeader' needs to be specified when 'proxy' authentication is used.") log.Fatal("The 'auth.header' needs to be specified when 'proxy' authentication is used.")
} }
log.Println("[WARN] Filebrowser authentication is configured to 'proxy' authentication. This can cause a huge security issue if the infrastructure is not configured correctly.") log.Println("[WARN] Filebrowser authentication is configured to 'proxy' authentication. This can cause a huge security issue if the infrastructure is not configured correctly.")
} }
@ -208,32 +223,28 @@ func handler() http.Handler {
log.Fatal(err) log.Fatal(err)
} }
recaptchaHost := "https://www.google.com"
if viper.GetBool("AlternativeRecaptcha") {
recaptchaHost = "https://recaptcha.net"
}
fm := &filebrowser.FileBrowser{ fm := &filebrowser.FileBrowser{
AuthMethod: viper.GetString("AuthMethod"), Auth: &filebrowser.Auth{
LoginHeader: viper.GetString("LoginHeader"), Method: viper.GetString("Auth.Method"),
NoAuth: viper.GetBool("NoAuth"), Header: viper.GetString("Auth.Header"),
BaseURL: viper.GetString("BaseURL"), },
PrefixURL: viper.GetString("PrefixURL"), ReCaptcha: &filebrowser.ReCaptcha{
ReCaptchaHost: recaptchaHost, Host: viper.GetString("Recaptcha.Host"),
ReCaptchaKey: viper.GetString("ReCaptchaKey"), Key: viper.GetString("Recaptcha.Key"),
ReCaptchaSecret: viper.GetString("ReCaptchaSecret"), Secret: viper.GetString("Recaptcha.Secret"),
},
DefaultUser: &filebrowser.User{ DefaultUser: &filebrowser.User{
AllowCommands: viper.GetBool("AllowCommands"), AllowCommands: viper.GetBool("Defaults.AllowCommands"),
AllowEdit: viper.GetBool("AllowEdit"), AllowEdit: viper.GetBool("Defaults.AllowEdit"),
AllowNew: viper.GetBool("AllowNew"), AllowNew: viper.GetBool("Defaults.AllowNew"),
AllowPublish: viper.GetBool("AllowPublish"), AllowPublish: viper.GetBool("Defaults.AllowPublish"),
Commands: viper.GetStringSlice("Commands"), Commands: viper.GetStringSlice("Defaults.Commands"),
Rules: []*filebrowser.Rule{}, Rules: []*filebrowser.Rule{},
Locale: viper.GetString("Locale"), Locale: viper.GetString("Defaults.Locale"),
CSS: "", CSS: "",
Scope: viper.GetString("Scope"), Scope: viper.GetString("Defaults.Scope"),
FileSystem: fileutils.Dir(viper.GetString("Scope")), FileSystem: fileutils.Dir(viper.GetString("Defaults.Scope")),
ViewMode: viper.GetString("ViewMode"), ViewMode: viper.GetString("Defaults.ViewMode"),
}, },
Store: &filebrowser.Store{ Store: &filebrowser.Store{
Config: bolt.ConfigStore{DB: db}, Config: bolt.ConfigStore{DB: db},
@ -245,6 +256,9 @@ func handler() http.Handler {
}, },
} }
fm.SetBaseURL(viper.GetString("BaseURL"))
fm.SetPrefixURL(viper.GetString("PrefixURL"))
err = fm.Setup() err = fm.Setup()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

View File

@ -41,6 +41,25 @@ var (
ErrInvalidOption = errors.New("invalid option") ErrInvalidOption = errors.New("invalid option")
) )
// ReCaptcha settings.
type ReCaptcha struct {
Host string
Key string
Secret string
}
// Auth settings.
type Auth struct {
// Define if which of the following authentication mechansims should be used:
// - 'default', which requires a user and a password.
// - 'proxy', which requires a valid user and the user name has to be provided through an
// http header.
// - 'none', which allows anyone to access the filebrowser instance.
Method string
// If 'Method' is set to 'proxy' the header configured below is used to identify the user.
Header string
}
// FileBrowser is a file manager instance. It should be creating using the // FileBrowser is a file manager instance. It should be creating using the
// 'New' function and not directly. // 'New' function and not directly.
type FileBrowser struct { type FileBrowser struct {
@ -67,24 +86,11 @@ type FileBrowser struct {
// edited directly. Use SetBaseURL. // edited directly. Use SetBaseURL.
BaseURL string BaseURL string
// NoAuth disables the authentication. When the authentication is disabled, // Authentication configuration.
// there will only exist one user, called "admin". Auth *Auth
NoAuth bool
// Define if which of the following authentication mechansims should be used:
// - 'default', which requires a user and a password.
// - 'proxy', which requires a valid user and the user name has to be provided through an
// http header.
// - 'none', which allows anyone to access the filebrowser instance.
AuthMethod string
// When 'AuthMethod' is set to 'proxy' the header configured below is used to identify the user.
LoginHeader string
// ReCaptcha host, key and secret. // ReCaptcha host, key and secret.
ReCaptchaHost string ReCaptcha *ReCaptcha
ReCaptchaKey string
ReCaptchaSecret string
// StaticGen is the static websit generator handler. // StaticGen is the static websit generator handler.
StaticGen StaticGen StaticGen StaticGen

View File

@ -51,14 +51,14 @@ func reCaptcha(host, secret, response string) (bool, error) {
// authHandler processes the authentication for the user. // authHandler processes the authentication for the user.
func authHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) { func authHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {
if c.NoAuth { if c.Auth.Method == "none" {
// NoAuth instances shouldn't call this method. // NoAuth instances shouldn't call this method.
return 0, nil return 0, nil
} }
if c.AuthMethod == "proxy" { if c.Auth.Method == "proxy" {
// Receive the Username from the Header and check if it exists. // Receive the Username from the Header and check if it exists.
u, err := c.Store.Users.GetByUsername(r.Header.Get(c.LoginHeader), c.NewFS) u, err := c.Store.Users.GetByUsername(r.Header.Get(c.Auth.Header), c.NewFS)
if err != nil { if err != nil {
return http.StatusForbidden, nil return http.StatusForbidden, nil
} }
@ -80,8 +80,8 @@ func authHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, er
} }
// If ReCaptcha is enabled, check the code. // If ReCaptcha is enabled, check the code.
if len(c.ReCaptchaSecret) > 0 { if len(c.ReCaptcha.Secret) > 0 {
ok, err := reCaptcha(c.ReCaptchaHost, c.ReCaptchaSecret, cred.ReCaptcha) ok, err := reCaptcha(c.ReCaptcha.Host, c.ReCaptcha.Secret, cred.ReCaptcha)
if err != nil { if err != nil {
return http.StatusForbidden, err return http.StatusForbidden, err
} }
@ -178,14 +178,14 @@ func (e extractor) ExtractToken(r *http.Request) (string, error) {
// validateAuth is used to validate the authentication and returns the // validateAuth is used to validate the authentication and returns the
// User if it is valid. // User if it is valid.
func validateAuth(c *fb.Context, r *http.Request) (bool, *fb.User) { func validateAuth(c *fb.Context, r *http.Request) (bool, *fb.User) {
if c.NoAuth { if c.Auth.Method == "none" {
c.User = c.DefaultUser c.User = c.DefaultUser
return true, c.User return true, c.User
} }
// If proxy auth is used do not verify the JWT token if the header is provided. // If proxy auth is used do not verify the JWT token if the header is provided.
if c.AuthMethod == "proxy" { if c.Auth.Method == "proxy" {
u, err := c.Store.Users.GetByUsername(r.Header.Get(c.LoginHeader), c.NewFS) u, err := c.Store.Users.GetByUsername(r.Header.Get(c.Auth.Header), c.NewFS)
if err != nil { if err != nil {
return false, nil return false, nil
} }

View File

@ -228,12 +228,12 @@ func renderFile(c *fb.Context, w http.ResponseWriter, file string) (int, error)
data := map[string]interface{}{ data := map[string]interface{}{
"BaseURL": c.RootURL(), "BaseURL": c.RootURL(),
"NoAuth": c.NoAuth, "NoAuth": c.Auth.Method == "none",
"Version": fb.Version, "Version": fb.Version,
"CSS": template.CSS(c.CSS), "CSS": template.CSS(c.CSS),
"ReCaptcha": c.ReCaptchaKey != "" && c.ReCaptchaSecret != "", "ReCaptcha": c.ReCaptcha.Key != "" && c.ReCaptcha.Secret != "",
"ReCaptchaHost": c.ReCaptchaHost, "ReCaptchaHost": c.ReCaptcha.Host,
"ReCaptchaKey": c.ReCaptchaKey, "ReCaptchaKey": c.ReCaptcha.Key,
} }
if c.StaticGen != nil { if c.StaticGen != nil {

View File

@ -12,15 +12,15 @@ import (
) )
func subtitlesHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) { func subtitlesHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {
files, err := ReadDir(filepath.Dir(c.File.Path)) files, err := readDir(filepath.Dir(c.File.Path))
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
var subtitles = make([]map[string]string, 0) subtitles := make([]map[string]string, 0)
for _, file := range files { for _, file := range files {
ext := filepath.Ext(file.Name()) ext := filepath.Ext(file.Name())
if ext == ".vtt" || ext == ".srt" { if ext == ".vtt" || ext == ".srt" {
var sub map[string]string = make(map[string]string) sub := make(map[string]string)
sub["src"] = filepath.Dir(c.File.Path) + "/" + file.Name() sub["src"] = filepath.Dir(c.File.Path) + "/" + file.Name()
sub["kind"] = "subtitles" sub["kind"] = "subtitles"
sub["label"] = file.Name() sub["label"] = file.Name()
@ -31,7 +31,7 @@ func subtitlesHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (in
} }
func subtitleHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) { func subtitleHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {
str, err := CleanSubtitle(c.File.Path) str, err := cleanSubtitle(c.File.Path)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
@ -55,7 +55,7 @@ func subtitleHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int
} }
func CleanSubtitle(filename string) (string, error) { func cleanSubtitle(filename string) (string, error) {
b, err := ioutil.ReadFile(filename) b, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
return "", err return "", err
@ -69,7 +69,7 @@ func CleanSubtitle(filename string) (string, error) {
return str, err return str, err
} }
func ReadDir(dirname string) ([]os.FileInfo, error) { func readDir(dirname string) ([]os.FileInfo, error) {
f, err := os.Open(dirname) f, err := os.Open(dirname)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -276,7 +276,7 @@ func usersPutHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int
// If we're updating the default user. Only for NoAuth // If we're updating the default user. Only for NoAuth
// implementations. Used to change the viewMode. // implementations. Used to change the viewMode.
if id == 0 && c.NoAuth { if id == 0 && c.Auth.Method == "none" {
c.DefaultUser.ViewMode = u.ViewMode c.DefaultUser.ViewMode = u.ViewMode
return http.StatusOK, nil return http.StatusOK, nil
} }