1
0
Fork 0
mirror of https://github.com/shouptech/tempgopher.git synced 2026-02-03 08:39:43 +00:00

Add auth to /api

This commit is contained in:
Emma 2018-10-11 21:41:48 -06:00
parent c817f27eb2
commit 89657c381b
6 changed files with 31 additions and 1 deletions

View file

@ -36,9 +36,16 @@ type Sensor struct {
Verbose bool `json:"verbose" yaml:"verbose"`
}
// User defines a user's configuration
type User struct {
Name string `json:"name" yaml:"name"`
Password string `json:"password" yaml:"password"`
}
// Config contains the applications configuration
type Config struct {
Sensors []Sensor `yaml:"sensors"`
Users []User `yaml:"users"`
BaseURL string `yaml:"baseurl"`
ListenAddr string `yaml:"listenaddr"`
DisplayFahrenheit bool `yaml:"displayfahrenheit"`

View file

@ -8,6 +8,11 @@ import (
func Test_LoadConfig(t *testing.T) {
testUser := User{
Name: "foo",
Password: "bar",
}
testConfig := Config{
Sensors: []Sensor{
Sensor{
@ -24,6 +29,7 @@ func Test_LoadConfig(t *testing.T) {
Verbose: true,
},
},
Users: []User{testUser},
BaseURL: "https://foo.bar",
ListenAddr: "127.0.0.1:8080",
DisplayFahrenheit: true,

View file

@ -21,6 +21,8 @@ sensors:
coolinvert: false
coolminutes: 10
verbose: true
users:
- foo: bar
baseurl: https://foo.bar
listenaddr: 127.0.0.1:8080
displayfahrenheit: true

View file

@ -21,6 +21,8 @@ sensors:
coolinvert: false
coolminutes: 10
verbose: true
users:
- foo: bar
baseurl: https://foo.bar
listenaddr: 127.0.0.1:8080
displayfahrenheit: true

View file

@ -10,6 +10,9 @@ sensors:
coolinvert: false
coolminutes: 10
verbose: true
users:
- name: foo
password: bar
baseurl: https://foo.bar
listenaddr: 127.0.0.1:8080
displayfahrenheit: true

12
web.go
View file

@ -40,6 +40,7 @@ func ConfigHandler(config *Config) gin.HandlerFunc {
} else if c.Param("alias") == "/" {
c.JSON(http.StatusOK, config.Sensors)
} else {
config.Users = nil // Never return the users in GET requests
c.JSON(http.StatusOK, config)
}
}
@ -125,7 +126,7 @@ func SetupRouter(config *Config, states *map[string]State) *gin.Engine {
r.GET("/ping", PingHandler)
// API Endpoints
api := r.Group("/api")
api := r.Group("/api", gin.BasicAuth(GetGinAccounts(config)))
{
api.GET("/status", StatusHandler(states))
api.GET("/status/*alias", StatusHandler(states))
@ -159,6 +160,15 @@ func reloadWebConfig(c *Config, p string) error {
return nil
}
// GetGinAccounts returns a gin.Accounts struct with values pulled from a Config struct
func GetGinAccounts(config *Config) gin.Accounts {
var a gin.Accounts
for _, user := range config.Users {
a[user.Name] = user.Password
}
return a
}
// RunWeb launches a web server. sc is used to update the states from the Thermostats.
func RunWeb(configpath string, sc <-chan State, wg *sync.WaitGroup) {
// Update sensor states when a new state comes back from the thermostat.