Finish adding simple user authentication

This commit is contained in:
2013-08-28 23:05:28 -04:00
parent 7009b0eda8
commit 9c442254a7
7 changed files with 60 additions and 21 deletions

View File

@ -22,6 +22,8 @@ type AsinkGlobals struct {
storage Storage
server string
port int
username string
password string
}
var globals AsinkGlobals
@ -42,6 +44,12 @@ func init() {
func main() {
flag.Parse()
//make sure config file's permissions are read-write only for the current user
if !util.FileExistsAndHasPermissions(globals.configFileName, 384 /*0b110000000*/) {
fmt.Println("Error: Either the file at "+globals.configFileName+" doesn't exist, or it doesn't have permissions such that the current user is the only one allowed to read and write.")
return
}
config, err := conf.ReadConfigFile(globals.configFileName)
if err != nil {
fmt.Println(err)
@ -73,8 +81,11 @@ func main() {
panic(err)
}
//TODO check errors on server settings
globals.server, err = config.GetString("server", "host")
globals.port, err = config.GetInt("server", "port")
globals.username, err = config.GetString("server", "username")
globals.password, err = config.GetString("server", "password")
globals.db, err = GetAndInitDB(config)
if err != nil {

View File

@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
@ -15,6 +16,25 @@ import (
const MIN_ERROR_WAIT = 100 // 1/10 of a second
const MAX_ERROR_WAIT = 10000 // 10 seconds
func AuthenticatedRequest(method, url, bodyType string, body io.Reader, username, password string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if bodyType != "" {
req.Header.Set("Content-Type", bodyType)
}
req.SetBasicAuth(username, password)
return client.Do(req)
}
func AuthenticatedGet(url string, username, password string) (*http.Response, error) {
return AuthenticatedRequest("GET", url, "", nil, username, password)
}
func AuthenticatedPost(url, bodyType string, body io.Reader, username, password string) (*http.Response, error) {
return AuthenticatedRequest("POST", url, bodyType, body, username, password)
}
func SendEvent(globals AsinkGlobals, event *asink.Event) error {
url := "http://" + globals.server + ":" + strconv.Itoa(int(globals.port)) + "/events/"
@ -28,7 +48,7 @@ func SendEvent(globals AsinkGlobals, event *asink.Event) error {
}
//actually make the request
resp, err := http.Post(url, "application/json", bytes.NewReader(b))
resp, err := AuthenticatedPost(url, "application/json", bytes.NewReader(b), globals.username, globals.password)
if err != nil {
return err
}
@ -80,7 +100,7 @@ func GetEvents(globals AsinkGlobals, events chan *asink.Event) {
} else {
fullUrl = url + "0"
}
resp, err := http.Get(fullUrl)
resp, err := AuthenticatedGet(fullUrl, globals.username, globals.password)
//if error, perform exponential backoff (with maximum timeout)
if err != nil {