add some gcf scaffolding

This commit is contained in:
41666 2020-11-23 05:09:41 -05:00
parent 3eba2d2de8
commit d8a25024de
5 changed files with 116 additions and 0 deletions

39
src/common/faas/auth.go Normal file
View file

@ -0,0 +1,39 @@
package faas
import (
"errors"
"net/http"
)
type AuthLevel uint
const (
AuthGuest = AuthLevel(iota)
AuthUser
AuthAdmin
AuthSuper
)
var (
ErrNotAuthorized = errors.New("common/faas: session not authorized")
)
func assertAuthLevel(err error, requiredAuthLevel AuthLevel, assertedAuthLevel AuthLevel) error {
if requiredAuthLevel == assertedAuthLevel {
return nil
} else {
return err
}
}
// AuthMustMatch will assert the current session's authorization group/level; only can match for Guest, User, and Super.
func AuthMustMatch(request *http.Request, authLevel AuthLevel) error {
authCookie, err := request.Cookie("Authorization")
if errors.Is(err, http.ErrNoCookie) {
// No cookie is present, assert guest.
return assertAuthLevel(ErrNotAuthorized, authLevel, AuthGuest)
} else if err != nil {
return err
}
}

60
src/functions/cmd/main.go Normal file
View file

@ -0,0 +1,60 @@
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"github.com/GoogleCloudPlatform/functions-framework-go/funcframework"
sessiondata "github.com/roleypoly/roleypoly/src/functions/session-data"
sessionprewarm "github.com/roleypoly/roleypoly/src/functions/session-prewarm"
)
var mappings map[string]http.HandlerFunc = map[string]http.HandlerFunc{
"/session-prewarm": sessionprewarm.SessionPrewarm,
"/session-data": sessiondata.SessionData,
}
var port string
func main() {
ctx := context.Background()
err := funcframework.RegisterHTTPFunctionContext(ctx, "/", rootHandler)
if err != nil {
log.Fatalf("funcframework.RegisterHTTPFunctionContext: %v\n", err)
}
for path, handler := range mappings {
err := funcframework.RegisterHTTPFunctionContext(ctx, path, handler)
if err != nil {
log.Fatalf("funcframework.RegisterHTTPFunctionContext: %v\n", err)
}
fmt.Println("Added", path)
}
// Use PORT environment variable, or default to 6600.
port = "6600"
if envPort := os.Getenv("PORT"); envPort != "" {
port = envPort
}
fmt.Printf("Starting on http://localhost:%s\n", port)
if err := funcframework.Start(port); err != nil {
log.Fatalf("funcframework.Start: %v\n", err)
}
}
func rootHandler(rw http.ResponseWriter, r *http.Request) {
body := `<!doctype html><meta charset="utf-8"><title>Roleypoly Functions</title><style>body{font-family: sans-serif; font-size: 1.4em}</style><h1>Function Index</h1>`
for path := range mappings {
body += fmt.Sprintf(`<a href="http://localhost:%s%s">%s</a><br>`, port, path, path)
}
fmt.Fprintln(rw, body)
}

View file

@ -0,0 +1,10 @@
package sessiondata
import (
"fmt"
"net/http"
)
func SessionData(rw http.ResponseWriter, r *http.Request) {
fmt.Fprintln(rw, "Hello world!")
}

View file

@ -0,0 +1,7 @@
package sessionprewarm
import "net/http"
func SessionPrewarm(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("hello work!"))
}