sessionauth

package module
v0.0.0-...-34e612b Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2022 License: MIT Imports: 16 Imported by: 0

README

Coverage Report Test Status

Echo Session Auth

This module help to use session based authentication for your echo web application.

Examples: link

Install

Install required modules

# Install `echo`
go get github.com/labstack/echo
go get github.com/jockerz/session-auth-echo

Preparation

1. Extending echo.Context

To have our session based auth works, User field is required.

type CustomContext struct {
    echo.Context
    User interface{}
}
2. User Struct

Create User struct for later use.

type User struct {
    ID       int
    Username string
    Password string
}
3. GetUser function

The GetUser(c echo.Context, UserID inteface{}) error function to get User instance and passed it to the User field on extended context struct.

Note: Main GetUser job is to assign the User instance to CustomContext.User field.

Usage example

// For demo only
var Users = []*User{
    &User{"First", 1},
    &User{"Second", 2},
}

function GetUser(c echo.Context, UserID interface{}) error {
    // required
	ctx := c.(*CustomContext)

	uid, _ := strconv.Atoi(fmt.Sprintf("%v", UserID))

	for _, user := range Users {
		if user.ID == uid {
            // REQUIRED
			ctx.User = user
			return nil
		}
	}
	return errors.New("user not found")
}

Usage

1. Create sessionauth.SessionAuth instance.

main.go

package main

import (
    ...
    sessionauth "github.com/jockerz/session-auth-echo"
)

var (
    auth *sessionauth.SessionAuth

    // Session auth config
    Config = sessionauth.MakeConfig(
		[]byte("changeme"),      // Secret Key
		"/login",                // UnAuthRedirect
		[]string{"favicon.ico"}, // Excluded path by strings
		[]*regexp.Regexp{},      // Exlcuded path by regex
	)
)

func main() {
    ...
    // Create session auth
	auth, _ = sessionauth.Create(Config, GetUser)
    ...
}
2. Use the Extended Context

Ref: Context

func main() {
    app := echo.New()
    
    app.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			cc := &CustomContext{
				Context: c,
			}
			return next(cc)
		}
	})
    ...
}
3. Middlewares
1. Session Middleware

After using the extended echo context, we need the *echo.Echo instance to use session and cookie. Therefore we load it after our custom context.

func main() {
    ...
    // Use session middleware
    app.Use(auth.GetSessionMiddleware())
}
2. Session Auth Middleware

Auth middleware is required to get User for each request session. Make sure you use this middleware after the session middleware.

func main() {
    ...
    // Use session middleware
    app.Use(auth.GetSessionMiddleware())
    // Session auth middleware
    app.Use(auth.AuthMiddlewareFunc)
}
4. Protecting Routes

Protected route example for authenticated user only

func ProtectedPage(c echo.Context) error {
	ctx := c.(*CustomContext)
    // required
	SessionAuth.LoginRequired(ctx)
    
    ...
}

Protected route example for freshly authenticated user only

func FreshOnlyProtectedPage(c echo.Context) error {
	ctx := c.(*CustomContext)
    // required
	SessionAuth.FreshLoginRequired(ctx)
	
    ...
}

Documentation

Index

Constants

View Source
const (
	ProtectionLevelBasic  int = 1
	ProtectionLevelStrong int = 2
)

TODO: Protection Level

View Source
const (
	InvalidCookie            = "invalid cookie"
	InvalidCookieIndentifier = "invalid cookie identifier"
)

Variables

This section is empty.

Functions

func CookieDigest

func CookieDigest(payload string, secret []byte) []byte

Create a endrypted remember cookie

func CreateSessionID

func CreateSessionID(realIP string, userAgent []string) string

Create auth session

func DecodeCookie

func DecodeCookie(cookieValue string, secret []byte) ([]byte, error)

Decode remember cookie

Types

type Config

type Config struct {
	// Session auth cookie name
	AuthSessionName string
	// Secret key that would be used for cookie and more
	// Loaded from shell environment `SECRET_KEY`
	SecretKey []byte
	// Redirection path for unauthorized access to protected page
	UnAuthRedirect string
	// Exluded path list. E.g. "/logout", "/register", etc
	Excluded []string
	// Exluded regex path. E.g. "/static/*"
	ExcludedRegex []*regexp.Regexp

	// Choose between `ProtectionLevelBasic` or `ProtectionLevelStrong`
	ProtectionLevel int

	// cookie name for login with `remember me` flag
	CookieName     string
	CookieDomain   string
	CookiePath     string
	CookieSecure   bool
	CookieHTTPOnly bool
	CookieSameSite http.SameSite
	// Cookie duration in seconds
	CookieDuration int

	SessionFresh            string
	SessionID               string
	SessionKey              string
	SessionNext             string
	SessionRememberCookie   string
	SessionRememberDuration string
}

Initial configurations

func MakeConfig

func MakeConfig(SecretKey []byte, UnAuthRedirect string, Excluded []string, ExcludedRegex []*regexp.Regexp) *Config

type ISessionAuth

type ISessionAuth interface {
	// Get Session (extended against our config) middleware function
	GetSessionMiddleware() echo.MiddlewareFunc

	// Get authentication middleware function
	AuthMiddlewareFunc() echo.HandlerFunc

	// Set authentication session and cookie
	Login(ctx echo.Context, UserId string, fresh bool) error

	// Clean authentication session and cookie
	Logout(ctx echo.Context)

	// Check if path is in excluded pattern list
	PathIsExcluded(path string)
}

type SessionAuth

type SessionAuth struct {
	Config *Config
	Cookie *sessions.CookieStore

	// Get user method
	// error is not nil if user is not found
	GetUser func(c echo.Context, UserId any) error
}

func Create

func Create(config *Config, getUser func(c echo.Context, UserId any) error) (*SessionAuth, error)

Create SessionAuth by

func (*SessionAuth) AuthMiddlewareFunc

func (s *SessionAuth) AuthMiddlewareFunc(next echo.HandlerFunc) echo.HandlerFunc

func (*SessionAuth) DeleteCookie

func (s *SessionAuth) DeleteCookie(ctx echo.Context)

func (*SessionAuth) FreshLoginRequired

func (s *SessionAuth) FreshLoginRequired(ctx echo.Context) error

Need to be called on restricted endpoints that accessed by freshly authenticated user Returns redirect to "config.UnauthRedirect" with last path as next URL query

func (*SessionAuth) GetCookie

func (s *SessionAuth) GetCookie(ctx echo.Context) (interface{}, error)

func (*SessionAuth) GetSessionMiddleware

func (s *SessionAuth) GetSessionMiddleware() echo.MiddlewareFunc

func (*SessionAuth) Login

func (s *SessionAuth) Login(ctx echo.Context, UserId string, fresh bool, remember bool) error

Save authenticated user session if "remember" is true, save remember_me cookie UserID should be represented as string

func (*SessionAuth) LoginRequired

func (s *SessionAuth) LoginRequired(ctx echo.Context) error

Need to be called on restricted endpoints that accessed by authenticated user Returns redirect to "config.UnauthRedirect" with last path as next URL query

func (*SessionAuth) Logout

func (s *SessionAuth) Logout(ctx echo.Context)

func (*SessionAuth) PathIsExcluded

func (s *SessionAuth) PathIsExcluded(path string) bool

func (*SessionAuth) SetCookie

func (s *SessionAuth) SetCookie(ctx echo.Context, UserID string)

Jump to

Keyboard shortcuts

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