mirror of
https://github.com/kataras/iris.git
synced 2025-12-17 18:07:01 +00:00
organise sessions examples
Former-commit-id: 682472d2cf4ebfc740687522fe5eef77b5bb1a72
This commit is contained in:
@@ -1,50 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris/v12"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris/v12/_examples/sessions/overview/example"
|
||||
"github.com/kataras/iris/v12/sessions"
|
||||
)
|
||||
|
||||
var (
|
||||
cookieNameForSessionID = "mycookiesessionnameid"
|
||||
sess = sessions.New(sessions.Config{Cookie: cookieNameForSessionID, AllowReclaim: true})
|
||||
)
|
||||
|
||||
func secret(ctx iris.Context) {
|
||||
// Check if user is authenticated
|
||||
if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth {
|
||||
ctx.StatusCode(iris.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
// Print secret message
|
||||
ctx.WriteString("The cake is a lie!")
|
||||
}
|
||||
|
||||
func login(ctx iris.Context) {
|
||||
session := sess.Start(ctx)
|
||||
|
||||
// Authentication goes here
|
||||
// ...
|
||||
|
||||
// Set user as authenticated
|
||||
session.Set("authenticated", true)
|
||||
}
|
||||
|
||||
func logout(ctx iris.Context) {
|
||||
session := sess.Start(ctx)
|
||||
|
||||
// Revoke users authentication
|
||||
session.Set("authenticated", false)
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/secret", secret)
|
||||
app.Get("/login", login)
|
||||
app.Get("/logout", logout)
|
||||
sess := sessions.New(sessions.Config{
|
||||
// Cookie string, the session's client cookie name, for example: "_session_id"
|
||||
//
|
||||
// Defaults to "irissessionid"
|
||||
Cookie: "_session_id",
|
||||
// it's time.Duration, from the time cookie is created, how long it can be alive?
|
||||
// 0 means no expire, unlimited life.
|
||||
// -1 means expire when browser closes
|
||||
// or set a value, like 2 hours:
|
||||
Expires: time.Hour * 2,
|
||||
// if you want to invalid cookies on different subdomains
|
||||
// of the same host, then enable it.
|
||||
// Defaults to false.
|
||||
DisableSubdomainPersistence: false,
|
||||
// Allow getting the session value stored by the request from the same request.
|
||||
AllowReclaim: true,
|
||||
})
|
||||
|
||||
app := example.NewApp(sess)
|
||||
app.Listen(":8080")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user