fixed no-auth problem (now works as intended)

This commit is contained in:
Bora M. Alper 2018-12-30 19:40:11 +03:00
parent b375658fca
commit f8a780068c
No known key found for this signature in database
GPG Key ID: 8F1A9504E1BD114D

View File

@ -41,12 +41,14 @@ var templates map[string]*template.Template
var database persistence.Database var database persistence.Database
var opts struct { var opts struct {
Addr string Addr string
Database string Database string
// Credentials is nil when no-auth cmd-line flag is supplied.
Credentials map[string][]byte // TODO: encapsulate credentials and mutex for safety Credentials map[string][]byte // TODO: encapsulate credentials and mutex for safety
CredentialsRWMutex sync.RWMutex CredentialsRWMutex sync.RWMutex
CredentialsPath string // CredentialsPath is nil when no-auth is supplied.
Verbosity int CredentialsPath string
Verbosity int
} }
func main() { func main() {
@ -230,22 +232,22 @@ func parseFlags() error {
opts.Database = cmdFlags.Database opts.Database = cmdFlags.Database
} }
if cmdFlags.Cred == "" && !cmdFlags.NoAuth { if !cmdFlags.NoAuth {
opts.CredentialsPath = path.Join( // Set opts.CredentialsPath to either the default value (computed by appdirs pkg) or to the one
appdirs.UserConfigDir("magneticow", "", "", false), // supplied by the user.
"credentials", if cmdFlags.Cred == "" {
) opts.CredentialsPath = path.Join(
} else { appdirs.UserConfigDir("magneticow", "", "", false),
opts.CredentialsPath = cmdFlags.Cred "credentials",
} )
} else {
opts.CredentialsPath = cmdFlags.Cred
}
if opts.CredentialsPath != "" {
opts.Credentials = make(map[string][]byte) opts.Credentials = make(map[string][]byte)
if err := loadCred(opts.CredentialsPath); err != nil { if err := loadCred(opts.CredentialsPath); err != nil {
return err return err
} }
} else {
opts.Credentials = nil
} }
opts.Verbosity = len(cmdFlags.Verbose) opts.Verbosity = len(cmdFlags.Verbose)
@ -309,6 +311,11 @@ func loadCred(cred string) error {
// Source: https://stackoverflow.com/a/39591234/4466589 // Source: https://stackoverflow.com/a/39591234/4466589
func BasicAuth(handler http.HandlerFunc, realm string) http.HandlerFunc { func BasicAuth(handler http.HandlerFunc, realm string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if opts.Credentials == nil { // --no-auth is supplied by the user.
handler(w, r)
return
}
username, password, ok := r.BasicAuth() username, password, ok := r.BasicAuth()
if !ok { // No credentials provided if !ok { // No credentials provided
authenticate(w, realm) authenticate(w, realm)