public static void SendMessageOnGroup(APIServer server, GroupRepository groupRepository) { Console.WriteLine("Enter the group on which you want to send messages:"); var groupName = Console.ReadLine(); string pubKeyFile = groupName + "PublicKey.txt"; string privKeyFile = groupName + "PrivateKey.txt"; Group group = server.GetGroupByName(groupName); if (pubKeyFile != null && privKeyFile != null) { var groupCreator = GetGroupCreator(server, pubKeyFile, privKeyFile); ParticipantMessage message = new ParticipantMessage(); Console.WriteLine("Enter the message you want to send:"); message.Message = Console.ReadLine(); Console.WriteLine("Enter your nickname:"); var nickname = Console.ReadLine(); ClientParticipant clientParticipant = new ClientParticipant(server, groupRepository); var blindparticipant = groupCreator.GetBlindParticipantByNickname(group.Id, nickname); VerifiedParticipant verifiedParticipant = new VerifiedParticipant { PublicKey = blindparticipant.PublicKey, Signature = blindparticipant.Signature }; message.BlindParticipant = blindparticipant.Id.ToString(); clientParticipant.AddMessage(group.Id, message, verifiedParticipant); Console.WriteLine("Participant verified"); Console.WriteLine("Message sent"); } else { Console.WriteLine("Group creator Keys were not saved to file, please go to step 1"); } }
static public void InviteParticipants(BlindChatDbContext context, APIServer server) { Console.WriteLine("Enter the group for which you want to invite participants:"); string groupName = Console.ReadLine(); string pubKeyFile = groupName + "PublicKey.txt"; string privKeyFile = groupName + "PrivateKey.txt"; if (pubKeyFile != null && privKeyFile != null) { var groupCreator = GetGroupCreator(server, pubKeyFile, privKeyFile); List <string> emails = new List <string>(); Console.WriteLine("Enter participant email address:"); var participantEmail = Console.ReadLine(); //var participantEmail = "*****@*****.**"; emails.Add(participantEmail); Console.WriteLine(); var getGroup = context.Groups.FirstOrDefault(g => g.Name == groupName); var getConfirmationCode = context.ConfirmationCodes.FirstOrDefault(c => c.GroupId == getGroup.Id); int confirmatioCode = getConfirmationCode.Code; groupCreator.AddParticipantsToGroup(emails, confirmatioCode); Console.WriteLine("Participant was added to the group"); } else { Console.WriteLine("Group creator Keys were not saved to file, please go to step 1"); } }
static public void SaveBlindParticipant(APIServer server, GroupRepository groupRepository) { Console.WriteLine("Enter the group for which you want to register participants:"); var groupName = Console.ReadLine(); Console.WriteLine("Enter participant email address that you want to be saved as blind participant:"); var participantEmail = Console.ReadLine(); var group = server.GetGroupByName(groupName); var factor = File.ReadAllText("BlindFactor.txt"); BigInteger blindFactor = new BigInteger(factor); var fileToRead = (participantEmail.Substring(0, participantEmail.IndexOf("@")) + "PublicKey.txt").ToString(); RsaKeyParameters participantPublicKey = (RsaKeyParameters)RsaKeyUtils.GetDeserializedKPublicKey(File.ReadAllText(fileToRead)); GroupRegistration groupRegistration = new GroupRegistration(group, new ContentBlinder(group.RsaPublicKey, blindFactor), participantPublicKey); ClientParticipant clientParticipant = new ClientParticipant(server, groupRepository); VerifiedParticipant verifiedParticipant = clientParticipant.CheckVerifiedEntity(group, participantEmail, groupRegistration); clientParticipant.AddClientCertificate(verifiedParticipant, group, participantEmail); Console.WriteLine("Enter nickname:"); var nickname = Console.ReadLine(); clientParticipant.AddBlindParticipant(group.Id, verifiedParticipant, nickname); Console.WriteLine(); Console.WriteLine("Participant was saved as a blind participant to the group"); }
public CommandHandlerHelper(APIClient client, Request request) { this.Server = client.Server; this.Client = client; this.Request = request; this.Command = request.Model.Command; }
static void Main(string[] args) { Console.WriteLine("API server initializing..."); config = new XmlDocument(); config.Load("config.xml"); var cancel = new CancellationTokenSource(); var appender = new log4net.Appender.ManagedColoredConsoleAppender(); appender.Threshold = log4net.Core.Level.All; var x = (XmlElement)config.SelectSingleNode("//backend/log4net"); if (x == null) { Console.WriteLine("Error: log4net configuration node not found. Check your config.xml"); Console.ReadKey(); return; } XmlConfigurator.Configure(x); api = new APIServer(); auth = new FDOAuthServerCheck(); iw4m = new Iw4mCheck(auth); iw5m = new Iw5mCheck(auth); forum = new WebCheck("http://fourdeltaone.net/index.php", 60); kmshost = new KmshostCheck(); auth.TestUsername = config.SelectSingleNode("//backend/auth-username").InnerText; auth.TestPassword = config.SelectSingleNode("//backend/auth-password").InnerText; BackendName = config.SelectSingleNode("//backend/backend-name").InnerText; api.Content.Add("login", auth); api.Content.Add("iw4m", iw4m); api.Content.Add("iw5m", iw5m); api.Content.Add("forum", forum); api.Content.Add("kmshost", kmshost); api.Content.Add("backend-name", BackendName); api.ServerLists.Add("iw4m", iw4m.AccessibleMasterServers[0].ServersListed); api.ServerLists.Add("iw5m", iw5m.ListedServers); api.StatusIndicators.Add("iw4m", new Iw4mStatusIndicator(ref iw4m)); api.StatusIndicators.Add("iw5m", new Iw5mStatusIndicator(ref iw5m)); api.StatusIndicators.Add("login", new LoginStatusIndicator(ref auth)); api.StatusIndicators.Add("forum", new WebStatusIndicator(ref forum)); api.StatusIndicators.Add("kmshost", new KmshostStatusIndicator(ref kmshost)); api.Start(); Console.WriteLine("API server starting, regular checks are now enabled."); while (true) { var task = Task.Factory.StartNew(() => CheckNow(), cancel.Token); Thread.Sleep(30 * 1000); task.Wait(); task.Dispose(); } }
public static void Exit(bool restarting, string msg) { Player[] players = PlayerInfo.Online.Items; foreach (Player p in players) { p.save(); } foreach (Player p in players) { p.Leave(msg); } if (APIServer != null) { APIServer.Stop(); } if (InfoServer != null) { InfoServer.Stop(); } Player.connections.ForEach(p => p.Leave(msg)); Plugin.Unload(); if (listen != null) { listen.Close(); } try { IRC.Disconnect(restarting ? "Server is restarting." : "Server is shutting down."); } catch { } }
static public void CreateGroup(APIServer server, CertificateGenerator generator) { // Generate group Certificate var groupKeys = generator.GenerateCertificate("C=DE,O=Organiztion", TimeSpan.FromDays(1), "cert.pfx", "Test.123"); Console.WriteLine("Group certificate was generated"); BlindSigner blindSigner = new BlindSigner(groupKeys); GroupCreator groupCreator = new GroupCreator(server, blindSigner); Console.WriteLine("Create group"); Console.WriteLine("Enter group name:"); string groupName = Console.ReadLine(); //string groupName = "Loazarii"; Group group = new Group(); group.Name = groupName; Console.WriteLine("Enter owner email:"); string ownerEmail = Console.ReadLine(); //string ownerEmail = "*****@*****.**"; group.OwnerEmail = ownerEmail; group.RsaPublicKey = (RsaKeyParameters)groupKeys.Public; groupCreator.RegisterGroup(group); Console.WriteLine(""); //Write keys to file File.WriteAllText(group.Name + "PublicKey.txt", RsaKeyUtils.GetSerializedPublicKey((RsaKeyParameters)groupKeys.Public)); File.WriteAllText(group.Name + "PrivateKey.txt", RsaKeyUtils.GetSerializedPrivateKey((RsaKeyParameters)groupKeys.Private)); Console.WriteLine("You're group " + group.Name + " was registered!"); }
static public GroupCreator GetGroupCreator(APIServer server, string pubKeyFile, string privKeyFile) { var keys = ImportCertificate(pubKeyFile, privKeyFile); BlindSigner blindSigner = new BlindSigner(keys); GroupCreator groupCreator = new GroupCreator(server, blindSigner); return(groupCreator); }
static public void stop() { Program.noStart = true; forceShutdown = true; ConsoleHelpers.forceShutdown = true; // Stop the keepalive thread PresenceList.stopKeepAlive(); // Stop the block processor blockProcessor.stopOperation(); // Stop the block sync blockSync.stop(); // Stop the API server if (apiServer != null) { apiServer.stop(); apiServer = null; } // Stop the miner if (miner != null) { miner.stop(); miner = null; } if (maintenanceThread != null) { maintenanceThread.Abort(); maintenanceThread = null; } // Stop the block storage Storage.stopStorage(); // stop activity storage ActivityStorage.stopStorage(); // Stop the network queue NetworkQueue.stop(); // Stop all network clients NetworkClientManager.stop(); // Stop the network server NetworkServer.stopNetworkOperations(); // Stop the console stats screen // Console screen has a thread running even if we are in verbose mode statsConsoleScreen.stop(); NetDump.Instance.shutdown(); presenceListActive = false; }
public APIClient(APIServer server, Socket socket, int id) { this.Server = server; this.Socket = socket; this.Id = id; this.io = new ClientIO(this, socket); this.connected = true; this.JSEngine = new JSEngine(this); this.eventList = new List <ClientEventInfo>(); Log.Info($"New client: {Name}"); }
public void HandleCategoryChildren(HttpListenerRequest request, string[] requestParts, HttpListenerResponse response) { if (string.Compare(request.HttpMethod, "GET", true) == 0) { HandleGetCategoryChildren(request, requestParts, response); } else { APIServer.SetResponse(response, HttpStatusCode.MethodNotAllowed, request.RawUrl); } }
static public void SignCertificate(APIServer server) { Console.WriteLine("Enter the group for which you want to register participants:"); string groupName = Console.ReadLine(); string pubKeyFile = groupName + "PublicKey.txt"; string privKeyFile = groupName + "PrivateKey.txt"; var groupCreator = GetGroupCreator(server, pubKeyFile, privKeyFile); var group = server.GetGroupByName(groupName); groupCreator.SignMessages(group); Console.WriteLine("Blind message was signed"); }
public static void CleanUp() { if (driver != null) { driver.Close(); driver.Quit(); if (server != null) { server.Disconnect(); server = null; } driver = null; } }
static void Main(string[] args) { SignatureVerifier signatureVerifier = new SignatureVerifier(); RNGRandomGenerator rngGenerator = new RNGRandomGenerator(); EmailSender emailSender = new EmailSender(); BlindChatDbContext context = new BlindChatDbContext(); GroupRepository groupRepository = new GroupRepository(context); APIServer server = new APIServer(groupRepository, emailSender, rngGenerator, signatureVerifier); CertificateGenerator generator = new CertificateGenerator(); int userInput = 0; do { userInput = DisplayMenu(); switch (userInput.ToString()) { case "1": CreateGroup(server, generator); break; case "2": InviteParticipants(context, server); break; case "3": RegisterParticipant(server, groupRepository, generator); break; case "4": SignCertificate(server); break; case "5": SaveBlindParticipant(server, groupRepository); break; case "6": SendMessageOnGroup(server, groupRepository); break; default: Console.WriteLine("Default case"); break; } } while (userInput != 7); }
public void Setup() { if (driver == null) { var appiumOptions = new AppiumOptions(); appiumOptions.AddAdditionalCapability("app", AppPath); appiumOptions.AddAdditionalCapability("deviceName", "WindowsPC"); driver = new WindowsDriver <WindowsElement>(new Uri(WindowsAppDriverUrl), appiumOptions); if (server == null) { server = new APIServer(); } } }
public void start(bool verboseConsoleOutput) { // Generate presence list PresenceList.init(IxianHandler.publicIP, Config.serverPort, 'R'); // Start the network queue NetworkQueue.start(); ActivityStorage.prepareStorage(); if (Config.apiBinds.Count == 0) { Config.apiBinds.Add("http://localhost:" + Config.apiPort + "/"); } // Start the HTTP JSON API server apiServer = new APIServer(Config.apiBinds, Config.apiUsers, Config.apiAllowedIps); // Prepare stats screen ConsoleHelpers.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (ConsoleHelpers.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Check for test client mode if (Config.isTestClient) { TestClientNode.start(); return; } // Start the node stream server NetworkServer.beginNetworkOperations(); // Start the network client manager NetworkClientManager.start(); // Start the keepalive thread PresenceList.startKeepAlive(); // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Start(); }
//---------------------------------------------------------------------- // public async Task searchByCoordenates(WCoord point) { View?.OnWaiting(); Console.WriteLine(point.lat + "lon: " + point.lon); Result <ForecastData> result = await _interactor.GetWeatherData(APIServer.RequestUriByLocation(point.lat, point.lon)); View?.OnStopWaiting(); if (result.Error == Error.None) { View?.setData(result.Data); } else if (result.Error == Error.Generic) { // View?.OnInvalidInput(Strings.Nofound); } }
private static void Main() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Converters = new List <JsonConverter> { new IPEndPointConverter() } }; AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; TaskScheduler.UnobservedTaskException += OnUnobservedTaskException; AuthDatabase.Initialize(); Logger.Info("Starting server..."); AuthServer.Instance.Start(Config.Instance.Listener); s_apiHost = new APIServer(); s_apiHost.Start(Config.Instance.API.Listener); Logger.Info("Ready for connections!"); if (Config.Instance.NoobMode) { Logger.Warn("!!! NOOB MODE IS ENABLED! EVERY LOGIN SUCCEEDS AND OVERRIDES ACCOUNT LOGIN DETAILS !!!"); } Console.CancelKeyPress += OnCancelKeyPress; while (true) { var input = Console.ReadLine(); if (input == null) { break; } if (input.Equals("exit", StringComparison.InvariantCultureIgnoreCase) || input.Equals("quit", StringComparison.InvariantCultureIgnoreCase) || input.Equals("stop", StringComparison.InvariantCultureIgnoreCase)) { break; } } Exit(); }
static public void stop() { Program.noStart = true; IxianHandler.forceShutdown = true; // Stop TIV tiv.stop(); // Stop the keepalive thread PresenceList.stopKeepAlive(); // Stop the API server if (apiServer != null) { apiServer.stop(); apiServer = null; } if (maintenanceThread != null) { maintenanceThread.Abort(); maintenanceThread = null; } ActivityStorage.stopStorage(); // Stop the network queue NetworkQueue.stop(); // Check for test client mode if (Config.isTestClient) { TestClientNode.stop(); return; } // Stop all network clients NetworkClientManager.stop(); // Stop the network server NetworkServer.stopNetworkOperations(); // Stop the console stats screen // Console screen has a thread running even if we are in verbose mode statsConsoleScreen.stop(); }
static public void start(bool verboseConsoleOutput) { // Network configuration NetworkUtils.configureNetwork(); PresenceList.generatePresenceList(Config.publicServerIP, 'R'); // Start the network queue NetworkQueue.start(); ActivityStorage.prepareStorage(); // Start the HTTP JSON API server apiServer = new APIServer(); // Prepare stats screen Config.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (Config.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Check for test client mode if (Config.isTestClient) { TestClientNode.start(); return; } // Start the node stream server NetworkServer.beginNetworkOperations(); // Start the network client manager NetworkClientManager.start(); // Start the keepalive thread PresenceList.startKeepAlive(); // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Start(); }
static public void RegisterParticipant(APIServer server, GroupRepository groupRepository, CertificateGenerator generator) { Console.WriteLine("Enter the group for which you want to register participants:"); string groupName = Console.ReadLine(); string pubKeyFile = groupName + "PublicKey.txt"; string privKeyFile = groupName + "PrivateKey.txt"; if (pubKeyFile != null && privKeyFile != null) { var groupCreator = GetGroupCreator(server, pubKeyFile, privKeyFile); Console.WriteLine(); Console.WriteLine("Enter participant email to be confirmed:"); var participantEmail = Console.ReadLine(); var participant = groupCreator.GetParticipantToConfirm(groupName, participantEmail); int invitationCode = participant.InvitationCode; Guid groupId = (Guid)participant.GroupId; string email = participant.Email; Group user_group = groupCreator.GetGroup(participant.InvitationCode); ClientParticipant clientParticipant = new ClientParticipant(server, groupRepository); var groupPublicKey = clientParticipant.GetGroupDetails(invitationCode); //Generate certificate var participantKeys = generator.GenerateCertificate("C=RO,O=Qubiz", TimeSpan.FromDays(1), "certParticipant.pfx", "Test.123"); Console.WriteLine("Client certificate was generated"); //Write keys to file File.WriteAllText(participantEmail.Substring(0, participantEmail.IndexOf("@")) + "PublicKey.txt", RsaKeyUtils.GetSerializedPublicKey((RsaKeyParameters)participantKeys.Public)); File.WriteAllText(participantEmail.Substring(0, participantEmail.IndexOf("@")) + "PrivateKey.txt", RsaKeyUtils.GetSerializedPrivateKey((RsaKeyParameters)participantKeys.Private)); Console.WriteLine("Participant keys were saved to file"); //Create GroupRegistration var groupRegistration = clientParticipant.GetGroupRegistration(invitationCode, (RsaKeyParameters)participantKeys.Public); Console.WriteLine("Blind factor was saved"); //Save blindedCertificate clientParticipant.RegisterBlindCertificate(invitationCode, groupRegistration); Console.WriteLine("Blind certificate was saved"); } else { Console.WriteLine("Group creator Keys were not saved to file, please go to step 1"); } }
private async void SyncClicked(object sender, EventArgs e) { //Ensure user wants to continue in offline mode if (Connectivity.NetworkAccess != NetworkAccess.Internet) { await DisplayAlert("Error", "You have lost internet connection. To sync data with server, please connect to wifi or cellular data", "Close"); return; } //Obtain new JWT token prior to sync Worker tempWorker = new Worker(); //Create temp WorkerID for Web API tempWorker.ReferenceNFC = Globals.NFCsignin; //Request JWT from Web API string IsValid = await APIServer.SEClient(tempWorker); //Check for API Error if (IsValid == "Card Not Active" | IsValid == "Unable to Sign In" | IsValid == "Invalid Card Used" | IsValid == "Server Error" | IsValid == "Server Connection Error") { DisplayAlert(IsValid, "Unable to sync data, please retry sign-in and repeat", "Return to login screen"); return; } //Sync will only use analytics logs and then refresh entrylogs with Db. Server side code to manage sync comparison var analyticsall = await App.Database.GetAnalytics(); var analyticslist = analyticsall.Where(c => c.EntryID == -1).ToList(); //API Sync request int isSuccess = await App.Database.SyncLogs(analyticslist); if (isSuccess == 1) { //Check if internet connection is now in place SyncButton.IsVisible = false; SyncText.IsVisible = false; Globals.OfflineMode = false; } }
//---------------------------------------------------------------------- // public async Task searchCity(string city) { if (!HasValidInput(city)) { View?.showMessage("Alert", "The city is mandatory"); return; } View?.OnWaiting(); Result <ForecastData> result = await _interactor.GetWeatherData(APIServer.RequestUriByCity(city)); View?.OnStopWaiting(); if (result.Error == Error.None) { View?.setData(result.Data); } else if (result.Error == Error.Generic) { // View?.OnInvalidInput(Strings.Nofound); } }
//---------------------------------------------------------------------- // async void OnGetWeatherButtonClicked(object sender, EventArgs e) { Console.WriteLine("Aloha"); if (!string.IsNullOrWhiteSpace(_cityEntry.Text)) { ForecastData weatherData = await _restService.GetWeatherData(APIServer.RequestUriByCity(_cityEntry.Text)); if (weatherData == null) { await DisplayAlert("Alert", "Not found", "OK"); return; } Console.WriteLine("Data: " + weatherData.city.name + weatherData.list[1].weather[0].description); Console.WriteLine(DateTime.Now.DayOfWeek); BindingContext = weatherData; WeatherData(weatherData.list); } else { await DisplayAlert("Alert", "Please enter a valid city name", "OK"); } }
// Start the node public void start(bool verboseConsoleOutput) { char node_type = 'M'; // TODO TODO TODO TODO change this to 'W' or 'C' after the upgrade if (Config.disableMiner) { node_type = 'M'; } // Check if we're in worker-only mode if (Config.workerOnly) { // Enable miner Config.disableMiner = false; node_type = 'W'; CoreConfig.simultaneousConnectedNeighbors = 4; } // Generate presence list PresenceList.init(IxianHandler.publicIP, Config.serverPort, node_type); // Initialize storage Storage.prepareStorage(); ActivityStorage.prepareStorage(); // Initialize the block chain blockChain = new BlockChain(); //runDiffTests(); //return; // Create the block processor and sync blockProcessor = new BlockProcessor(); blockSync = new BlockSync(); if (Config.devInsertFromJson) { Console.WriteLine("Inserting from JSON"); devInsertFromJson(); Program.noStart = true; return; } if (Config.apiBinds.Count == 0) { Config.apiBinds.Add("http://localhost:" + Config.apiPort + "/"); } // Start the HTTP JSON API server apiServer = new APIServer(Config.apiBinds, Config.apiUsers, Config.apiAllowedIps); if (IXICore.Platform.onMono() == false && !Config.disableWebStart) { System.Diagnostics.Process.Start(Config.apiBinds[0]); } miner = new Miner(); // Start the network queue NetworkQueue.start(); // prepare stats screen ConsoleHelpers.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (ConsoleHelpers.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Distribute genesis funds IxiNumber genesisFunds = new IxiNumber(Config.genesisFunds); // Check if this is a genesis node if (genesisFunds > (long)0) { Logging.info(String.Format("Genesis {0} specified. Starting operation.", genesisFunds)); distributeGenesisFunds(genesisFunds); genesisNode = true; blockProcessor.resumeOperation(); serverStarted = true; if (!isMasterNode()) { Logging.info("Network server is not enabled in modes other than master node."); } else { NetworkServer.beginNetworkOperations(); } } else { if (File.Exists(Config.genesisFile)) { Block genesis = new Block(Crypto.stringToHash(File.ReadAllText(Config.genesisFile))); blockChain.setGenesisBlock(genesis); } ulong lastLocalBlockNum = Meta.Storage.getLastBlockNum(); if (lastLocalBlockNum > 6) { lastLocalBlockNum = lastLocalBlockNum - 6; } if (Config.lastGoodBlock > 0 && Config.lastGoodBlock < lastLocalBlockNum) { lastLocalBlockNum = Config.lastGoodBlock; } if (lastLocalBlockNum > 0) { Block b = blockChain.getBlock(lastLocalBlockNum, true); if (b != null) { ConsensusConfig.minRedactedWindowSize = ConsensusConfig.getRedactedWindowSize(b.version); ConsensusConfig.redactedWindowSize = ConsensusConfig.getRedactedWindowSize(b.version); } } if (Config.recoverFromFile) { Block b = Meta.Storage.getBlock(lastLocalBlockNum); blockSync.onHelloDataReceived(b.blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getSignatureCount(), lastLocalBlockNum); } else { ulong blockNum = WalletStateStorage.restoreWalletState(lastLocalBlockNum); if (blockNum > 0) { Block b = blockChain.getBlock(blockNum, true); if (b != null) { blockSync.onHelloDataReceived(blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getSignatureCount(), lastLocalBlockNum); } else { walletState.clear(); } } else { blockSync.lastBlockToReadFromStorage = lastLocalBlockNum; } // Start the server for ping purposes serverStarted = true; if (!isMasterNode()) { Logging.info("Network server is not enabled in modes other than master node."); } else { NetworkServer.beginNetworkOperations(); } // Start the network client manager NetworkClientManager.start(); } } PresenceList.startKeepAlive(); TLC = new ThreadLiveCheck(); // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Name = "Node_Maintenance_Thread"; maintenanceThread.Start(); }
private async void SEClicked(object sender, EventArgs e) { //Get SE Badge Swipe var inputPopup = new BadgeReader(); await PopupNavigation.Instance.PushAsync(inputPopup, true); var ret = await inputPopup.PopupClosedTask; string SEBadge = ret.SETag; //Globals.NFCsignin = SEBadge; //Check if NFC scan was cancelled if (SEBadge == null) { return; } //Check if user wants to continue in offline mode when internet missing if (Connectivity.NetworkAccess != NetworkAccess.Internet) { bool answer = await DisplayAlert("Warning", "Internet connection not available. It is recommended to obtain connection and retry sign-in. Continue with sign-in in offline mode?", "Yes", "No"); if (answer) { //Pull database list var workerlist = await App.Database.GetWorkers(); //Determine if login card is in Db Worker activeworker = workerlist.Where(c => c.ReferenceNFC == SEBadge).ToList().FirstOrDefault(); if (activeworker == null) { await DisplayAlert("Login Error", "Card not active and/or valid. Return to Sign-in page and obtain internet connection", "Return"); return; } else { Globals.SELevel = activeworker.SELevel; Globals.ServerName = "OFFLINE MODE"; Globals.UserDisplay = activeworker.LastName; Globals.OfflineMode = true; await Navigation.PushModalAsync(new MainPage(), false).ConfigureAwait(false); return; } } else { return; } } //Start Loading Icon AIndicator.IsRunning = true; //Create temp WorkerID for Web API Worker tempWorker = new Worker(); tempWorker.ReferenceNFC = SEBadge; //Request JWT from Web API string IsValid = await APIServer.SEClient(tempWorker); //Check for API Error if (IsValid == "Card Not Active" | IsValid == "Unable to Sign In" | IsValid == "Invalid Card Used" | IsValid == "Server Error" | IsValid == "Server Connection Error") { DisplayAlert(IsValid, "The scanned card is not valid or has not been activited, please contact your administrator", "Return to login screen"); AIndicator.IsRunning = false; } else { //Determine if new database selected and if local data clear required var workerlist = await App.Database.GetWorkers(); string CurrentServ = workerlist.Select(c => c.ReferenceNFC).ToList().FirstOrDefault(); string ServerName; try //Get new Servername { int idx = tempWorker.ReferenceNFC.IndexOf('_'); ServerName = tempWorker.ReferenceNFC.Substring(0, idx); } catch //Catch bad access card { ServerName = null; } //Updating local data with new entries if (CurrentServ == ServerName) //Update local Db if accessing same server { await App.Database.GetWorkersAPI(); await App.Database.GetUnitsAPI(); await App.Database.GetVesselsAPI(); await App.Database.GetLogsAPI(); await App.Database.GetAnalyticsAPI(); } else //Clear local Db if new server accessed { await App.Database.ClearLocal(); await App.Database.GetWorkersAPI(); await App.Database.GetUnitsAPI(); await App.Database.GetVesselsAPI(); await App.Database.GetLogsAPI(); await App.Database.GetAnalyticsAPI(); } //await Navigation.PushModalAsync(new VesselEntryPage(), false).ConfigureAwait(false); await Navigation.PushModalAsync(new MainPage(), false).ConfigureAwait(false); } }
static void Main(string[] args) { //Asta va fi inlocuit cu un API call SignatureVerifier signatureVerifier = new SignatureVerifier(); RNGRandomGenerator rngGenerator = new RNGRandomGenerator(); EmailSender emailSender = new EmailSender(); BlindChatDbContext context = new BlindChatDbContext(); GroupRepository groupRepository = new GroupRepository(context); APIServer server = new APIServer(groupRepository, emailSender, rngGenerator, signatureVerifier); //Set participants List <Participant> unconfirmedParticipants = server.GetParticipantsToConfirm("Loazarii"); foreach (var participant in unconfirmedParticipants) { int invitationCode = participant.InvitationCode; Guid groupId = (Guid)participant.GroupId; string email = participant.Email; Group group = server.GetGroup(participant.InvitationCode); ClientParticipant clientParticipant = new ClientParticipant(server, groupRepository); var groupPublicKey = clientParticipant.GetGroupDetails(invitationCode); //Generate certificate CertificateGenerator generator = new CertificateGenerator(); var participantKeys = generator.GenerateCertificate("C=RO,O=Qubiz", TimeSpan.FromDays(1), "certParticipant.pfx", "Test.123"); //Serialize var privateSerializedKey = RsaKeyUtils.GetSerializedPrivateKey(participantKeys.Private); var publicSerializedKey = RsaKeyUtils.GetSerializedPublicKey(participantKeys.Public); //Concatenante serialized key var content = RsaKeyUtils.Combine(publicSerializedKey, privateSerializedKey); //Generate blind content ContentBlinder contentBlinder = new ContentBlinder((RsaKeyParameters)groupPublicKey, "Loazarii"); var blindedContent = contentBlinder.GetBlindedContent(content); var groupRegistration = clientParticipant.GetGroupRegistration(invitationCode, (RsaKeyParameters)participantKeys.Public); //Save blindedCertificate clientParticipant.RegisterBlindCertificate(invitationCode, groupRegistration); //Send for sign DONE //Get blindSignature var blindMessage = server.GetSignedMessage(groupId, email); var signature = Convert.FromBase64CharArray(blindMessage.Signature.ToCharArray(), 0, blindMessage.Signature.Length); //Unblind signature var unblindedSignature = contentBlinder.GetUnblindedSignature(signature); //Verify var verifiedParticipant = clientParticipant.CheckVerifiedEntity(group, participant.Email, groupRegistration); clientParticipant.AddClientCertificate(verifiedParticipant, group, email); ParticipantMessage message = new ParticipantMessage(); message.Message = "Andreiu, ce nevoie faci?"; clientParticipant.AddMessage(groupId, message, verifiedParticipant); } Console.ReadKey(); }
public void start(bool verboseConsoleOutput) { UpdateVerify.start(); // Generate presence list PresenceList.init(IxianHandler.publicIP, Config.serverPort, 'C'); // Start the network queue NetworkQueue.start(); ActivityStorage.prepareStorage(); if (Config.apiBinds.Count == 0) { Config.apiBinds.Add("http://localhost:" + Config.apiPort + "/"); } // Start the HTTP JSON API server apiServer = new APIServer(Config.apiBinds, Config.apiUsers, Config.apiAllowedIps); if (IXICore.Platform.onMono() == false && !Config.disableWebStart) { System.Diagnostics.Process.Start(Config.apiBinds[0]); } // Prepare stats screen ConsoleHelpers.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (ConsoleHelpers.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Start the node stream server NetworkServer.beginNetworkOperations(); // Start the network client manager NetworkClientManager.start(2); // Start the keepalive thread PresenceList.startKeepAlive(); // Start TIV string headers_path = ""; if (IxianHandler.isTestNet) { headers_path = Path.Combine(Config.dataDirectory, "testnet-headers"); } else { headers_path = Path.Combine(Config.dataDirectory, "headers"); } if (generatedNewWallet || !File.Exists(Path.Combine(Config.dataDirectory, Config.walletFile))) { generatedNewWallet = false; tiv.start(headers_path); } else { tiv.start(headers_path, 0, null); } // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Start(); pushNotifications = new PushNotifications(Config.pushServiceUrl); pushNotifications.start(); }
public ClientAccepter(APIServer server) { this.server = server; }
public CommandManager(APIServer server) { this.Server = server; this.handlerList = new List <ICommandHandler>(); }