private async Task <SecureString> DecryptCryptoKeyAsync(string application, string tenantId, byte[] cipherTextBytes)
        {
            using (var scope = new ProfileContext($"Decrypting crypto key using kms for {application} {tenantId}"))
            {
                DecryptRequest  request   = null;
                DecryptResponse response  = null;
                bool            isSuccess = false;
                try
                {
                    request = GetDecryptRequest(application, tenantId, cipherTextBytes);

                    var client = await _kmsClientFactory.GetGlobalClientAsync();

                    response = await client.DecryptAsync(request);

                    if (response == null || response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        throw Errors.ServerSide.KMSCommunicationError();
                    }
                    isSuccess = true;
                    //PlaintText is Base64-encoded binary data
                    return(ConvertStreamToSecureString(response.Plaintext));
                }
                catch (Exception ex)
                {
                    Platform.Common.ExceptionPolicy.HandleException(ex, Constants.LogOnlyPolicy);
                }
                finally
                {
                    request.CiphertextBlob = null;
                    await LogRQRS(request, SanitizedResponse(response), application, tenantId, "aws_kms_provider", "decrypt_key", isSuccess);
                }
                throw Errors.ServerSide.KMSCommunicationError();
            }
        }
Beispiel #2
0
        public void AddNewProfile_Return_IdAndTrue()
        {
            //Arrange
            var options    = GetContextOptions();
            var newProfile = new ProfileViewModel()
            {
                Balance    = 1,
                BankBook   = Guid.NewGuid().ToString(),
                FirstName  = Guid.NewGuid().ToString(),
                LastName   = Guid.NewGuid().ToString(),
                SecondName = Guid.NewGuid().ToString(),
                Passport   = Guid.NewGuid().ToString(),
                OrgName    = Guid.NewGuid().ToString(),
                IsSeller   = false,
                OrgNumber  = Guid.NewGuid().ToString()
            };

            var guid    = string.Empty;
            var result  = string.Empty;
            var success = false;

            //Act
            using (var context = new ProfileContext(options))
            {
                IProfileService profileService = new ProfileService(context, _mapper, _rabbitMQService.Object, _scopeFactory);
                (result, success) = profileService.AddNewProfileAsync(newProfile).GetAwaiter().GetResult();

                guid = context.Profiles.FirstOrDefault().Id.ToString();
            }

            //Assert
            Assert.True(success);
            Assert.Equal(guid, result);
        }
Beispiel #3
0
 public RequestController(ProfileContext context, IHostingEnvironment hostingEnvironment, UserManager <ApplicationUser> userManager, IEmailSend emailSend)
 {
     _context = context;
     this.hostingEnvironment = hostingEnvironment;
     _userManager            = userManager;
     _emailSend = emailSend;
 }
        //we are using same stream for serialization and compression, this yields performance
        private async Task <T> DeserializeWithDecompression <T>(byte[] data, ISerializer serializer, CancellationToken cancellationToken, bool enableTraces = true)
        {
            T         response;
            Stopwatch stopwatch = null;

            if (enableTraces)
            {
                stopwatch = new Stopwatch(); stopwatch.Start();
            }
            using (var scope = new ProfileContext("session data - deserialize with decompression"))
            {
                using (var outputStream = await _memoryStreamPool.GetMemoryStream(data))
                {
                    using (var compressionStream = new DeflateStream(outputStream, CompressionMode.Decompress))
                    {
                        response = serializer.Deserialize <T>(compressionStream);
                    }
                }
            }
            if (enableTraces)
            {
                stopwatch.Stop();
                PutTimeTrace(stopwatch.ElapsedMilliseconds, "deserialize_decompression");
            }
            return(response);
        }
Beispiel #5
0
        public async Task TestProfileDataCollectionWhenProfilingDisabled()
        {
            bool disposeActionInvoked = false;

            using (new AmbientContextScope(new SampleContext()
            {
                IsProfilingEnabled = false
            }))
            {
                var container = GetContainer();

                Action <ProfileTreeNode> assertions = (profileNode) =>
                {
                    disposeActionInvoked = true;
                };

                using (var context = new ProfileContext("Sample profiling", ensureRoot: true))
                {
                    context.OnDispose += assertions;
                    await container.GetInstance <IOuter>().DoOuterStuff().ConfigureAwait(false);
                }

                Assert.False(disposeActionInvoked);
            }
        }
        public async Task HandleAsync(AccountCreatedForEmail e, IMessageContext context)
        {
            try
            {
                var      db            = new ProfileContext(_accountContext);
                Employee existEmployee = await db.Employees.Where(x => x.Email == e.Email).FirstOrDefaultAsync();

                if (existEmployee == null)
                {
                    Employee newEmployee = new Employee();
                    newEmployee.Position     = db.Positions.FirstOrDefault(p => p.PositionId == e.Position);
                    newEmployee.Email        = e.Email;
                    newEmployee.BirthDate    = e.Birthday;
                    newEmployee.PhoneNumber  = e.PhoneNumber;
                    newEmployee.FirstName    = e.FirstName;
                    newEmployee.LastName     = e.LastName;
                    newEmployee.Gender       = e.Gender;
                    newEmployee.RemainingDay = CommonConstant.RemaimDayOff;
                    db.Employees.Add(newEmployee);
                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                throw new CustomException("CREATE EMPLOYEE ERROR");
            }
        }
        public void Add(string key, string path, byte[] value)
        {
            using (var scope = new ProfileContext($"Add data bytes to S3"))
            {
                var request = GetPutObjectRequest(key, path, value);
                PutObjectResponse response = null;
                var waitHandle             = new ManualResetEvent(false);

                Task.Factory.StartNew(async() =>
                {
                    try
                    {
                        response = await _client.PutObjectAsync(request);
                    }
                    catch (Exception ex)
                    {
                        Platform.Common.ExceptionPolicy.HandleException(ex, Constants.LogOnlyPolicy);
                        throw Errors.ServerSide.S3CommunicationError();
                    }
                    finally
                    {
                        waitHandle.Set();
                    }
                });
                waitHandle.WaitOne();

                if (response.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw Errors.ServerSide.S3CommunicationError();
                }

                return;
            }
        }
        public async Task <byte[]> GetAsync(string key, string path)
        {
            try
            {
                using (var scope = new ProfileContext($"Get data bytes to S3"))
                {
                    var request = GetObjectRequest(key, path);

                    var response = await _client.GetObjectAsync(request);

                    if (response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        throw Errors.ServerSide.S3CommunicationError();
                    }

                    return(ParseResponse(response));
                }
            }
            catch (AmazonS3Exception s3Exception)
                when(s3Exception.StatusCode.Equals(HttpStatusCode.NotFound))
                {
                    Platform.Common.ExceptionPolicy.HandleException(s3Exception, Constants.LogOnlyPolicy);
                    return(null);
                }
            catch (Exception ex)
            {
                Platform.Common.ExceptionPolicy.HandleException(ex, Constants.LogOnlyPolicy);
            }
            throw Errors.ServerSide.S3CommunicationError();
        }
        void IsUserAuthorized(AuthorizationContext filtercontext)
        {
            var user = filtercontext.HttpContext.User;
            var id   = filtercontext.HttpContext.User.Identity.GetUserId(); //get user id

            if (id == null)                                                 // null value user is not logged in
            {
                //redirect to login page
                filtercontext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary {
                    { "controller", "Account" }, //account controller
                    { "action", "Login" }
                });                              //action method
                return;
            }
            ProfileContext db      = new ProfileContext();                                                                  //Access the Db at this point since this is the most overhead.
            bool?          profile = db.Profiles.Where(x => x.USERID == id).Select(x => x.PROFILECREATED).FirstOrDefault(); // get if user has created created a profile

            if (profile == null || profile == false)                                                                        //if user hasn't made a profile redirect them
            {
                //redirect to profile creation
                filtercontext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
                {
                    { "controller", "Profiles" },
                    { "action", "Create" }
                });
                return; //finish
            }
            else
            {
                return;  //user met all requirements let them go ahead
            }
        }
Beispiel #10
0
        protected void Init()
        {
            var dbContext = new DbContextOptionsBuilder <ProfileContext>().UseInMemoryDatabase("Test");

            Context = new ProfileContext(dbContext.Options);
            Context.Database.EnsureCreated();
        }
 public ProfileApiController(ProfileContext context, UserManager <ApplicationUser> userManager,
                             IProfileRepository profileRepository)
 {
     _userManager       = userManager;
     _context           = context;
     _profileRepository = profileRepository;
 }
Beispiel #12
0
        public void UpdateProfile_Return_True()
        {
            //Arrange
            var options = GetContextOptions();

            var newProfile = new ProfileModel()
            {
                Balance    = 1,
                BankBook   = "BankBook",
                FirstName  = "FirstName",
                LastName   = "LastName",
                SecondName = "SecondName",
                Passport   = "Passport",
                OrgName    = "OrgName",
                IsSeller   = false,
                OrgNumber  = "OrgNumber"
            };

            ProfileModel oldProfile;
            ProfileModel updatedProfile;

            var result = false;

            //Act
            using (var context = new ProfileContext(options))
            {
                context.Profiles.Add(newProfile);
                context.SaveChanges();

                oldProfile                = context.Profiles.AsNoTracking().LastOrDefault();
                updatedProfile            = context.Profiles.LastOrDefault();
                updatedProfile.Balance    = 2;
                updatedProfile.BankBook   = Guid.NewGuid().ToString();
                updatedProfile.FirstName  = Guid.NewGuid().ToString();
                updatedProfile.IsSeller   = true;
                updatedProfile.LastName   = Guid.NewGuid().ToString();
                updatedProfile.SecondName = Guid.NewGuid().ToString();
                updatedProfile.Passport   = Guid.NewGuid().ToString();
                updatedProfile.OrgName    = Guid.NewGuid().ToString();
                updatedProfile.OrgNumber  = Guid.NewGuid().ToString();

                var updatedProfileViewModel = _mapper.Map <ProfileViewModel>(updatedProfile);

                IProfileService profileService = new ProfileService(context, _mapper, _rabbitMQService.Object, _scopeFactory);
                result = profileService.UpdateProfileAsync(updatedProfileViewModel).GetAwaiter().GetResult();

                updatedProfile = context.Profiles.LastOrDefault();
            }

            //Assert
            Assert.True(result);
            Assert.NotEqual(oldProfile.Balance, updatedProfile.Balance);
            Assert.NotEqual(oldProfile.BankBook, updatedProfile.BankBook);
            Assert.NotEqual(oldProfile.FirstName, updatedProfile.FirstName);
            Assert.NotEqual(oldProfile.SecondName, updatedProfile.SecondName);
            Assert.NotEqual(oldProfile.LastName, updatedProfile.LastName);
            Assert.NotEqual(oldProfile.OrgName, updatedProfile.OrgName);
            Assert.NotEqual(oldProfile.OrgNumber, updatedProfile.OrgNumber);
            Assert.NotEqual(oldProfile.IsSeller, updatedProfile.IsSeller);
        }
 public ProfileController(ProfileContext context, ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient, IOptions <MicrosoftGraphOptions> graphOptions)
 {
     _context            = context;
     _tokenAcquisition   = tokenAcquisition;
     _graphServiceClient = graphServiceClient;
     _graphOptions       = graphOptions;
 }
Beispiel #14
0
 public GetProfileByEmailAddressQueryHandler(ProfileContext db)
 {
     _db = db;
     _mapperConfiguration = new MapperConfiguration(cfg =>
     {
         cfg.AddProfile <ProfileProfile>();
     });
 }
 public AddAppProfileCommandHandler(ProfileContext db)
 {
     _db = db;
     _mapperConfiguration = new MapperConfiguration(cfg =>
     {
         cfg.AddProfile <ProfileDAOProfile>();
     });
 }
 public GetAppProfileByAuthUserIdQueryHandler(ProfileContext db)
 {
     _db = db;
     _mapperConfiguration = new MapperConfiguration(cfg =>
     {
         cfg.AddProfile <ProfileProfile>();
     });
 }
Beispiel #17
0
        public void AddContext(UInt32 contextID, string name)
        {
            if (!m_Contexts.Contains(contextID))
            {
                ProfileContext context = new ProfileContext(name, contextID);

                m_Contexts[contextID] = context;
            }
        }
Beispiel #18
0
 public HomeController(ProfileContext context, UserManager <ApplicationUser> userManager,
                       SignInManager <ApplicationUser> signInManager, RoleManager <IdentityRole> roleManager, IEmailSend emailSend)
 {
     _userManager     = userManager;
     _signInManager   = signInManager;
     this.roleManager = roleManager;
     _context         = context;
     _emailSend       = emailSend;
 }
Beispiel #19
0
 public GetSubscriptionsByProfileIdQueryHandler(ProfileContext db, IMediator mediator)
 {
     _db                  = db;
     _mediator            = mediator;
     _mapperConfiguration = new MapperConfiguration(cfg =>
     {
         cfg.AddProfile <ProfileProfile>();
     });
 }
        public async Task HandleAsync(RequestForgotPasswordForEmail e, IMessageContext context)
        {
            var db = new ProfileContext(_accountContext);
            var existingProfile = db.Employees.FirstOrDefault(t => t.Email == e.Email);

            if (existingProfile != null)
            {
            }
        }
 public void Add(string application, string tenantId, string keyIdentifier, byte[] value)
 {
     using (var scope = new ProfileContext($"Add key to crypto key store: application {application} and tenant {tenantId}"))
     {
         var    client       = _storeFactory.GetGlobalClient();
         string formattedKey = ConstructKey(application, tenantId, keyIdentifier);
         string bucket       = GetBucket();
         client.Add(formattedKey, bucket, value);
     }
 }
 public byte[] Get(string application, string tenantId, string keyIdentifier)
 {
     using (var scope = new ProfileContext($"Get key from crypto key store : application {application} and tenant {tenantId}"))
     {
         var    client       = _storeFactory.GetGlobalClient();
         string formattedKey = ConstructKey(application, tenantId, keyIdentifier);
         string bucket       = GetBucket();
         return(client.Get(formattedKey, bucket));
     }
 }
Beispiel #23
0
        public void SetUp()
        {
            var settings = new ResumeDatabaseSettings {
                ConnectionString     = "mongodb://*****:*****@localhost",
                DatabaseName         = "resume",
                ResumeCollectionName = "profiles"
            };
            var factory = new MongoDbFactory();

            sut = new ProfileContext(factory, settings);
        }
Beispiel #24
0
 public UpdateAppProfileToStudentCommandHandler(ProfileContext db, IMediator mediator)
 {
     _db                  = db;
     _mediator            = mediator;
     _mapperConfiguration = new MapperConfiguration(cfg =>
     {
         cfg.AddProfile <ProfileDAOProfile>();
         cfg.CreateMap <GetAppProfileByProfileIdResult, Model.Profile>();
         cfg.CreateMap <GetAppProfileByProfileIdAppDetailsResult, AppDetails>()
         .ForMember(m => m.AccountType, opt => opt.MapFrom(source => Enum.Parse(typeof(AccountType), source.AccountType)));
     });
 }
        public async Task <byte[]> DecryptAsync(string application, string tenantId, string keyIdentifier, byte[] cipherTextBytes)
        {
            using (var scope = new ProfileContext("AesCryptoService: decrypt_async"))
            {
                Validators.ValidateDecryptRequest(application, tenantId, keyIdentifier, cipherTextBytes);
                var client = await _keyProviderFactory.GetKeyProviderAsync();

                var dataKey = await client.GetCryptoKeyAsync(application, tenantId, keyIdentifier);

                return(Decrypt(dataKey, cipherTextBytes));
            }
        }
        public string Decrypt(string application, string tenantId, string keyIdentifier, string cipherText)
        {
            using (var scope = new ProfileContext("AesCryptoService: decrypt_sync"))
            {
                Validators.ValidateDecryptRequest(application, tenantId, keyIdentifier, cipherText);
                var client    = _keyProviderFactory.GetKeyProvider();
                var dataKey   = client.GetCryptoKey(application, tenantId, keyIdentifier);
                var plainText = Decrypt(dataKey, Convert.FromBase64String(cipherText));

                return(GetStringFromBytes(plainText));
            }
        }
 public GetAppProfileByIdQueryHandler(ProfileContext db)
 {
     _db = db;
     _mapperConfiguration = new MapperConfiguration(cfg =>
     {
         cfg.AddProfile <ProfileProfile>();
         cfg.CreateMap <ProfileDAO, GetAppProfileByProfileIdResult>()
         .ForMember(m => m.AppDetails, opt => opt.MapFrom(src => src.AppDetails))
         .ForMember(m => m.PersonalDetails, opt => opt.MapFrom(src => src.PersonalDetails));
         cfg.CreateMap <AppDetailsDAO, GetAppProfileByProfileIdAppDetailsResult>()
         .ForMember(m => m.AccountType, opt => opt.MapFrom(source => Enum.GetName(typeof(AccountType), source.AccountType)));
     });
 }
        public string Encrypt(string application, string tenantId, string keyIdentifier, string plainText)
        {
            using (var scope = new ProfileContext("AesCryptoService: encrypt_sync"))
            {
                Validators.ValidateEncryptRequest(application, tenantId, keyIdentifier, plainText);
                var client     = _keyProviderFactory.GetKeyProvider();
                var dataKey    = client.GenerateCryptoKey(application, tenantId, keyIdentifier);
                var cipherText = Encrypt(dataKey, GetBytes(plainText));

                //encrypted data is in Base64 encoded returned by AWS
                return(Convert.ToBase64String(cipherText));
            }
        }
        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="profileContext">контекст.</param>
        /// <param name="mapper">профиль AutoMapper.</param>
        /// <param name="rabbitService">Сервис брокера сообщений.</param>
        /// /// <param name="scopeFactory">Фабрика для создания объектов IServiceScope.</param>
        public ProfileService(ProfileContext profileContext,
                              IMapper mapper,
                              IRabbitMQService rabbitService,
                              IServiceScopeFactory scopeFactory)
        {
            _profileContext = profileContext ?? throw new ArgumentException(nameof(profileContext));
            _mapper         = mapper ?? throw new ArgumentException(nameof(mapper));
            _rabbitService  = rabbitService ?? throw new ArgumentException(nameof(rabbitService));
            _scopeFactory   = scopeFactory ?? throw new ArgumentException(nameof(scopeFactory));

            _rabbitService.ConfigureServiceDefault();
            _rabbitService.SetListener("ProfileAPI", OnIncomingMessage);
        }
Beispiel #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseCors("AllowAllOrigins");
            app.UseStaticFiles();
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            ProfileContext.UpdateDatabase(app);
            app.UseMvc();

            var _rawRabbitClient = app.ApplicationServices.GetService <IBusClient>();

            _setupEvents(app, env);
        }