Standard library · Network

net/http/session

User sessions over a cookie: keeping data between requests, and a CSRF token.

import net.http.session

A session keeps each user's data on the server and gives the browser nothing but a random id in a cookie. In a handler, Start finds the user's session or makes a new one; call Save after you change the values.

Once a user has logged in, have Regenerate change the id so the earlier one is of no use. The data lives in the memory of this process and is gone on a restart.

Types

SessionData

struct SessionData
The keys and values of the session.
NameTypeDescription
itemsHashMapThe values.
net-http-session-Session.salam
import net.http
import net.http.session
import net.router
import conv

func visit(ctx: i64):
    mut s := session.Start(ctx)
    mut count := 1
    if session.HasValue(s, "visits"):
        count = conv.Atoi(session.Value(s, "visits")) + 1
    end
    session.SetValue(s, "visits", "" + count)
    session.Save(s)
    http.Ctx_text(ctx, "visit " + count)
end

func login(ctx: i64):
    mut s := session.Start(ctx)
    session.Regenerate(ctx, s)
    session.SetValue(s, "user", "ali")
    token := session.CSRFToken(s)
    session.Save(s)
    http.Ctx_text(ctx, "" + session.CSRFVerify(s, token) + " " + session.CSRFVerify(s, "x"))
end

func logout(ctx: i64):
    session.End(ctx)
    http.Ctx_text(ctx, "goodbye")
end

func main:
    session.Configure("sid", 3600, false, "Lax")
    mut r := router.NewRouter()
    router.Get(r, "/", visit)
    router.Post(r, "/login", login)
    router.Post(r, "/logout", logout)
    mut srv := http.NewServer(19626)
    http.Use(srv, r)
    _ := http.RunBackground(srv)
    mut c := http.NewClient()
    base := "http://127.0.0.1:19626"
    println http.Body(c.Get(base + "/"))
    println http.Body(c.Get(base + "/"))
    println http.Body(c.Post(base + "/login", ""))
    println http.Body(c.Get(base + "/"))
    println http.Body(c.Post(base + "/logout", ""))
    println http.Body(c.Get(base + "/"))
    mut s := session.New()
    session.SetValue(s, "a", "1")
    session.SetValue(s, "b", "2")
    println session.DeleteValue(s, "a"), s.data.items.size()
    session.Save(s)
    mut found := false
    back := session.Get(s.id, found)
    println found, session.Value(back, "b"), back.max_age, s.id.len() > 0
    session.ClearValues(s)
    session.Destroy(s.id)
    _ := session.Get(s.id, found)
    println found, session.CleanupExpired() >= 0
    println session.DefaultCookieName, session.DefaultMaxAge
end
Outputvisit 1 visit 2 true false visit 3 goodbye visit 1 true 1 true 2 3600 true false true salam_sid 86400

Session

struct Session
One user's session.
NameTypeDescription
idstr = ""The random id that sits in the cookie.
dataSessionDataThe session data.
created_ati64 = 0When it was made.
last_seeni64 = 0When it was last used.
max_ageint = 0The session lifetime in seconds.

The example for this item is shown with the ones above: net-http-session-Session.salam

Constants and variables

DefaultCookieName

const DefaultCookieName: str = "salam_sid"
The default name of the session cookie.

The example for this item is shown with the ones above: net-http-session-Session.salam

DefaultMaxAge

const DefaultMaxAge: i32 = 86400
The default lifetime: one day.

The example for this item is shown with the ones above: net-http-session-Session.salam

Functions

Configure

func Configure(cookie_name: str, max_age_seconds: int, secure: bool, same_site: str)
Sets the cookie name, the lifetime, whether it is HTTPS only, and SameSite, for every session.

The example for this item is shown with the ones above: net-http-session-Session.salam

CleanupExpired

func CleanupExpired(): int
Deletes the expired sessions and returns how many.

The example for this item is shown with the ones above: net-http-session-Session.salam

Get

func Get(id: str, ok &: bool): Session
Finds a session by id; ok is false when there is none or it has expired.

The example for this item is shown with the ones above: net-http-session-Session.salam

Value

func Value(s: Session, key: str): str
The value of one key; an empty string when there is none.

The example for this item is shown with the ones above: net-http-session-Session.salam

HasValue

func HasValue(s: Session, key: str): bool
True when the key is there.

The example for this item is shown with the ones above: net-http-session-Session.salam

SetValue

func SetValue(s &: Session, key: str, value: str)
Sets the value of a key.

The example for this item is shown with the ones above: net-http-session-Session.salam

DeleteValue

func DeleteValue(s &: Session, key: str): bool
Takes the key away and says whether it was there.

The example for this item is shown with the ones above: net-http-session-Session.salam

Start

func Start(h: i64): Session
Finds the session of this request from the cookie or makes a new one, and sets the cookie.

The example for this item is shown with the ones above: net-http-session-Session.salam

End

func End(h: i64)
Deletes the session and expires the cookie in the browser; for logging out.

The example for this item is shown with the ones above: net-http-session-Session.salam

Regenerate

func Regenerate(h: i64, s &: Session)
Gives the session a fresh id and invalidates the earlier one; after logging in.

The example for this item is shown with the ones above: net-http-session-Session.salam

CSRFToken

func CSRFToken(s &: Session): str
Returns the CSRF token of the session, making one when there is none; put it in your forms.

The example for this item is shown with the ones above: net-http-session-Session.salam

CSRFVerify

func CSRFVerify(s: Session, token: str): bool
True when the token matches the session token.

The example for this item is shown with the ones above: net-http-session-Session.salam