webext

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: MIT Imports: 23 Imported by: 0

README

displayName

donation link

A collection of website middleware to extend basic tasks for gofiber.

Note: this module assumes you are using gofiber/v2

Installation

go get github.com/AspieSoft/webext

# dependencies
go get github.com/gofiber/fiber/v2

Usage


package main

import (
  "github.com/AspieSoft/webext"
  "github.com/gofiber/fiber/v2"
)

func main(){
  app := fiber.New()

  origins := []string{
    "localhost",
    "example.com",
  }

  proxies := []string{
    "127.0.0.1",
    "192.168.0.1",
  }

  // enforce specific domain and ip origins
  app.Use(webext.VerifyOrigin(origins, proxies, func(c *fiber.Ctx, err error) error {
    c.SendStatus(403)
    return c.SendString(err.Error())
  }))

  // auto redirect http to https
  app.Use(webext.RedirectSSL(8080, 8443))

  // do anything with gofiber
  app.Get("/", func(c *fiber.Ctx) error {
    return c.SendString("Hello, World!")
  })

  // listen to both http and https ports and
  // auto generate a self signed ssl certificate
  // (will also auto renew every year)
  webext.ListenAutoTLS(app, 8080, 8443, "db/ssl/auto_ssl", proxies)

  // by using self signed certs, you can use a proxy like cloudflare and
  // not have to worry about verifying a certificate athority like lets encrypt
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GetPCID func(c *fiber.Ctx) string = func(c *fiber.Ctx) string {
	id := sha512.Sum512([]byte(c.Context().RemoteAddr().String() + "@" + string(c.Context().UserAgent())))
	return string(id[:])
}

GetPCID is a method you can override.

This method should return a unique identifier of the users ip and browser, and the result needs to be connsistantly the same even between sessions.

This ID is used as a secondary way to verify if a session token is valid, and the goal is to verify that the token is being used by the same machine it was generated for. This can help protect users from cookie injection. A hacker would have to know all the info about the user this string returns.

This string should only be stored server side, and never sent to the client.

By default, this returns a hash of the users IP Address (RemoteAddr) and UserAgent.

View Source
var Hooks hookList = hookList{}

Functions that you should override to handle database interaction and other methods that may be called within the module.

View Source
var IsRoot bool = os.Geteuid() == 0

IsRoot returns true if the EUID is 0

(i.e. if you ran your app with sudo)

PWD is initialized to the parent working directory of your app

View Source
var RenderError func(c *fiber.Ctx, url string, statusError *StatusError, args map[string]any) error = func(c *fiber.Ctx, url string, statusError *StatusError, args map[string]any) error {
	if statusError != nil {
		c.SendStatus(statusError.status)
		return c.SendString(statusError.msg)
	}
	return nil
}

RenderError is a method you can override.

It is used to handle http errors. You can decide how you want to handle rendering http errors here. You can also setup a templating engine of your choice with this method.

View Source
var RenderPage func(c *fiber.Ctx, url string, status int, args map[string]any) error = func(c *fiber.Ctx, url string, status int, args map[string]any) error {

	c.SendStatus(500)
	return c.SendString("Render Page Handler Needs Setup")
}

RenderPage is a method you can override.

It is used to handle page rendering. You can decide how you want to handle pages here. You can also setup a templating engine of your choice with this method.

Functions

func DelCron

func DelCron(name string)

DelCron removes a named cron job

func GenRsaKey

func GenRsaKey(crtPath string, keyPath string) error

GenRsaKey generates a new ssl certificate and key pair

  • expires: 3 years
  • rsa: 4096
  • x509
  • sha256
  • recommended renewal: once a year

func GenRsaKeyIfNeeded

func GenRsaKeyIfNeeded(crtPath string, keyPath string) error

GenRsaKeyIfNeeded auto detects if the certificates generated by the GenRsaKey method are either

  • not synchronized by date modified
  • are possibly expired (assuming a 1 year renewal)

If it detects this is true, it will automatically regenerate a new certificate

func GetLoginSession added in v0.0.9

func GetLoginSession() func(c *fiber.Ctx) error

GetLoginSession will populate c.Locals("uuid") with a user uuid if a login session is verified.

Note: Unlike the VerifyLogin middleware, this middleware will Not prevent c.Next() if the user is not logged in.

func HasCron

func HasCron(name string) bool

HasCron checks if a named cron job exists

func ListenAutoTLS

func ListenAutoTLS(app *fiber.App, httpPort, sslPort uint16, certPath string, proxy ...[]string) error

ListenAutoTLS will automatically generate a self signed tls certificate if needed and listen to both http and https ports

@httpPort: 80, @sslPort: 443

@certPath: file path to store ssl certificates to (this will generate a my/path.crt and my/path.key file)

@proxy: optional, if only one proxy is specified, the app will only listen to that ip address

func NewCron

func NewCron(interval time.Duration, cb func() bool) error

NewCron adds a new, unnamed cron job to the queue

minimum interval: 1 minute

in the callback, return true to keep the job running, and return false to end the job

func PrintMsg

func PrintMsg(color string, msg string, size int, end bool)

PrintMsg prints to console and auto inserts spaces

func RedirectSSL

func RedirectSSL(httpPort, sslPort uint16) func(c *fiber.Ctx) error

RedirectSSL can be added to `app.Use` to auto redirect http to https

@httpPort: 80, @sslPort: 443

func SetCron

func SetCron(name string, interval time.Duration, cb func() bool)

SetCron adds or overwrites a named cron job

func TryPerm

func TryPerm(perm rfs.FileMode, nonrootPerm rfs.FileMode) rfs.FileMode

TryPerm attempts to set a directory permission to @perm only if it can access that directory

if it fails due to permission restrictions, and if IsRoot returns false, it will instead return @nonrootPerm as a fallback

func VerifyLogin added in v0.0.2

func VerifyLogin() func(c *fiber.Ctx) error

VerifyLogin will verify if a user is loggedin or present them with a login form on GET requests.

Note: POST requests will return a 401 error if the user is not loggedin.

Notice: This method is still in development and is experimental. Use at your own risk.

If user is successfully logged in, their uuid will be returned in c.Locals("uuid")

func VerifyOrigin

func VerifyOrigin(origin []string, proxy []string, handleErr ...func(c *fiber.Ctx, err error) error) func(c *fiber.Ctx) error

VerifyOrigin can be added to `app.Use` to enforce that all connections are coming through a specified domain and proxy ip

@origin: list of valid domains

@proxy: list of valid ip proxies

@handleErr: optional, allows you to define a function for handling invalid origins, instead of returning the default http error

Types

type FormAuth added in v0.0.2

type FormAuth struct {
	Enabled bool

	Email string
}

FormAuth is used to return possible options for 2 step authentication.

@Enabled: True if a user has enabled 2 step authentication. False to skip 2auth.

@Email: The email address of the user to send an authentication code to.

type StatusError added in v0.0.5

type StatusError struct {
	// contains filtered or unexported fields
}

StatusError is an http status error

func NewStatusError added in v0.0.7

func NewStatusError(status int, msg string) *StatusError

NewStatusError returns a new status error

func (*StatusError) Msg added in v0.0.6

func (statusError *StatusError) Msg() string

Msg returns the status error message

func (*StatusError) Status added in v0.0.6

func (statusError *StatusError) Status() int

Status returns the status error code

Jump to

Keyboard shortcuts

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