Example #1
0
        public Chat()
            : base(new Irc("Tomestone", "oauth:npafwpg44j0a5iullxo2dt385n5jeco", new[] { MainChannel }))
        {
            var twitch = new TwitchConnection();

            _userDatabase = new UserDatabase(_db, twitch);
            _gameDatabase = new GameDatabase(_db, twitch);
            _statistics = new Statistics(_userDatabase, _gameDatabase, twitch);
        }
Example #2
0
        /// <summary>
        /// Loads the best sessions.json it can find - first look in SpecialFolder 
        /// (if not there, load the one that was included in the app download)
        /// </summary>
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder
            libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder
            var builtInJsonPath = Path.Combine (System.Environment.CurrentDirectory, ConferenceManager.JsonDataFilename);
            jsonPath = Path.Combine (libraryPath, ConferenceManager.JsonDataFilename); //
            UserData = new UserDatabase(Path.Combine (libraryPath, SqliteDataFilename));

            Conference = new ConferenceManager();
            Conference.OnDownloadSucceeded += (jsonString) => {
                File.WriteAllText (jsonPath, jsonString);
                NSUserDefaults.StandardUserDefaults.SetString(ConferenceManager.LastUpdatedDisplay, "LastUpdated");

                Console.WriteLine("Local json file updated " + jsonPath);
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            };
            Conference.OnDownloadFailed += (error) => {
                Console.WriteLine("OnDownloadFailed:" + error);
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            };

            #region Get session data from json into memory...

            var json = "";
            if (!File.Exists(jsonPath)) {
                //jsonPath = builtInJsonPath; // use the bundled file
                NSUserDefaults.StandardUserDefaults.SetString("2012-09-15 15:15:15", "LastUpdated");

                File.Copy (builtInJsonPath, jsonPath); // so it is there for loading
            }
            json = File.ReadAllText(jsonPath);

            MonkeySpace.Core.ConferenceManager.LoadFromString (json);

            #endregion

            // Create the tab bar
            tabBarController = new TabBarController ();

            //#d4563e
            UINavigationBar.Appearance.TintColor = new UIColor(212/255f, 86/255f, 62/255f, 1f);

            // Create the main window and add the navigation controller as a subview
            window = new UIWindow (UIScreen.MainScreen.Bounds);
            window.RootViewController = tabBarController;
            window.MakeKeyAndVisible ();
            showSplashScreen();

            return true;
        }
Example #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainViewModel"/> class.
        /// </summary>
        /// <param name="currentUser">All the required information about the current logged in user.</param>
        /// <param name="data">Instance of <see cref="DataComponents"/> that allows access to user database and certificates.</param>
        /// <param name="thisWindow">Window in which MainControl is shown.</param>
        public MainViewModel(UserInformation currentUser, UserDatabase data, ViewModelHistory thisWindow)
        {
            this.currentUserInfo = currentUser;
            this.thisWindow      = thisWindow;

            this.operationModes.Add("Encrypt");
            this.operationModes.Add("Decrypt");
            this.ChosenMode = this.operationModes[0];

            this.hashAlgorithms.Add(new HashAlgorithmChoice("SHA256", SHA256.Create()));
            this.hashAlgorithms.Add(new HashAlgorithmChoice("MD5", MD5.Create()));
            this.ChosenHashAlgorithm = this.hashAlgorithms[0];

            this.encryptionAlgorithms.Add(new EncryptionAlgorithmChoice("AES", new AesMachine()));
            this.encryptionAlgorithms.Add(new EncryptionAlgorithmChoice("TripleDES", new TDesMachine()));
            this.encryptionAlgorithms.Add(new EncryptionAlgorithmChoice("Twofish", new TwofishMachine()));
            this.ChosenEncryptionAlgorithm = this.encryptionAlgorithms[0];

            this.allUsers.AddRange(data.GetAllUsers().Where((user) => user.Username != currentUser.Username));
        }
Example #4
0
        private async void JoinGameCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var user = UserDatabase.GetUser(message.Chat.Id);

            if (user.User.ActiveGameId != null)
            {
                await Bot.SendTextMessageAsync(message.Chat.Id,
                                               "Вы уже участвуете в игре. Закончите предыдущую игру или введите команду /exit",
                                               ParseMode.Markdown);

                return;
            }
            var games = service.Games.GetAllGamesAsync().Result.Select(g => g.ToGameRoom())
                        .ToArray();

            if (!games.Any())
            {
                var menu = new ReplyMenu("", true, new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton("« Назад в главное меню")
                    },
                    new KeyboardButton[]
                    {
                        new KeyboardButton("🌃 Создать игру")
                    }
                });

                await Bot.SendTextMessageAsync(message.Chat.Id,
                                               "Список игр *пуст* ",
                                               ParseMode.Markdown, false, false, 0, menu.Keyboard);

                return;
            }

            else
            {
                await new GamesListGenerator(games).GenerateMenu().ShowAsync(message.Chat.Id, Bot, "Список доступных игр:");
            }
        }
Example #5
0
 public AccountPage()
 {
     InitializeComponent();
     // Check if user is connected to internet, if not, skip this
     if (CheckNetwork.IsInternet())
     {
         var userDatabase = new UserDatabase();
         var userdata     = userDatabase.GetAllUsers();
         if (userdata.Count < 1)
         {
             BtnLoginProcess.IsVisible    = true;
             LblAccountText.IsVisible     = true;
             LblUserName.IsVisible        = false;
             BtnLogoutProcess.IsVisible   = false;
             BtnRegisterProcess.IsVisible = true;
         }
         else
         {
             var Displayname = userdata.First().Displayname;
             BtnLoginProcess.IsVisible    = false;
             LblUserName.Text             = "Welcome " + Displayname;
             LblUserName.TextColor        = Color.White;
             LblUserName.IsVisible        = true;
             LblAccountText.IsVisible     = false;
             BtnLogoutProcess.IsVisible   = true;
             BtnRegisterProcess.IsVisible = false;
         }
     }
     else
     {
         BtnLoginProcess.IsVisible    = false;
         LblAccountText.IsVisible     = false;
         BtnLogoutProcess.IsVisible   = false;
         BtnRegisterProcess.IsVisible = false;
         LblUserName.IsVisible        = false;
         LblAccountText.IsVisible     = false;
         ErrMessage.IsVisible         = true;
         ErrMessage.TextColor         = Color.Red;
         ErrMessage.Text = "You're not connected to the internet. Please make sure you are connected to use the app.";
     }
 }
        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            // Na inicialização do pedido, modificamos os encaminhamentos de solicitação para
            // inclui autenticação sem estado
            // Configurar a autenticação sem estado é simples. Basta usar o
            // NancyContext para obter o apiKey. Em seguida, use o apiKey para obter
            // a identidade do seu usuário.
            var configuration =
                new StatelessAuthenticationConfiguration(nancyContext =>
            {
                // recupera o token do Cabeçalho http
                var apiKey = (string)nancyContext.Request.Headers.Authorization;

                //Obtem a identidade do usuário
                return(UserDatabase.GetUserFromApiKey(apiKey));
            });

            AllowAccessToConsumingSite(pipelines);

            StatelessAuthentication.Enable(pipelines, configuration);
        }
        public IActionResult Delete(string login)
        {
            UserDatabase Database        = UserDatabase.GetDatabase();
            var          userParaRemover = Database.Users.FirstOrDefault(user => user.Login == login);

            if (userParaRemover == null)
            {
                return(NotFound("O usuário que você tentou remover não existe"));
            }

            Database.Users.Remove(userParaRemover);
            Database.salvar();
            return(Ok(new{
                userParaRemover.Id,
                userParaRemover.PrimeiroNome,
                userParaRemover.UltimoNome,
                userParaRemover.Telefone,
                userParaRemover.Email,
                userParaRemover.Login
            }));
        }
        public ListUsersModule()
        {
            // add an after hook to send the user to access denied if they are NOT admin
            After += context =>
            {
                if (context.Response.StatusCode == HttpStatusCode.Forbidden)
                {
                    context.Response = Response.AsRedirect("/denied");
                }
            };
            this.RequiresAnyClaim(new[] { "admin" });

            Get["/users"] = _ =>
            {
                this.RequiresAuthentication();

                var users = UserDatabase.GetAllUsers();
                ViewBag.Title = "Application Users";
                return(View["Views/User/Users", users]);
            };
        }
Example #9
0
        protected void Register_Click(object sender, EventArgs e)
        {
            UserModel    userModel    = new UserModel();
            UserDatabase userDatabase = new UserDatabase();

            userModel.Name     = nameTxt.Text;
            userModel.Address  = addressTxt.Text;
            userModel.Contact  = contactTxt.Text;
            userModel.Email    = emailTxt.Text;
            userModel.Username = usernameTxt.Text;
            userModel.Password = passwordTxt.Text;
            userModel.Role     = 2;
            if (userDatabase.saveUser(userModel))
            {
                ltrText.Text = "User Registered Successfully";
            }
            else
            {
                ltrText.Text = "Sorry Registration Failed";
            }
        }
Example #10
0
        private void SaveB_Click(object sender, RoutedEventArgs e)
        {
            using (SQLiteConnection conn = UserDatabase.GetDbConnection())
            {
                TableQuery <UserAccount> t = conn.Table <UserAccount>();
                var q = (from s in t
                         orderby s.user_id
                         where s.user_id == this_account
                         select s).SingleOrDefault();

                q.nickname = reNameBox.Text;
                conn.Update(q);
                //q.First().nickname = reNameBox.Text;

                //conn.InsertOrReplace(q);
            }
            if (this.Frame.CanGoBack)
            {
                Frame.GoBack();
            }
        }
Example #11
0
        private async void ExitGameCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var user = UserDatabase.GetUser(message.Chat.Id);

            if (user.User.ActiveGameId == null)
            {
                await Bot.SendTextMessageAsync(message.Chat.Id, "Вы не участвуете ни в одной из игр :c", ParseMode.Markdown);

                return;
            }
            var game = service.Games.GetGameAsync(user.User.ActiveGameId.Value).Result;

            if (game.Players.Count() == 1 || game.Id == user.User.ActiveGameId)
            {
                DeleteGame(message, Bot, user, game);
            }
            else
            {
                DeleteUser(message, Bot, user, game);
            }
        }
 private void TimerOnTick(object sender, EventArgs e)
 {
     try
     {
         if (isValidAccount(tbEmailReset.Text.Trim(), tbPasswordReset.Password.Trim(), tbConfirmPassReset.Password.Trim()))
         {
             user.Email = tbEmailReset.Text.Trim();
             try
             {
                 UserProfile userProfile = ProfileDatabase.GetProfile(user);
                 if (userProfile != null)
                 {
                     if (userProfile.Hint.Equals(lbAnswerReset.Text.Trim()))
                     {
                         user.Password = tbPasswordReset.Password.Trim();
                         UserDatabase.Update(user, user.Email);
                         Helpers.MakeConfirmMessage(Window.GetWindow(this), "Reset Password Successfully~", "Notify");
                     }
                     else
                     {
                         Helpers.MakeErrorMessage(Window.GetWindow(this), "Hint is not correct", "Error");
                     }
                 }
                 else
                 {
                     Helpers.MakeErrorMessage(Window.GetWindow(this), "Email not exists", " Error ");
                 }
             }
             catch (Exception eh)
             {
                 Helpers.MakeErrorMessage(Window.GetWindow(this), "Error", "ERROR PROCESSING....");
             }
         }
         dispatcherTimer.Stop();
         icLoading.Visibility = Visibility.Collapsed;
     }
     catch (Exception er)
     {
     }
 }
Example #13
0
        private async void CreateGameCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var user = UserDatabase.GetUser(message.Chat.Id);

            if (user.GameRoomCreation == null)
            {
                GameNotFound(message, Bot, user);
                return;
            }

            else
            {
                GameRoom game = null;
                try
                {
                    game = service.Games
                           .CreateGameAsync(GameRoom.CreateGameRoom(user.GameRoomCreation))
                           .Result.ToGameRoom();

                    CommandsCenter.Add(new InlineButton($"{game.Name}| {game.ActiveRoles} |{game.Players.Count() + "/" + game.MaxPlayers}",
                                                        game.Id.ToString(), InGame.EnterRoomCallback));
                }
                catch (Exception ex)
                {
                    await Bot.SendTextMessageAsync(message.Chat.Id,
                                                   "Ошибка при создании игры 😢: " + ex.Message);

                    return;
                }

                user.SetRoom(user.User.Id);
                await CommandsCenter.GetMenu("ExitGameMenu").ShowAsync(message.Chat.Id, Bot,
                                                                       "Комната успешно создана!\n*Ожидание игроков...*");

                Bot.ShowAnswerMessage((arg as CallbackQuery).Id,
                                      "На этом всё! :c\n\n" +
                                      "Увы, время защиты ограничено. Но не переживайте!\n" +
                                      "Подписывайтесь на бота и ждите обновлений!");
            }
        }
Example #14
0
        public void TestAddUpdateRemove()
        {
            UserDatabase userDb = new UserDatabase(_settingsLookup[ConnectionKey]);

            GetTestUser(out var name, out User user);

            // Test User is not there
            Assert.IsNotNull(userDb.LoadedItems);
            int           numberInitialItems = userDb.LoadedItems.Count;
            List <string> userNames          = userDb.LoadedItems.ToList().Select(x => x.Name).ToList();

            Assert.IsFalse(userNames.Contains(name));

            // Add new User
            userDb.AddNewItemToDatabase(user);
            userDb.ConnectToDatabase();
            Assert.AreNotEqual(numberInitialItems, userDb.LoadedItems.Count);
            Assert.AreEqual(1, userDb.LoadedItems.Count - numberInitialItems);
            List <string> userNames2 = userDb.LoadedItems.ToList().Select(x => x.Name).ToList();

            Assert.IsTrue(userNames2.Contains(name));

            // Update the User to have different name
            user.Name = UpdatedUserName;
            userDb.UpdateDatabaseItem(user);
            userDb.ConnectToDatabase();
            List <string> userNames3 = userDb.LoadedItems.ToList().Select(x => x.Name).ToList();

            Assert.IsTrue(userNames3.Contains(UpdatedUserName));

            // Remove the new user
            userDb.RemoveItemFromDatabase(user);
            userDb.ConnectToDatabase();

            Assert.AreEqual(userDb.LoadedItems.Count, numberInitialItems);
            List <string> userNames4 = userDb.LoadedItems.ToList().Select(x => x.Name).ToList();

            Assert.IsFalse(userNames4.Contains(name));
        }
Example #15
0
        public LoginUserResponse Login(LoginUserRequest req)
        {
            LoginUserResponse res = new LoginUserResponse();

            try
            {
                User user;

                using (UserDatabase daUser = new UserDatabase())
                {
                    user = daUser.LoginUserAsync(req.Email, $"{req.Email}:{req.Password}".GenerateSHA512());
                }

                if (user != null)
                {
                    res.User = user;
                    //res.Token = BuildToken(user);
                    res.IsSuccessful = true;
                }
                else
                {
                    res.IsSuccessful = false;
                    res.Errors.Add(new Error()
                    {
                        Code = ((int)ErrorCodes.NotFound).ToString(), Message = "Email or Password is incorrect"
                    });
                }
            }
            catch (Exception)
            {
                res.IsSuccessful = false;
                res.Errors.Add(new Error()
                {
                    Code = ((int)ErrorCodes.Unknown).ToString(), Message = "There was a problem. Please try again later"
                });
            }
            return(res);
        }
Example #16
0
    public void submit(object sender, EventArgs e)
    {
        // need to add test to see if any usernames are already taken in db
        // should add encryption

        string userName = txtUsername.Text;
        string password = txtPassword.Text;



        foreach (char c in userName)
        {
            if (!IsValid(c))
            {
                userName = null;
            }
        }

        foreach (char c in password)
        {
            if (!IsValid(c))
            {
                password = null;
            }
        }


        if (userName == null || password == null || txtUsername.Text.Length < 1 || txtPassword.Text.Length < 1)
        {
            errorLbl.Visible = true;
            errorLbl.Text    = "Please enter the correct information";
        }
        else
        {
            UserDatabase.AddUser(userName, password);
            Server.Transfer("HomePage.aspx", true);
        }
    }
Example #17
0
 private void TimerOnTick(object sender, EventArgs e)
 {
     try
     {
         if (isValidAccount(tbEmailSignUp.Text.Trim(), tbPasswordSignUp.Password.Trim(), tbConfirmPassSignUp.Password.Trim(), cbAgreeTerm))
         {
             if (UserDatabase.Insert(tbEmailSignUp.Text.Trim(), tbPasswordSignUp.Password.Trim(), 0))
             {
                 ProfileDatabase.Insert(tbEmailSignUp.Text.Trim());
                 Helpers.MakeConfirmMessage(Window.GetWindow(this), "Registered Successfully~", "Notify");
             }
             else
             {
                 Helpers.MakeErrorMessage(Window.GetWindow(this), "Error", "Email is already exits");
             }
         }
         dispatcherTimer.Stop();
         icLoading.Visibility = Visibility.Collapsed;
     }
     catch (Exception er)
     {
     }
 }
        public TokenModule() : base("api/token")
        {
            Post("/", args =>
            {
                var apiKey = UserDatabase.ValidateUser(
                    (string)this.Request.Form.Username,
                    (string)this.Request.Form.Password);

                return(string.IsNullOrEmpty(apiKey)
                    ? new Response {
                    StatusCode = HttpStatusCode.Unauthorized
                }
                : this.Response.AsJson(new { ApiKey = apiKey }));
            });
            Delete("/", args =>
            {
                var apiKey = (string)this.Request.Form.ApiKey;
                UserDatabase.RemoveApiKey(apiKey);
                return(new Response {
                    StatusCode = HttpStatusCode.OK
                });
            });
        }
Example #19
0
        public IActionResult ConfirmRegistration(string token)
        {
            var tokenValidation = Jwt.Validate(token, out ClaimsIdentity claimsIdentity);

            if (!tokenValidation)
            {
                return(Unauthorized("Token invalid or expired"));
            }
            if (claimsIdentity.AuthenticationType != TokenScope.Registration)
            {
                return(Unauthorized("JWT was generated for another scope"));
            }

            var username = claimsIdentity.FindFirst(claim => claim.Type == ClaimTypes.Name).Value;

            if (String.IsNullOrEmpty(username))
            {
                return(Problem("Invalid username"));
            }

            UserDatabase.ConfirmAccount(username);
            return(Ok());
        }
Example #20
0
    IEnumerator LoadUserDatas()
    {
        PopupManager.Get().OpenLoading("", "Loading...");

        Task <UserData[]> task = UserDatabase.Get().GetAllUserData();

        yield return(TaskExtension.YieldWait(task));

        if (task.IsCompleted)
        {
            UserData[] userDatas = task.Result;
            if (userDatas.Length > 0)
            {
                foreach (UserData userData in userDatas)
                {
                    ScoreBoardEntry entry = Instantiate(scoreBoardEntryPrefab, scoreBoardTable);
                    entry.Init(userData.iconURL, userData.name, userData.highScore);
                    scoreBoardEntries.Add(entry);
                }
            }
        }
        PopupManager.Get().CloseLoading();
    }
        public IActionResult Put(string login, [FromBody] User updatedUser)
        {
            UserDatabase Database       = UserDatabase.GetDatabase();
            var          userASerMudado = Database.Users.FirstOrDefault(user => user.Login == login);

            if (userASerMudado == null)
            {
                return(NotFound("Não existe um usuário com login informado"));
            }
            updatedUser.Id = userASerMudado.Id;

            Database.Users.Remove(userASerMudado);
            Database.Users.Add(updatedUser);
            Database.salvar();
            return(Ok(new{
                updatedUser.Id,
                updatedUser.PrimeiroNome,
                updatedUser.UltimoNome,
                updatedUser.Telefone,
                updatedUser.Email,
                updatedUser.Login
            }));
        }
Example #22
0
        private void CorrectNameCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var user = UserDatabase.GetUser(message.Chat.Id);

            user.GameRoomCreation = new GameRoomCreation()
            {
                Name = message.Text, AdminId = message.Chat.Id
            };

            var menu = new ReplyMenu("", true, new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("« Назад в главное меню")
                }
            }, user.GameRoomCreation.ToString());

            menu.ShowAsync(message.Chat.Id, Bot,
                           "Укажите *максимальное количество игроков* игры (4-19 игроков):", true);

            user.CommandRegex = (new Regex("[4-9]|([1][1-9])"), new ReplyCallback(CorrectMaxPlayersCallback),
                                 new ReplyCallback(UncorrectMaxPlayersCallback));
        }
        /// <summary>
        /// authenticate user by user name and password
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public Result <UserModel> LoginUser(string userName, string password)
        {
            var userDB = new UserDatabase();
            Result <UserModel> result = null;

            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                result = userDB.LoginUser(userName, password);
                if (result.Model == null)
                {
                    result.Success = false;
                    result.Message = "Please enter valid user name/password";
                }
            }
            else
            {
                result         = new Result <UserModel>();
                result.Message = "Please enter valid user name/password";
                result.Success = false;
                return(result);
            }
            return(result);
        }
Example #24
0
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            UserDatabase userDatabase = new UserDatabase();
            int          id           = userDatabase.isUserValid(usernameTxt.Text, passwordTxt.Text);

            if (id > 0)
            {
                msg.Text = "login sucessfull";
                UserModel userModel = userDatabase.getUser(id);

                Session["username"] = userModel.Name;
                Session["user_id"]  = userModel.Id;

                if (userModel.Role == 2)
                {
                    Response.Redirect("/Pages/Client/Dashboard.aspx");
                }
                else if (userModel.Role == 1)
                {
                    Response.Redirect("/Pages/Admin/Dashboard.aspx");
                }
            }
        }
Example #25
0
        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            // At request startup we modify the request pipelines to
            // include stateless authentication
            //
            // Configuring stateless authentication is simple. Just use the
            // NancyContext to get the apiKey. Then, use the apiKey to get
            // your user's identity.
            var configuration =
                new StatelessAuthenticationConfiguration(nancyContext =>
            {
                //for now, we will pull the apiKey from the querystring,
                //but you can pull it from any part of the NancyContext
                var apiKey = (string)nancyContext.Request.Query.ApiKey.Value;

                //get the user identity however you choose to (for now, using a static class/method)
                return(UserDatabase.GetUserFromApiKey(apiKey));
            });

            AllowAccessToConsumingSite(pipelines);

            StatelessAuthentication.Enable(pipelines, configuration);
        }
Example #26
0
        /// <summary>
        /// Second part of 2FA.
        /// </summary>
        /// <param name="user">User information.</param>
        /// <param name="certificate">User <see cref="X509Certificate2"/> public certificate in raw form.</param>
        /// <param name="usersDb">Enigma's user database.</param>
        /// <param name="crlListPath">Path on FS to CRL directory.</param>
        /// <param name="caTrustListPath">Path on FS to CA trust list.</param>
        public void LoginPartTwo(User user, byte[] certificate, UserDatabase usersDb, string crlListPath, string caTrustListPath)
        {
            var userCert = new X509Certificate2(certificate);
            var publicKeyFromCertificate = ((RSACryptoServiceProvider)userCert.PublicKey.Key).ExportParameters(false);

            // compare user public RSA key from x509 public certificate with a public RSA key that was stored when user first registered
            if (!RsaAlgorithm.CompareKeys(publicKeyFromCertificate, RsaAlgorithm.ExportParametersFromXmlString(user.PublicKey, false)))
            {
                throw new Exception("Wrong certificate used.");
            }
            // if wrong file is loaded instead of the x509 public certificate in PEM format
            if (userCert == null)
            {
                throw new Exception("Certificate error.");
            }

            // update user last login time and reset atttemp count
            usersDb.UpdateLoginTime(user, DateTime.Now.ToString("dddd, MMM dd yyyy, hh:mm:ss"));

            // reset login attempt if necessary
            if (user.LoginAttempt != 0)
            {
                usersDb.ResetLoginAttempts(user);
            }

            //if (CertificateValidator.VerifyCertificate(userCert, out var errorMsg, false) == false)
            //{
            //    throw new Exception(errorMsg);
            //}

            // Check if the certificate has been revoked and set Revoked value if necessary.
            if (CertificateValidator.VerifyCertificateRevocationStatus(userCert, crlListPath, caTrustListPath))
            {
                usersDb.SetCertificateRevokeStatus(user);
                //throw new Exception("Certificate has been revoked.");
            }
        }
Example #27
0
    protected void submit(object sender, EventArgs e)
    {
        string password = txtPassword.Text;
        string username = txtUsername.Text;

        foreach (char c in username)
        {
            if (!IsValid(c))
            {
                username = null;
            }
        }

        foreach (char c in password)
        {
            if (!IsValid(c))
            {
                password = null;
            }
        }


        int userId = UserDatabase.GetUserIdByUsernameAndPassword(username, password);

        if (userId > 0)
        {
            // Now put userid in a session-variable
            // and redirect the user to the protected area of your website.
            loginresult.Text  = string.Format("You are userId : {0}", userId);
            Session["userId"] = userId;
            Response.Redirect("ViewPictures.aspx");
        }
        else
        {
            loginresult.Text = "Wrong username or password";
        }
    }
Example #28
0
        private void Restore()
        {
            List <long> UserIds = new List <long>();

            UserIds.AddRange(Online);
            UserIds.AddRange(Offline);

            if (UserIds.Count == 0)
            {
                foreach (var Settings in Global.GuildSettings.Settings)
                {
                    foreach (long Id in Settings.Value.TwitchTrack.UserIds)
                    {
                        if (!UserIds.Contains(Id))
                        {
                            UserIds.Add(Id);
                        }
                    }
                }
            }

            Tracking.AddRange(UserIds);

            List <UserResponse> Users = new List <UserResponse>();

            for (int i = 0; i < UserIds.Count; i += 100)
            {
                GetUsersResponse resp = api.Helix.Users.GetUsersAsync(UserIds.Skip(i).Take(100).Select(t => t.ToString()).ToList()).Result;
                Users.AddRange(resp.Users.Select(t => new UserResponse(t)));
            }

            for (int i = 0; i < Users.Count; i++)
            {
                UserResponse User = Users[i];
                UserDatabase.Add(User.Id, User);
            }
        }
Example #29
0
        //by this time, the api key should have already been pulled out of our querystring
        //and, using the api key, an identity assigned to our NancyContext
        public SecureModule() : base("secure")
        {
            this.RequiresAuthentication();

            Get("/", args =>
            {
                //Context.CurrentUser was set by StatelessAuthentication earlier in the pipeline
                var identity = this.Context.CurrentUser;

                //return the secure information in a json response
                var userModel = new User(identity.Identity.Name);
                return(this.Response.AsJson(new
                {
                    SecureContent = "here's some secure content that you can only see if you provide a correct apiKey",
                    User = userModel
                }));
            });

            Post("/create_user", args =>
            {
                Tuple <string, string> user = UserDatabase.CreateUser(this.Context.Request.Form["username"], this.Context.Request.Form["password"]);
                return(this.Response.AsJson(new { username = user.Item1 }));
            });
        }
Example #30
0
        public RegisterStatus Register(string Username)
        {
            GetUsersResponse resp = api.Helix.Users.GetUsersAsync(logins: new List <string>()
            {
                Username
            }).Result;
            List <UserResponse> user = resp.Users.Select(t => new UserResponse(t)).ToList();

            if (user.Count == 0)
            {
                return(RegisterStatus.UserNotFound);
            }

            if (Tracking.Contains(user[0].Id))
            {
                return(RegisterStatus.AlreadyTracking);
            }

            Tracking.Add(user[0].Id);
            Offline.Add(user[0].Id);
            UserDatabase.Add(user[0].Id, user[0]);

            return(RegisterStatus.Success);
        }
        public UserInformation Login(string username, string password, out UserDatabase data)
        {
            UserDatabase dataComp = new UserDatabase(this.userDatabasePath);

            var user = dataComp.GetUser(username);

            if (user != null && user.IsPasswordValid(password))
            {
                var userCert = new X509Certificate2(user.PublicCertificate);

                if (userCert == null)
                {
                    throw new Exception("Certificate error.");
                }

                if (CertificateValidator.VerifyCertificate(userCert) == false)
                {
                    throw new Exception("Certificate is invalid.");
                }

                byte[] keyRaw            = File.ReadAllBytes(this.privateKeyPath);
                var    privateParameters = new KeyFileParser(keyRaw).GetParameters();
                RSACryptoServiceProvider publicKeyProvider = (RSACryptoServiceProvider)userCert.PublicKey.Key;
                if (!RsaMachine.AreKeysMatched(publicKeyProvider.ExportParameters(false), privateParameters))
                {
                    throw new Exception("The given private key does not match this user's certificate.");
                }

                data = dataComp;
                return(new UserInformation(user, privateParameters));
            }
            else
            {
                throw new Exception("Invalid username or password.");
            }
        }
Example #32
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add(new ReplyButton("/send", (message, bot, arg) =>
     {
         if ((message.Chat.Id == 422672483))
         {
             const string command = "/send";
             message.Text         = message.Text.Replace(command, "");
             if (!String.IsNullOrEmpty(message.Text))
             {
                 UserDatabase.Broadcast(user => true, user => message.Text, bot);
                 BotConsole.Write("Расслыка завершена.", MessageType.Info);
             }
         }
     }));
     CommandsCenter.Add(new ReplyButton("/count", async(message, bot, arg) =>
     {
         if ((message.Chat.Id == 422672483))
         {
             await bot.SendTextMessageAsync(message.Chat.Id,
                                            $"Количество пользователей: {UserDatabase.UsersCount()}", ParseMode.Markdown);
         }
     }));
 }
 public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
     global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
     global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
     UserDatabase ds = new UserDatabase();
     global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
     any1.Namespace = "http://www.w3.org/2001/XMLSchema";
     any1.MinOccurs = new decimal(0);
     any1.MaxOccurs = decimal.MaxValue;
     any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
     sequence.Items.Add(any1);
     global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
     any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
     any2.MinOccurs = new decimal(1);
     any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
     sequence.Items.Add(any2);
     global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
     attribute1.Name = "namespace";
     attribute1.FixedValue = ds.Namespace;
     type.Attributes.Add(attribute1);
     global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
     attribute2.Name = "tableTypeName";
     attribute2.FixedValue = "UsersDataTable";
     type.Attributes.Add(attribute2);
     type.Particle = sequence;
     global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
     if (xs.Contains(dsSchema.TargetNamespace)) {
         global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
         global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
         try {
             global::System.Xml.Schema.XmlSchema schema = null;
             dsSchema.Write(s1);
             for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
                 schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                 s2.SetLength(0);
                 schema.Write(s2);
                 if ((s1.Length == s2.Length)) {
                     s1.Position = 0;
                     s2.Position = 0;
                     for (; ((s1.Position != s1.Length) 
                                 && (s1.ReadByte() == s2.ReadByte())); ) {
                         ;
                     }
                     if ((s1.Position == s1.Length)) {
                         return type;
                     }
                 }
             }
         }
         finally {
             if ((s1 != null)) {
                 s1.Close();
             }
             if ((s2 != null)) {
                 s2.Close();
             }
         }
     }
     xs.Add(dsSchema);
     return type;
 }
 public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
     UserDatabase ds = new UserDatabase();
     global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
     global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
     global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
     any.Namespace = ds.Namespace;
     sequence.Items.Add(any);
     type.Particle = sequence;
     global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
     if (xs.Contains(dsSchema.TargetNamespace)) {
         global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
         global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
         try {
             global::System.Xml.Schema.XmlSchema schema = null;
             dsSchema.Write(s1);
             for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
                 schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                 s2.SetLength(0);
                 schema.Write(s2);
                 if ((s1.Length == s2.Length)) {
                     s1.Position = 0;
                     s2.Position = 0;
                     for (; ((s1.Position != s1.Length) 
                                 && (s1.ReadByte() == s2.ReadByte())); ) {
                         ;
                     }
                     if ((s1.Position == s1.Length)) {
                         return type;
                     }
                 }
             }
         }
         finally {
             if ((s1 != null)) {
                 s1.Close();
             }
             if ((s2 != null)) {
                 s2.Close();
             }
         }
     }
     xs.Add(dsSchema);
     return type;
 }
Example #35
0
        /// <summary>
        /// Loads the best sessions.json it can find - first look in SpecialFolder 
        /// (if not there, load the one that was included in the app download)
        /// </summary>
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            AppDelegate.current = this;

            documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder
            libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder
            var builtInJsonPath = Path.Combine (System.Environment.CurrentDirectory, ConferenceManager.JsonDataFilename);
            jsonPath = Path.Combine (libraryPath, ConferenceManager.JsonDataFilename); //
            UserData = new UserDatabase(Path.Combine (libraryPath, SqliteDataFilename));

            Conference = new ConferenceManager();
            Conference.OnDownloadSucceeded += (jsonString) => {
                File.WriteAllText (jsonPath, jsonString);
                NSUserDefaults.StandardUserDefaults.SetString(ConferenceManager.LastUpdatedDisplay, "LastUpdated");

                Console.WriteLine("Local json file updated " + jsonPath);
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            };
            Conference.OnDownloadFailed += (error) => {
                Console.WriteLine("OnDownloadFailed:" + error);
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            };

            #region Get session data from json into memory...

            var json = "";
            if (!File.Exists(jsonPath)) {
                //jsonPath = builtInJsonPath; // use the bundled file
                NSUserDefaults.StandardUserDefaults.SetString("2013-05-28 15:15:15", "LastUpdated");

                File.Copy (builtInJsonPath, jsonPath); // so it is there for loading
            }
            json = File.ReadAllText(jsonPath);

            MonkeySpace.Core.ConferenceManager.LoadFromString (json);

            #endregion

            #region APPEARANCE
            //#d4563e
            UINavigationBar.Appearance.TintColor = new UIColor(212/255f, 86/255f, 62/255f, 1f);
            UILabel.Appearance.Font = UIFont.FromName (FontLightName, 14f); // Avenir-Heavy, Avenir-Black, Avenir-Medium, ...Oblique
            UINavigationBar.Appearance.SetTitleTextAttributes (FontTitleTextAttributes);
            UIBarButtonItem.Appearance.SetTitleTextAttributes (FontBackTextAttributes, UIControlState.Normal);
            #endregion

            FlyoutNavigation = new CustomFlyoutNavigationController ();

            window = new UIWindow (UIScreen.MainScreen.Bounds);
            window.RootViewController = FlyoutNavigation;
            window.MakeKeyAndVisible ();

            return true;
        }