foweb

package module
v0.0.0-...-b41b3c6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 31, 2019 License: MIT Imports: 6 Imported by: 0

README

foweb

foweb is a minimal framework for web backends written in Go using the default net/http package. This is currently only intended for my personal use, but if I am willing to fix bugs and add features if requested and I find the feature fits.

Example

package main

import (
	"fmt"
	"net/http"

	"github.com/s22h/foweb"
)

// APIBaseURL is the base URL of the API endpoint
const APIBaseURL = "/api/v1"

var users = map[string]string{
	"user": "test",
}

func main() {
	// this is the method that will be called when a user tries to authenticate,
	// to check if the credentials are valid, this would be querying a database
	// or users file in a real programme
	foweb.SigninCallback = func(creds foweb.Credentials) bool {
		expectedPassword, ok := users[creds.Username]
		return ok && expectedPassword == creds.Password
	}

	http.Handle(APIBaseURL+"/test", test)
	http.Handle("/", http.FileServer(http.Dir("./web/")))

	fmt.Println("Listening on port 3003")
	http.ListenAndServe(":3003", nil)
}

var test = foweb.MaybeAuthHandler{
	Callback: func(handler foweb.MaybeAuthHandler) {
		// handle GET request without authentication
		if handler.Request.Method == "GET" {
			foweb.WriteJSON(handler.Response, "Hello Go!")
			return
		}

		// check if authenticated, send unauthorized otherwise and return
		if !handler.CheckAuth() {
			return
		}

		// handle POST request only if authenticated
		if handler.Request.Method == "POST" {
			foweb.WriteJSON(handler.Response, "Hello POST")
		} else {
			foweb.WriteJSONResponse(handler.Response, foweb.JSONResponse{
				Status:  http.StatusMethodNotAllowed,
				Message: "Request method not allowed",
			})
		}
	},
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var SigninHandler = PlainHandler{
	Callback: func(handler PlainHandler) {
		var creds Credentials
		err := json.NewDecoder(handler.Request.Body).Decode(&creds)

		if err != nil {
			WriteJSONResponse(handler.Response, JSONResponse{
				Status:  http.StatusBadRequest,
				Message: "Body is not a valid JSON string.",
			})
			return
		}

		if !validationCallback(creds) {
			WriteUnauthorized(handler.Response)
			return
		}

		tokenString, err := GenerateToken(creds.Username)

		if err != nil {
			WriteJSONResponse(handler.Response, JSONResponse{
				Status:  http.StatusInternalServerError,
				Message: "Could not create JWT claim.",
			})
			return
		}

		WriteJSON(handler.Response, tokenString)
	},
}

SigninHandler is the default auth handler which generates a JWT when user and password match

Functions

func GenerateToken

func GenerateToken(username string) (string, error)

GenerateToken generates a JWT token with username and expiration as payload

func SetSecret

func SetSecret(s string)

func SetValidationCallback

func SetValidationCallback(f ValidationFunc)

SetValidationCallback sets the validation callback for the signin process

func ValidateJWT

func ValidateJWT(token string) (bool, error)

ValidateJWT validates the given token string and returns true if valid, false otherwise

func WriteJSON

func WriteJSON(w http.ResponseWriter, message string)

WriteJSON encodes and writes a string to the ResponseWriter

func WriteJSONResponse

func WriteJSONResponse(w http.ResponseWriter, response JSONResponse)

WriteJSONResponse encodes and writes a JSONResponse to the ResponseWriter

func WriteUnauthorized

func WriteUnauthorized(w http.ResponseWriter)

WriteUnauthorized writes the unauthorized status to the browser

Types

type AuthHandler

type AuthHandler struct {
	Callback func(handler AuthHandler)
	Response http.ResponseWriter
	Request  *http.Request
	Token    *string
}

AuthHandler requires an authenticated user to handle the request

func (AuthHandler) ServeHTTP

func (handler AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Claims

type Claims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

Claims is the default JWT claims struct

type Credentials

type Credentials struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

Credentials is the default credentials struct

type JSONResponse

type JSONResponse struct {
	Status  int         `json:"status"`
	Message interface{} `json:"message"`
}

JSONResponse is a generic response that can be marshalled for output

type MaybeAuthHandler

type MaybeAuthHandler struct {
	Callback func(handler MaybeAuthHandler)
	Response http.ResponseWriter
	Request  *http.Request

	Token *string
	// contains filtered or unexported fields
}

MaybeAuthHandler checks for authentication but does not quit if unauthorized

func (MaybeAuthHandler) CheckAuth

func (handler MaybeAuthHandler) CheckAuth() bool

CheckAuth checks if authorized and sends message

func (MaybeAuthHandler) ServeHTTP

func (handler MaybeAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type PlainHandler

type PlainHandler struct {
	Callback func(handler PlainHandler)
	Response http.ResponseWriter
	Request  *http.Request
}

PlainHandler is the default request handler without auth etc.

func (PlainHandler) ServeHTTP

func (handler PlainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ValidationFunc

type ValidationFunc func(creds Credentials) bool

ValidationFunc is the expected type of the validation callback

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL