Skip to content

Instantly share code, notes, and snippets.

@Fadhil
Created May 7, 2016 07:02
Show Gist options
  • Save Fadhil/8bcda644da6fc29762cc138dc4c27a09 to your computer and use it in GitHub Desktop.
Save Fadhil/8bcda644da6fc29762cc138dc4c27a09 to your computer and use it in GitHub Desktop.
defmodule Plug.Anonymous do
import Plug.Conn
require IEx
def init(options), do: options
def call(conn, _opts) do
anonymous_id = get_session(conn, "anonymous_id")
case anonymous_id do
nil -> put_session(conn, "anonymous_id", "Testing")
_ -> conn
end
end
end
defmodule Plug.AnonymousTest do
use ExUnit.Case, async: true
use Plug.Test
alias Plug.Anonymous
require IEx
@default_opts [
store: :cookie,
key: "_test_key",
encryption_salt: "encrypted salt",
signing_salt: "signing salt",
log: false
]
@opts Plug.Session.init(@default_opts)
@secret String.duplicate("abcdef0123456789", 8)
defmodule SomeApp do
defmodule SomeController do
use Plug.Builder
plug Plug.Session,
store: :cookie,
key: "_wankrank_key",
signing_salt: "cmwAUEpB",
max_age: 86400
plug :fetch_session
plug Anonymous
end
end
def create_conn(conn, secret \\ @secret) do
put_in(conn.secret_key_base, secret)
|> Plug.Session.call(@opts)
|> fetch_session
end
test "assigns user_id session key" do
conn = conn(:get, "/") |> SomeApp.SomeController.call([])
refute get_session(conn, "anonymous_id") == nil
end
test "returns existing user session key" do
anonymous_id = %{anonymous_id: "some_id"}
new_conn = create_conn(conn(:get, "/"))
|> put_session("anonymous_id", "some_id")
|> Plug.Anonymous.call([])
assert get_session(new_conn, "anonymous_id") == "some_id"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment