2016-04-29 06:00:04 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2016-04-30 05:59:13 +02:00
|
|
|
"os"
|
2016-04-29 06:00:04 +02:00
|
|
|
|
|
|
|
"github.com/apexskier/httpauth"
|
|
|
|
)
|
|
|
|
|
2016-04-29 16:37:21 +02:00
|
|
|
type AuthHTTP struct {
|
2016-04-29 06:00:04 +02:00
|
|
|
backend httpauth.LeveldbAuthBackend
|
|
|
|
aaa httpauth.Authorizer
|
|
|
|
}
|
|
|
|
|
2016-04-30 05:59:13 +02:00
|
|
|
type User struct {
|
|
|
|
Username string
|
|
|
|
Password string
|
|
|
|
Role string
|
|
|
|
}
|
|
|
|
|
2016-04-29 16:37:21 +02:00
|
|
|
func initAuth() *AuthHTTP {
|
|
|
|
return &AuthHTTP{}
|
2016-04-29 06:00:04 +02:00
|
|
|
}
|
|
|
|
|
2016-04-30 05:59:13 +02:00
|
|
|
func (auth *AuthHTTP) createAuthDb(backendFile string) error {
|
|
|
|
var err error
|
|
|
|
os.Mkdir(backendFile, 0755)
|
|
|
|
|
|
|
|
auth.backend, err = httpauth.NewLeveldbAuthBackend(backendFile)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error creating Auth backend: %s", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-29 16:37:21 +02:00
|
|
|
func (auth *AuthHTTP) createRoles() {
|
|
|
|
var err error
|
2016-04-29 06:00:04 +02:00
|
|
|
roles := make(map[string]httpauth.Role)
|
|
|
|
|
|
|
|
roles["user"] = 30
|
|
|
|
roles["admin"] = 80
|
2016-04-29 16:37:21 +02:00
|
|
|
auth.aaa, err = httpauth.NewAuthorizer(auth.backend, []byte("topsecretkey"), "user", roles)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error creating roles: %s", err)
|
|
|
|
}
|
2016-04-29 06:00:04 +02:00
|
|
|
}
|
|
|
|
|
2016-04-30 23:48:45 +02:00
|
|
|
func (auth *AuthHTTP) createInitialUser(username, password, role, email string) error {
|
2016-04-29 16:37:21 +02:00
|
|
|
user := httpauth.UserData{Username: username, Role: role, Email: email}
|
|
|
|
err := auth.backend.SaveUser(user)
|
2016-04-29 06:00:04 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error saving user: %s", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-04-29 16:37:21 +02:00
|
|
|
err = auth.aaa.Update(nil, nil, username, password, "")
|
2016-04-29 06:00:04 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error saving user: %s", err)
|
|
|
|
return err
|
|
|
|
}
|
2016-04-29 16:37:21 +02:00
|
|
|
|
|
|
|
return nil
|
2016-04-29 06:00:04 +02:00
|
|
|
}
|
2016-05-05 03:05:50 +02:00
|
|
|
|
|
|
|
func (auth *AuthHTTP) listUsers() ([]httpauth.UserData, error) {
|
|
|
|
users, err := auth.backend.Users()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error list users: %s", err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("listing users: %+v", users)
|
|
|
|
return users, nil
|
|
|
|
}
|