Exemplo n.º 1
0
// NewCustomerHandler superuser route to create new api customers/apikeys
func NewCustomerHandler(w http.ResponseWriter, r *http.Request) {
	NetworkLogger.Debug("[In] ", r)

	// Check auth key
	if !CheckAuthKey(w, r) {
		return
	}

	// new customer
	apikey := utils.NewAPIKey(12)
	customer := Customer{Apikey: apikey}
	err := DB.InsertCustomer(customer)
	if err != nil {
		ServerLogger.Error(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	data := HttpMessageResponse{Status: "success", Apikey: apikey, Data: "customer created"}
	js, err := MarshalJsonFromStruct(w, r, data)
	if err != nil {
		return
	}

	SendJsonResponse(w, r, js)
}
Exemplo n.º 2
0
func init() {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		app.ServerLogger.Error(err)
	}
	db := strings.Replace(dir, "bin", "bolt", -1)
	flag.StringVar(&configFile, "c", DEFAULT_CONFIG, "server config file")
	flag.IntVar(&port, "p", 8080, "server port")
	flag.StringVar(&database, "db", db, "app database")
	// flag.StringVar(&app.SuperuserKey, "s", "7q1qcqmsxnvw", "superuser key")
	flag.StringVar(&app.SuperuserKey, "s", "su", "superuser key")
	flag.BoolVar(&versionReport, "V", false, "App Version")
	flag.BoolVar(&app.Verbose, "v", false, "verbose")
	flag.BoolVar(&debugMode, "d", false, "Enable debug mode")
	flag.StringVar(&app.LogDirectory, "L", "log", "logging directory") // check if directory exists
	flag.StringVar(&app.LogLevel, "l", "trace", "logging level")

	flag.Parse()
	if versionReport {
		fmt.Println("Version:", VERSION)
		os.Exit(0)
	}

	app.Version = VERSION

	app.ResetLogging()

	// check if file exists!!!
	if _, err := os.Stat(configFile); err == nil {
		file, err := ioutil.ReadFile(configFile)
		if err != nil {
			panic(err)
		}
		configuration := serverConfig{}
		err = json.Unmarshal(file, &configuration)
		if err != nil {
			fmt.Println("error:", err)
		}
		port = configuration.Port
		database = configuration.Db
		database = strings.Replace(database, ".db", "", -1)
		app.SuperuserKey = configuration.Authkey
		app.ServerLogger.Info(configuration)
	} else {
		// create config file
		configuration := serverConfig{}
		configuration.Port = port
		configuration.Db = database

		if "su" == app.SuperuserKey {
			authkey := utils.NewAPIKey(12)
			configuration.Authkey = authkey
			app.SuperuserKey = authkey
		}
		app.ServerLogger.Info(configuration)
	}

}
Exemplo n.º 3
0
// Handles incoming requests.
func (self TcpServer) tcpClientHandler(conn net.Conn) {

	reader := bufio.NewReader(conn)
	tp := textproto.NewReader(reader)

	defer conn.Close()

	authenticated := false

	for {

		// will listen for message to process ending in newline (\n)
		//message, _ := bufio.NewReader(conn).ReadString('\n') // sometimes read partial messages
		message, _ := tp.ReadLine()

		// go self.handleTcpMessage(authenticated, message, conn)

		// output message received
		NetworkLogger.Info("Message Received: ", string(message), " [TCP]")

		// json parse message
		req := TcpMessage{}
		err := json.Unmarshal([]byte(message), &req)
		if err != nil {
			// invalid message
			// close connection
			NetworkLogger.Warn("error:", err)
			resp := `{"status": "error", "error": "` + fmt.Sprintf("%v", err) + `",""}`
			conn.Write([]byte(resp + "\n"))
			NetworkLogger.Info("Connection closed", " [TCP]")
			return
		}

		// get method
		if !authenticated {
			if req.Method == "authenticate" {
				// {"method":"authenticate", "authkey": "7q1qcqmsxnvw"}
				authenticated = SuperuserKey == req.Authkey
				if authenticated {
					resp := `{"status": "success", "data": {}}`
					conn.Write([]byte(resp + "\n"))
				} else {
					NetworkLogger.Warn("error: incorrect authkey", " [TCP]")
					resp := `{"status": "error", "error": "incorrect authkey"}`
					conn.Write([]byte(resp + "\n"))
				}
			} else if req.Method == "help" {
				conn.Write([]byte("Methods:\n"))
				conn.Write([]byte("\t authenticate\n"))
				conn.Write([]byte("\t create_user\n"))
				conn.Write([]byte("\t insert_apikey\n"))
				conn.Write([]byte("\t export_apikeys\n"))
				conn.Write([]byte("\t export_apikey\n"))
				conn.Write([]byte("\t new_layer\n"))
				conn.Write([]byte("\t insert_feature\n"))
				conn.Write([]byte("\t export_datasource\n"))
				conn.Write([]byte("\t export_datasources\n"))
			} else {
				resp := `{"status": "error", "error": "connection not authenticated"}`
				conn.Write([]byte(resp + "\n"))
			}
		} else {

			success := false
			switch {
			/*
				case req.Method == "assign_datasource" && authenticated:
					datasource_id := req.Datasource //["datasource_id"]
					apikey := req.Apikey            //["apikey"]
					customer, err := DB.GetCustomer(apikey)
					resp := `{"status": "success", "data": {}}`
					if err != nil {
						fmt.Println("Customer key not found!")
						resp = `{"status": "error", "data": {"error": "` + err.Error() + `", "message": "Customer key not found!"}}`
					}
					// CHECK IF DATASOURCE EXISTS
					// *****
					fmt.Println(DB.GetLayer(datasource_id))

					customer.Datasources = append(customer.Datasources, datasource_id)
					DB.InsertCustomer(customer)
					conn.Write([]byte(resp + "\n"))
					success = true
			*/
			case req.Method == "create_user" && authenticated:
				// {"method":"create_user"}
				apikey := utils.NewAPIKey(12)
				customer := Customer{Apikey: apikey}
				resp := `{"status": "success", "data": {"apikey": "` + apikey + `"}}`
				err := DB.InsertCustomer(customer)
				if err != nil {
					fmt.Println(err)
					resp = `{"status": "error", "data": {"error": "` + err.Error() + `", "message": "error creating customer"}}`
				}
				conn.Write([]byte(resp + "\n"))
				success = true

			//  Replay database
			case req.Method == "insert_apikey" && authenticated:
				customer := Customer{Apikey: req.Data.Apikey, Datasources: req.Data.Datasources}
				resp := `{"status": "success", "data": {"apikey": "` + req.Data.Apikey + `"}}`
				err := DB.InsertCustomer(customer)
				if err != nil {
					fmt.Println(err)
					resp = `{"status": "error", "data": {"error": "` + err.Error() + `", "message": "error creating customer"}}`
				}
				conn.Write([]byte(resp + "\n"))
				success = true

			case req.Method == "insert_feature" && authenticated:
				err = DB.InsertFeature(req.Data.Datasource, req.Data.Feature)
				if err != nil {
					fmt.Println(err)
				}
				resp := `{"status":"ok","datasource":"` + req.Data.Datasource + `", "message":"feature added"}`
				conn.Write([]byte(resp + "\n"))
				success = true

			case req.Method == "new_layer" && authenticated:
				err = DB.InsertLayer(req.Data.Datasource, req.Data.Layer)
				if err != nil {
					fmt.Println(err)
				}
				resp := `{"status":"ok","datasource":"` + req.Data.Datasource + `"}`
				conn.Write([]byte(resp + "\n"))
				success = true

			case req.Method == "export_apikeys" && authenticated:
				// {"method":"export_apikeys"}
				apikeys, err := DB.SelectAll("apikeys")
				if err != nil {
					fmt.Println(err)
				}
				js, err := json.Marshal(apikeys)
				if err != nil {
					fmt.Println(err)
				}
				resp := `{"status":"ok","data":"` + string(js) + `"}`
				conn.Write([]byte(resp + "\n"))
				success = true

			case req.Method == "export_apikey" && authenticated:
				// {"method":"export_apikey","apikey":"4AvJJ3oW0zeT"}
				apikey, err := DB.GetCustomer(req.Apikey)
				if err != nil {
					fmt.Println(err)
				}
				fmt.Println(apikey)
				js, err := json.Marshal(apikey)
				if err != nil {
					fmt.Println(err)
				}
				resp := `{"status":"ok","data":"` + string(js) + `"}`
				conn.Write([]byte(resp + "\n"))
				success = true

			case req.Method == "export_datasources" && authenticated:
				// {"method":"export_datasources"}
				layers, err := DB.SelectAll("layers")
				if err != nil {
					fmt.Println(err)
				}
				js, err := json.Marshal(layers)
				if err != nil {
					fmt.Println(err)
				}
				resp := `{"status":"ok","data":"` + string(js) + `"}`
				conn.Write([]byte(resp + "\n"))
				success = true

			case req.Method == "export_datasource" && authenticated:
				// {"method":"export_datasource","datasource":"3b1f5d633d884b9499adfc9b49c45236"}
				layer, err := DB.GetLayer(req.Datasource)
				if err != nil {
					fmt.Println(err)
				}
				js, err := json.Marshal(layer)
				if err != nil {
					fmt.Println(err)
				}
				resp := `{"status":"ok","data":"` + string(js) + `"}`
				conn.Write([]byte(resp + "\n"))
				success = true

			}

			if !success {
				resp := `{"status": "error", "error": "method not found"}`
				conn.Write([]byte(resp + "\n"))
			}

		}

	}
}