• Stars
    star
    23
  • Rank 1,016,462 (Top 21 %)
  • Language
    Crystal
  • License
    MIT License
  • Created almost 9 years ago
  • Updated almost 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Cookie based sessions in Crystal HTTP applications

Session Build Status

Session is a Crystal's HTTP::Handler that implements cookie based sessions. It can be combined with other bultin or custom handlers, as well as with other Crystal libraries that implement HTTP::Handlers such as kemal.

It takes a lot of inspiration from Rack::Session::Cookie, but it's much smaller, simpler, and obviously less feature-rich. Also less widespread and tested, but you can help with that!

WARNING: this is work in progress and most likely contains security, performance and other kinds of issues I'm working on finding and fixing. I don't use it in production and you shouldn't either.

Installation

Add this to your application's shard.yml:

dependencies:
  session:
    github: porras/session

Session requires Crystal 0.11.

Usage

Session::Handler is a generic class, that is, requires a type to be passed when instantiating it. This type is the data structure where your session data will be stored. This type has to be:

  • Serializable to JSON, either because it's a bultin type that is, or via JSON.mapping if it's a custom type
  • Initializable without parameters

Hash(String, String) makes a sensible yet simple and flexible example. A more strict alternative can be a class whose attributes are nilable so you can define an empty initializer (or provide defaults on it):

class MySession
  JSON.mapping({
    time:   {type: String, key: "t", nilable: true},
    visits: {type: Int32, key: "v"},
  })

  def initialize
    @visits = 0
  end
end

Providing a shorter key helps keeping the cookie size small.

Once you instantiate the handler passing the underlying type and the wanted options (see below), and you put it in the HTTP handlers chain, all downstream handlers will have a context.session available to read and update.

Options

  • secret (mandatory): the content of the session cookie are not encrypted but signed. That is, a user could read the contents (provided that they know the algorithim, which is available in the source code, and pretty simple), but not change it (because the signature wouldn't match). This secret is used for that.
  • session_key (defaults to "cr.session"): name of the cookie where the data will be stored.

Raw HTTP::Handler example

require "http/server"
require "session"

session_handler = Session::Handler(Hash(String, String)).new(secret: "SUPERSECRET")

server = HTTP::Server.new("0.0.0.0", "3000", [
  HTTP::LogHandler.new,
  HTTP::ErrorHandler.new,
  session_handler,
]) do |context|
  # context.session is a Hash(String, String)
  context.session["first_seen_at"] ||= Time.now.to_s
  context.response.print "You came first at #{context.session["first_seen_at"]}"
end

server.listen

Kemal example

You can easily integrate with Kemal.

require "kemal"
require "session"

session_handler = Session::Handler(Hash(String, String)).new(secret: "SUPERSECRET")
# Add session_handler to Kemal handlers
add_handler session_handler

get "/" do |env|
  env.session["first_seen_at"] ||= Time.now.to_s
  "You came first at #{env.session["first_seen_at"]}"
end

Contributing

  1. Fork it ( https://github.com/porras/session/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

  • porras Sergio Gil - creator, maintainer

More Repositories

1

crul

Command line HTTP client written in Crystal
Crystal
113
star
2

i3-keyboard-layout

Change keyboard layout with a keystroke + show it in the status bar
Shell
95
star
3

dmenu-emoji

Search an emoji by name and copy it to the clipboard [i3, dmenu, rofi]
Shell
62
star
4

mrproper

Property Based Testing in Ruby
Ruby
34
star
5

imdb

Wrapper library to search IMDB parsing its HTML
Ruby
29
star
6

duct

Duct allows you to embed a Gemfile in a single file script
Ruby
27
star
7

livevalidation

Client-side validations for Ruby on Rails (using javascript library livevalidation.com)
Ruby
26
star
8

tlcr

Simple terminal-based client for TLDR pages, written in Crystal. TLDR pages is a collection of simplified and community-driven man pages.
Crystal
23
star
9

rakegrowl

Get Growled when your long running rake tasks finish
Ruby
19
star
10

ghcontributors

Github Contributors
JavaScript
13
star
11

mock

Doubles (stubs and mocks) library for Crystal, inspired by the API of rspec-mocks
Crystal
13
star
12

evil-ruby-text-objects

Emacs package that adds some text objects and keybindings to work with Ruby code with Evil.
Emacs Lisp
10
star
13

rosendo

Minimalistic and naive Sinatra reimplementation, without any dependencies other than the ruby socket library
Ruby
9
star
14

language_detection

Rails plugin to detect the language of a given string
Ruby
8
star
15

sonic-pi-akai-apc-mini

Utility functions to use the Akai APC mini MIDI controller with Sonic Pi
Ruby
7
star
16

includer

Easy way to include files into another files
Ruby
6
star
17

store

File based storage library for Crystal (inspired by Ruby's PStore)
Crystal
6
star
18

random_items

Rails plugin to pick random items from a model (without using :order => "RAND()")
Ruby
6
star
19

rubystdlib

Slides, examples and reference links from my talk “5 gems of the Ruby Standard Library”
Ruby
5
star
20

madrid-rb-feb-2010

Sample application I used in my talk about acceptance testing with Steak and Capybara in Madrid-rb
Ruby
5
star
21

RGSoC_material

Ruby
5
star
22

tkn2

Tkn2 is a presentation tool for the terminal heavily inspired by Xavier Noria's tkn (Terminal Keynote)
Ruby
5
star
23

pipes

Ruby
4
star
24

nested_open_struct

Ruby
4
star
25

enumerator-talk

Examples for the talk about Enumerable and Enumerator I gave in RUG::B July 2015
3
star
26

-

Semantically awesome testing library
Ruby
3
star
27

twitter_common_friends

GreaseMonkey script which shows your common friends with any other Twitter user (a la Facebook)
JavaScript
3
star
28

hyperdelegate

Rails plugin which adds two options to delegate to make it more flexible and support two frequent patterns in delegation.
3
star
29

trenza

Ruby
2
star
30

pouchdb_test

JavaScript
2
star
31

ujfalusi

Ruby
2
star
32

magit-spinner

Emacs Lisp
1
star
33

sem_ver

Semantic Versioning parser
Ruby
1
star
34

fragments

1
star
35

sonic-pi-mode

Emacs Lisp
1
star