auth

package module
v0.0.0-...-7568b44 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2022 License: MIT Imports: 3 Imported by: 0

README


Auth

Auth is a simple cookie/session based authentication middleware for HTTP handlers.

  • Easy to use with minimal API surface
  • 100% compatible with http.Handler
  • Bring your own user type (uses Generics)
  • Uses github.com/alexedwards/scs under the hood

Installation

go get -u github.com/philippta/auth

Usage

View example/main.go for a complete example.

type user struct {
    name string
}

func lookupUser(id string) (*user, ok bool) {
    return &user{name: "John Doe"}, true
}

auth := auth.New(lookupUser)

// Start and stop session
auth.Login(r.Context(), userID)
auth.Logout(r.Context())

// Get user or login state from session
user, ok := auth.User(r.Context())
      ok := auth.Ok(r.Context())

// Wrap handler or router
auth.Handler(router)

License

Copyright (c) 2022 Philipp Tanlak

Licensed under MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Auth

type Auth[User any, ID any] struct {
	SessionManager *scs.SessionManager
	// contains filtered or unexported fields
}

Auth is an authentication middleware.

func New

func New[User any, ID any](f LookupFunc[User, ID]) *Auth[User, ID]

New returns a new Auth.

func (*Auth[User, ID]) Handler

func (a *Auth[User, ID]) Handler(h http.Handler) http.Handler

Handler returns a handler that wraps h and authenticates requests.

func (*Auth[User, ID]) Login

func (a *Auth[User, ID]) Login(ctx context.Context, id ID)

Login logs in the user with the given id.

func (*Auth[User, ID]) Logout

func (a *Auth[User, ID]) Logout(ctx context.Context)

Logout logs out the user.

func (*Auth[User, ID]) Ok

func (a *Auth[User, ID]) Ok(ctx context.Context) bool

Ok returns true if the request is authenticated.

func (*Auth[User, ID]) User

func (a *Auth[User, ID]) User(ctx context.Context) (*User, bool)

User returns the user associated with the request.

type LookupFunc

type LookupFunc[User any, ID any] func(id ID) (*User, bool)

LookupFunc is a function that returns a user for a given id.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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