All Projects → kemalcr → kemal-session

kemalcr / kemal-session

Licence: MIT License
Simple session handler for Kemal

Programming Languages

crystal
512 projects

Projects that are alternatives of or similar to kemal-session

laravel-remember-all
A Laravel session driver to remember all devices a user has logged in with.
Stars: ✭ 30 (-36.17%)
Mutual labels:  session
OSAPI
👋 OSAPI 是依靠通用性后台管理平台搭建的API管理平台,基于 vue3、Nestjs 技术栈实现,包含 RBAC 角色权限模块、数据展示、编辑等模块。
Stars: ✭ 32 (-31.91%)
Mutual labels:  session
nestjs-cookie-session
Idiomatic Cookie Session Module for NestJS. Built on top of `cookie-session` 😻
Stars: ✭ 35 (-25.53%)
Mutual labels:  session
kemal-watcher
Kemal plugin to watch files and live-reload the browser
Stars: ✭ 21 (-55.32%)
Mutual labels:  kemal
laminas-session
Object-oriented interface to PHP sessions and storage
Stars: ✭ 35 (-25.53%)
Mutual labels:  session
Agile-Server
A simple, fast, complete Node.js server solution, based on KOA. 简单快速的 、性能强劲的、功能齐全的 node 服务器解决方案合集,基于 KOA。
Stars: ✭ 24 (-48.94%)
Mutual labels:  session
fastify-session
session plugin for fastify
Stars: ✭ 93 (+97.87%)
Mutual labels:  session
visual-ts-game-engine
Typescript project based on matter.ts implementation."This version 2 of visualjs game engine, totally different approach. Whole project is based fully dependency build. Main file is app.ts and ioc.ts. Class ioc saves singleton instances also bind. In this project html and css is also present, webpack helps and handle this type of files. GamePlay…
Stars: ✭ 15 (-68.09%)
Mutual labels:  session
keycloak-session-restrictor
Simple event-listener for Keycloak which restricts the current user sessions to one (last one wins) only. Demo purposes only!
Stars: ✭ 48 (+2.13%)
Mutual labels:  session
neo4j-php-client
Php client and driver for neo4j database
Stars: ✭ 95 (+102.13%)
Mutual labels:  session
laravel-localizer
Automatically detect and set an app locale that matches your visitor's preference.
Stars: ✭ 34 (-27.66%)
Mutual labels:  session
kemal-basic-auth
Basic auth for your Kemal application
Stars: ✭ 14 (-70.21%)
Mutual labels:  kemal
mnemosyne
Session management service with RPC API based on protobuf.
Stars: ✭ 15 (-68.09%)
Mutual labels:  session
fastapi-framework
A FastAPI Framework for things like Database, Redis, Logging, JWT Authentication, Rate Limits and Sessions
Stars: ✭ 26 (-44.68%)
Mutual labels:  session
sessionx
Go's web session library.
Stars: ✭ 75 (+59.57%)
Mutual labels:  session
Kalbi
Kalbi - Golang Session Initiated Protocol Framework
Stars: ✭ 85 (+80.85%)
Mutual labels:  session
crystular
Crystal regex tester http://www.crystular.org/
Stars: ✭ 31 (-34.04%)
Mutual labels:  kemal
egg-session
session plugin for egg
Stars: ✭ 48 (+2.13%)
Mutual labels:  session
session
A session service, PSR-15 session middleware, and a flash message service which helps use one-time messages.
Stars: ✭ 14 (-70.21%)
Mutual labels:  session
telethon-session-sqlalchemy
SQLAlchemy backend for Telethon session storage
Stars: ✭ 34 (-27.66%)
Mutual labels:  session

kemal-session

Build Status

Session support for Kemal 🚀

Installation

Add this to your application's shard.yml:

dependencies:
  kemal-session:
    github: kemalcr/kemal-session

Usage

Basic Usage

require "kemal"
require "kemal-session"

get "/set" do |env|
  env.session.int("number", rand(100)) # set the value of "number"
  "Random number set."
end

get "/get" do |env|
  num  = env.session.int("number") # get the value of "number"
  env.session.int?("hello") # get value or nil, like []?
  "Value of random number is #{num}."
end

Kemal.run

Available Types

The session can save many different types but the method names differ from the type.

Type Access Method
Int32 session.int
Int64 session.bigint
String session.string
Float64 session.float
Bool session.bool
StorableObject session.object

You can also access the underyling hash directly by appending s to the name: session.ints. This way you can use hash functions like

session.ints.each do |k, v|
  puts "#{k} => #{v}"
end

BUT: This should only be used for reading and analyzing values, never for changing them. Because otherwise the session won't automatically save the changes and you may produce really weird bugs...

StorableObject

kemal-session has the ability to save objects to session storage. By saving objects to session storage, this opens up the ability to have more advanced data types that aren't supported by the base types (Int32, Int64, Float64, String, Bool). Any object that you want to save to session storage needs to include the Kemal::Session::StorableObject module. The class must respond to to_json and from_json. NOTE The module must be included after the definition of to_json and from_json. Otherwise the compiler will not know that those methods have been defined on the class. Here's an example implementation:

class UserStorableObject
  include JSON::Serializable
  include Kemal::Session::StorableObject

  property id : Int32
  property name : String

  def initialize(@id : Int32, @name : String); end
end

Once a Kemal::Session::StorableObject has been defined, you can save that in session storage just like the base types. Here's an example using the UserStorableObject implementation:

require "kemal"
require "kemal-session"

get "/set" do |env|
  user = UserStorableObject.new(123, "charlie")
  env.session.object("user", user)
end

get "/get" do |env|
  user = env.session.object("user").as(UserStorableObject)
  "The user stored in session is #{user.name}"
end

Serialization is up to you. You can define how you want that to happen so long as the resulting type is a String. If you need recommendations or advice, check with the underlying session storage implementation.

Configuration

The Session can be configured in the same way as Kemal itself:

Kemal::Session.config do |config|
  config.cookie_name = "session_id"
  config.secret = "some_secret"
  config.gc_interval = 2.minutes # 2 minutes
end

or

Kemal::Session.config.cookie_name = "session_id"
Kemal::Session.config.secret = "some_secret"
Kemal::Session.config.gc_interval = 2.minutes # 2 minutes
Option explanation default
timeout How long is the session valid after last user interaction? Time::Span.new(1, 0, 0) (1 hour)
cookie_name Name of the cookie that holds the session_id on the client "kemal_sessid"
engine How are the sessions saved on the server? (see section below) Kemal::Session::MemoryEngine.new
gc_interval In which interval should the garbage collector find and delete expired sessions from the server? Time::Span.new(0, 4, 0) (4 minutes)
secret Used to sign the session ids before theyre saved in the cookie. Strongly encouraged to create your own secret ""
secure The cookie used for session management should only be transmitted over encrypted connections. false
domain Domain to use to scope cookie nil
path Scope cookie to a particular path "/"

Setting the Engine

The standard engine is the MemoryEngine

The engine you use has a huge impact on performance and can enable you to share sessions between different servers, make them available to any other application or whatever you can imagine. So the choice of engine is very important.

Kemal::Session.config.engine = Kemal::Session::FileEngine.new({:sessions_dir => "/var/foobar/sessions/"})

You can also write your own engine if you like. Take a look at the wiki page. If you think it might also be helpful for others just let me know about it and I will include it in a list of known engines or something.

Creating a new secret

crystal eval 'require "random/secure"; puts Random::Secure.hex(64)'

Once this has been generated, it's very important that you keep this in a safe place. Environment variables tend to be a good place for that. If the secret is lost all of the sessions will get reset.

Logout and managing sessions

If you want to log a user out, simply call destroy on the session object:

get "/logout" do |env|
  env.session.destroy
  "You have been logged out."
end

It is also possible to manage other users' sessions if you want to build an administrator's interface, for example:

  • Kemal::Session.get(session_id) returns the session object identified by the given id
  • Kemal::Session.each { |session| … } executes the given block on every session
  • Kemal::Session.all returns an array containing all sessions
  • Kemal::Session.destroy(session_id) destroys the session identified by the given id (logs the user out)
  • Kemal::Session.destroy_all destroys all sessions (logs everyone out including you)

You should be very careful with those, though. These functions enable you to access and modify all information that is stored in all sessions, also in those that do not belong to the current user. So take extra care of security when using them. Additionally, depending on the engine used and on how many active sessions there are, Kemal::Session.all and Kemal::Session.each might be memory intensive as they have to load all the sessions into memory at once, in the worst case. It is best to check/ask how your engine handles that when in doubt.

Securing the cookies

You can use the samesite parameter like the following

Kemal::Session.config do |config|
  config.samesite = HTTP::Cookie::SameSite::Strict
end

Compatible Engines

Thanks

Special thanks to Thyra for initial efforts.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].