// ************* CHECK AUTHENTICATION EVENT: Check if the session cookie is created, if not go to login page or show error static int check_auth(struct mg_connection *conn) { char ssid[100], calculated_ssid[100], name[100], expire[100]; // Always authenticate requests to login page if (strcmp(conn->uri, s_login_uri) == 0 ||strcmp(conn->uri, s_error_uri) == 0) { return MG_TRUE; } // Look for session ID in the Cookie. // That session ID can be validated against the database that stores // current active sessions. mg_parse_header(mg_get_header(conn, "Cookie"), "ssid", ssid, sizeof(ssid)); if (sscanf(ssid, "%[^|]|%[^|]|", name, expire) == 2) { generate_ssid(name, expire, calculated_ssid, sizeof(calculated_ssid)); if (strcmp(ssid, calculated_ssid) == 0) { //fprintf(stderr,"\n SSid generated: ssid %s ,calculated ssid %s , name %s,expire %s ... \n",ssid,calculated_ssid,name,expire); return MG_TRUE; // Authenticate } } // Auth failed, do NOT authenticate, redirect to login page mg_printf(conn, "HTTP/1.1 302 Moved\r\nLocation: %s\r\n\r\n", s_error_uri); return MG_FALSE; }
static const char *test_mg_parse_header(void) { const char *str = "xx=1 kl yy, ert=234 kl=123, " "ii=\"12\\\"34\" zz='aa bb',tt=2,gf=\"xx d=1234"; char buf[10]; ASSERT(mg_parse_header(str, "yy", buf, sizeof(buf)) == 0); ASSERT(mg_parse_header(str, "ert", buf, sizeof(buf)) == 3); ASSERT(strcmp(buf, "234") == 0); ASSERT(mg_parse_header(str, "ert", buf, 2) == 0); ASSERT(mg_parse_header(str, "ert", buf, 3) == 0); ASSERT(mg_parse_header(str, "ert", buf, 4) == 3); ASSERT(mg_parse_header(str, "gf", buf, sizeof(buf)) == 0); ASSERT(mg_parse_header(str, "zz", buf, sizeof(buf)) == 5); ASSERT(strcmp(buf, "aa bb") == 0); ASSERT(mg_parse_header(str, "d", buf, sizeof(buf)) == 4); ASSERT(strcmp(buf, "1234") == 0); buf[0] = 'x'; ASSERT(mg_parse_header(str, "MMM", buf, sizeof(buf)) == 0); ASSERT(buf[0] == '\0'); ASSERT(mg_parse_header(str, "kl", buf, sizeof(buf)) == 3); ASSERT(strcmp(buf, "123") == 0); ASSERT(mg_parse_header(str, "xx", buf, sizeof(buf)) == 1); ASSERT(strcmp(buf, "1") == 0); ASSERT(mg_parse_header(str, "ii", buf, sizeof(buf)) == 5); ASSERT(strcmp(buf, "12\"34") == 0); ASSERT(mg_parse_header(str, "tt", buf, sizeof(buf)) == 1); ASSERT(strcmp(buf, "2") == 0); return NULL; }