This module help to use session based authentication for your echo
web application.
Examples: link
Install required modules
# Install `echo`
go get github.com/labstack/echo
go get github.com/jockerz/session-auth-echo
To have our session based auth works, User
field is required.
type CustomContext struct {
echo.Context
User interface{}
}
Create User
struct
for later use.
type User struct {
ID int
Username string
Password string
}
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 theUser
instance toCustomContext.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")
}
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)
...
}
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)
}
})
...
}
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())
}
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)
}
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)
...
}