Esempio n. 1
0
int             smb_session_login_spnego(smb_session *s, const char *domain,
        const char *user, const char *password)
{
    int           res;
    assert(s != NULL && domain != NULL && user != NULL && password != NULL);

    // Clear User ID that might exists from previous authentication attempt
    s->srv.uid = 0;

    if (init_asn1(s) != DSM_SUCCESS)
        return DSM_ERROR_GENERIC;

    if ((res = negotiate(s, domain)) != DSM_SUCCESS)
        goto error;
    if ((res = challenge(s)) != DSM_SUCCESS)
        goto error;

    res = auth(s, domain, user, password);

    clean_asn1(s);

    return res;

error:
    BDSM_dbg("login_spnego Interrupted\n");
    clean_asn1(s);
    return res;
}
Esempio n. 2
0
int main (int argc, char **argv)
{
  s_rules rr;
  if (argv[argc])
    err(1, "bad argument list");
  if (argc != 3)
    usage(argv[0]);
  if (strcmp(argv[1], "-c"))
    usage(argv[0]);
  openlog(argv[0], LOG_PID, LOG_AUTH);
  log_args("NEW", argc, (const char **)argv);
  init_package();
  {
    const char *env_auth_id = getenv(ENV_AUTH_ID);
    t_sym id = sympackage_intern(&g_sympkg, env_auth_id ? env_auth_id : "");
    s_symtable cmd;
    cmd_init(&cmd, id, argv[2]);
    rules_init(&rr);
    rules_read(&rr, "/etc/git-auth.conf");
    {
      int auth_ok = auth(&rr, &cmd);
      rules_free(&rr);
      log_rule(auth_ok ? "ALLOW" : "DENY", &cmd);
      if (auth_ok) {
	exec_cmd(&cmd);
	// never reached
      }
    }
    log_rule("DENY", &cmd);
  }
  cleanup();
  return 1;
}
Esempio n. 3
0
void HTTPRequest::setCredentials(const std::string& header, const std::string& scheme, const std::string& authInfo)
{
	std::string auth(scheme);
	auth.append(" ");
	auth.append(authInfo);
	set(header, auth);
}
Esempio n. 4
0
static int process_auth(ETERM *pid, ETERM *data)
{
  int retval = 0;
  ETERM *pattern, *srv, *user, *pass;
  char *service, *username, *password;
  pattern = erl_format("{Srv, User, Pass}");
  if (erl_match(pattern, data))
    {
      srv = erl_var_content(pattern, "Srv");
      service = erl_iolist_to_string(srv);
      user = erl_var_content(pattern, "User");
      username = erl_iolist_to_string(user);
      pass = erl_var_content(pattern, "Pass");
      password = erl_iolist_to_string(pass);
      retval = process_reply(pid, CMD_AUTH, auth(service, username, password));
      erl_free_term(srv);
      erl_free_term(user);
      erl_free_term(pass);
      erl_free(service);
      erl_free(username);
      erl_free(password);
    };
  erl_free_term(pattern);
  return retval;
}
bool TestDspCmdDirGetVmList::getExpectedVmList(QList<QDomDocument>& expectedList)
{
   QString  errorMsg;
   int      errorLine, errorColumn;

   expectedList.clear();

   CAuthHelper auth(TestConfig::getUserLogin());
   if (!auth.AuthUser(TestConfig::getUserPassword()))
   {
      WRITE_TRACE(DBG_FATAL, "can't auth user[%s] on localhost ", TestConfig::getUserLogin());
      return false;
   }

	// __asm int 3;
   SmartPtr<CVmDirectory> pVmDir = GetUserVmDirectory();
   if( !pVmDir )
   {
      WRITE_TRACE(DBG_FATAL, "can't get vm directory from ");
      return false;
   }

   for (int idx=0; idx< pVmDir->m_lstVmDirectoryItems.size(); idx++)
   {
      CVmDirectoryItem* pDirItem= pVmDir->m_lstVmDirectoryItems[idx];
      QString strVmHome=pDirItem->getVmHome();
      QString strChangedBy=pDirItem->getChangedBy();
      QString strChangeDateTime=pDirItem->getChangeDateTime().toString(XML_DATETIME_FORMAT);

      //FIXME: add checking access permission to vm.xml
      // fixed: when i started as test-user it doing automatically

      if (!CFileHelper::FileCanRead(strVmHome, &auth))
         continue;

      QFile vmConfig(strVmHome);
      if(!vmConfig.open(QIODevice::ReadOnly))
      {
         WRITE_TRACE(DBG_FATAL, "can't open file [%s]", strVmHome.toUtf8().data());
         break;
      }

      expectedList.push_back(QDomDocument());
      QDomDocument& doc=expectedList[expectedList.size()-1];
      if(!doc.setContent(&vmConfig, false, &errorMsg, &errorLine, &errorColumn ))
      {
         WRITE_TRACE(DBG_FATAL, "error of parsing file: [fname=%s], errorMsg=%s, line=%d, column=%d"
            , strVmHome.toUtf8().data()
            , errorMsg.toUtf8().data(), errorLine, errorColumn);
         expectedList.clear();
         return false;
      }

      addNodeToIdentityPart(doc, XML_VM_DIR_ND_VM_HOME, strVmHome);
      addNodeToIdentityPart(doc, XML_VM_DIR_ND_CHANGED_BY, strChangedBy);
      addNodeToIdentityPart(doc, XML_VM_DIR_ND_CHANGED_DATETIME, strChangeDateTime);
   }//for
   return (true);
}
bool CommandHandler::checkAuth( const Message& command )
{
    if( auth( command ) )
    {
        return true;
    }
    return false;
}
Esempio n. 7
0
/*!
 * Запись данных сети.
 */
void NetworkItem::write()
{
  ChatSettings *settings = ChatCore::settings();

  settings->setValue(m_id + LS("/Auth"), auth(), false, true);
  settings->setValue(m_id + LS("/Name"), m_name, false, true);
  settings->setValue(m_id + LS("/Url"),  m_url, false, true);
}
AuthentificationSystem::AuthentificationSystemPtr AuthentificationSystem::CreateAuthentification()
{
    AuthentificationSystem::AuthentificationSystemPtr auth(new AuthentificationSystem(QString::null, QString::null));
    auth->m_State = NoStartYet;
    auth->m_Error = NoError;

    return auth;
}
Esempio n. 9
0
int
main(int argc, char *argv[])
{
	int sockfd, fdmax, i, ret;
	struct sockaddr_in server_addr;
	fd_set master, read_fds;
	struct User user;
	strncpy(user.room, "Default", 8);

	if (argc < 2) {
		getlogin_r(user.name, sizeof(user.name));
		if (strcmp(user.name,"") == 0 )
			printf
			    ("\nNO user informed: Using system's username: %s\n",
			    user.name);
	} else if (argc == 3 || argc > 3) {
		strncpy(user.room, argv[2], sizeof(argv[2])+1);
		strncpy(user.name, argv[1], sizeof(argv[1])+1);
	} else
		strncpy(user.name, argv[1], sizeof(argv[1])+1);

	

	ret = connect_request(&sockfd, &server_addr);
	if (ret)
		exit (1);


	FD_ZERO(&master);
	FD_ZERO(&read_fds);
	FD_SET(0, &master);
	FD_SET(sockfd, &master);
	fdmax = sockfd + 1;

	ret = auth(user, sockfd);
	if (ret) {
		printf("\nERROR: authentication error\n");
		return (401);
	}

	printf("\n\nWellcome to Room #(%s) \n\n", user.room);
	fflush(stdout);

	while (1) {
		read_fds = master;
		if (select(fdmax, &read_fds, NULL, NULL, NULL) == -1) {
			perror("select");
			exit (4);
		}

		for (i = 0; i <= fdmax; i++)
			if (FD_ISSET(i, &read_fds))
				send_recv(i, sockfd, user);
	}

	close (sockfd);
	return 0;
}
Esempio n. 10
0
Client::Client(ContactModel *contactModel, QObject *parent) :
QObject(parent),m_trackInterval(5),
m_authentificated(0), m_trackingPermitted(Settings::getInstance().getPermission()),
m_isHavingOwnChannel(true), m_contactModel(contactModel)
{
  m_timer = new QTimer(this);
  connect(m_timer, SIGNAL(timeout()), SLOT(track()));

  m_additionalTimer = new QTimer(this);
  connect(m_additionalTimer, SIGNAL(timeout()),SLOT(getTagsRequest()));

  m_loginQuery = new LoginQuery(this);
  connect(m_loginQuery, SIGNAL(connected()), SLOT(onAuthentificated()));
  connect(m_loginQuery, SIGNAL(errorOccured(QString)), SLOT(onError(QString)));
  connect(m_loginQuery, SIGNAL(errorOccured(int)),SLOT(onError(int)));

  m_RegisterUserQuery = new RegisterUserQuery(this);
  connect(m_RegisterUserQuery, SIGNAL(connected()), SLOT(onRegistered()));
  connect(m_RegisterUserQuery, SIGNAL(errorOccured(int)),SLOT(onError(int)));

  m_netManager = new QNetworkConfigurationManager(this);

  m_history = new MarksHistory(this);
  connect(m_history,SIGNAL(isFull()),SLOT(onHistoryFull()));
  m_history->setHistoryLimit(Settings::getInstance().getTimeInterval()/m_trackInterval);

  m_addNewMarkQuery = new WriteTagQuery(this);
  connect(m_addNewMarkQuery,SIGNAL(tagAdded()),SLOT(onMarkAdded()));
  //  connect(m_addNewMarkQuery, SIGNAL(errorOccured(QString)), SIGNAL(error(QString)));

  m_applyChannelQuery = new ApplyChannelQuery(this);
  connect(m_applyChannelQuery, SIGNAL(channelAdded(QSharedPointer<Channel>)),SLOT(subscribeToOwnChannel()));
  connect(m_applyChannelQuery, SIGNAL(errorOccured(int)), SLOT(onError(int)));

  m_subscribeChannelQuery = new SubscribeChannelQuery(this);
  connect(m_subscribeChannelQuery,SIGNAL(channelSubscribed(QSharedPointer<Channel>)),SLOT(onChannelSubscribed(QSharedPointer<Channel>)));
  connect(m_subscribeChannelQuery, SIGNAL(errorOccured(int)), SLOT(onError(int)));

  m_subscibedChannelsQuery = new SubscribedChannelsQuery(this);
  //connect(m_subscibedChannelsQuery,SIGNAL(responseReceived()),SLOT(constructContactModel()));
  connect(m_subscibedChannelsQuery,SIGNAL(errorOccured(int)), SLOT(onError(int)));

  m_loadTagsQuery = new LoadTagsQuery(this);
  connect(m_loadTagsQuery, SIGNAL(tagsReceived()), SLOT(onGetTags()));
  connect(m_loadTagsQuery,SIGNAL(errorOccured(int)), SLOT(onError(int)));

  m_unsubscribeChannelQuery = new UnsubscribeChannelQuery(this);
  connect(m_unsubscribeChannelQuery, SIGNAL(channelUnsubscribed()),SLOT(onChannelUnsubscribed()));
  connect(m_unsubscribeChannelQuery,SIGNAL(errorOccured(int)), SLOT(onError(int)));

  qDebug()<<Settings::getInstance().getLogin();
  qDebug()<<Settings::getInstance().getPassword();

  if (Settings::getInstance().isHavingAuthData())
    auth(Settings::getInstance().getLogin(),Settings::getInstance().getPassword());

}
Esempio n. 11
0
bool database::accessid_auth(int AccessID, char *AccessIDpwd, int *UserID,
                             bool *is_enabled) {
  if (AccessID == 0) return false;

  return auth(
      "SELECT id, user_id, enabled FROM `supla_accessid` WHERE id = ? AND "
      "password = unhex(?)",
      AccessID, AccessIDpwd, SUPLA_ACCESSID_PWDHEX_MAXSIZE, UserID, is_enabled);
}
Esempio n. 12
0
int
main (int ac, char *ag[])
{
  uchar buf[10000];
  int len;
  int i;
  EIBConnection *con;
  eibaddr_t dest;
  fd_set read;
  char *prog = ag[0];

  parseKey (&ac, &ag);
  if (ac != 3)
    die ("usage: %s [-k key] url eibaddr", prog);
  con = EIBSocketURL (ag[1]);
  if (!con)
    die ("Open failed");
  dest = readaddr (ag[2]);

  if (EIB_MC_Connect (con, dest) == -1)
    die ("Connect failed");
  auth (con);

  len = EIB_MC_PropertyScan_async (con, sizeof (buf), buf);
  if (len == -1)
    die ("Read failed");

lp:
  FD_ZERO (&read);
  FD_SET (EIB_Poll_FD (con), &read);
  printf ("Waiting\n");
  if (select (EIB_Poll_FD (con) + 1, &read, 0, 0, 0) == -1)
    die ("select failed");
  printf ("Data available\n");
  len = EIB_Poll_Complete (con);
  if (len == -1)
    die ("Read failed");
  if (len == 0)
    goto lp;
  printf ("Completed\n");

  len = EIBComplete (con);

  for (i = 0; i < len; i += 6)
    if (buf[i + 1] == 1 && buf[i + 2] == 4)
      printf ("Obj: %d Property: %d Type: %d Objtype:%d Access:%02X\n",
	      buf[i + 0], buf[i + 1], buf[i + 2],
	      (buf[i + 3] << 8) | buf[i + 4], buf[i + 5]);
    else
      printf ("Obj: %d Property: %d Type: %d Count:%d Access:%02X\n",
	      buf[i + 0], buf[i + 1], buf[i + 2],
	      (buf[i + 3] << 8) | buf[i + 4], buf[i + 5]);

  EIBClose (con);
  return 0;
}
Esempio n. 13
0
void SignInDialog::on_submit_clicked()
{
    QString login = ui->userNameLineEdit->text();
    QString pass = ui->userPasswordLineEdit->text();
    bool logged = dir->authentification(login, pass);
    if (!logged) QMessageBox::critical(this, "Login failed", "Failed to log as " + login);
    else QMessageBox::about(this, "Login succeed", "You are now logged as " + login);
    emit auth(logged, login);
    parent()->deleteLater();
}
Esempio n. 14
0
bool ipc_client::set_char_value(int user_id, int device_id, int channel_id,
                                char value) {
  if (!auth()) return false;

  snprintf(buffer, IPC_BUFFER_SIZE, "%s:%i,%i,%i,%i\n", cmd_set_char_value,
           user_id, device_id, channel_id, value);
  send(sfd, buffer, strnlen(buffer, IPC_BUFFER_SIZE - 1), 0);

  return check_set_result();
}
void HTTPServerResponseImpl::requireAuthentication(const std::string& realm)
{
	poco_assert (!_pStream);

	setStatusAndReason(HTTPResponse::HTTP_UNAUTHORIZED);
	std::string auth("Basic realm=\"");
	auth.append(realm);
	auth.append("\"");
	set("WWW-Authenticate", auth);
}
Esempio n. 16
0
static void
lfm_send_nowplaying (void) {
    if (auth () < 0) {
        trace ("auth failed! nowplaying cancelled.\n");
        lfm_nowplaying[0] = 0;
        return;
    }
    trace ("auth successful! setting nowplaying\n");
    char s[100];
    snprintf (s, sizeof (s), "s=%s&", lfm_sess);
    int l = strlen (lfm_nowplaying);
    strcpy (lfm_nowplaying+l, s);
    trace ("content:\n%s\n", lfm_nowplaying);
#if !LFM_NOSEND
    for (int attempts = 2; attempts > 0; attempts--) {
        int status = curl_req_send (lfm_nowplaying_url, lfm_nowplaying);
        if (!status) {
            if (strncmp (lfm_reply, "OK", 2)) {
                trace ("nowplaying failed, response:\n%s\n", lfm_reply);
                if (!strncmp (lfm_reply, "BADSESSION", 7)) {
                    trace ("got badsession; trying to restore session...\n");
                    lfm_sess[0] = 0;
                    curl_req_cleanup ();
                    if (auth () < 0) {
                        trace ("fail!\n");
                        break; // total fail
                    }
                    trace ("success! retrying send nowplaying...\n");
                    snprintf (s, sizeof (s), "s=%s&", lfm_sess);
                    strcpy (lfm_nowplaying+l, s);
                    continue; // retry with new session
                }
            }
            else {
                trace ("nowplaying success! response:\n%s\n", lfm_reply);
            }
        }
        curl_req_cleanup ();
        break;
    }
#endif
    lfm_nowplaying[0] = 0;
}
Esempio n. 17
0
bool database::location_auth(int LocationID, char *LocationPWD, int *UserID,
                             bool *is_enabled) {
  if (LocationID == 0) return false;

  return auth(
      "SELECT id, user_id, enabled FROM `supla_location` WHERE id = ? AND "
      "password = unhex(?)",
      LocationID, LocationPWD, SUPLA_LOCATION_PWDHEX_MAXSIZE, UserID,
      is_enabled);
}
Esempio n. 18
0
void KfmServIpc::parse_auth( char *_data, int _len )
{
	int pos = 0;

	// Parsing string
	const char* _password;
	_password = read_string( _data, pos, _len );
	// Calling function
	emit auth( _password );
	free( (void*)_password );
}
Esempio n. 19
0
BOOL CHwSMTP::SendEmail()
{
	BOOL bRet = TRUE;
	char szLocalHostName[64] = {0};
	gethostname ( (char*)szLocalHostName, sizeof(szLocalHostName) );

	// hello,握手
	CString str;
	str.Format(_T("HELO %s\r\n"), GetCompatibleString(szLocalHostName,FALSE));
	if ( !Send (  str ))
	{
		return FALSE;
	}
	if ( !GetResponse ( _T("250") ) )
	{
		return FALSE;
	}
	// 身份验证
	if ( m_bMustAuth && !auth() )
	{
		return FALSE;
	}
	// 发送邮件头
	if ( !SendHead() )
	{
		return FALSE;
	}
	// 发送邮件主题
	if ( !SendSubject() )
	{
		return FALSE;
	}
	// 发送邮件正文
	if ( !SendBody() )
	{
		return FALSE;
	}
	// 发送附件
	if ( !SendAttach() )
	{
		return FALSE;
	}
	// 结束邮件正文
	if ( !Send ( CString(_T(".\r\n") ) ) ) return FALSE;
	if ( !GetResponse ( _T("250") ) )
		return FALSE;

	// 退出发送
	if ( HANDLE_IS_VALID(m_SendSock.m_hSocket) )
		Send ( CString(_T("QUIT\r\n")) );
	m_bConnected = FALSE;

	return bRet;
}
Esempio n. 20
0
ArcSec::SecHandlerStatus LegacyMap::Handle(Arc::Message* msg) const {
  if(blocks_.size()<=0) {
    logger.msg(Arc::ERROR, "LegacyMap: no configurations blocks defined");
    return false;
  };
  Arc::SecAttr* sattr = msg->Auth()->get("ARCLEGACY");
  if(!sattr) {
    // Only if information collection is done per context.
    // Check if decision is already made.
    Arc::SecAttr* dattr = msg->AuthContext()->get("ARCLEGACYMAP");
    if(dattr) {
      LegacyMapAttr* mattr = dynamic_cast<LegacyMapAttr*>(dattr);
      if(mattr) {
        // Mapping already was done in this context
        std::string id = mattr->GetID();
        if(!id.empty()) {
          msg->Attributes()->set("SEC:LOCALID",id);
        };
        return true;
      };
    };
  };
  if(!sattr) sattr = msg->AuthContext()->get("ARCLEGACY");
  if(!sattr) {
    logger.msg(Arc::ERROR, "LegacyPDP: there is no ARCLEGACY Sec Attribute defined. Probably ARC Legacy Sec Handler is not configured or failed.");
    return false;
  };
  LegacySecAttr* lattr = dynamic_cast<LegacySecAttr*>(sattr);
  if(!lattr) {
    logger.msg(Arc::ERROR, "LegacyPDP: ARC Legacy Sec Attribute not recognized.");
    return false;
  };
  // Populate with collected info
  AuthUser auth(*msg);
  auth.add_groups(lattr->GetGroups());
  auth.add_vos(lattr->GetVOs());
  std::string id;
  for(std::list<cfgfile>::const_iterator block = blocks_.begin();
                              block!=blocks_.end();++block) {
    LegacyMapCP parser(*block,logger,auth);
    if(!parser) return false;
    if(!parser.Parse()) return false;
    id = parser.LocalID();
    if(!id.empty()) {
      logger.msg(Arc::INFO,"Grid identity is mapped to local identity '%s'",id);
      msg->Attributes()->set("SEC:LOCALID",id);
      break;
    };
  };
  // Store decision even if no id was selected
  msg->AuthContext()->set("ARCLEGACYMAP",new LegacyMapAttr(id));
  return true;
}
Esempio n. 21
0
//------------------------------------------------------------------------------
void ServerFiber::main()
{
  server_->config_->parse();
  stdErr.setDebugLevels(server_->config_->value("debug_levels","+0,+1,+2,+3"));
  union {
    uint8_t cmd;
    uint8_t ui8;
  };
  auth();
  while( !terminated_ ){
    *this >> cmd;
    switch( cmd ){
      case cmQuit :
        putCode(eOK);
        terminate();
        break;
      case cmGetProcessStartTime :
        *this << getProcessStartTime();
        break;
      case cmSelectServerType :
        *this >> ui8;
        putCode(ui8 < stCount ? eOK : eInvalidServerType);
        serverType_ = ServerType(ui8);
        break;
      case cmRegisterClient :
        registerClient();
        break;
      case cmRegisterDB :
        registerDB();
        break;
      case cmGetDB :
        getDB();
        break;
      case cmSendMail :
        sendMail();
        break;
      case cmRecvMail :
        recvMail();
        break;
      case cmRemoveMail :
        removeMail();
        break;
      case cmSelectProtocol :
        *this >> ui8;
        putCode(ui8 < 2 ? eOK : eInvalidProtocol);
        protocol_ = ui8;
        break;
      default : // unrecognized or unsupported command, terminate
        putCode(eInvalidCommand);
        terminate();
    }
  }
}
Esempio n. 22
0
void QgsAppAuthRequestHandler::handleAuthRequest( QNetworkReply *reply, QAuthenticator *auth )
{
  Q_ASSERT( qApp->thread() == QThread::currentThread() );

  QString username = auth->user();
  QString password = auth->password();

  if ( username.isEmpty() && password.isEmpty() && reply->request().hasRawHeader( "Authorization" ) )
  {
    QByteArray header( reply->request().rawHeader( "Authorization" ) );
    if ( header.startsWith( "Basic " ) )
    {
      QByteArray auth( QByteArray::fromBase64( header.mid( 6 ) ) );
      int pos = auth.indexOf( ':' );
      if ( pos >= 0 )
      {
        username = auth.left( pos );
        password = auth.mid( pos + 1 );
      }
    }
  }

  for ( ;; )
  {
    bool ok = QgsCredentials::instance()->get(
                QStringLiteral( "%1 at %2" ).arg( auth->realm(), reply->url().host() ),
                username, password,
                QObject::tr( "Authentication required" ) );
    if ( !ok )
      return;

    if ( auth->user() != username || ( password != auth->password() && !password.isNull() ) )
    {
      // save credentials
      QgsCredentials::instance()->put(
        QStringLiteral( "%1 at %2" ).arg( auth->realm(), reply->url().host() ),
        username, password
      );
      break;
    }
    else
    {
      // credentials didn't change - stored ones probably wrong? clear password and retry
      QgsCredentials::instance()->put(
        QStringLiteral( "%1 at %2" ).arg( auth->realm(), reply->url().host() ),
        username, QString() );
    }
  }

  auth->setUser( username );
  auth->setPassword( password );
}
Esempio n. 23
0
int proxy_connect(struct proxy *self, const char *dst_ip, unsigned short dst_port)
{
	int err;

	err = socket_connect(self->s, self->ip, self->port);
	if (err < 0)
		return err;

	struct socket5_select_request	request;
	struct socket5_select_response	response;

	assert(self->ip);
	assert(self->usr);
	assert(self->pwd);

	err = socket_connect(self->s, self->ip, self->port);
	if (err < 0)
		return err;

	request.ver = 0x05;
	request.method_nr = 2;
	request.method_tbl[0] = 0x00;	/* no auth */
	request.method_tbl[2] = 0x02;	/* user pwd */

	err = socket_send_data(
				self->s,
				(char *)&request,
				2 + request.method_nr * sizeof(request.method_tbl[0])
				);

	if (err < 0)
		return err;

	err = socket_recv_data(
				self->s,
				(char *)&response,
				sizeof(response)
				);

	if (err < 0)
		return err;

	if (response.method == 0x02)
		err = auth(self->s, self->usr, self->pwd);

	if (err < 0)
		return err;

	err = conn(self->s, dst_ip, dst_port);
	
	return err;
}
Esempio n. 24
0
void ExternalAuthTask::done(const QVariantMap &data)
{
  AuthResult result = auth(data);
  if (result.action == AuthResult::Reject) {
    Core::i()->reject(m_data, result, m_socket);
  }
  else if (result.action == AuthResult::Accept) {
    Core::i()->accept(m_data, result, m_host);
  }

  m_timer->stop();
  deleteLater();
}
Esempio n. 25
0
void
HTTPRequestHeader::SetAuthentication(int type, std::string userName, std::string password)
{
	if (type != HTTP_AUTH_TYPE_BASIC)
		return;

	std::string auth("Basic ");
	std::string authString;
	authString.append(userName).append(":").append(password);
	authString = Base64Encode(authString);
	auth.append(authString);
	SetValue("Authorization", auth);
}
Esempio n. 26
0
        int runNormal() {
            bool showHeaders = ! hasParam( "noheaders" );
            int rowCount = getParam( "rowcount" , 0 );
            int rowNum = 0;

            auth();

            BSONObj prev = stats();
            if ( prev.isEmpty() )
                return -1;

            int maxLockedDbWidth = 0;

            while ( rowCount == 0 || rowNum < rowCount ) {
                sleepsecs((int)ceil(_statUtil.getSeconds()));
                BSONObj now;
                try {
                    now = stats();
                }
                catch ( std::exception& e ) {
                    cout << "can't get data: " << e.what() << endl;
                    continue;
                }

                if ( now.isEmpty() )
                    return -2;

                try {

                    BSONObj out = _statUtil.doRow( prev , now );

                    // adjust width up as longer 'locked db' values appear
                    setMaxLockedDbWidth( &out, &maxLockedDbWidth ); 
                    if ( showHeaders && rowNum % 10 == 0 ) {
                        printHeaders( out );
                    }

                    printData( out , out );

                }
                catch ( AssertionException& e ) {
                    cout << "\nerror: " << e.what() << "\n"
                         << now
                         << endl;
                }

                prev = now;
                rowNum++;
            }
            return 0;
        }
Esempio n. 27
0
void Connection::send_initial_auth_response(const std::string& class_name) {
  SharedRefPtr<Authenticator> auth(config_.auth_provider()->new_authenticator(host_, class_name));
  if (!auth) {
    notify_error("Authentication required but no auth provider set", CONNECTION_ERROR_AUTH);
  } else {
    std::string response;
    if (!auth->initial_response(&response)) {
      notify_error("Failed creating initial response token: " + auth->error(), CONNECTION_ERROR_AUTH);
      return;
    }
    AuthResponseRequest* auth_response = new AuthResponseRequest(response, auth);
    internal_write(new StartupHandler(this, auth_response));
  }
}
Esempio n. 28
0
void NewPattern::save()
{
	Auth auth(this);
	auth.preprocess(input->path);

	QSettings settings;
	QByteArray salt = Crypto::generateSalt();
	settings.setValue("pattern_hash", Crypto::getHash(auth.strokesToString(), salt));
	settings.setValue("touchpad_mode", auth.touchpad_mode);
	settings.setValue("salt", salt);
	settings.setValue("usage_total", 0);
	settings.setValue("usage_failed", 0);
	settings.sync();
}
Esempio n. 29
0
void leadHQConnect() {

  if (Scout.wifi.client.connected()) {
    char token[33];
    StringBuffer auth(64);
    token[32] = 0;
    Scout.getHQToken(token);
    auth.appendSprintf("{\"type\":\"token\",\"token\":\"%s\"}\n", token);
    leadSignal(auth);
  } else {
    if (hqVerboseOutput) {
      Serial.println(F("server unvailable"));
    }
  }
}
static bool_t getPage(EFSRepoRef const repo, HTTPConnectionRef const conn, HTTPMethod const method, strarg_t const URI) {
	if(HTTP_GET != method) return false;
	size_t pathlen = prefix("/", URI);
	if(!pathlen) return false;
	if(!pathterm(URI, (size_t)pathlen)) return false;
	EFSSessionRef const session = auth(repo, conn, method, URI+pathlen);
	if(!session) {
		HTTPConnectionSendStatus(conn, 403);
		return true;
	}

	// TODO: Parse querystring `q` parameter
	EFSFilterRef const filter = EFSFilterCreate(EFSTypeFilter);
	EFSFilterAddStringArg(filter, "text/html; charset=utf-8");

	EFSFileInfo *const files = EFSSessionCreateFileInfoList(session, filter, RESULTS_MAX);

	HTTPConnectionWriteResponse(conn, 200, "OK");
	HTTPConnectionWriteHeader(conn, "Content-Type", "text/html; charset=utf-8");
	HTTPConnectionWriteHeader(conn, "Transfer-Encoding", "chunked");
	HTTPConnectionBeginBody(conn);

	// TODO: Page header

	uv_fs_t req = { .data = co_active(); }
	for(index_t i = 0; i < files->count; ++i) {
		uv_fs_open(loop, &req, path, O_RDONLY, 0400, async_fs_cb);
		co_switch(yield);
		uv_fs_req_cleanup(&req);
		uv_file const file = req.result;
		if(file < 0) continue;
		HTTPConnectionWriteChunkLength(conn, files->items[i].size);
		HTTPConnectionWriteFile(conn, file);
		uv_fs_close(loop, &req, file, async_fs_cb);
		co_switch(yield);
		uv_fs_req_cleanup(&req);
		HTTPConnectionWrite(conn, "\r\n", 2);
	}

	// TODO: Page trailer

	HTTPConnectionWriteChunkLength(conn, 0);
	HTTPConnectionWrite(conn, "\r\n", 2);
	HTTPConnectionEnd(conn);

	EFSFileInfoListFree(files);
	return true;
}