예제 #1
0
파일: auth.cpp 프로젝트: jagguli/cppwebapp
void register_handler(request_args &r){
    mustache::Context* dict = base_template_variables(new mustache::Context(), scripts);
    mustache::PlustacheTypes::ObjectType registration_form_section, message_section;
    if(header_value(r.req.headers,"METHOD") == "POST"){
        std::unordered_map<std::string,std::string> registration_form = getFormFields(r.req.body);
        for(auto fields:registration_form){
            std::cout << fields.first << " = " << fields.second << std::endl;
        }
        time_t now = time(NULL);
        std::tm *timeinfo = localtime(&now);
        std::vector<std::string> names = {"",""};
        boost::split(names, registration_form["name"], boost::is_any_of(" "));
        User u(registration_form["userid"],
               names[0],
               names[1],
             registration_form["password"],
             *timeinfo);
        soci::session sql(r.db_pool);
        int status = User::create(sql,u);
        if(status==1){
            message_section["STATUS"] = "success";
        }else if(status==2){
            message_section["STATUS"] = "User id already exists.";
        }else{
            message_section["STATUS"] = "fail";
        }
    }
    dict->add("REGISTER_FORM",registration_form_section);
    dict->add("MESSAGE",message_section);
    r.conn.reply_http(r.req,render_template("register",dict),200,"OK",default_headers);
}
예제 #2
0
파일: auth.cpp 프로젝트: jagguli/cppwebapp
void login_handler(request_args &r){
    int code=200;
    std::vector<m2pp::header> redir_headers = {{"Content-Type","text/html"}};
    mustache::Context* dict = base_template_variables(new mustache::Context(), scripts);
    mustache::PlustacheTypes::ObjectType login_form_section, message_section;
    soci::session sql(r.db_pool);
    User *user  = new User();
    if(header_value(r.req.headers,"METHOD") == "POST"){
        std::unordered_map<std::string,std::string> login_form = getFormFields(r.req.body);
        for(auto fields:login_form){
            std::cout << fields.first << " = " << fields.second << std::endl;
        }
        std::string username = login_form["userid"];
        log_DEBUG(username);
        sql << "select * from users where username = '******'",soci::into(*user);
        if(!sql.got_data()){
            message_section["STATUS"] = "Username is not registered.";
        }else{
            redir_headers.push_back({"Location","/nutrition/" });
            code = 303;
        }
    }
    dict->add("LOGIN_FORM", login_form_section);
    dict->add("MESSAGE", message_section);
    
    r.conn.reply_http(r.req,render_template("login",dict),code,"OK",redir_headers);
}
예제 #3
0
int header_equal( connection* conn, char* name, char* value )
{
	char* v = header_value( conn, name );
	if( !value[0]&&v[0] )
		return 0;
	if( strnicmp( value, v, strlen(value) ) == 0 )
		return 1;
	return 0;
}
예제 #4
0
void Request::addHeader(const char* key, const char* value) {
  std::string header_type(key);
  std::string header_value(value);
  
  if(!header_type.compare("If-Modified-Since")){
    headers[header_type] = header_value;}
  else{
    header_type = standardize(header_type);
    header_value = standardize(header_value);
    headers[header_type] = header_value;
  }
}
예제 #5
0
bool net::internet::http::error::build_page(connection& conn, unsigned short status_code)
{
	const err* e;
	if ((e = search(status_code)) == NULL) {
		return false;
	}

	if (!conn.add_common_headers(_M_headers)) {
		return false;
	}

	char buffer[2 * PATH_MAX];
	header_value value;
	value.value = buffer;

	switch (status_code) {
		case MOVED_PERMANENTLY:
			if (conn._M_hostlen > 0) {
				value.len = snprintf(buffer, sizeof(buffer), "%.*s/", conn._M_urllen - conn._M_querylen - conn._M_fragmentlen, conn._M_in.data() + conn._M_url);
			} else {
				bool https = (conn._M_listener->_M_data != NULL);
				in_port_t port = conn._M_listener->port();

				if (!https) {
					if (port == HTTP_DEFAULT_PORT) {
						value.len = snprintf(buffer, sizeof(buffer), "http://%.*s%.*s/", conn._M_vhost->namelen(), conn._M_vhost->name(), conn._M_path.length(), conn._M_path.data());
					} else {
						value.len = snprintf(buffer, sizeof(buffer), "http://%.*s:%u%.*s/", conn._M_vhost->namelen(), conn._M_vhost->name(), port, conn._M_path.length(), conn._M_path.data());
					}
				} else {
					if (port == HTTPS_DEFAULT_PORT) {
						value.len = snprintf(buffer, sizeof(buffer), "https://%.*s%.*s/", conn._M_vhost->namelen(), conn._M_vhost->name(), conn._M_path.length(), conn._M_path.data());
					} else {
						value.len = snprintf(buffer, sizeof(buffer), "https://%.*s:%u%.*s/", conn._M_vhost->namelen(), conn._M_vhost->name(), port, conn._M_path.length(), conn._M_path.data());
					}
				}
			}

			if (!_M_headers.add(header_name::LOCATION, value)) {
				return false;
			}

			if (!_M_headers.add(header_name::CONTENT_TYPE, header_value("text/html; charset=UTF-8", 24))) {
				return false;
			}

			if (!_M_headers.add(header_name::CONTENT_LENGTH, (uint64_t) e->body.length())) {
				return false;
			}

			break;
		case NOT_MODIFIED:
			value.len = snprintf(buffer, sizeof(buffer), "\"%x-%x\"", conn._M_last_modified, conn._M_filesize);

			if (!_M_headers.add(header_name::ETAG, value)) {
				return error::INTERNAL_SERVER_ERROR;
			}

			// The 304 response MUST NOT contain a message-body.
			if (!_M_headers.add_time(header_name::LAST_MODIFIED, conn._M_last_modified)) {
				return false;
			}

			break;
		case REQUESTED_RANGE_NOT_SATISFIABLE:
			value.len = snprintf(buffer, sizeof(buffer), "bytes */%lld", conn._M_filesize);

			if (!_M_headers.add(header_name::CONTENT_RANGE, value)) {
				return error::INTERNAL_SERVER_ERROR;
			}

			// Fall through.
		default:
			if (!_M_headers.add(header_name::CONTENT_TYPE, header_value("text/html; charset=UTF-8", 24))) {
				return false;
			}

			if (!_M_headers.add(header_name::CONTENT_LENGTH, (uint64_t) e->body.length())) {
				return false;
			}
	}

	if (!conn._M_out.format("HTTP/1.1 %u %s\r\n", e->status_code, e->reason_phrase)) {
		return false;
	}

	if (!_M_headers.serialize(conn._M_out)) {
		return false;
	}

	conn._M_bodyp = &e->body;

	return true;
}
예제 #6
0
RedirectPlugin::LookUpStatus
SipRedirectorJoin::lookUpDialog(
   const UtlString& requestString,
   const UtlString& incomingCallId,
   ContactList& contactList,
   RedirectPlugin::RequestSeqNo requestSeqNo,
   int redirectorNo,
   SipRedirectorPrivateStorage*& privateStorage,
   const char* subscribeUser,
   State stateFilter)
{
   Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                 "%s::lookUpDialog requestString = '%s', "
                 "requestSeqNo = %d, redirectorNo = %d, privateStorage = %p, "
                 "subscribeUser = '******', stateFilter = %d",
                 mLogName.data(),
                 requestString.data(), requestSeqNo, redirectorNo,
                 privateStorage, subscribeUser, stateFilter);

   // If the private storage is already allocated, then this is a
   // reprocessing cycle, and the dialog to pick up (if any) is
   // recorded in private storage.
   if (privateStorage)
   {
      // Cast the private storage pointer to the right type so we can
      // access the needed dialog information.
      SipRedirectorPrivateStorageJoin* dialog_info =
         dynamic_cast<SipRedirectorPrivateStorageJoin*> (privateStorage);

      if (dialog_info->mTargetDialogDuration !=
          SipRedirectorPrivateStorageJoin::TargetDialogDurationAbsent)
      {
         // A dialog has been recorded.  Construct a contact for it.
         // Beware that as recorded in the dialog event notice, the
         // target URI is in addr-spec format; any parameters are URI
         // parameters.  (Field parameters have been broken out in
         // param elements.)
         Url contact_URI(dialog_info->mTargetDialogLocalURI, TRUE);

         // Construct the Join: header value the caller should use.
         UtlString header_value(dialog_info->mTargetDialogCallId);
         // Note that according to RFC 3891, the to-tag parameter is
         // the local tag at the destination of the INVITE/Join.
         // But the INVITE/Join goes to the end of the call that
         // we queried with SUBSCRIBE, so the to-tag in the
         // Join: header is the *local* tag from the NOTIFY.
         header_value.append(";to-tag=");
         header_value.append(dialog_info->mTargetDialogLocalTag);
         header_value.append(";from-tag=");
         header_value.append(dialog_info->mTargetDialogRemoteTag);
         // Add a header parameter to specify the Join: header.
         contact_URI.setHeaderParameter("Join", header_value.data());

         // We add a header parameter to cause the redirection to
         // include a "Require: join" header.  Then if the caller
         // phone does not support INVITE/Join:, the pick-up will
         // fail entirely.  Without it, if the caller phone does not
         // support INVITE/Join, the caller will get a
         // simultaneous incoming call from the executing phone.
         // Previously, we thought the latter behavior was better, but
         // it is not -- Consider if the device is a gateway from the
         // PSTN.  Then the INVITE/Join will generate an outgoing
         // call to the calling phone.
         contact_URI.setHeaderParameter(SIP_REQUIRE_FIELD,
                                        SIP_JOIN_EXTENSION);

         // Record the URI as a contact.
         contactList.add( contact_URI, *this );
      }

      // We do not need to suspend this time.
      return RedirectPlugin::SUCCESS;
   }
   else
   {
      UtlString userId;
      Url requestUri(requestString);
      requestUri.getUserId(userId);
      Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                    "%s::lookUpDialog userId '%s'",
                    mLogName.data(), userId.data());

      // Construct the SUBSCRIBE for the call join.
      SipMessage subscribe;
      UtlString subscribeRequestUri("sip:");
      // The user of the request URI is our subscribeUser parameter.
      subscribeRequestUri.append(subscribeUser);
      subscribeRequestUri.append("@");
      subscribeRequestUri.append(mDomain);

      // Construct a Call-Id for the SUBSCRIBE.
      UtlString callId;
      CallId::getNewCallId(callId);

      // Construct the From: value.
      UtlString fromUri;
      {
         // Get the local address and port.
         UtlString address;
         int port;
         mpSipUserAgent->getLocalAddress(&address, &port);
         // Use the first 8 chars of the MD5 of the Call-Id as the from-tag.
         NetMd5Codec encoder;
         UtlString tag;
         encoder.encode(callId.data(), tag);
         tag.remove(8);
         // Assemble the URI.
         SipMessage::buildSipUri(&fromUri,
                                 address.data(),
                                 port,
                                 NULL, // protocol
                                 NULL, // user
                                 NULL, // userLabel,
                                 tag.data());
      }

      // Set the standard request headers.
      // Allow the SipUserAgent to fill in Contact:.
      subscribe.setRequestData(
         SIP_SUBSCRIBE_METHOD,
         subscribeRequestUri.data(), // request URI
         fromUri, // From:
         subscribeRequestUri.data(), // To:
         callId,
         mCSeq);
      // Increment CSeq and roll it over if necessary.
      mCSeq++;
      mCSeq &= 0x0FFFFFFF;
      // Set the Expires header.
      // If "1 second subscriptions" is set (needed for some versions
      // of Snom phones), use a 1-second subscription.  Otherwise, use
      // a 0-second subscription, so we get just one NOTIFY.
      subscribe.setExpiresField(mOneSecondSubscription ? 1 : 0);
      // Set the "Event: dialog" header.
      subscribe.setEventField("dialog");
      // Set the "Accept: application/dialog-info+xml" header.
      // Not strictly necessary (per the I-D), but it makes the SUBSCRIBE
      // more strictly compliant.
      subscribe.setHeaderValue(SIP_ACCEPT_FIELD,
                               DIALOG_EVENT_CONTENT_TYPE);
      // Set the References header for tracing dialog associations.
      {
         UtlString referencesValue(incomingCallId);
         referencesValue.append(";rel=inquiry");
         subscribe.setHeaderValue(SIP_REFERENCES_FIELD,
                                  referencesValue);
      }

      // Send the SUBSCRIBE.
      mpSipUserAgent->send(subscribe);

      // Allocate private storage.
      SipRedirectorPrivateStorageJoin *storage =
         new SipRedirectorPrivateStorageJoin(requestSeqNo,
                                             redirectorNo);
      privateStorage = storage;

      // Record the Call-Id of the SUBSCRIBE, so we can correlated the
      // NOTIFYs with it.
      storage->mSubscribeCallId = callId;
      // Record the state filtering criterion.
      storage->mStateFilter = stateFilter;

      // If we are printing debug messages, record when the SUBSCRIBE
      // was sent, so we can report how long it took to get the NOTIFYs.
      if (Os::Logger::instance().willLog(FAC_SIP, PRI_DEBUG))
      {
         OsDateTime::getCurTime(storage->mSubscribeSendTime);
      }

      // Set the timer to resume.
      storage->mTimer.oneshotAfter(OsTime(mWaitSecs, mWaitUSecs));

      // Suspend processing the request.
      return RedirectPlugin::SEARCH_PENDING;
   }
}
int httpconnection_on_header_value(http_parser* p, const char* at, size_t len) {
  HTTPConnection* c = static_cast<HTTPConnection*>(p->data);
  std::string header_value(at, len);
  c->headers.add(HTTPHeader(c->last_header, header_value));
  return 0;
}