Пример #1
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Initialize the configuration and logging systems. Plus anything
	// else the web app layer needs.
	tests.Init("XENIA")

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, cfg.MustURL("MONGO_URI").String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	db, err := db.NewMGO(tests.Context, tests.TestSession)
	if err != nil {
		fmt.Println("MongoDB is not configured")
		return 1
	}
	defer db.CloseMGO(tests.Context)

	if err := loadTestData(tests.Context, db); err != nil {
		fmt.Println("test data is not loaded: " + err.Error())
		return 1
	}
	defer unloadTestData(tests.Context, db)

	return m.Run()
}
Пример #2
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, cfg.MustURL("MONGO_URI").String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	// Setup the app for performing tests.
	a = routes.API()

	// Snatch the mongo session so we can create some test data.
	db, err := db.NewMGO(tests.Context, tests.TestSession)
	if err != nil {
		fmt.Println("Unable to get Mongo session")
		return 1
	}
	defer db.CloseMGO(tests.Context)

	// Generate the test data.
	tstdata.Generate(db)
	defer tstdata.Drop(db)

	// Load in the submissions from the fixture.
	if err = loadSubmissions(db); err != nil {
		fmt.Println("Unable to load submissions: ", err)
	}
	defer aggfix.Remove(tests.Context, db, "")

	return m.Run()
}
Пример #3
0
// loadTestData adds all the test data into the database.
func loadTestData(context interface{}, db *db.DB) error {

	// Make sure the old data is clear.
	if err := unloadTestData(context, db); err != nil {
		if !graph.IsQuadNotExist(err) {
			return err
		}
	}

	// -----------------------------------------------------------
	// Load example items, relationships, views, and patterns.

	items, rels, vs, pats, err := wirefix.Get()
	if err != nil {
		return err
	}

	if err := wirefix.Add(context, db, items, rels, vs, pats); err != nil {
		return err
	}

	// -----------------------------------------------------------
	// Build the example graph.

	mongoURI := cfg.MustURL("MONGO_URI")

	if err := cayleyshelf.InitQuadStore(mongoURI.String()); err != nil {
		return err
	}

	var quads []quad.Quad
	quads = append(quads, quad.Make(wirePrefix+"d1dfa366-d2f7-4a4a-a64f-af89d4c97d82", wirePrefix+"on", wirePrefix+"c1b2bbfe-af9f-4903-8777-bd47c4d5b20a", ""))
	quads = append(quads, quad.Make(wirePrefix+"6eaaa19f-da7a-4095-bbe3-cee7a7631dd4", wirePrefix+"on", wirePrefix+"c1b2bbfe-af9f-4903-8777-bd47c4d5b20a", ""))
	quads = append(quads, quad.Make(wirePrefix+"d16790f8-13e9-4cb4-b9ef-d82835589660", wirePrefix+"on", wirePrefix+"c1b2bbfe-af9f-4903-8777-bd47c4d5b20a", ""))
	quads = append(quads, quad.Make(wirePrefix+"80aa936a-f618-4234-a7be-df59a14cf8de", wirePrefix+"authored", wirePrefix+"d1dfa366-d2f7-4a4a-a64f-af89d4c97d82", ""))
	quads = append(quads, quad.Make(wirePrefix+"80aa936a-f618-4234-a7be-df59a14cf8de", wirePrefix+"authored", wirePrefix+"6eaaa19f-da7a-4095-bbe3-cee7a7631dd4", ""))
	quads = append(quads, quad.Make(wirePrefix+"a63af637-58af-472b-98c7-f5c00743bac6", wirePrefix+"authored", wirePrefix+"d16790f8-13e9-4cb4-b9ef-d82835589660", ""))
	quads = append(quads, quad.Make(wirePrefix+"a63af637-58af-472b-98c7-f5c00743bac6", wirePrefix+"flagged", wirePrefix+"80aa936a-f618-4234-a7be-df59a14cf8de", ""))

	tx := cayley.NewTransaction()
	for _, quad := range quads {
		tx.AddQuad(quad)
	}

	if err := db.NewCayley(tests.Context, tests.TestSession); err != nil {
		return err
	}

	store, err := db.GraphHandle(tests.Context)
	if err != nil {
		return err
	}
	defer store.Close()

	if err := store.ApplyTransaction(tx); err != nil {
		return err
	}

	return nil
}
Пример #4
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Initialize the configuration and logging systems. Plus anything
	// else the web app layer needs.
	tests.Init("ASK")

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, cfg.MustURL("MONGO_URI").String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	db, err := db.NewMGO(tests.Context, tests.TestSession)
	if err != nil {
		log.Fatalf("Should be able to get a Mongo session : %v", err)
	}
	defer db.CloseMGO(tests.Context)

	// We need the database indexes setup before we can call anything, so do this
	// first. This is fairly important, so we want to fail the entire test suite
	// if we can't setup the indexes.
	if err := submission.EnsureIndexes(tests.Context, db); err != nil {
		log.Fatal("Can't ensure the database indexes")
	}

	return m.Run()
}
Пример #5
0
// TestNotExists validates the ability to load configuration values
// using the OS-level environment variables and panic when something
// is missing.
func TestNotExists(t *testing.T) {
	t.Log("Given the need to panic when environment variables are missing.")
	{
		os.Setenv("MYAPP_PROC_ID", "322")
		os.Setenv("MYAPP_SOCKET", "./tmp/sockets.po")
		os.Setenv("MYAPP_PORT", "4034")
		os.Setenv("MYAPP_FLAG", "true")

		cfg.Init("MYAPP")

		t.Log("\tWhen given a namspace key to search for that does NOT exist.")
		{
			shouldPanic(t, "STAMP", func() {
				cfg.MustTime("STAMP")
			})

			shouldPanic(t, "PID", func() {
				cfg.MustInt("PID")
			})

			shouldPanic(t, "DEST", func() {
				cfg.MustString("DEST")
			})

			shouldPanic(t, "ACTIVE", func() {
				cfg.MustBool("ACTIVE")
			})

			shouldPanic(t, "SOCKET_DSN", func() {
				cfg.MustURL("SOCKET_DSN")
			})
		}
	}
}
Пример #6
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, cfg.MustURL("MONGO_URI").String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	// Setup the app for performing tests.
	a = routes.API()

	// Snatch the mongo session so we can create some test data.
	db, err := db.NewMGO(tests.Context, tests.TestSession)
	if err != nil {
		fmt.Println("Unable to get Mongo session")
		return 1
	}
	defer db.CloseMGO(tests.Context)

	if err := loadItems(tests.Context, db); err != nil {
		fmt.Println("Could not load items")
		return 1
	}
	defer itemfix.Remove(tests.Context, db, itemPrefix)

	if err := loadPatterns(tests.Context, db); err != nil {
		fmt.Println("Could not load patterns")
		return 1
	}
	defer patternfix.Remove(tests.Context, db, patternPrefix)

	return m.Run()
}
Пример #7
0
func main() {
	app.Init(cfg.EnvProvider{Namespace: Namespace})

	// Pull options from the config.
	var conn *db.DB
	if _, errHost := cfg.String(cfgWebHost); errHost != nil {
		xenia.Println("Configuring MongoDB")

		mongoURI := cfg.MustURL(cfgMongoURI)

		err := db.RegMasterSession("startup", mongoURI.Path, mongoURI.String(), 0)
		if err != nil {
			xenia.Println("Unable to initialize MongoDB")
			os.Exit(1)
		}

		conn, err = db.NewMGO("startup", mongoURI.Path)
		if err != nil {
			xenia.Println("Unable to get MongoDB session")
			os.Exit(1)
		}
		defer conn.CloseMGO("startup")
	}

	xenia.AddCommand(
		cmddb.GetCommands(conn),
		cmdquery.GetCommands(),
		cmdscript.GetCommands(),
		cmdregex.GetCommands(),
		cmdmask.GetCommands(),
		cmdrelationship.GetCommands(),
		cmdview.GetCommands(),
	)
	xenia.Execute()
}
Пример #8
0
// setup initializes for each indivdual test.
func setup(t *testing.T) *cayley.Handle {
	tests.ResetLog()

	store, err := cayleyshelf.New(cfg.MustURL("MONGO_URI").String(), nil)
	if err != nil {
		t.Fatalf("\t%s\tShould be able to connect to the cayley graph : %s", tests.Failed, err)
	}

	return store
}
Пример #9
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, cfg.MustURL("MONGO_URI").String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	return m.Run()
}
Пример #10
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Create stub server for Sponged.
	server := setup()
	cfg.SetString("SPONGED_URL", server)

	mongoURI := cfg.MustURL("MONGO_URI")

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, mongoURI.String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	a = routes.API()

	// Snatch the mongo session so we can create some test data.
	db, err := db.NewMGO(tests.Context, tests.TestSession)
	if err != nil {
		fmt.Println("Unable to get Mongo session")
		return 1
	}
	defer db.CloseMGO(tests.Context)

	if err = db.NewCayley(tests.Context, tests.TestSession); err != nil {
		fmt.Println("Unable to get Cayley support")
	}

	store, err := db.GraphHandle(tests.Context)
	if err != nil {
		fmt.Println("Unable to get Cayley handle")
		return 1
	}
	defer store.Close()

	if err := tstdata.Generate(db); err != nil {
		fmt.Println("Could not generate test data.")
		return 1
	}
	defer tstdata.Drop(db)

	if err := loadItems("context", db, store); err != nil {
		fmt.Println("Could not import items")
		return 1
	}
	defer unloadItems("context", db, store)

	return m.Run()
}
Пример #11
0
// API returns a handler for a set of routes.
func API() http.Handler {
	mongoURI := cfg.MustURL(cfgMongoURI)

	// The web framework middleware for Mongo is using the name of the
	// database as the name of the master session by convention. So use
	// cfg.DB as the second argument when creating the master session.
	if err := db.RegMasterSession("startup", mongoURI.Path, mongoURI.String(), 25*time.Second); err != nil {
		log.Error("startup", "Init", err, "Initializing MongoDB")
		os.Exit(1)
	}

	w := web.New(logm.Midware, errorm.Midware)

	publicKey, err := cfg.String(cfgAuthPublicKey)
	if err != nil || publicKey == "" {
		log.User("startup", "Init", "%s is missing, internal authentication is disabled", cfgAuthPublicKey)
	}

	// If the public key is provided then add the auth middleware or fail using
	// the provided public key.
	if publicKey != "" {
		log.Dev("startup", "Init", "Initializing Auth")

		authm, err := authm.Midware(publicKey, authm.MidwareOpts{})
		if err != nil {
			log.Error("startup", "Init", err, "Initializing Auth")
			os.Exit(1)
		}

		// Apply the authentication middleware on top of the application as the
		// first middleware.
		w.Use(authm)
	}

	// Add the Mongo and Cayley middlewares possibly after the auth middleware.
	w.Use(mongo.Midware(mongoURI), cayley.Midware(mongoURI))

	if cors, err := cfg.Bool(cfgEnableCORS); err == nil && cors {
		log.Dev("startup", "Init", "Initializing CORS : CORS Enabled")
		w.Use(w.CORS())
	} else {
		log.Dev("startup", "Init", "CORS Disabled")
	}

	log.Dev("startup", "Init", "Initalizing routes")
	routes(w)

	return w
}
Пример #12
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Initialize the configuration and logging systems. Plus anything
	// else the web app layer needs.
	tests.Init("XENIA")

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, cfg.MustURL("MONGO_URI").String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	return m.Run()
}
Пример #13
0
// routes manages the handling of the API endpoints.
func routes(w *web.Web) {
	w.Handle("GET", "/v1/version", handlers.Version.List)

	w.Handle("GET", "/v1/script", handlers.Script.List)
	w.Handle("PUT", "/v1/script", handlers.Script.Upsert)
	w.Handle("GET", "/v1/script/:name", handlers.Script.Retrieve)
	w.Handle("DELETE", "/v1/script/:name", handlers.Script.Delete)

	w.Handle("GET", "/v1/query", handlers.Query.List)
	w.Handle("PUT", "/v1/query", handlers.Query.Upsert)
	w.Handle("GET", "/v1/query/:name", handlers.Query.Retrieve)
	w.Handle("DELETE", "/v1/query/:name", handlers.Query.Delete)

	w.Handle("PUT", "/v1/index/:name", handlers.Query.EnsureIndexes)

	w.Handle("GET", "/v1/regex", handlers.Regex.List)
	w.Handle("PUT", "/v1/regex", handlers.Regex.Upsert)
	w.Handle("GET", "/v1/regex/:name", handlers.Regex.Retrieve)
	w.Handle("DELETE", "/v1/regex/:name", handlers.Regex.Delete)

	w.Handle("GET", "/v1/mask", handlers.Mask.List)
	w.Handle("PUT", "/v1/mask", handlers.Mask.Upsert)
	w.Handle("GET", "/v1/mask/:collection/:field", handlers.Mask.Retrieve)
	w.Handle("GET", "/v1/mask/:collection", handlers.Mask.Retrieve)
	w.Handle("DELETE", "/v1/mask/:collection/:field", handlers.Mask.Delete)

	w.Handle("POST", "/v1/exec", handlers.Exec.Custom)
	w.Handle("GET", "/v1/exec/:name", handlers.Exec.Name)

	// Create the Cayley middleware which will only be binded to specific
	// endpoints.
	cayleym := cayley.Midware(cfg.MustURL(cfgMongoURI))

	// These endpoints require Cayley, we will add the middleware onto the routes.
	w.Handle("GET", "/v1/exec/:name/view/:view/:item", handlers.Exec.NameOnView, cayleym)
	w.Handle("POST", "/v1/exec/view/:view/:item", handlers.Exec.CustomOnView, cayleym)

	w.Handle("GET", "/v1/relationship", handlers.Relationship.List)
	w.Handle("PUT", "/v1/relationship", handlers.Relationship.Upsert)
	w.Handle("GET", "/v1/relationship/:predicate", handlers.Relationship.Retrieve)
	w.Handle("DELETE", "/v1/relationship/:predicate", handlers.Relationship.Delete)

	w.Handle("GET", "/v1/view", handlers.View.List)
	w.Handle("PUT", "/v1/view", handlers.View.Upsert)
	w.Handle("GET", "/v1/view/:name", handlers.View.Retrieve)
	w.Handle("DELETE", "/v1/view/:name", handlers.View.Delete)
}
Пример #14
0
// API returns a handler for a set of routes.
func API() http.Handler {
	mongoURI := cfg.MustURL(cfgMongoURI)

	// The web framework middleware for Mongo is using the name of the
	// database as the name of the master session by convention. So use
	// cfg.DB as the second argument when creating the master session.
	if err := db.RegMasterSession("startup", mongoURI.Path, mongoURI.String(), 25*time.Second); err != nil {
		log.Error("startup", "Init", err, "Initializing MongoDB")
		os.Exit(1)
	}

	// Ensure that the database indexes are setup on the underlying MongoDB
	// database.
	if err := ensureDBIndexes(mongoURI); err != nil {
		log.Error("startup", "Init", err, "Initializing DB Indexes")
		os.Exit(1)
	}

	w := web.New(logm.Midware, errorm.Midware, mongo.Midware(mongoURI))

	// Load in the recaptcha secret from the config.
	if recaptcha, err := cfg.String(cfgRecaptchaSecret); err == nil && recaptcha != "" {
		w.Ctx["recaptcha"] = recaptcha
		log.Dev("startup", "Init", "Recaptcha Enabled")
	} else {
		log.Dev("startup", "Init", "%s is missing, recaptcha is disabled", cfgRecaptchaSecret)
	}

	if cors, err := cfg.Bool(cfgEnableCORS); err == nil && cors {
		log.Dev("startup", "Init", "Initializing CORS : CORS Enabled")
		w.Use(w.CORS())
	} else {
		log.Dev("startup", "Init", "CORS Disabled")
	}

	log.Dev("startup", "Init", "Initalizing routes")
	routes(w)

	return w
}
Пример #15
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, cfg.MustURL("MONGO_URI").String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	db, err := db.NewMGO(tests.Context, tests.TestSession)
	if err != nil {
		fmt.Println("Can't get mongo session: " + err.Error())
		return 1
	}
	defer db.CloseMGO(tests.Context)

	loadPatterns("context", db)
	defer patternfix.Remove("context", db, patternPrefix)

	defer itemfix.Remove("context", db, itemPrefix)

	return m.Run()
}
Пример #16
0
// TestNotExists validates the ability to load configuration values
// using the OS-level environment variables and panic when something
// is missing.
func TestNotExists(t *testing.T) {
	t.Log("Given the need to panic when environment variables are missing.")
	{

		cfg.Init(cfg.MapProvider{
			Map: map[string]string{
				"PROC_ID": "322",
				"SOCKET":  "./tmp/sockets.po",
				"PORT":    "4034",
				"FLAG":    "on",
			},
		})

		t.Log("\tWhen given a namspace key to search for that does NOT exist.")
		{
			shouldPanic(t, "STAMP", func() {
				cfg.MustTime("STAMP")
			})

			shouldPanic(t, "PID", func() {
				cfg.MustInt("PID")
			})

			shouldPanic(t, "DEST", func() {
				cfg.MustString("DEST")
			})

			shouldPanic(t, "ACTIVE", func() {
				cfg.MustBool("ACTIVE")
			})

			shouldPanic(t, "SOCKET_DSN", func() {
				cfg.MustURL("SOCKET_DSN")
			})
		}
	}
}
Пример #17
0
func init() {
	if err := cfg.Init(cfg.EnvProvider{Namespace: "XENIA"}); err != nil {
		log.Println("Unable to initialize configuration")
		os.Exit(1)
	}

	// Insert the base url for requests by this client.
	DefaultClient.BaseURL = cfg.MustURL(cfgWebHost).String()

	platformPrivateKey, err := cfg.String(cfgPlatformPrivateKey)
	if err != nil || platformPrivateKey == "" {
		if err != nil {
			log.Printf("Downstream Auth : Disabled : %s\n", err.Error())
			return
		}

		log.Printf("Downstream Auth : Disabled\n")
		return
	}

	// If the platformPrivateKey is provided, then we should generate the token
	// signing function to be used when composing requests down to the platform.
	signer, err := auth.NewSigner(platformPrivateKey)
	if err != nil {
		log.Printf("Downstream Auth : Error : %s", err.Error())
		os.Exit(1)
	}

	// Requests can now be signed with the given signer function which we will
	// save on the application wide context. In the event that a function
	// requires a call down to a downstream platform, we will include a signed
	// header using the signer function here.
	DefaultClient.Signer = signer

	log.Println("Downstream Auth : Enabled")
}
Пример #18
0
func main() {

	// Initialize the configuration
	if err := cfg.Init(cfg.EnvProvider{Namespace: "WIRE"}); err != nil {
		wire.Println("Unable to initialize configuration")
		os.Exit(1)
	}

	// Initialize the logging
	logLevel := func() int {
		ll, err := cfg.Int(cfgLoggingLevel)
		if err != nil {
			return log.NONE
		}
		return ll
	}

	log.Init(os.Stderr, logLevel, log.Ldefault)
	wire.Println("Using log level", logLevel())

	// Pull options from the config.
	var mgoDB *db.DB
	var graphDB *cayley.Handle

	// Configure MongoDB.
	wire.Println("Configuring MongoDB")

	mongoURI := cfg.MustURL(cfgMongoURI)

	err := db.RegMasterSession("startup", mongoURI.Path, mongoURI.String(), 0)
	if err != nil {
		wire.Println("Unable to initialize MongoDB")
		os.Exit(1)
	}

	mgoDB, err = db.NewMGO("startup", mongoURI.Path)
	if err != nil {
		wire.Println("Unable to get MongoDB session")
		os.Exit(1)
	}
	defer mgoDB.CloseMGO("")

	// Configure Cayley.
	wire.Println("Configuring Cayley")
	if err := mgoDB.NewCayley("startup", mongoURI.Path); err != nil {
		wire.Println("Unable to get Cayley support")
	}

	graphDB, err = mgoDB.GraphHandle("startup")
	if err != nil {
		wire.Println("Unable to get Cayley handle")
		os.Exit(1)
	}

	// Add the graph and view commands to the CLI tool.
	wire.AddCommand(
		cmdview.GetCommands(mgoDB, graphDB),
	)

	// Execute the command.
	wire.Execute()
}
Пример #19
0
// runTest initializes the environment for the tests and allows for
// the proper return code if the test fails or succeeds.
func runTest(m *testing.M) int {
	mongoURI := cfg.MustURL("MONGO_URI")

	// Initialize MongoDB using the `tests.TestSession` as the name of the
	// master session.
	if err := db.RegMasterSession(tests.Context, tests.TestSession, mongoURI.String(), 0); err != nil {
		fmt.Println("Can't register master session: " + err.Error())
		return 1
	}

	// Setup the app for performing tests.
	a = routes.API()

	// Snatch the mongo session so we can create some test data.
	db, err := db.NewMGO(tests.Context, tests.TestSession)
	if err != nil {
		fmt.Println("Unable to get Mongo session")
		return 1
	}
	defer db.CloseMGO(tests.Context)

	if err := db.NewCayley(tests.Context, tests.TestSession); err != nil {
		fmt.Println("Unable to get Cayley support")
	}

	store, err := db.GraphHandle(tests.Context)
	if err != nil {
		fmt.Println("Unable to get Cayley handle")
		return 1
	}
	defer store.Close()

	if err := tstdata.Generate(db); err != nil {
		fmt.Println("Could not generate test data.")
		return 1
	}
	defer tstdata.Drop(db)

	// Load the queries.
	if err := loadQuery(db, "basic.json"); err != nil {
		fmt.Println("Could not load queries in basic.json")
		return 1
	}

	if err := loadQuery(db, "basic_view.json"); err != nil {
		fmt.Println("Could not load queries in basic.json")
		return 1
	}
	if err := loadQuery(db, "basic_var.json"); err != nil {
		fmt.Println("Could not load queries in basic_var.json")
		return 1
	}
	defer qfix.Remove(db, "QTEST_O")

	if err := loadScript(db, "basic_script_pre.json"); err != nil {
		fmt.Println("Could not load scripts in basic_script_pre.json")
		return 1
	}
	if err := loadScript(db, "basic_script_pst.json"); err != nil {
		fmt.Println("Could not load scripts in basic_script_pst.json")
		return 1
	}
	defer sfix.Remove(db, "STEST_O")

	if err := loadMasks(db, "basic.json"); err != nil {
		fmt.Println("Could not load masks.")
		return 1
	}
	defer mfix.Remove(db, "test_xenia_data")

	if err := loadRelationships("context", db); err != nil {
		fmt.Println("Could not load relationships.")
		return 1
	}
	defer relationshipfix.Remove("context", db, relPrefix)

	if err := loadViews("context", db); err != nil {
		fmt.Println("Could not load views.")
		return 1
	}
	defer viewfix.Remove("context", db, viewPrefix)

	if err := loadPatterns("context", db); err != nil {
		fmt.Println("Could not load patterns")
		return 1
	}
	defer patternfix.Remove("context", db, "PTEST_")

	if err := loadItems("context", db, store); err != nil {
		fmt.Println("Could not import items")
		return 1
	}
	defer unloadItems("context", db, store)

	return m.Run()
}
Пример #20
0
// API returns a handler for a set of routes.
func API() http.Handler {
	w := web.New(logm.Midware, errorm.Midware)

	publicKey, err := cfg.String(cfgAuthPublicKey)
	if err != nil || publicKey == "" {
		log.User("startup", "Init", "%s is missing, internal authentication is disabled", cfgAuthPublicKey)
	}

	// If the public key is provided then add the auth middleware or fail using
	// the provided public key.
	if publicKey != "" {
		log.Dev("startup", "Init", "Initializing Auth")

		authm, err := authm.Midware(publicKey, authm.MidwareOpts{})
		if err != nil {
			log.Error("startup", "Init", err, "Initializing Auth")
			os.Exit(1)
		}

		// Apply the authentication middleware on top of the application as the
		// first middleware.
		w.Use(authm)
	}

	platformPrivateKey, err := cfg.String(cfgPlatformPrivateKey)
	if err != nil || platformPrivateKey == "" {
		log.User("startup", "Init", "%s is missing, downstream platform authentication is disabled", cfgPlatformPrivateKey)
	}

	// If the platformPrivateKey is provided, then we should generate the token
	// signing function to be used when composing requests down to the platform.
	if platformPrivateKey != "" {
		log.Dev("startup", "Init", "Initializing Downstream Platform Auth")

		signer, err := auth.NewSigner(platformPrivateKey)
		if err != nil {
			log.Error("startup", "Init", err, "Initializing Downstream Platform Auth")
			os.Exit(1)
		}

		// Requests can now be signed with the given signer function which we will
		// save on the application wide context. In the event that a function
		// requires a call down to a downstream platform, we will include a signed
		// header using the signer function here.
		w.Ctx["signer"] = signer
	}

	if cors, err := cfg.Bool(cfgEnableCORS); err == nil && cors {
		log.Dev("startup", "Init", "Initializing CORS : CORS Enabled")
		w.Use(w.CORS())
	} else {
		log.Dev("startup", "Init", "CORS Disabled")
	}

	// We need the URL for the services Sponged and Xeniad that needs to be running.
	spongedURL, err = cfg.String(cfgSpongedURL)
	if err != nil || spongedURL == "" {
		log.Error("startup", "Init", err, "Service Sponged needs to be setup.")
		os.Exit(1)
	}
	w.Ctx["spongedURL"] = cfg.MustURL(cfgSpongedURL).String()

	xeniadURL, err = cfg.String(cfgXeniadURL)
	if err != nil || xeniadURL == "" {
		log.Error("startup", "Init", err, "Service Xeniad needs to be setup.")
		os.Exit(1)
	}
	w.Ctx["xeniadURL "] = cfg.MustURL(cfgXeniadURL).String()

	log.Dev("startup", "Init", "Initalizing routes")
	routes(w)

	return w
}