Railsconf Slides

http events nginx

Tue Jun 03 22:19:00 -0700 2008

Here’s my slides from Railsconf. More thoughts to come once I recover a bit more - it was pretty intense for my partners and I this year, what with doing three talks and manning a booth.

Someone in the session asked to see get_logged_in_user() (called from the code shown in slide 36). Here it is, in all its C string-manipulation glory:

void get_logged_in_user(ngx_http_request_t *r, u_char *user, int user_size)
{
   ngx_table_elt_t **cookies;
   ngx_table_elt_t *elt;
   char cookie[256] = "";
   int i;

   cookies = r->headers_in.cookies.elts;
   for (i = 0; i < (int)r->headers_in.cookies.nelts; i++)
   {
      elt = cookies[i];
      if (extract_and_overwrite_cookie((char *)elt->value.data, "heroku_session=", cookie, sizeof(cookie)))
         break;
   }

   if (cookie[0] != 0)
      find_user_by_cookie(cookie, (char *)user, user_size);
}

void find_user_by_cookie(const char *cookie, char *email, int size)
{
   char sql[256], scratch[128];
   snprintf(sql, sizeof(sql)-1,
      "SELECT username FROM sessions WHERE cookie='%s'",
      pg_escape(cookie, scratch, sizeof(scratch)));

   pg_select_one_string(sql, email, size);
}

Also, one correction: I incorrectly stated that redirect() was an Nginx function. It’s actually a helper function I created; here’s the code.

void redirect(ngx_http_request_t *r, char *url)
{
   location = ngx_palloc(r->pool, strlen(url));
   r->headers_out.location = ngx_palloc(r->pool, sizeof(ngx_table_elt_t));

   ngx_copy(location, url, strlen(url));

   r->headers_out.location->value.data = location;
   r->headers_out.location->value.len = strlen(url);      
   r->headers_out.content_length_n = 0;
   r->header_only = 1;
   r->keepalive = 0;
}

If you use this, make sure to return NGX_HTTP_MOVED_TEMPORARILY immediately after calling it, as shown in the slides.