Create initial user if User table is empty. Also make model.QueryOptions compatible with rest.QueryOptions

This commit is contained in:
Deluan 2020-01-19 22:36:15 -05:00
parent 2ab0cecd48
commit 491bfb1f69
11 changed files with 130 additions and 38 deletions

View file

@ -2,16 +2,21 @@ package app
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/cloudsonic/sonic-server/log"
"github.com/cloudsonic/sonic-server/model"
"github.com/cloudsonic/sonic-server/server"
"github.com/deluan/rest"
"github.com/go-chi/chi"
"github.com/google/uuid"
)
const initialUser = "admin"
type Router struct {
ds model.DataStore
mux http.Handler
@ -21,6 +26,7 @@ type Router struct {
func New(ds model.DataStore, path string) *Router {
r := &Router{ds: ds, path: path}
r.mux = r.routes()
r.createDefaultUser()
return r
}
@ -46,6 +52,24 @@ func (app *Router) routes() http.Handler {
return r
}
func (app *Router) createDefaultUser() {
c, err := app.ds.User().CountAll()
if err != nil {
panic(fmt.Sprintf("Could not access User table: %s", err))
}
if c == 0 {
id, _ := uuid.NewRandom()
initialPassword, _ := uuid.NewRandom()
log.Warn("Creating initial user. Please change the password!", "user", initialUser, "password", initialPassword)
app.ds.User().Put(&model.User{
ID: id.String(),
Name: initialUser,
Password: initialPassword.String(),
IsAdmin: true,
})
}
}
func R(r chi.Router, pathPrefix string, newRepository rest.RepositoryConstructor) {
r.Route(pathPrefix, func(r chi.Router) {
r.Get("/", rest.GetAll(newRepository))