app

package
v0.0.0-...-4260fa3 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2024 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package app provides the glue that holds the application together.

Index

Constants

View Source
const SKCurrentUserID = "currentUserID"

SKCurrentUserID is the session key for the current user id.

View Source
const SKFlash = "flash"

SKFlash is the session key for storing flash.

View Source
const TMPDir = "tmp"

TMPDir is the temporary directory for the application.

Variables

View Source
var Collections = ContextKey("Collection")

Collections is the array of collections loaded to be rendered on the top menu bar.

View Source
var CurrentUser = ContextKey("CurrentUser")

CurrentUser is the context key for the currently logged in user if any. By having the current user in the context we avoid loading it many times throughout the lifespan of the request.

View Source
var ErrAuthenticationFailed = errors.New("authentication failed")

ErrAuthenticationFailed indicates that either the username or the password was wrong.

Functions

This section is empty.

Types

type App

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

App is a container that holds parts of the application together. It encapsulates a logger, transaction handling, session management etc.

func New

func New(logger Log, repo *repository.Repository, sm SessionManager, tmpl Template) *App

New creates a new application.

func (*App) AuthenticateUser

func (a *App) AuthenticateUser(ctx context.Context, name, password string) (*repository.User, error)

AuthenticateUser attempts a user login. I returns ErrAuthenticationFailed in case of invalid credentials. It returns the logged in user in case of successful login.

The login is stored in the session for following requests, until a user logout happens, or the session expires.

func (*App) BaseTemplate

func (a *App) BaseTemplate(r *http.Request) renderData

BaseTemplate is the basic template that every page needs. Use With* methods to add more data to the base template.

func (*App) ClearCurrentUser

func (a *App) ClearCurrentUser(ctx context.Context) error

ClearCurrentUser logs out the current user by removing it from the session.

func (*App) ClientError

func (a *App) ClientError(w http.ResponseWriter, err error, status int)

ClientError logs the error happened and responds with the status code.

func (*App) CurrentUser

func (a *App) CurrentUser(ctx context.Context) *repository.User

CurrentUser returns the current user from the request context. This relies on the app.Dynamic middleware to transfer the user from the session to the request context.

func (*App) DecodeForm

func (a *App) DecodeForm(values any, r *http.Request) error

DecodeForm decodes the POST form from r into the form structure pointed by values.

func (*App) Dynamic

func (a *App) Dynamic(next http.Handler) http.Handler

Dynamic is a middleware that enables sessions, and loads the current user.

func (*App) FlashError

func (a *App) FlashError(ctx context.Context, msg string)

FlashError is a flash message that indicates an error.

func (*App) FlashInfo

func (a *App) FlashInfo(ctx context.Context, msg string)

FlashInfo is a flash message with general information.

func (*App) FlashWarning

func (a *App) FlashWarning(ctx context.Context, msg string)

FlashWarning is a flash message that indicates a warning.

func (*App) Headers

func (a *App) Headers(next http.Handler) http.Handler

Headers is a middleware that adds common http headers.

func (*App) LogAction

func (a *App) LogAction(ctx context.Context, action string, args ...any)

LogAction logs the action happened. args are passed to the logger.

func (*App) LogRequest

func (a *App) LogRequest(next http.Handler) http.Handler

LogRequest is a middleware that logs the request.

func (*App) NoSurf

func (a *App) NoSurf(next http.Handler) http.Handler

NoSurf is a middleware that gives CSRF protection.

func (*App) ProcessGPXFile

func (a *App) ProcessGPXFile(path string, id int, uid int)

ProcessGPXFile reads a GPX file pointed by path and loads the GPX data into the database. It assumes that the file is already created in the gpxfiles table, with status repository.Filestatus/uploaded. If the processing fails the record will be updated with repository.Filestatus/ProcessingFailed, otherwise repository.Filestatus/Processed.

func (*App) Q

func (a *App) Q(ctx context.Context) repository.Queries

Q returns the database accessors / app data repository.

func (*App) Recover

func (a *App) Recover(next http.Handler) http.Handler

Recover is a middleware that catches any uncaught panic, and logs a backtrace.

func (*App) Render

func (a *App) Render(w io.Writer, name string, data renderData) error

Render renders the template from ui/html/<resource>/page.html. name is the path name with ui/html/ removed. renderData can be obtained by calling BaseTemplate().

func (*App) RequiresLogIn

func (a *App) RequiresLogIn(next http.Handler) http.Handler

RequiresLogIn is a middleware that enforces the user to be logged in.

func (*App) ServerError

func (a *App) ServerError(w http.ResponseWriter, err error)

ServerError logs the error happened and responds with 500.

func (*App) StandardChain

func (a *App) StandardChain() alice.Chain

StandardChain is a middleware to be used for every request that does not require further special treatment.

func (*App) WithTx

func (a *App) WithTx(ctx context.Context, blk func(ctx context.Context) error) (err error)

WithTx executes blk inside a transaction. If blk fails with error the transaction is rolled back and the error is returned. The transaction handle is passed to blk and the blk code is supposed to pass this handle to app.Repo.

type ContextKey

type ContextKey string

ContextKey is used to store data in the request context.

type Flash

type Flash = map[string][]string

Flash is a message that appears on the site for the next request.

Flash messages are stored in the session and thus they require the app.Dynamic middleware.

type Log

type Log interface {

	// ServerError indicates that an internal server error happened.
	//
	// The handler should stop execution at this point, and internal server error
	// will be sent to the client and the error will be logged.
	ServerError(err error)

	// ClientError indicates that there was a problem with the client request.
	//
	// The handler should stop execution at this point, and the given status code
	// will be sent to the client and the error will be logged.
	ClientError(err error, status int)

	// Info creates a generic info level log message.
	//
	// args should be in pairs following the slog APIs.
	Info(msg string, args ...any)

	// Panic logs a recover() handling an uncought panic from a handler.
	//
	// dumps stack trace
	Panic(err any)
}

Log defines the application logger.

type SessionManager

type SessionManager interface {

	// Get returns the value associated with the given key.
	//
	// If the key is not found, false is returned.
	Get(ctx context.Context, key string) any

	// Put associates the given value with the given key.
	Put(ctx context.Context, key string, value any)

	// Remove removes the value associated with the given key.
	Remove(ctx context.Context, key string)

	// Pop removes and returns the value associated with the given key.
	Pop(ctx context.Context, key string) any

	// RenewToken updates the session data to have a new session token while
	// retaining the current session data. The session lifetime is also reset and
	// the session data status will be set to Modified.
	//
	// The old session token and accompanying data are deleted from the session store.
	//
	// To mitigate the risk of session fixation attacks, it's important that you
	// call RenewToken before making any changes to privilege levels (e.g. login
	// and logout operations). See
	// [https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session\_Management\_Cheat\_Sheet.md#renew-the-session-id-after-any-privilege-level-change](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change)
	// for additional information.
	RenewToken(ctx context.Context) error

	// LoadAndSave loads the session data from the session store.
	LoadAndSave(next http.Handler) http.Handler
}

SessionManager provides access to the session store.

type Template

type Template interface {
	// Render produces html content identified by name and writes it to w. The data
	// carries page specific sideband data required on the page.
	Render(w io.Writer, name string, data any) error
}

Template provides html page rendering.

Directories

Path Synopsis
Package handler defines the collection of request handlers.
Package handler defines the collection of request handlers.
log
slog
Package slog uses log/slog back end for pkg/github.com/paulsonkoly/tracks/app.Log interface.
Package slog uses log/slog back end for pkg/github.com/paulsonkoly/tracks/app.Log interface.
session_manager
scs
Package scs uses alexedwards/scs for session management.
Package scs uses alexedwards/scs for session management.
Package template serves html from ui/html.
Package template serves html from ui/html.

Jump to

Keyboard shortcuts

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