1

I use this to create a session for a user:

put_session(conn, :user_id, user_id)

but it expires quite fast, in about a day I think. I want it be around 2 weeks. How can I specify a time frame within which it's valid?

Junidi
  • 23
  • 2

2 Answers2

6

By default session cookies do not have an expiry date set, which creates a session cookie that exists until the user closes the browsing session. You can set a specific duration by passing max_age: <integer> to the plug Plug.Session call in lib/my_app/endpoint.ex:

Change:

plug Plug.Session,
  store: :cookie,
  key: "_my_app_key",
  signing_salt: "..."

to:

plug Plug.Session,
  store: :cookie,
  key: "_my_app_key",
  signing_salt: "...",
  max_age: 2 * 7 * 24 * 60 * 60 # number of seconds in 2 weeks

You can verify this by inspecting the set-cookie headers from your app. They'll turn from:

$ curl -I localhost:4000 | grep set-cookie

set-cookie: _my_app_key=SFMyNTY.g3QAAAABbQAAAANmb29GP-MM4khcFDg.V3iUo5xw9HqgCmvRLBvhRguMixOlzZH_pqxRIYVAwdQ; path=/; HttpOnly

to:

$ curl -I localhost:4000 | grep set-cookie

set-cookie: _my_app_key=SFMyNTY.g3QAAAABbQAAAANmb29GP-M66RqWt64.6PvtX96B9jwgyIhjJBX5AiDV9_96838plEpgGxS9u0Q; path=/; expires=Thu, 23 Mar 2017 15:06:48 GMT; max-age=1209600; HttpOnly

Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

You are putting it into a session which has limited flexibility. You can create a separate cookie, as one way to go and set its max_age like this:

put_resp_cookie(conn, :user_id, user_id, max_age: 30 * 24 * 60 * 60)
NoDisplayName
  • 15,246
  • 12
  • 62
  • 98