Commit 07d97a4c authored by Mo Firouz's avatar Mo Firouz Committed by Chris Molozian
Browse files

Add runtime base64 and base16 conversion functions. (#75)

parent efbcb535
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -4,8 +4,12 @@ All notable changes to this project are documented below.
The format is based on [keep a changelog](http://keepachangelog.com/) and this project uses [semantic versioning](http://semver.org/).

## [Unreleased]
### Added
- Runtime Base64 and Base16 conversion util functions.

### Fixed
- Update storage write permissions validation.
- Runtime module path must derive from `--data-dir` flag value.

## [0.13.0] - 2017-05-29
### Added
+9 −4
Original line number Diff line number Diff line
@@ -151,8 +151,8 @@ func parseArgs(consoleLogger *zap.Logger) server.Config {
	flags := flag.NewFlagSet("main", flag.ExitOnError)
	flags.BoolVar(&server.VerboseLogging, "verbose", false, "Turn verbose logging on.")
	flags.BoolVar(&server.StdoutLogging, "logtostdout", false, "Log to stdout instead of file.")
	var filepath string
	flags.StringVar(&filepath, "config", "", "The absolute file path to configuration YAML file.")
	var configPath string
	flags.StringVar(&configPath, "config", "", "The absolute file path to configuration YAML file.")
	var name string
	flags.StringVar(&name, "name", "", "The virtual name of this server.")
	var datadir string
@@ -168,8 +168,8 @@ func parseArgs(consoleLogger *zap.Logger) server.Config {
		consoleLogger.Error("Could not parse command line arguments - ignoring command-line overrides", zap.Error(err))
	} else {

		if len(filepath) > 0 {
			data, err := ioutil.ReadFile(filepath)
		if len(configPath) > 0 {
			data, err := ioutil.ReadFile(configPath)
			if err != nil {
				consoleLogger.Error("Could not read config file, using defaults", zap.Error(err))
			} else {
@@ -198,6 +198,11 @@ func parseArgs(consoleLogger *zap.Logger) server.Config {
		}
	}

	// if the runtime path is not overridden, set it to `datadir/modules`
	if config.GetRuntime().Path == "" {
		config.GetRuntime().Path = filepath.Join(config.GetDataDir(), "modules")
	}

	return config
}

+3 −3
Original line number Diff line number Diff line
@@ -64,7 +64,7 @@ func NewConfig() *config {
		Transport: NewTransportConfig(),
		Database:  NewDatabaseConfig(),
		Social:    NewSocialConfig(),
		Runtime:   NewRuntimeConfig(dataDirectory),
		Runtime:   NewRuntimeConfig(),
	}
}

@@ -187,10 +187,10 @@ type RuntimeConfig struct {
}

// NewRuntimeConfig creates a new RuntimeConfig struct
func NewRuntimeConfig(dataDirectory string) *RuntimeConfig {
func NewRuntimeConfig() *RuntimeConfig {
	return &RuntimeConfig{
		Environment: make(map[string]interface{}),
		Path:        filepath.Join(dataDirectory, "modules"),
		Path:        "",
		HTTPKey:     "defaultkey",
	}
}
+103 −41
Original line number Diff line number Diff line
@@ -22,9 +22,12 @@ import (
	"strings"
	"time"

	"encoding/base64"

	"github.com/satori/go.uuid"
	"github.com/yuin/gopher-lua"
	"go.uber.org/zap"
	"encoding/hex"
)

type NakamaxModule struct {
@@ -44,9 +47,13 @@ func NewNakamaxModule(logger *zap.Logger) *NakamaxModule {
func (nx *NakamaxModule) Loader(l *lua.LState) int {
	mod := l.SetFuncs(l.NewTable(), map[string]lua.LGFunction{
		"uuid_v4":       nx.uuidV4,
		"http_request":  nx.httpRequest,
		"json_encode":   nx.jsonEncode,
		"json_decode":   nx.jsonDecode,
		"http_request": nx.httpRequest,
		"base64_encode": nx.base64Encode,
		"base64_decode": nx.base64Decode,
		"base16_encode": nx.base16Encode,
		"base16_decode": nx.base16decode,
	})

	l.Push(mod)
@@ -59,43 +66,6 @@ func (nx *NakamaxModule) uuidV4(l *lua.LState) int {
	return 1
}

func (nx *NakamaxModule) jsonEncode(l *lua.LState) int {
	// TODO allow top-level arrays or primitives?
	jsonTable := l.CheckTable(1)
	if jsonTable == nil {
		l.ArgError(1, "Expects a table to encode")
		return 0
	}

	jsonData := ConvertLuaTable(jsonTable)
	jsonBytes, err := json.Marshal(jsonData)
	if err != nil {
		l.ArgError(1, "Error encoding to JSON")
		return 0
	}

	l.Push(lua.LString(string(jsonBytes)))
	return 1
}

func (nx *NakamaxModule) jsonDecode(l *lua.LState) int {
	jsonString := l.CheckString(1)
	if jsonString == "" {
		l.ArgError(1, "Expects JSON string")
		return 0
	}

	// TODO allow top-level arrays or primitives?
	var jsonData map[string]interface{}
	if err := json.Unmarshal([]byte(jsonString), &jsonData); err != nil {
		l.RaiseError("Not a valid JSON string: %v", err.Error())
		return 0
	}

	l.Push(ConvertMap(l, jsonData))
	return 1
}

func (nx *NakamaxModule) httpRequest(l *lua.LState) int {
	url := l.CheckString(1)
	method := l.CheckString(2)
@@ -159,3 +129,95 @@ func (nx *NakamaxModule) httpRequest(l *lua.LState) int {
	l.Push(lua.LString(string(responseBody)))
	return 3
}

func (nx *NakamaxModule) jsonEncode(l *lua.LState) int {
	// TODO allow top-level arrays or primitives?
	jsonTable := l.CheckTable(1)
	if jsonTable == nil {
		l.ArgError(1, "Expects a table to encode")
		return 0
	}

	jsonData := ConvertLuaTable(jsonTable)
	jsonBytes, err := json.Marshal(jsonData)
	if err != nil {
		l.ArgError(1, "Error encoding to JSON")
		return 0
	}

	l.Push(lua.LString(string(jsonBytes)))
	return 1
}

func (nx *NakamaxModule) jsonDecode(l *lua.LState) int {
	jsonString := l.CheckString(1)
	if jsonString == "" {
		l.ArgError(1, "Expects JSON string")
		return 0
	}

	// TODO allow top-level arrays or primitives?
	var jsonData map[string]interface{}
	if err := json.Unmarshal([]byte(jsonString), &jsonData); err != nil {
		l.RaiseError("Not a valid JSON string: %v", err.Error())
		return 0
	}

	l.Push(ConvertMap(l, jsonData))
	return 1
}

func (nx *NakamaxModule) base64Encode(l *lua.LState) int {
	input := l.CheckString(1)
	if input == "" {
		l.ArgError(1, "Expects string")
		return 0
	}

	output := base64.StdEncoding.EncodeToString([]byte(input))
	l.Push(lua.LString(output))
	return 1
}
func (nx *NakamaxModule) base64Decode(l *lua.LState) int {
	input := l.CheckString(1)
	if input == "" {
		l.ArgError(1, "Expects string")
		return 0
	}

	output, err := base64.StdEncoding.DecodeString(input)
	if err != nil {
		l.RaiseError("Not a valid base64 string: %v", err.Error())
		return 0
	}

	l.Push(lua.LString(output))
	return 1
}
func (nx *NakamaxModule) base16Encode(l *lua.LState) int {
	input := l.CheckString(1)
	if input == "" {
		l.ArgError(1, "Expects string")
		return 0
	}

	output := hex.EncodeToString([]byte(input))
	l.Push(lua.LString(output))
	return 1
}
func (nx *NakamaxModule) base16decode(l *lua.LState) int {
	input := l.CheckString(1)
	if input == "" {
		l.ArgError(1, "Expects string")
		return 0
	}

	output, err := hex.DecodeString(input)
	if err != nil {
		l.RaiseError("Not a valid base16 string: %v", err.Error())
		return 0
	}

	l.Push(lua.LString(output))
	return 1
}
+22 −4
Original line number Diff line number Diff line
@@ -98,6 +98,13 @@ end
  Nakamax module
]]--

-- uuid_v4
do
  local uuid = nx.uuid_v4()
  assert(uuid, "'uuid' must not be nil")
  assert(type(uuid) == "string", "'uuid' type must be string")
end

-- http_request
do
  local url = "https://google.com/"
@@ -119,9 +126,20 @@ do
  assert(json == '{"id":"blah"}', '"json" must equal "{"id":"blah"}"')
end

-- uuid_v4
-- base64_encode_decode
do
  local uuid = nx.uuid_v4()
  assert(uuid, "'uuid' must not be nil")
  assert(type(uuid) == "string", "'uuid' type must be string")
  local objectEncode = nx.base64_encode('{"hello": "world"}')
  assert(objectEncode, "'objectEncode' must not be nil")
  local objectDecode = nx.base64_decode(objectEncode)
  assert(objectDecode, "'objectDecode' must not be nil")
  assert(objectDecode == '{"hello": "world"}', '"objectDecode" must equal {"hello": "world"}')
end

-- base16_encode_decode
do
  local objectEncode = nx.base16_encode('{"hello": "world"}')
  assert(objectEncode, "'objectEncode' must not be nil")
  local objectDecode = nx.base16_decode(objectEncode)
  assert(objectDecode, "'objectDecode' must not be nil")
  assert(objectDecode == '{"hello": "world"}', '"objectDecode" must equal {"hello": "world"}')
end
Loading