Commit 05c9d364 authored by Sonja Happ's avatar Sonja Happ
Browse files

Merge branch 'json-testdata' into 'master'

Read testdata from JSON

See merge request !26
parents d99b7691 2fb4dec1
......@@ -68,8 +68,6 @@ test:
DB_PASS: ${POSTGRES_PASSWORD}
BASE_PATH: /api
MODE: release
ADMIN_USER: User_0
ADMIN_PASS: xyz789
services:
- postgres:latest
- rabbitmq:latest
......@@ -106,8 +104,6 @@ test:files_postgres:
DB_PASS: ${POSTGRES_PASSWORD}
BASE_PATH: /api
MODE: release
ADMIN_USER: User_0
ADMIN_PASS: xyz789
services:
- postgres:latest
script:
......
......@@ -61,6 +61,7 @@ func InitConfig() error {
s3PathStyle = flag.Bool("s3-pathstyle", false, "Use path-style S3 API")
jwtSecret = flag.String("jwt-secret", "This should NOT be here!!@33$8&", "The JSON Web Token secret")
jwtExpiresAfter = flag.String("jwt-expires-after", "168h" /* 1 week */, "The time after which the JSON Web Token expires")
testDataPath = flag.String("test-data-path", "database/testdata.json", "The path to the test data json file (used in test mode)")
)
flag.Parse()
......@@ -85,6 +86,7 @@ func InitConfig() error {
"s3.region": *s3Region,
"jwt.secret": *jwtSecret,
"jwt.expires-after": *jwtExpiresAfter,
"test.datapath": *testDataPath,
}
if *s3NoSSL == true {
......@@ -122,6 +124,7 @@ func InitConfig() error {
"S3_PATHSTYLE": "s3.pathstyle",
"JWT_SECRET": "jwt.secret",
"JWT_EXPIRES_AFTER": "jwt.expires-after",
"TEST_DATA_PATH": "test.datapath",
}
defaults := config.NewStatic(static)
......
......@@ -23,8 +23,11 @@ package database
import (
"fmt"
"golang.org/x/crypto/bcrypt"
"log"
"math/rand"
"strings"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
......@@ -110,3 +113,58 @@ func MigrateModels() {
DBpool.AutoMigrate(&Widget{})
DBpool.AutoMigrate(&Result{})
}
// DBAddAdminUser adds a default admin user to the DB
func DBAddAdminUser(cfg *config.Config) (error, string) {
DBpool.AutoMigrate(User{})
// Check if admin user exists in DB
var users []User
err := DBpool.Where("Role = ?", "Admin").Find(&users).Error
adminPW := ""
if len(users) == 0 {
fmt.Println("No admin user found in DB, adding default admin user.")
name, err := cfg.String("admin.user")
if err != nil || name == "" {
name = "admin"
}
adminPW, err = cfg.String("admin.pass")
if err != nil || adminPW == "" {
adminPW = generatePassword(16)
fmt.Printf(" Generated admin password: %s\n", adminPW)
}
mail, err := cfg.String("admin.mail")
if err == nil || mail == "" {
mail = "admin@example.com"
}
pwEnc, _ := bcrypt.GenerateFromPassword([]byte(adminPW), 10)
// create a copy of global test data
user := User{Username: name, Password: string(pwEnc),
Role: "Admin", Mail: mail, Active: true}
// add admin user to DB
err = DBpool.Create(&user).Error
}
return err, adminPW
}
func generatePassword(Len int) string {
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789")
var b strings.Builder
for i := 0; i < Len; i++ {
b.WriteRune(chars[rand.Intn(len(chars))])
}
return b.String()
}
{
"users": [
{
"username": "User_0",
"password": "xyz789",
"role": "Admin",
"mail": "User_0@example.com"
},
{
"username": "User_A",
"password": "abc123",
"role": "User",
"mail": "User_A@example.com"
},
{
"username": "User_B",
"password": "bcd234",
"role": "User",
"mail": "User_B@example.com"
},
{
"username": "User_C",
"password": "guestpw",
"role": "Guest",
"mail": "User_C@example.com"
}
],
"ics": [
{
"uuid": "7be0322d-354e-431e-84bd-ae4c9633138b",
"name": "ACS Demo Signals",
"type": "villas-node",
"category": "gateway",
"websocketurl": "https://villas.k8s.eonerc.rwth-aachen.de/ws/ws_sig",
"apiurl": "https://villas.k8s.eonerc.rwth-aachen.de/ws/api/v2",
"location": "K8S",
"description": "A signal generator for testing purposes",
"state": "idle",
"managedexternally": false,
"startparameterscheme": {
"param1": 42,
"param2": "testvalue"
}
},
{
"uuid": "4854af30-325f-44a5-ad59-b67b2597de68",
"name": "Test DPsim Simulator",
"type": "dpsim",
"category": "simulator",
"location": "acs lab",
"description": "DPsim simulator",
"state": "running",
"managedexternally": true,
"startparameterscheme": {
"param1": 55,
"param2": "testvalue2"
}
}
],
"scenarios": [
{
"name": "Scenario_A",
"startParameters": {
"param1": "a nice param",
"param2": "a not so nice param"
}
},
{
"name": "Scenario_B",
"startParameters": {
"param1": "another nice param",
"param2": "another not so nice param"
}
}
],
"configs": [
{
"name": "Example for Signal generator",
"startParameters": {
"param1": "nice param",
"param2": "not so nice"
},
"fileIDs" : []
},
{
"name": "Example for DPsim simulator",
"startParameters": {
"param1": "cool thing",
"param2": "who needs this"
},
"fileIDs" : []
}
],
"dashboards": [
{
"name": "Dashboard_A",
"grid": 15
},
{
"name": "Dashboard_B",
"grid": 10
}
],
"results": [
{
"description": "Test run 1"
},
{
"description": "Test run 2"
}
],
"widgets": [
{
"name": "MyLabel",
"type": "Label",
"width": 100,
"height": 50,
"minWidth": 40,
"minHeight": 80,
"x": 10,
"y": 10,
"z": 200,
"isLocked": false,
"signalIDs": [],
"customProperties": {
"textSize" : "20",
"fontColor" : "#4287f5",
"fontColor_opacity": 1
}
},
{
"name": "MySlider",
"type": "Slider",
"width": 400,
"height": 50,
"minWidth": 30,
"minHeight": 380,
"x": 70,
"y": 400,
"z": 0,
"isLocked": false,
"signalIDs": [],
"customProperties": {
"default_value" : 0,
"orientation" : 0,
"rangeMin" : 0,
"rangeMax": 200,
"rangeUseMinMax" : true,
"showUnit": true,
"continous_update": false,
"value": "",
"resizeLeftRightLock": false,
"resizeTopBottomLock": true,
"step": 0.1
}
},
{
"name": "MyBox",
"type": "Box",
"width": 200,
"height": 200,
"minWidth": 10,
"minHeight": 50,
"x": 300,
"y": 10,
"z": 0,
"isLocked": false,
"signalIDs": [],
"customProperties": {
"border_color" : "#4287f5",
"border_color_opacity": 1,
"background_color" : "#961520",
"background_color_opacity" : 1
}
},
{
"name": "MyButton",
"type": "Button",
"width": 100,
"height": 100,
"minWidth": 50,
"minHeight": 100,
"x": 10,
"y": 50,
"z": 0,
"isLocked": false,
"signalIDs": [],
"customProperties": {
"pressed": false,
"toggle" : false,
"on_value" : 1,
"off_value" : 0,
"background_color": "#961520",
"font_color": "#4287f5",
"border_color": "#4287f5",
"background_color_opacity": 1
}
},
{
"name": "MyLamp",
"type": "Lamp",
"width": 200,
"height": 20,
"minWidth": 10,
"minHeight": 50,
"x": 50,
"y": 300,
"z": 0,
"isLocked": false,
"signalIDs": [],
"customProperties": {
"on_color" : "#4287f5",
"off_color": "#961520",
"threshold" : 0.5,
"on_color_opacity": 1,
"off_color_opacity": 1
}
}
],
"signals": [
{
"name": "outSignal_A",
"direction": "out",
"unit": "V",
"index": 1
},
{
"name": "outSignal_B",
"direction": "out",
"unit": "V",
"index": 2
},
{
"name": "outSignal_C",
"direction": "out",
"unit": "---",
"index": 3
},
{
"name": "outSignal_D",
"direction": "out",
"unit": "---",
"index": 4
},
{
"name": "outSignal_E",
"direction": "out",
"unit": "---",
"index": 5
},
{
"name": "inSignal_A",
"direction": "in",
"unit": "---",
"index": 1
},
{
"name": "inSignal_B",
"direction": "in",
"unit": "---",
"index": 2
}
]
}
\ No newline at end of file
/** Helper package, test data.
*
* @author Sonja Happ <sonja.happ@eonerc.rwth-aachen.de>
* @copyright 2014-2019, Institute for Automation of Complex Power Systems, EONERC
* @license GNU General Public License (version 3)
*
* VILLASweb-backend-go
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*********************************************************************************/
package helper
import (
"encoding/json"
"fmt"
"math/rand"
"strings"
"time"
"git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
"github.com/jinzhu/gorm/dialects/postgres"
"github.com/zpatrick/go-config"
"golang.org/x/crypto/bcrypt"
)
// #######################################################################
// #################### Data used for testing ############################
// #######################################################################
// Credentials
var StrPassword0 = "xyz789"
var StrPasswordA = "abc123"
var StrPasswordB = "bcd234"
var StrPasswordC = "guestpw"
// Hash passwords with bcrypt algorithm
var bcryptCost = 10
var pw0, _ = bcrypt.GenerateFromPassword([]byte(StrPassword0), bcryptCost)
var pwA, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordA), bcryptCost)
var pwB, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordB), bcryptCost)
var pwC, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordC), bcryptCost)
var User0 = database.User{Username: "User_0", Password: string(pw0),
Role: "Admin", Mail: "User_0@example.com", Active: true}
var UserA = database.User{Username: "User_A", Password: string(pwA),
Role: "User", Mail: "User_A@example.com", Active: true}
var UserB = database.User{Username: "User_B", Password: string(pwB),
Role: "User", Mail: "User_B@example.com", Active: true}
var UserC = database.User{Username: "User_C", Password: string(pwC),
Role: "Guest", Mail: "User_C@example.com", Active: true}
type UserRequest struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
OldPassword string `json:"oldPassword,omitempty"`
Mail string `json:"mail,omitempty"`
Role string `json:"role,omitempty"`
Active string `json:"active,omitempty"`
}
var NewUserA = UserRequest{
Username: UserA.Username,
Password: StrPasswordA,
Role: UserA.Role,
Mail: UserA.Mail,
}
var NewUserB = UserRequest{
Username: UserB.Username,
Password: StrPasswordB,
Role: UserB.Role,
Mail: UserB.Mail,
}
var NewUserC = UserRequest{
Username: UserC.Username,
Password: StrPasswordC,
Role: UserC.Role,
Mail: UserC.Mail,
}
// Infrastructure components
var propertiesA = json.RawMessage(`{"prop1" : "a nice prop"}`)
var propertiesB = json.RawMessage(`{"prop1" : "not so nice"}`)
var ICA = database.InfrastructureComponent{
UUID: "7be0322d-354e-431e-84bd-ae4c9633138b",
WebsocketURL: "https://villas.k8s.eonerc.rwth-aachen.de/ws/ws_sig",
APIURL: "https://villas.k8s.eonerc.rwth-aachen.de/ws/api/v2",
Type: "villas-node",
Category: "gateway",
Name: "ACS Demo Signals",
Uptime: -1.0,
State: "idle",
Location: "k8s",
Description: "A signal generator for testing purposes",
StartParameterScheme: postgres.Jsonb{propertiesA},
ManagedExternally: false,
}
var ICB = database.InfrastructureComponent{
UUID: "4854af30-325f-44a5-ad59-b67b2597de68",
WebsocketURL: "xxx.yyy.zzz.aaa",
Type: "dpsim",
Category: "simulator",
Name: "Test DPsim Simulator",
Uptime: -1.0,
State: "running",
Location: "ACS Laboratory",
Description: "This is a test description",
StartParameterScheme: postgres.Jsonb{propertiesB},
ManagedExternally: true,
}
// Scenarios
var startParametersA = json.RawMessage(`{"parameter1" : "testValue1A", "parameter2" : "testValue2A", "parameter3" : 42}`)
var startParametersB = json.RawMessage(`{"parameter1" : "testValue1B", "parameter2" : "testValue2B", "parameter3" : 43}`)
var ScenarioA = database.Scenario{
Name: "Scenario_A",
Running: true,
StartParameters: postgres.Jsonb{startParametersA},
}
var ScenarioB = database.Scenario{
Name: "Scenario_B",
Running: false,
StartParameters: postgres.Jsonb{startParametersB},
}
// Component Configuration
var ConfigA = database.ComponentConfiguration{
Name: "Example for Signal generator",
StartParameters: postgres.Jsonb{startParametersA},
FileIDs: []int64{},
}
var ConfigB = database.ComponentConfiguration{
Name: "VILLASnode gateway X",
StartParameters: postgres.Jsonb{startParametersB},
FileIDs: []int64{},
}
// Signals
var OutSignalA = database.Signal{
Name: "outSignal_A",
Direction: "out",
Index: 1,
Unit: "V",
}
var OutSignalB = database.Signal{
Name: "outSignal_B",
Direction: "out",
Index: 2,
Unit: "V",
}
var OutSignalC = database.Signal{
Name: "outSignal_C",
Direction: "out",
Index: 3,
Unit: "---",
}
var OutSignalD = database.Signal{
Name: "outSignal_D",
Direction: "out",
Index: 4,
Unit: "---",
}
var OutSignalE = database.Signal{
Name: "outSignal_E",
Direction: "out",
Index: 5,
Unit: "---",
}
var InSignalA = database.Signal{
Name: "inSignal_A",
Direction: "in",
Index: 1,
Unit: "---",
}
var InSignalB = database.Signal{
Name: "inSignal_B",
Direction: "in",
Index: 2,
Unit: "---",
}
// Dashboards
var DashboardA = database.Dashboard{
Name: "Dashboard_A",
Grid: 15,
}
var DashboardB = database.Dashboard{
Name: "Dashboard_B",
Grid: 10,
}
// Files
var FileA = database.File{
Name: "File_A",
Type: "text/plain",
Size: 42,
Date: time.Now().String(),
}
var FileB = database.File{
Name: "File_B",
Type: "text/plain",
Size: 1234,
Date: time.Now().String(),
}
var FileC = database.File{
Name: "File_C",
Type: "text/plain",