added basic auth
This commit is contained in:
@@ -23,7 +23,7 @@ func Start(config *types.AppConfig) {
|
||||
|
||||
client := client.NewClient(db, s3Client)
|
||||
|
||||
err = web.StartWebserver(config.Address, *client)
|
||||
err = web.StartWebserver(config.Address, *client, config.APIUsername, config.APIPassword)
|
||||
if err != nil {
|
||||
logrus.Fatal(err.Error())
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ type AppConfig struct {
|
||||
S3SSL bool
|
||||
S3Bucket string
|
||||
Address string
|
||||
APIUsername string
|
||||
APIPassword string
|
||||
}
|
||||
|
||||
type Metadata struct {
|
||||
|
||||
@@ -2,6 +2,7 @@ package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -20,7 +21,11 @@ type deleteShare struct {
|
||||
Slug string `json:"slug"`
|
||||
}
|
||||
|
||||
func StartWebserver(addr string, client client.Client) error {
|
||||
func StartWebserver(addr string, client client.Client, username, password string) error {
|
||||
if username == "" || password == "" {
|
||||
return errors.New("API username and password must be set")
|
||||
}
|
||||
|
||||
r := mux.NewRouter()
|
||||
|
||||
r.HandleFunc("/{slug:[a-zA-Z0-9]{6}}", func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -53,11 +58,16 @@ func StartWebserver(addr string, client client.Client) error {
|
||||
}).Methods("HEAD")
|
||||
|
||||
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !checkAuth(w, r, username, password) {
|
||||
return
|
||||
}
|
||||
|
||||
}).Methods("GET")
|
||||
|
||||
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
|
||||
// TODO: check auth
|
||||
if !checkAuth(w, r, username, password) {
|
||||
return
|
||||
}
|
||||
|
||||
var shareParams createShare
|
||||
err := json.NewDecoder(r.Body).Decode(&shareParams)
|
||||
@@ -81,7 +91,9 @@ func StartWebserver(addr string, client client.Client) error {
|
||||
}).Methods("POST")
|
||||
|
||||
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
|
||||
//TODO: check auth
|
||||
if !checkAuth(w, r, username, password) {
|
||||
return
|
||||
}
|
||||
|
||||
var shareParams deleteShare
|
||||
err := json.NewDecoder(r.Body).Decode(&shareParams)
|
||||
@@ -136,3 +148,18 @@ func getShareHead(client client.Client, w http.ResponseWriter, r *http.Request)
|
||||
|
||||
return share
|
||||
}
|
||||
|
||||
func checkAuth(w http.ResponseWriter, r *http.Request, username, password string) bool {
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return false
|
||||
}
|
||||
|
||||
if username != username || password != password {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user