Remove web interface using echo

This commit is contained in:
Tobie Morgan Hitchcock 2016-04-03 22:45:51 +01:00
parent 519d29b598
commit 9479fb24c5
15 changed files with 0 additions and 873 deletions

View file

@ -1,27 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"github.com/labstack/echo"
)
func code(code int) *echo.HTTPError {
return echo.NewHTTPError(code, "")
}
func sock(c *echo.Context) bool {
return c.Request().Header.Get(echo.Upgrade) == echo.WebSocket
}

View file

@ -1,63 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"encoding/base64"
"strings"
"github.com/labstack/echo"
)
// AuthOpts defines options for the Head middleward
type AuthOpts struct {
}
// Auth defines middleware for reading JWT authentication tokens
func Auth(opts *AuthOpts) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// TODO need to decide how users select the namespace and database
c.Set("NS", "abcum")
c.Set("DB", "onlineplatforms")
head := c.Request().Header.Get("Authorization")
auth := c.Get("opts.auth").(string)
user := c.Get("opts.user").(string)
pass := c.Get("opts.pass").(string)
if auth == "" {
return h(c)
}
if head != "" && head[:5] == "Basic" {
base, _ := base64.StdEncoding.DecodeString(head[6:])
cred := strings.SplitN(string(base), ":", 2)
if len(cred) == 2 && cred[0] == user && cred[1] == pass {
return h(c)
}
}
return echo.NewHTTPError(401)
}
}
}

View file

@ -1,84 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"net/http"
"strconv"
"strings"
"github.com/labstack/echo"
)
// CorsOpts defines options for the Head middleward
type CorsOpts struct {
AllowedMethods []string
AllowedHeaders []string
AccessControlMaxAge int
}
// Cors defines middleware for specifying CORS headers
func Cors(opts *CorsOpts) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
origin := c.Request().Header.Get("Origin")
if origin == "" {
return h(c)
}
// Set default values for opts.AllowedMethods
allowedMethods := opts.AllowedMethods
if len(allowedMethods) == 0 {
allowedMethods = []string{"GET", "PUT", "POST", "PATCH", "TRACE", "DELETE"}
}
// Set default values for opts.AllowedHeaders
allowedHeaders := opts.AllowedHeaders
if len(allowedHeaders) == 0 {
allowedHeaders = []string{"Accept", "Content-Type", "Origin"}
}
// Set default values for opts.AccessControlMaxAge
accessControlMaxAge := opts.AccessControlMaxAge
if accessControlMaxAge == 0 {
accessControlMaxAge = 3600
}
// Normalize AllowedMethods and make comma-separated-values
normedMethods := []string{}
for _, allowedMethod := range allowedMethods {
normed := http.CanonicalHeaderKey(allowedMethod)
normedMethods = append(normedMethods, normed)
}
// Normalize AllowedHeaders and make comma-separated-values
normedHeaders := []string{}
for _, allowedHeader := range allowedHeaders {
normed := http.CanonicalHeaderKey(allowedHeader)
normedHeaders = append(normedHeaders, normed)
}
c.Response().Header().Set("Access-Control-Allow-Methods", strings.Join(normedMethods, ","))
c.Response().Header().Set("Access-Control-Allow-Headers", strings.Join(normedHeaders, ","))
c.Response().Header().Set("Access-Control-Max-Age", strconv.Itoa(accessControlMaxAge))
c.Response().Header().Set("Access-Control-Allow-Origin", origin)
return h(c)
}
}
}

View file

@ -1,43 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"github.com/labstack/echo"
)
// HeadOpts defines options for the Head middleward
type HeadOpts struct {
CacheControl string
}
// Head defines middleware for setting miscellaneous headers
func Head(opts *HeadOpts) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Set default values for opts.PoweredBy
cacheControl := opts.CacheControl
if cacheControl == "" {
cacheControl = "no-cache"
}
c.Response().Header().Set("Cache-control", cacheControl)
return h(c)
}
}
}

View file

@ -1,43 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"github.com/labstack/echo"
)
// InfoOpts defines options for the Info middleware
type InfoOpts struct {
PoweredBy string
}
// Info defines middleware for specifying the server powered-by header
func Info(opts *InfoOpts) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Set default values for opts.PoweredBy
poweredBy := opts.PoweredBy
if poweredBy == "" {
poweredBy = "Surreal"
}
c.Response().Header().Set("X-Powered-By", poweredBy)
return h(c)
}
}
}

View file

@ -1,45 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"github.com/abcum/surreal/cnf"
"github.com/labstack/echo"
)
// Opts defines middleware for storing Surreal server options in the context
func Opts(opts *cnf.Options) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
c.Set("opts", opts)
c.Set("opts.db", opts.Db)
c.Set("opts.base", opts.Base)
c.Set("opts.auth", opts.Auth)
c.Set("opts.user", opts.User)
c.Set("opts.pass", opts.Pass)
c.Set("opts.port", opts.Port)
c.Set("opts.http", opts.Http)
c.Set("opts.sock", opts.Sock)
return h(c)
}
}
}

View file

@ -1,45 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"github.com/labstack/echo"
)
// SizeOpts defines options for the Size middleward
type SizeOpts struct {
Maximum int64
}
// Size defines middleware for limiting request size
func Size(opts *SizeOpts) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Set default values for opts.Maximum
maximum := opts.Maximum
if maximum == 0 {
maximum = 1000000
}
if c.Request().ContentLength <= maximum {
return h(c)
}
return echo.NewHTTPError(413)
}
}
}

View file

@ -1,62 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"mime"
"sort"
"github.com/labstack/echo"
)
// TypeOpts defines options for the Head middleward
type TypeOpts struct {
AllowedContent []string
}
// Type defines middleware for checking the request content-type
func Type(opts *TypeOpts) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Set default values for opts.AllowedContent
allowedContent := opts.AllowedContent
if len(allowedContent) == 0 {
allowedContent = []string{echo.ApplicationJSON}
}
// Extract the Content-Type header
header := c.Request().Header.Get(echo.ContentType)
cotype, _, _ := mime.ParseMediaType(header)
// Sort and search opts.AllowedContent types
sort.Strings(allowedContent)
i := sort.SearchStrings(allowedContent, cotype)
if c.Request().ContentLength == 0 {
return h(c)
}
if c.Request().ContentLength >= 1 {
if i < len(allowedContent) {
return h(c)
}
}
return code(415)
}
}
}

View file

@ -1,47 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"github.com/labstack/echo"
"github.com/abcum/surreal/util/uuid"
)
// UniqOpts defines options for the Uniq middleware
type UniqOpts struct {
HeaderKey string
}
// Uniq defines middleware for assigning a unique request id
func Uniq(opts *UniqOpts) echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Set default values for opts.HeaderKey
headerKey := opts.HeaderKey
if headerKey == "" {
headerKey = "Request-Id"
}
id := uuid.NewV4().String()
c.Response().Header().Set(headerKey, id)
return h(c)
}
}
}

View file

@ -1,36 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"github.com/abcum/surreal/db"
"github.com/labstack/echo"
)
func crud(c *echo.Context) error {
s, e := db.Execute(c, c.Request().Body)
if e == nil {
return c.JSON(200, show(s))
}
if e != nil {
return c.JSON(400, oops(e))
}
return nil
}

View file

@ -1,118 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"github.com/labstack/echo"
)
func show(i interface{}) interface{} {
return i
}
func oops(e error) interface{} {
return map[string]interface{}{
"code": 400,
"details": "Request problems detected",
"documentation": docs,
"information": e.Error(),
}
}
func errors(err error, c *echo.Context) {
code := 500
if e, ok := err.(*echo.HTTPError); ok {
code = e.Code()
}
c.JSON(code, errs[code])
}
const docs = "https://docs.surreal.io/"
var errs = map[int]interface{}{
200: map[string]interface{}{
"code": 200,
"details": "Information",
"documentation": docs,
"information": "Visit the documentation for details on accessing the api.",
},
400: map[string]interface{}{
"code": 400,
"details": "Request problems detected",
"documentation": docs,
"information": "There is a problem with your request. The request needs to adhere to certain constraints.",
},
401: map[string]interface{}{
"code": 401,
"details": "Authentication failed",
"documentation": docs,
"information": "Your authentication details are invalid. Reauthenticate using a valid token.",
},
403: map[string]interface{}{
"code": 403,
"details": "Request resource forbidden",
"documentation": docs,
"information": "Your request was forbidden. Perhaps you don't have the necessary permissions to access this resource.",
},
404: map[string]interface{}{
"code": 404,
"details": "Request resource not found",
"documentation": docs,
"information": "The requested resource does not exist. Check that you have entered the url correctly.",
},
405: map[string]interface{}{
"code": 405,
"details": "This method is not allowed",
"documentation": docs,
"information": "The requested http method is not allowed for this resource. Refer to the documentation for allowed methods.",
},
409: map[string]interface{}{
"code": 409,
"details": "Request conflict detected",
"documentation": docs,
"information": "The request could not be processed because of a conflict in the request.",
},
413: map[string]interface{}{
"code": 413,
"details": "Request content length too large",
"documentation": docs,
"information": "All SQL requests to the database must not exceed the predefined content length.",
},
415: map[string]interface{}{
"code": 415,
"details": "Unsupported content type requested",
"documentation": docs,
"information": "Requests to the database must use the 'Content-Type: application/json' header. Check your request settings and try again.",
},
500: map[string]interface{}{
"code": 500,
"details": "There was a problem with our servers, and we have been notified",
"documentation": docs,
},
}

View file

@ -1,25 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"github.com/labstack/echo"
)
func info(c *echo.Context) error {
return c.JSON(200, stat.Data())
}

View file

@ -1,30 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"encoding/json"
)
func encode(i interface{}) interface{} {
obj, _ := json.Marshal(i)
return string(obj)
}
func decode(i interface{}) interface{} {
var obj map[string]interface{}
json.Unmarshal([]byte(i.(string)), &obj)
return obj
}

View file

@ -1,152 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"log"
"sync"
"github.com/thoas/stats"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/abcum/surreal/cnf"
"github.com/abcum/surreal/db"
"github.com/abcum/surreal/server/api"
)
var stat *stats.Stats
// Setup sets up the server for remote connections
func Setup(opts *cnf.Options) (e error) {
var wg sync.WaitGroup
wg.Add(3)
// -------------------------------------------------------
// Stats
// -------------------------------------------------------
stat = stats.New()
// -------------------------------------------------------
// GUI handler
// -------------------------------------------------------
w := echo.New()
w.Get("/info", info)
w.Static("/", "tpl")
w.SetDebug(opts.Verbose)
w.AutoIndex(false)
w.SetHTTPErrorHandler(errors)
w.Use(stat.Handler)
w.Use(middleware.Gzip())
w.Use(middleware.Logger())
w.Use(middleware.Recover())
w.Use(api.Opts(opts))
w.Use(api.Uniq(&api.UniqOpts{}))
w.Use(api.Size(&api.SizeOpts{}))
w.Use(api.Head(&api.HeadOpts{}))
w.Use(api.Type(&api.TypeOpts{}))
w.Use(api.Cors(&api.CorsOpts{}))
w.Use(api.Auth(&api.AuthOpts{}))
// -------------------------------------------------------
// REST handler
// -------------------------------------------------------
r := echo.New()
r.Any("/", crud)
r.SetDebug(opts.Verbose)
r.AutoIndex(false)
r.SetHTTPErrorHandler(errors)
r.Use(stat.Handler)
r.Use(middleware.Gzip())
r.Use(middleware.Logger())
r.Use(middleware.Recover())
r.Use(api.Opts(opts))
r.Use(api.Uniq(&api.UniqOpts{}))
r.Use(api.Size(&api.SizeOpts{}))
r.Use(api.Head(&api.HeadOpts{}))
r.Use(api.Type(&api.TypeOpts{}))
r.Use(api.Cors(&api.CorsOpts{}))
r.Use(api.Auth(&api.AuthOpts{}))
// -------------------------------------------------------
// SOCK handler
// -------------------------------------------------------
s := echo.New()
s.WebSocket("/", sock)
r.SetDebug(opts.Verbose)
s.AutoIndex(false)
s.SetHTTPErrorHandler(errors)
s.Use(stat.Handler)
s.Use(middleware.Gzip())
s.Use(middleware.Logger())
s.Use(middleware.Recover())
s.Use(api.Opts(opts))
s.Use(api.Uniq(&api.UniqOpts{}))
s.Use(api.Size(&api.SizeOpts{}))
s.Use(api.Head(&api.HeadOpts{}))
s.Use(api.Type(&api.TypeOpts{}))
s.Use(api.Cors(&api.CorsOpts{}))
s.Use(api.Auth(&api.AuthOpts{}))
// -------------------------------------------------------
// Start servers
// -------------------------------------------------------
go func() {
defer wg.Done()
defer db.Stop()
log.Printf("Starting Web server on %s", opts.Port)
w.Run(opts.Port)
}()
go func() {
defer wg.Done()
defer db.Stop()
log.Printf("Starting HTTP server on %s", opts.Http)
r.Run(opts.Http)
}()
go func() {
defer wg.Done()
defer db.Stop()
log.Printf("Starting SOCK server on %s", opts.Sock)
s.Run(opts.Sock)
}()
// -------------------------------------------------------
// Start server
// -------------------------------------------------------
wg.Wait()
return nil
}

View file

@ -1,53 +0,0 @@
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"github.com/abcum/surreal/db"
"github.com/labstack/echo"
"golang.org/x/net/websocket"
)
func sock(c *echo.Context) error {
ws := c.Socket()
var msg string
for {
if err := websocket.Message.Receive(ws, &msg); err != nil {
break
}
s, e := db.Execute(c, msg)
if e == nil {
if err := websocket.Message.Send(ws, encode(show(s))); err != nil {
break
}
}
if e != nil {
if err := websocket.Message.Send(ws, encode(oops(e))); err != nil {
break
}
}
}
return nil
}