Ejemplo n.º 1
0
        public RetrieveGameCollectionOutput RetrieveGameCollection(RetrieveGameCollectionInput input)
        {
            if (Session.UserId == null)
            {
                return(new RetrieveGameCollectionOutput());
            }

            KeyRepository.Includes.Add(r => r.Game);
            KeyRepository.Includes.Add(r => r.Game.Location);
            KeyRepository.Includes.Add(r => r.Game.GameStatus);
            KeyRepository.Includes.Add(r => r.Game.GameTasks);
            KeyRepository.Includes.Add(r => r.Game.GameTasks.Select(e => e.GameTaskType));
            //KeyRepository.Includes.Add(r => r.Game.GameTasks.SelectMany(e => e.Conditions));
            //KeyRepository.Includes.Add(r => r.Game.GameTasks.SelectMany(e => e.Conditions.Select(k => k.ConditionType)));
            //KeyRepository.Includes.Add(r => r.Game.GameTasks.SelectMany(e => e.Tips));

            List <GameLightDto> gameCollection = GamePolicy.CanRetrieveManyEntitiesLight(
                KeyRepository.GetAll()
                .Where(r => r.OwnerUserId == Session.UserId).Select(r => r.Game))
                                                 .ToList().MapIList <Game, GameLightDto>().ToList();

            KeyRepository.Includes.Clear();

            return(new RetrieveGameCollectionOutput()
            {
                GameCollection = gameCollection
            });
        }
Ejemplo n.º 2
0
        private void SaveHandler(NhanVien item)
        {
            if (String.IsNullOrWhiteSpace(item.Luong) || String.IsNullOrWhiteSpace(item.MatKhau))
            {
                MessageBox.Show("Vui lòng nhập đầy đủ thông tin cho nhân viên " + item.MaNV);
                return;
            }

            var existItem = DbLib.GetOne <NhanVien>("SP_GETBYMANV_PUBLIC_ENCRYPT_NHANVIEN", new List <SqlParameter> {
                new SqlParameter {
                    ParameterName = "MaNV", Value = item.MaNV
                }
            });

            if (existItem != null)
            {
                //ko duoc cap nhat
            }
            //Insert
            else
            {
                item.PubKey = item.MaNV;
                var keyPairs = rsaCryptoService.GenerateKeys();
                KeyRepository.StoreKeyPairs(item.PubKey, keyPairs, item.MatKhau);
                item.MatKhau = item.MatKhau.GetSHA1Hash();

                item.Luong = rsaCryptoService.Encrypt(keyPairs.publicKey, item.Luong);
                DbLib.ExecuteNonQuery("SP_INS_PUBLIC_ENCRYPT_NHANVIEN", item.ToSqlParameter());
            }
        }
        public void should_create_table_from_context()
        {
            _databaseFixture = new DatabaseFixture();
            var keyRepository = new KeyRepository(_databaseFixture.TestDatabase.ConnectionString);

            should_have_correct_schema(_databaseFixture.TestDatabase.ConnectionString, keyRepository);
        }
Ejemplo n.º 4
0
        public GenerateKeysForGameOutput GenerateKeysForGame(GenerateKeysForGameInput input)
        {
            Game gameEntity = GameRepository.Get(input.GameId);

            if (gameEntity == null)
            {
                throw new CityQuestItemNotFoundException(CityQuestConsts.CityQuestItemNotFoundExceptionMessageBody, "\"Game\"");
            }

            if (!GamePolicy.CanGenerateKeysForEntity(gameEntity) ||
                !(input.Count > 0 && input.Count <= CityQuestConsts.MaxCountForKeyGeneration))
            {
                throw new CityQuestPolicyException(CityQuestConsts.CQPolicyExceptionCreateDenied, "\"Key\"");
            }

            IList <string> newKeys = KeyGenerationService.Generate(input.Count);

            IList <Key> newKeyEntities = new List <Key>(input.Count);

            foreach (string newKey in newKeys)
            {
                newKeyEntities.Add(new Key()
                {
                    KeyValue = newKey, GameId = input.GameId
                });
            }

            KeyRepository.AddRange(newKeyEntities);

            return(new GenerateKeysForGameOutput()
            {
                Keys = newKeys
            });
        }
Ejemplo n.º 5
0
        public async Task <String> BuyIn(Int16 seat, UInt64 amount)
        {
            if (amount >= _table.MinBuyIn && amount <= _table.MaxBuyIn)
            {
                BitcoinSecret  secret  = new BitcoinSecret(KeyRepository.GetWif(), Network.TestNet);
                BitcoinAddress address = secret.PubKey.GetAddress(Network.TestNet);

                BitPoker.Models.Messages.BuyInRequest message = new BitPoker.Models.Messages.BuyInRequest()
                {
                    BitcoinAddress = address.ToString(),
                    //Amount = amount,
                    //Seat = seat,
                    TimeStamp = DateTime.UtcNow
                };

                //buyIn.Signature = secret.PrivateKey.SignMessage(buyIn.ToString());
                BitPoker.Models.IRequest request = new BitPoker.Models.Messages.RPCRequest()
                {
                    Method = "BuyInRequest"
                };

                request.Params = message;

                return(Newtonsoft.Json.JsonConvert.SerializeObject(message));
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 6
0
        public ActivateKeyOutput ActivateKey(ActivateKeyInput input)
        {
            IList <Key> keys = KeyRepository.GetAll().Where(r => r.KeyValue == input.Key && r.OwnerUserId == null).ToList();

            if (keys.Count != 1)
            {
                throw new KeyActivationException(input.Key);
            }

            Key keyEntity = keys.Single();

            keyEntity.OwnerUserId = Session.UserId;
            KeyRepository.Update(keyEntity);

            GameRepository.Includes.Add(r => r.Location);
            GameRepository.Includes.Add(r => r.GameStatus);
            GameRepository.Includes.Add(r => r.GameTasks);
            GameRepository.Includes.Add(r => r.LastModifierUser);
            GameRepository.Includes.Add(r => r.CreatorUser);

            GameLightDto activatedGame = GameRepository.Get(keyEntity.GameId).MapTo <GameLightDto>();

            GameRepository.Includes.Clear();

            UowManager.Current.Completed += (sender, e) =>
            {
                GameChangesNotifier.RaiseOnKeyActivated(new KeyActivatedMessage(activatedGame, Session.UserId, input.Key));
            };

            return(new ActivateKeyOutput()
            {
                ActivatedGame = activatedGame
            });
        }
Ejemplo n.º 7
0
        public async Task Create_UserIdIsSet_SetsCorrectResourceAndMethod()
        {
            var sut = new KeyRepository(_requestFactory);

            await sut.Create("title", "key", 0);

            _requestFactory.Received().Create("users/{userId}/keys", Method.Post);
        }
Ejemplo n.º 8
0
        public async Task GetAll_UserIdIsSet_SetsCorrectResourceAndMethod()
        {
            var sut = new KeyRepository(_requestFactory);

            await sut.GetAll(0);

            _requestFactory.Received().Create("users/{userId}/keys", Method.Get);
        }
Ejemplo n.º 9
0
        public async Task FindWithUser_ValidParameters_SetsCorrectResourceAndMethod()
        {
            var sut = new KeyRepository(_requestFactory);

            await sut.FindWithUser(0);

            _requestFactory.Received().Create("keys/{id}", Method.Get);
        }
Ejemplo n.º 10
0
        private void button1_Click(object sender, EventArgs e)
        {
            RSACryptography rsa    = new RSACryptography();
            var             rsaKey = rsa.GenerateKeys();

            KeyRepository.StorePublicKey(textBox1.Text, rsaKey.publicKey);
            //KeyRepository.StorePrivateKey(textBox1.Text, rsaKey.privateKey);
        }
Ejemplo n.º 11
0
        public async Task Delete_UserIdIsNotSet_SetsCorrectResourceAndMethod()
        {
            var sut = new KeyRepository(_requestFactory);

            await sut.Delete(0);

            _requestFactory.Received().Create("user/keys/{id}", Method.Delete);
        }
Ejemplo n.º 12
0
        public async Task TestFindByIdReturnsNullIfNotFound()
        {
            var db         = GetDatabaseInstance();
            var repository = new KeyRepository(db);
            var key        = await repository.FindById("124");

            Assert.IsNull(key);
        }
Ejemplo n.º 13
0
        public async Task FindWithUser_ValidParameters_AddsIdUrlSegment()
        {
            const uint expected = 0;
            var        sut      = new KeyRepository(_requestFactory);

            await sut.FindWithUser(expected);

            _request.Received().AddUrlSegment("id", expected);
        }
Ejemplo n.º 14
0
        private void handleDecryptLuong(NhanVien item)
        {
            var priKey = KeyRepository.GetPrivateKey(this.nhanVienDangNhap.PubKey, password);

            if (!String.IsNullOrEmpty(priKey))
            {
                item.Luong = rsaCryptoService.Decrypt(priKey, item.Luong);
            }
        }
Ejemplo n.º 15
0
        public async Task Create_UserIdIsSet_AddsUserIdUrlSegment()
        {
            const uint expected = 0;
            var        sut      = new KeyRepository(_requestFactory);

            await sut.Create("title", "key", expected);

            _request.Received().AddUrlSegmentIfNotNull("userId", expected);
        }
Ejemplo n.º 16
0
        public async Task Create_ValidParameters_AddsTitleParameter()
        {
            const string expected = "title";
            var          sut      = new KeyRepository(_requestFactory);

            await sut.Create(expected, "key");

            _request.Received().AddParameter("title", expected);
        }
        public async Task AddKeyToFileRepositoryTest()
        {
            var keyRepository = new KeyRepository(VaultName);
            var isInserted = await keyRepository.Add(KeyWithIdentifier);
            Assert.IsTrue(isInserted);
            Assert.IsTrue(keyRepository.GetAll().Result.Count() == 1);

            var newKeyRepository = new KeyRepository(VaultName);
            Assert.IsTrue(newKeyRepository.GetAll().Result.Count() == 1);
        }
        public KeyRepositoryTests()
        {
            var contextOptions = new DbContextOptions <DataContext>();

            _contextMock = new Mock <DataContext>(contextOptions);

            _keyFactoryMock = new Mock <IKeyFactory>();

            _keyRepository = new KeyRepository(_contextMock.Object, _keyFactoryMock.Object);
        }
 private void should_have_correct_schema(string connectionString, KeyRepository keyRepository)
 {
     SchemaValidationHelpers.TableExists(_databaseFixture.TestDatabase.ConnectionString,
                                         keyRepository.Table).ShouldBeTrue();
     SchemaValidationHelpers.ColumnExists(_databaseFixture.TestDatabase.ConnectionString,
                                          keyRepository.Table, keyRepository.FriendlyNameColumn);
     SchemaValidationHelpers.ColumnExists(_databaseFixture.TestDatabase.ConnectionString,
                                          keyRepository.Table, keyRepository.IdColumn);
     SchemaValidationHelpers.ColumnExists(_databaseFixture.TestDatabase.ConnectionString,
                                          keyRepository.Table, keyRepository.XmlColumn);
 }
        public async Task AddKeyToFileRepositoryTest()
        {
            var keyRepository = new KeyRepository(VaultName);
            var isInserted    = await keyRepository.Add(KeyWithIdentifier);

            Assert.IsTrue(isInserted);
            Assert.IsTrue(keyRepository.GetAll().Result.Count() == 1);

            var newKeyRepository = new KeyRepository(VaultName);

            Assert.IsTrue(newKeyRepository.GetAll().Result.Count() == 1);
        }
Ejemplo n.º 21
0
        public async Task TestCreate()
        {
            var db         = GetDatabaseInstance();
            var repository = new KeyRepository(db);
            await repository.Save(new Key { Body = "bdy", Id = "12", Sha = "sha", CreatedAt = DateTime.Now, ShortSha = "sh" });

            var key = await repository.FindById("12");

            Assert.AreEqual(key.ShortSha, "sh");
            Assert.AreEqual(key.Sha, "sha");
            Assert.AreEqual(key.Body, "bdy");
        }
Ejemplo n.º 22
0
        public static void CadastraUsuarioDemonstracao(string nome, string email, string keyDescriptografada)
        {
            try
            {
                UsuarioRepository usuarioRepository = new UsuarioRepository();
                KeyRepository     keyRepository     = new KeyRepository();
                SaltRepository    saltRepository    = new SaltRepository();

                if (usuarioRepository.getAll().Count == 0)
                {
                    // Recupero o Salt inicial e o final
                    string salt1 = SaltService.geraSalt();
                    string salt2 = SaltService.geraSalt();

                    // Criptografo a senha
                    string KeyCriptografada = CriptografaService.GetKey(salt1, salt2, keyDescriptografada);

                    // Divido a Senha em duas partes
                    // A idéia á aumentar a segurança gravando a senha do usuário em
                    // dois locais diferentes. Preferencialmente servidores diferentes
                    string InitialKey = CriptografaService.InitialKey(KeyCriptografada);
                    string FinalKey   = CriptografaService.FinalKey(KeyCriptografada);

                    // Crio novo usuario
                    Usuario usuario = new Usuario();
                    usuario.Nome  = nome;
                    usuario.Email = email;
                    usuarioRepository.Add(usuario);

                    // Crio nova key
                    Key key = new Key();
                    key.UsuarioId = usuario.Id;
                    key.KeyString = InitialKey;
                    keyRepository.Add(key);

                    // Crio novo Salt e armazeno a parte final da key
                    Salt salt = new Salt();
                    salt.KeyId          = key.Id;
                    salt.Salt1          = salt1;
                    salt.Salt2          = salt2;
                    salt.FinalKeyString = FinalKey;

                    // A gravação do Salt e da parte final da key deveria ser realizada através
                    // de uma chamada a uma outra api, com uma credencial valida.
                    // Por motivos de tempo estou simplificando e chamando diretamente o repositório
                    saltRepository.Add(salt);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 23
0
        private void bangDiemFrmButton_Click(object sender, EventArgs e)
        {
            var         priKey = KeyRepository.GetPrivateKey(this.curNhanVien.PubKey, password);
            frmBangDiem frm    = null;

            if (!String.IsNullOrEmpty(priKey))
            {
                frm = new frmBangDiem(curNhanVien, priKey);
            }
            else
            {
                frm = new frmBangDiem();
            }
            frm.Show();
        }
Ejemplo n.º 24
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
                                                      Server.MapPath("programmingforthecloudbf-c9a8408204a8.json"));

            var cipher = KeyRepository.Encrypt("hello world");

            //string realvalue = KeyRepository.Decrypt(cipher);
            new LogsRepository().WriteLogEntry("App starting...");
        }
        public void should_store_key_in_context_configured_store()
        {
            _databaseFixture = new DatabaseFixture(true);
            var name = "SampleKey";

            var keyRepository = new KeyRepository(_databaseFixture.TestDatabase.ConnectionString);

            keyRepository.StoreElement(new XElement("Key", 1), name);

            _databaseFixture.Context.DataProtectionKeys.Count().ShouldEqual(1);

            var elements = keyRepository.GetAllElements();

            elements.Count().ShouldEqual(1);
            elements.First().Value.ShouldEqual("1");
        }
        public async Task DeleteKeyFromFileRepositoryTest()
        {
            this.Initialize();

            var keyRepository = new KeyRepository(VaultName);
            var isInserted = await keyRepository.Add(KeyWithIdentifier);
            Assert.IsTrue(isInserted);
            Assert.IsTrue(keyRepository.GetAll().Result.Count() == 1);

            var newKeyRepository = new KeyRepository(VaultName);
            Assert.IsTrue(newKeyRepository.GetAll().Result.Count() == 1);
            var isDeleted = await newKeyRepository.Delete(newKeyRepository.GetAll().Result.First());
            Assert.IsTrue(isDeleted);
            Assert.IsTrue(!newKeyRepository.GetAll().Result.Any());

            newKeyRepository = new KeyRepository(VaultName);
            Assert.IsTrue(!newKeyRepository.GetAll().Result.Any());
        }
        public void should_get_all_keys_from_repository()
        {
            _databaseFixture = new DatabaseFixture();
            var name       = "SampleKey";
            var xmlElement = new XElement("Key", 1);

            _databaseFixture.Context.DataProtectionKeys.Add(new DataProtectionKey
            {
                FriendlyName = name,
                Xml          = xmlElement.ToString()
            });
            _databaseFixture.Context.SaveChanges();

            var keyRepository = new KeyRepository(_databaseFixture.TestDatabase.ConnectionString);
            var elements      = keyRepository.GetAllElements();

            elements.Count.ShouldEqual(1);
            elements.First().Value.ShouldEqual("1");
        }
Ejemplo n.º 28
0
        public async Task TestCreateShortSha()
        {
            var db = GetDatabaseInstance();

            CleanDb(db);
            var repository = new KeyRepository(db);
            await repository.Save(new Key { Body = "key1", Id = "1", Sha = "sha_temp123", CreatedAt = DateTime.Now, ShortSha = "s" });

            await repository.Save(new Key { Body = "key2", Id = "2", Sha = "sha_temp234", CreatedAt = DateTime.Now, ShortSha = "sh" });

            await repository.Save(new Key { Body = "key3", Id = "3", Sha = "sha_temp231", CreatedAt = DateTime.Now, ShortSha = "sha" });

            await repository.Save(new Key { Body = "key4", Id = "4", Sha = "pak_test", CreatedAt = DateTime.Now, ShortSha = "p" });

            await repository.Save(new Key { Body = "key5", Id = "5", Sha = "lom", CreatedAt = DateTime.Now, ShortSha = "l" });

            var actualSha = await repository.FindNextShortSha("sna_temp232");

            Assert.AreEqual("sna_", actualSha);
        }
Ejemplo n.º 29
0
        private void xoaButton_Click(object sender, EventArgs e)
        {
            var curItem = nhanVienBindingSource.Current as NhanVien;

            if (curItem.MaNV == nhanVienDangNhap.MaNV)
            {
                MessageBox.Show("Không được xóa nhân viên đang đăng nhập");
                return;
            }

            if (curItem != null)
            {
                var result = DbLib.Delete(curItem);
                if (result != 0)
                {
                    this.ReloadGrid();
                    KeyRepository.DeleteKeyPairs(curItem.PubKey);
                }
            }
        }
Ejemplo n.º 30
0
 public static Key GetKeyByUsuarioId(long usuarioId)
 {
     try
     {
         KeyRepository keyRepository = new KeyRepository();
         Key           key           = keyRepository.getKeyByUsuario(usuarioId);
         if (key != null)
         {
             return(key);
         }
         else
         {
             throw new Exception("Key não localizada do usuário: " + usuarioId.ToString());
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Ejemplo n.º 31
0
        /// <summary> Creates a new <see cref="GitLabClient" /> instance. </summary>
        /// <param name="hostUri"> The GitLab server to connect to. </param>
        /// <param name="privateToken"> The private token to use when making requests to the GitLab API. </param>
        public GitLabClient(Uri hostUri, string privateToken = null)
        {
            if (hostUri == null)
            {
                throw new ArgumentNullException(nameof(hostUri));
            }

            var baseUri = new Uri(hostUri, ApiPath);

            _authenticator = new PrivateTokenAuthenticator(privateToken);
            var clientFactory  = new ClientFactory(baseUri, _authenticator);
            var requestFactory = new RequestFactory(clientFactory);

            Branches        = new BranchRepository(requestFactory);
            Builds          = new BuildRepository(requestFactory);
            BuildTriggers   = new BuildTriggerRepository(requestFactory);
            BuildVariables  = new BuildVariableRepository(requestFactory);
            Commits         = new CommitRepository(requestFactory);
            DeployKeys      = new DeployKeyRepository(requestFactory);
            Emails          = new EmailRepository(requestFactory);
            Files           = new FileRepository(requestFactory);
            GitLabLicense   = new GitLabLicenseRepository(requestFactory);
            GitLabSettings  = new GitLabSettingsRepository(requestFactory);
            Issues          = new IssueRepository(requestFactory);
            Keys            = new KeyRepository(requestFactory);
            Labels          = new LabelRepository(requestFactory);
            Licenses        = new LicenseRepository(requestFactory);
            MergeRequests   = new MergeRequestRepository(requestFactory);
            Milestones      = new MilestoneRepository(requestFactory);
            Namespaces      = new NamespaceRepository(requestFactory);
            ProjectSnippets = new ProjectSnippetRepository(requestFactory);
            Repositories    = new RepositoryRepository(requestFactory);
            Runners         = new RunnerRepository(requestFactory);
            Session         = new SessionRepository(requestFactory);
            SystemHooks     = new SystemHookRepository(requestFactory);
            Tags            = new TagRepository(requestFactory);
            Users           = new UserRepository(requestFactory);
            Projects        = new ProjectRepository(requestFactory);
            ProjectMembers  = new ProjectMemberRepository(requestFactory);
            GroupMembers    = new GroupMemberRepository(requestFactory);
        }
        public async Task DeleteKeyFromFileRepositoryTest()
        {
            this.Initialize();

            var keyRepository = new KeyRepository(VaultName);
            var isInserted    = await keyRepository.Add(KeyWithIdentifier);

            Assert.IsTrue(isInserted);
            Assert.IsTrue(keyRepository.GetAll().Result.Count() == 1);

            var newKeyRepository = new KeyRepository(VaultName);

            Assert.IsTrue(newKeyRepository.GetAll().Result.Count() == 1);
            var isDeleted = await newKeyRepository.Delete(newKeyRepository.GetAll().Result.First());

            Assert.IsTrue(isDeleted);
            Assert.IsTrue(!newKeyRepository.GetAll().Result.Any());

            newKeyRepository = new KeyRepository(VaultName);
            Assert.IsTrue(!newKeyRepository.GetAll().Result.Any());
        }
 public void DirectoryExistsAfterKeyRepositoryCreated()
 {
     var keyRepository = new KeyRepository(VaultName);
     Assert.IsTrue(Directory.Exists(string.Format(KeyPath, VaultName)));
 }