示例#1
0
        public Account CreateAccount(string privateKey)
        {
            var password          = _authenticationService.GetPassword();
            var encryptionResults = _encryptionService.Encrypt(password, privateKey);

            var keyPair = stellar_dotnet_sdk.KeyPair.FromSecretSeed(privateKey);
            var account = new Account
            {
                EncryptedPrivateKey = encryptionResults.EncryptedBytes,
                EncryptionKeys      = encryptionResults.EncryptionKeys,
                PublicKey           = stellar_dotnet_sdk.StrKey.EncodeStellarAccountId(keyPair.PublicKey)
            };

            return(account);
        }
示例#2
0
 protected override DriverResult Editor(SinaSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
 {
     if (updater.TryUpdateModel(part, Prefix, null, null))
     {
         if (!string.IsNullOrWhiteSpace(part.ClientSecret))
         {
             part.Record.EncryptedClientSecret = _service.Encrypt(part.ClientSecret);
         }
         if (!string.IsNullOrWhiteSpace(part.Additional))
         {
             part.Record.Additional = part.Additional;
         }
     }
     return(Editor(part, shapeHelper));
 }
示例#3
0
        private async Task <Tenant> CreatePoteantialTenant(RegisterRequest registerRequest)
        {
            var tenant = new Tenant
            {
                AppName      = registerRequest.Appname.Trim(),
                Host         = registerRequest.Hostname.Trim(),
                Responsibles = new List <TenantContact>
                {
                    new TenantContact {
                        Email          = registerRequest.Email,
                        Name           = registerRequest.Name,
                        EmailConfirmed = false,
                        PasswordHash   = _encryptionService.Encrypt(registerRequest.Password),
                        Surname        = registerRequest.Surname,
                        Tokens         = new List <TenantContactToken>
                        {
                            new TenantContactToken
                            {
                                Name  = "EmailConfirmationToken",
                                Valid = true,
                                Value = Guid.NewGuid().ToString().Replace("-", string.Empty)
                            }
                        }
                    }
                },
                TenantSetting = new TenantSetting {
                    Language = "tr-TR"
                }
            };

            var tenantLicence = new TenantLicence
            {
                Tenant  = tenant,
                Licence = new Licence {
                    LicenceType = Enums.LicenceType.Trial
                }
            };

            tenant.Licences = new List <TenantLicence> {
                tenantLicence
            };

            //finally insert tenant to host database (and additional other info)
            _hostRepository.Create(tenant);
            await _hostRepository.SaveAsync();

            return(tenant);
        }
示例#4
0
        // Internal methods
        private async Task <UserEntity> LoginUser(string username, string password)
        {
            // TODO: [TESTS] (UserService.LoginUser) Add tests
            var encryptedPass = _encryptionService.Encrypt(password);
            var userEntity    = await _userRepo.GetUsingCredentials(username, encryptedPass);

            if (userEntity == null)
            {
                // TODO: [COMPLETE] (UserService.LoginUser) Complete this
                return(null);
            }

            await _userRepo.UpdateLastLoginDate(userEntity.UserId);

            return(userEntity);
        }
            public async Task SetLoginAsync(InteractionContext ctx,
                                            [Option("username", "Account Username")] string username,
                                            [Option("password", "Account Password")] string password)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new() { IsEphemeral = true });

                GuildConfig config = await guildConfig.FindOrCreateConfigAsync(ctx.Guild.Id);

                config.ApiLogin = new() { Username = username, Password = encryption.Encrypt(password) };

                await guildConfig.UpdateOneAsync(
                    Builders <GuildConfig> .Filter.Eq(c => c.Id, config.Id),
                    Builders <GuildConfig> .Update.Set(c => c.ApiLogin, config.ApiLogin));

                await ctx.FollowUpAsync($"API credentials has been set.", true);
            }
示例#6
0
        private void InternalSave(Container container, Password password)
        {
            if (container is null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            if (password is null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            using (var writeStream = _storageStreamProvider.GetWriteStream())
            {
                _encryptionService.Encrypt(password, container, writeStream);
            }
        }
示例#7
0
        public async Task <bool> Store(Guid documentId, IFormFile file)
        {
            var compressedFile = _compressionService.Compress(file);
            var encryptedFile  = _encryptionService.Encrypt(compressedFile);

            _contentTypeProvider.TryGetContentType(file.FileName, out string contentType);
            var documentContent = new DocumentContentEntity()
            {
                DocumentId = documentId,
                Content    = encryptedFile,
                Length     = encryptedFile.Length,
                Name       = file.FileName,
                Type       = contentType
            };

            return(await _repo.Store(documentContent));
        }
        /// <summary>
        /// Update mapping data and mapping file
        /// </summary>
        /// <param name="key"></param>
        /// <param name="hostname"></param>
        private void UpdateMapping(string key, string hostname)
        {
            var path = Path.Combine(Constants.IconsPath, Constants.IconsMappingFile);

            mapping.Add(key, hostname);

            try
            {
                var json          = JsonConvert.SerializeObject(mapping);
                var encryptedData = encryptionService.Encrypt(json);
                File.WriteAllText(path, encryptedData);
            }
            catch (Exception)
            {
                // Ignore
            }
        }
        public async Task <IActionResult> Upload(IFormFile file)
        {
            string[] encryptedItems;
            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);

                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Read, false))
                {
                    encryptedItems = archive.Entries.Select(e => _encryptionService.Encrypt(e.FullName)).ToArray();
                }
            }
            var jsonContent = JsonConvert.SerializeObject(encryptedItems).ToString();

            await _httpService.PostAsync("http://localhost:5001/api/values", jsonContent);

            return(RedirectToAction("Index"));
        }
示例#10
0
        public async Task <IActionResult> Post([Bind("Firstname,Lastname,Password")] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            user.Password = _crypto.Encrypt(user.Password);
            user.Username = $"{user.Lastname}{user.Firstname}";

            try
            {
                _context.User.Add(user);
            }
            catch (DbUpdateException ex)
            {
                _logger.LogError(ex, "Error adding model");
                throw;
            }
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                if (ex.InnerException != null &&
                    ex.InnerException.Message.Contains("IX_User_Username"))
                {
                    ModelState.AddModelError(
                        "Username", "Correctly failed to add duplicate user - " +
                        "if users have the same name add a number to the firstname");
                    return(BadRequest(ModelState));
                }
                else
                {
                    _logger.LogError(ex, "Failed to store new model in db");
                    throw;
                }
            }

            user.Password = null;

            return(CreatedAtAction("Index", user));
        }
 public bool SaveSettings(string password)
 {
     try
     {
         var json = JsonConvert.SerializeObject(this);
         json = _encryptionService.Encrypt(json, password);
         if (!Directory.Exists(FilePaths.ApplicationSettingsDirectory))
         {
             Directory.CreateDirectory(FilePaths.ApplicationSettingsDirectory);
         }
         File.WriteAllText(FilePaths.ApplicationSettingsPath, json);
         IsLoaded = true;
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
        public void Write(string name, string information, DateTime?expires = null, bool secure = false, bool httpOnly = false, string path = "/", string domain = null)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }

            var salt = _environment.GetRequest().Uri.DnsSafeHost;

            _environment.GetResponse().Cookies.Append(name, HttpUtility.UrlEncode(_encryptionService.Encrypt(information, salt)),
                                                      new WebEnvironmentExtensions.CookieOptions
            {
                Expires  = expires,
                Secure   = secure,
                Path     = path,
                HttpOnly = httpOnly,
                Domain   = domain
            });
        }
示例#13
0
        public string GenerateJwtToken(string merchantId, string apiKey)
        {
            // generate token that is valid for 7 days
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.JwtKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim("merchantId", merchantId),
                    new Claim("apiKey", apiKey)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(_encryptionService.Encrypt(tokenHandler.WriteToken(token)));
        }
示例#14
0
            public async Task <ICommandQueryResponse> Handle(Command request, CancellationToken cancellationToken)
            {
                var encryptedPassword = _encryptionService.Encrypt(request.Password);
                var data = _dataContext.User.Where(x => x.Username == request.Username && x.Password == encryptedPassword);

                if (data.Count() == 0)
                {
                    throw new DataNoFoundException(ExceptionMessageConstants.DataNotFound);
                }

                var user = data.ToSingleUserViewModel();

                var jwtResponse = _authenticationService.Authenticate(user, request.IpAddress);
                //Create RefreshToken
                await _mediator.Send(new CreateRefreshToken.Command {
                    RefreshTokenModel = jwtResponse.RefreshTokenModel
                });

                return(await Task.FromResult(jwtResponse));
            }
        private bool UpdateCardInfo(int type, int tickets)
        {
            if (type != 0)
            {
                return(true);
            }

            tickets--;
            byte[] cardKey          = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
            byte[] content          = GetContent(tickets.ToString());
            byte[] encriptedContent = encryptionService.Encrypt(content);

            bool result = nfcService.WriteByteBlock(13, cardKey, encriptedContent, NfcKeyType.KeyB);

            if (!result)
            {
                DisplayAlert("Error", "Error updating card", "Ok");
            }

            return(result);
        }
示例#16
0
        public async Task <byte[]> Parse(string value, PropertyType propertyType, List <ProviderPropertyAttribute> attributes)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return(new byte[0]);
            }

            attributes = attributes ?? new List <ProviderPropertyAttribute>();
            string genericType = attributes.FirstOrDefault(a => a.Name == PropertyAttribute.GenericParameter)?.Value;

            object parsedValue;

            switch (propertyType)
            {
            case PropertyType.Bool:
                parsedValue = Convert.ToBoolean(value);
                break;

            case PropertyType.Number:
                parsedValue = Convert.ToInt64(value);
                break;

            case PropertyType.Authentication:
                Type authenticatedClientType = typeof(AuthenticatedClient <>);
                authenticatedClientType = authenticatedClientType.MakeGenericType(Type.GetType(genericType));
                parsedValue             = Activator.CreateInstance(authenticatedClientType, Convert.ToInt32(value));

                ((dynamic)parsedValue).SetLoadMethod((Func <int, Task <object> >)GetAuthenticatedSessionClient);
                break;

            default:
            case PropertyType.String:
                parsedValue = value;
                break;
            }

            byte[] encryptedValue = await encryptionService.Encrypt(parsedValue);

            return(encryptedValue);
        }
示例#17
0
        public bool SendMessage(Contact destination, string content)
        {
            if (destination.PublicKey == null)
            {
                destination.PublicKey = FetchPublicKeyOfContact(destination.PhoneNumber);
                _contactRepository.UpdateContact(destination);
            }

            MessageDTO messageDTO = new MessageDTO()
            {
                SenderPhoneNumber = _phoneNumber,
                Content           = content,
                Timestamp         = DateTime.Now,
                Signature         = _encryptionService.GenerateSignature(destination.PhoneNumber)
            };

            string standard_message           = JsonConvert.SerializeObject(messageDTO);
            string encrypted_standard_message = _encryptionService.Encrypt(standard_message, destination);

            EncryptedMessage encryptedMessage = new EncryptedMessage()
            {
                Content = encrypted_standard_message,
                DestinationPhoneNumber = destination.PhoneNumber,
            };

            var guid = ServerCommunication.CreateMessage(encryptedMessage);

            Message message = new Message()
            {
                Id      = guid,
                Content = content,
                DestinationPhoneNumber = destination.PhoneNumber,
                Sender    = _contactRepository.GetSelf(),
                Timestamp = messageDTO.Timestamp
            };

            _messageRepository.AddMessage(message);

            return(true);
        }
        public async Task <IActionResult> Post([FromBody] PostPaymentRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var paymentId = Guid.NewGuid();

            try
            {
                var payment = _mapper.Map <Payment>(request);
                payment.Id         = paymentId;
                payment.CardNumber = _encryptionService.Encrypt(request.CardNumber);
                var bankRequest = _mapper.Map <BankRequest>(request);

                await _paymentRepository.AddPaymentAsync(payment);

                _logger.LogInformation($"POST - Starting request to bank for payment {payment.Id}");

                var bankResponse = await _bankRequestService.PostBankRequestAsync(bankRequest);

                payment.BankResponseId = bankResponse.Id;
                payment.PaymentStatus  = bankResponse.PaymentStatus;

                await _paymentRepository.UpdatePaymentAsync(payment);

                var postPaymentResponse = new PostPaymentResponse {
                    PaymentId = payment.Id
                };

                return(Ok(postPaymentResponse));
            }
            catch (Exception ex)
            {
                _logger.LogError($"POST - Failed due to exception ${ex.GetType()} with error ${ex.Message} for request ${paymentId}");
                return(StatusCode(500));
            }
        }
示例#19
0
        public MockUserRepository(IEncryptionService encryptionService)
        {
            _encryptionService = encryptionService;

            _userList = new List <User>()
            {
                new User()
                {
                    UserId = new Guid("20fce906-f1b9-4b33-a70a-36baefaf78ba"), UserUsername = "******", UserPassword = "******", UserFirstName = "Kate", UserLastName = "Montesdeoca", UserEmail = "*****@*****.**"
                },
                new User()
                {
                    UserId = new Guid("878ac96a-516d-47b8-8228-285c1cc71559"), UserUsername = "******", UserPassword = "******", UserFirstName = "Dalan", UserLastName = "Ienatsch", UserEmail = "*****@*****.**"
                },
                new User()
                {
                    UserId = new Guid("38238dd7-f0aa-49ed-b463-0ea064d9beae"), UserUsername = "******", UserPassword = "******", UserFirstName = "John", UserLastName = "Jones", UserEmail = "*****@*****.**"
                },
            };

            _userList.ForEach(x => x.UserPassword = _encryptionService.Encrypt(x.UserPassword));
        }
示例#20
0
        public static Wallet Create(
            IEncryptionService encryptionService,
            long walletGenerationRequestId,
            string protocolCode,
            NetworkType networkType,
            string blockchainId,
            string tenantId,
            string group)
        {
            var addressGeneratorFactory = new AddressGeneratorFactory();

            IAddressGenerator addressGenerator;

            try
            {
                addressGenerator = addressGeneratorFactory.Create(protocolCode);
            }
            catch (ArgumentOutOfRangeException exception)
            {
                throw new BlockchainIsNotSupportedException(exception);
            }

            var generatedWallet = addressGenerator.Generate(networkType);
            var privateKey      = encryptionService.Encrypt(generatedWallet.PrivateKey);

            var wallet = new Wallet(
                walletGenerationRequestId,
                blockchainId,
                DateTime.UtcNow,
                generatedWallet.Address,
                generatedWallet.PublicKey,
                privateKey,
                networkType,
                protocolCode,
                tenantId,
                group);

            return(wallet);
        }
示例#21
0
        public async Task <Token> AuthenticateAsync(
            string username, string password)
        {
            Token value = null;

            var index = await _context.User.ToListAsync();

            password = _crypto.Encrypt(password);

            var user = index
                       .Where(u => u.Username == username)
                       .Where(u => u.Password == password)
                       .FirstOrDefault();

            if (user != null)
            {
                //authentication successful so generate jwt token
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(Props.ClientSecret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.UserId.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(1),
                    SigningCredentials = new SigningCredentials(
                        new SymmetricSecurityKey(key),
                        SecurityAlgorithms.HmacSha256Signature)
                };

                var token        = tokenHandler.CreateToken(tokenDescriptor);
                var access_token = tokenHandler.WriteToken(token);
                var expires_in   = (tokenDescriptor.Expires - DateTime.Now).Value.TotalSeconds;
                value = new Token("Bearer", (int)expires_in, access_token);
            }
            return(value);
        }
        /// <summary>
        /// Converts <see cref="MailTemplate"/> to a <see cref="MailTemplateEntity"/>.
        /// </summary>
        /// <param name="mailTempalteItem">Email template item.</param>
        /// <param name="applicationName">Application associated to the notification item.</param>
        /// <param name="encryptionService">Instance of encryption service to protect the secure content before saving in datastore.</param>
        /// <returns><see cref="MailTemplateEntity"/>.</returns>
        public static MailTemplateEntity ToEntity(this MailTemplate mailTempalteItem, string applicationName, IEncryptionService encryptionService)
        {
            if (encryptionService is null)
            {
                throw new ArgumentNullException(nameof(encryptionService));
            }

            if (mailTempalteItem != null)
            {
                return(new MailTemplateEntity()
                {
                    PartitionKey = applicationName,
                    RowKey = mailTempalteItem.TemplateId,
                    Application = applicationName,
                    TemplateId = mailTempalteItem.TemplateId,
                    Description = mailTempalteItem.Description,
                    TemplateType = mailTempalteItem.TemplateType,
                    Content = encryptionService.Encrypt(mailTempalteItem.Content),
                });
            }

            return(null);
        }
示例#23
0
        public ActionResult BindingUserOauthCallback(string code)
        {
            var result = OAuthApi.GetAccessToken(appId, appSecret, code);

            if (result.errcode == 0)
            {
                User user = userService.GetUserByWeChatOpenID(result.openid);
                if (user != null)
                {
                    return(View("MessagePage", new MessagePageModel {
                        Title = "绑定成功", Message = "您已成功绑定零度云账号,请勿重复操作。"
                    }));
                }
                else
                {
                    ViewBag.WeChatSessionID = encryptionService.Encrypt(result.openid, appSecret);
                    return(View("BindingUserLogin"));
                }
            }

            return(View("MessagePage", new MessagePageModel {
                HasError = true, Title = "操作失败", Message = "绑定过程出错,请稍后再试。"
            }));
        }
示例#24
0
 public static EncryptedString Create(string value, IEncryptionService encryptionService)
 {
     return(new EncryptedString(encryptionService.Encrypt(value)));
 }
示例#25
0
        public static void EncryptValue(this IEncryptionService encryptionService, ref string stringToEncrypt, IOutgoingLogicalMessageContext context)
        {
            var encryptedValue = encryptionService.Encrypt(stringToEncrypt, context);

            stringToEncrypt = $"{encryptedValue.EncryptedBase64Value}@{encryptedValue.Base64Iv}";
        }
        /// <summary>
        /// Called by Json.NET prior to serialization
        /// </summary>
        /// <param name="target">The object instance to which the target property belongs</param>
        /// <returns>Encrypted Base64 Encoded string of the target property's original value</returns>
        public object GetValue(object target)
        {
            string decryptedString = (string)_targetProperty.GetValue(target);

            return(_encryption.Encrypt(decryptedString));
        }
 public static void EncryptValue(this IEncryptionService encryptionService, EncryptedString encryptedString, IOutgoingLogicalMessageContext context)
 {
     encryptedString.EncryptedValue = encryptionService.Encrypt(encryptedString.Value, context);
     encryptedString.Value          = null;
 }
示例#28
0
        public async Task <StatusDTO> PostFile(string file, string username, string password)
        {
            //encrypt file
            byte[] encryptedText = _encryptionService.Encrypt(file);
            //add the file to request body
            var dic = new Dictionary <string, byte[]>
            {
                { "Content", encryptedText }
            };
            var jsonContent = JsonConvert.SerializeObject(dic);
            var body        = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
            //create client
            string URI    = _config.DMS.BaseURL + "/" + _config.DMS.FileMethod;
            var    client = _clientFactory.CreateClient();

            //add authentication headers
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                       Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))));

            try
            {
                var response = await client.PostAsync(URI, body);

                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    return(new StatusDTO {
                        IsSuccess = false,
                        Message = "Invalid Username or Password"
                    });
                }

                var msg = await response.Content.ReadAsStringAsync();

                var jsonObj = JsonConvert.DeserializeAnonymousType(msg, new { Message = string.Empty, FileId = string.Empty });

                if (!string.IsNullOrEmpty(jsonObj.FileId))
                {
                    return(new StatusDTO
                    {
                        IsSuccess = true,
                        Message = string.Concat("Message from Data Management Service : ", jsonObj.Message,
                                                string.Concat("File id : ", jsonObj.FileId))
                    });
                }
                else
                {
                    return(new StatusDTO
                    {
                        IsSuccess = false,
                        Message = jsonObj.Message
                    });
                }
            }
            catch (Exception)
            {
                return(new StatusDTO
                {
                    IsSuccess = false,
                    Message = "Error connecting to Data Management Services"
                });
            }
        }
示例#29
0
 /// <summary>
 /// ConvertTo function that is used internally to convert the value of a property to its encrypted representation.
 /// Warning: this function is used internally and only public as it's tested by the unit test project.
 /// </summary>
 /// <param name="service">the encryption service</param>
 /// <param name="model">the model that should be encrypted</param>
 /// <returns>prefixed and encrypted representation of the value</returns>
 public static string ConvertTo(IEncryptionService service, TModel model)
 {
     return(WrapEncryptedString(service.Encrypt(model)));
 }
示例#30
0
        public async Task Seed()
        {
            var user = await _userManager.FindByNameAsync("admin");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "78945612",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "ItAcademy",
                        City       = "Tbilisi",
                        FirstName  = "Admin",
                        LastName   = "Adminashvili",
                        PassportId = "555777888",
                        Sex        = "Male",
                        ImageName  = "A.png"
                    },

                    LoginReports = new List <LoginReport>
                    {
                        new LoginReport
                        {
                            LastLogin     = DateTime.Now,
                            FirstLogin    = DateTime.Now,
                            AvgPerday     = 1,
                            PerMonth      = 30,
                            CounterLogsIn = 30,
                        }
                    }
                }, "asdASD123!@#");
            }
            var role = await _roleManager.FindByNameAsync("Admin");

            if (role == null)
            {
                await _roleManager.CreateAsync(new IdentityRole <int>() { Name = "Admin" });

                var createdAdmin = await _userManager.FindByNameAsync("admin");

                await _userManager.AddToRoleAsync(createdAdmin, "Admin");
            }

            user = await _userManager.FindByNameAsync("Andrii");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "14881488",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Gldanula",
                        City       = "Gldanopolis",
                        FirstName  = "Andrii",
                        LastName   = "Turianskyi",
                        PassportId = "123456789",
                        Sex        = "Male",
                        ImageName  = "A.png"
                    }
                }, "asdASD123!@#");
            }

            user = await _userManager.FindByNameAsync("Jimmy");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "197345682",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Plato",
                        City       = "JimmyWown",
                        FirstName  = "Jimmy",
                        LastName   = "Page",
                        PassportId = "1000101",
                        Sex        = "Male",
                        ImageName  = "jimmy.png"
                    }
                }, "asdASD123!@#");
            }

            user = await _userManager.FindByNameAsync("John");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "15978453",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Foreignstan",
                        City       = "Cityburg",
                        FirstName  = "John",
                        LastName   = "Bergmann",
                        PassportId = "5558888777",
                        Sex        = "Male",
                        ImageName  = "J.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Irinka");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "11111222",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Gagarini",
                        City       = "Tbilisi",
                        FirstName  = "Irinka",
                        LastName   = "Inashvili",
                        PassportId = "1000103",
                        Sex        = "Female",
                        ImageName  = "I.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Vano");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "5554445",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Vazisubani",
                        City       = "Tbilisi",
                        FirstName  = "Vano",
                        LastName   = "Tsiklauri",
                        PassportId = "1000104",
                        Sex        = "Male",
                        ImageName  = "V.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Nini");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "4448444",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Makhata",
                        City       = "Tbilisi",
                        FirstName  = "Nini",
                        LastName   = "Kurtanidze",
                        PassportId = "1000105",
                        Sex        = "Female",
                        ImageName  = "N.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Aleksandre");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "4777585",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Uznadze",
                        City       = "Tbilisi",
                        FirstName  = "Aleksandre",
                        LastName   = "Gabelashvili",
                        PassportId = "1000106",
                        Sex        = "Male",
                        ImageName  = "A.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Sergii");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "48878789",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Politkovskaya",
                        City       = "Kyiv",
                        FirstName  = "Sergii",
                        LastName   = "Kovach",
                        PassportId = "1000107",
                        Sex        = "Male",
                        ImageName  = "S.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Natali");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "8888877",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Sarajishvili",
                        City       = "Akhalkalaki",
                        FirstName  = "Natali",
                        LastName   = "Japaridze",
                        PassportId = "1000108",
                        Sex        = "Female",
                        ImageName  = "N.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Anna");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "30002001",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Guramishvili",
                        City       = "Tbilisi",
                        FirstName  = "Anna",
                        LastName   = "Zakaidze",
                        PassportId = "1000109",
                        Sex        = "Female",
                        ImageName  = "A.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Giga");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "70707080",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Marjanishvili",
                        City       = "Tbilisi",
                        FirstName  = "Giga",
                        LastName   = "Baidoshvili",
                        PassportId = "1000111",
                        Sex        = "Male",
                        ImageName  = "G.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Shota");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "125554445",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Saburtalo",
                        City       = "Tbilisi",
                        FirstName  = "Shota",
                        LastName   = "Gotsadze",
                        PassportId = "1000112",
                        Sex        = "Male",
                        ImageName  = "S.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Tamari");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "11145454",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Nojikhevi",
                        City       = "Zugdidi",
                        FirstName  = "Tamar",
                        LastName   = "Nasrashvili",
                        PassportId = "1000113",
                        Sex        = "Female",
                        ImageName  = "T.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Nana");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "99996523",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Sarajishvili",
                        City       = "Tbilisi",
                        FirstName  = "Nana",
                        LastName   = "Rogava",
                        PassportId = "1000114",
                        Sex        = "Female",
                        ImageName  = "N.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Nika");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "550040040",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Varketili",
                        City       = "Tbilisi",
                        FirstName  = "Nika",
                        LastName   = "Tsivilashvili",
                        PassportId = "1000115",
                        Sex        = "Male",
                        ImageName  = "N.png"
                    }
                }, "asdASD123!@#");
            }
            user = await _userManager.FindByNameAsync("Tatia");

            if (user == null)
            {
                await _userManager.CreateAsync(new User()
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "599797998",
                    UserInfo    = new UserInfo()
                    {
                        Address    = "Konstitucia",
                        City       = "Rustavi",
                        FirstName  = "Tatia",
                        LastName   = "Sebiskveradze",
                        PassportId = "1000116",
                        Sex        = "Female",
                        ImageName  = "T.png"
                    }
                }, "asdASD123!@#");
            }

            var existingAccounts = _context.Accounts.Where(x => x.AccountName == "johnAcc" || x.AccountName == "andriiAcc").ToList();

            if (existingAccounts != null && existingAccounts.Count != 0)
            {
                return;
            }

            _context.Database.EnsureCreated();

            var transaction = new TransactionsHistory()
            {
                Date        = DateTime.Now,
                Currency    = "USD",
                Amount      = 100,
                Description = "Sending someone some money",
            };

            var accountDeposit1 = new AccountDeposit()
            {
                Status        = Status.IsActive.ToString(),
                DepositAmount = 100,
                AccountId     = 1,
                Term          = typeof(Term).GetValues().ToArray()[0]
            };

            var accountDeposit2 = new AccountDeposit()
            {
                Status        = Status.Pending.ToString(),
                DepositAmount = 100,
                AccountId     = 2,
                Term          = typeof(Term).GetValues().ToArray()[1]
            };

            var accountDeposit3 = new AccountDeposit()
            {
                Status        = Status.Pending.ToString(),
                DepositAmount = 5000,
                AccountId     = 3,
                Term          = typeof(Term).GetValues().ToArray()[2]
            };

            _context.Deposits.Add(new Deposit()
            {
                Annual              = 20,
                Benefits            = 0,
                Bonus               = 0,
                Description         = "Some deposit",
                InterestPaymentDate = new DateTime(2000, 01, 01),
                MaxAMount           = 5000,
                MinAmount           = 200,
                Name            = "Deposit01",
                Replenishment   = 0,
                AccountDeposits = new List <AccountDeposit>
                {
                    accountDeposit1
                },
                Currency     = "USD",
                InterestRate = 3
            });

            _context.Deposits.Add(new Deposit()
            {
                Annual              = 20,
                Benefits            = 0,
                Bonus               = 0,
                Description         = "Some deposit",
                InterestPaymentDate = new DateTime(2000, 01, 01),
                MaxAMount           = 7000,
                MinAmount           = 1000,
                Name            = "Deposit02",
                Replenishment   = 0,
                AccountDeposits = new List <AccountDeposit>
                {
                    accountDeposit2
                },
                Currency     = "USD",
                InterestRate = 2
            });

            _context.Deposits.Add(new Deposit()
            {
                Annual              = 20,
                Benefits            = 0,
                Bonus               = 0,
                Description         = "Some deposit",
                InterestPaymentDate = new DateTime(2000, 01, 01),
                MaxAMount           = 2000,
                MinAmount           = 300,
                Name            = "Deposit03",
                Replenishment   = 0,
                AccountDeposits = new List <AccountDeposit>
                {
                    accountDeposit3
                },
                Currency     = "USD",
                InterestRate = 1
            });

            var accountLoan1 = new AccountLoan()
            {
                Currency   = "USD",
                Status     = Status.IsActive.ToString(),
                Sum        = 2000,
                Term       = typeof(Term).GetValues().ToArray()[1],
                Employment = "SomePosition"
            };

            var accountLoan2 = new AccountLoan()
            {
                Currency   = "USD",
                Status     = Status.Pending.ToString(),
                Sum        = 2000,
                Term       = typeof(Term).GetValues().ToArray()[2],
                Employment = "SomePosition"
            };

            var accountLoan3 = new AccountLoan()
            {
                Currency   = "USD",
                Status     = Status.Pending.ToString(),
                Sum        = 2000,
                Term       = typeof(Term).GetValues().ToArray()[0],
                Employment = "SomePosition"
            };

            _context.Accounts.Add(
                new Account()
            {
                UserId        = (await _userManager.FindByNameAsync("admin")).Id,
                AccountNumber = "123BANK123",
                AccountName   = "BankBalance",
                Balance       = 10000000000
            }
                );

            _context.Accounts.Add(
                new Account()
            {
                UserId        = (await _userManager.FindByNameAsync("Andrii")).Id,
                AccountNumber = "98745612358",
                AccountName   = "andriiAcc",
                Balance       = 200000,
                Cards         = new List <Card>
                {
                    new Card()
                    {
                        CardNumber = _encryptionService.Encrypt("5987458521365478"),
                        CCV        = 985,
                        CreatedAt  = DateTime.Now,
                        ExpireDate = DateTime.Now.AddYears(3),
                        Status     = CardStatus.Active.ToString(),
                        CardType   = "MasterCard"
                    },

                    new Card()
                    {
                        CardNumber = _encryptionService.Encrypt("5987458521365479"),
                        CCV        = 985,
                        CreatedAt  = DateTime.Now,
                        ExpireDate = DateTime.Now.AddYears(3),
                        Status     = CardStatus.Active.ToString(),
                        CardType   = "MasterCard"
                    },

                    new Card()
                    {
                        CardNumber = _encryptionService.Encrypt("5987458521365470"),
                        CCV        = 985,
                        CreatedAt  = DateTime.Now,
                        ExpireDate = DateTime.Now.AddYears(3),
                        Status     = CardStatus.Active.ToString(),
                        CardType   = "MasterCard"
                    }
                },
                AccountLoans = new List <AccountLoan>
                {
                    accountLoan1, accountLoan2
                },
                AccrueAccountLoans = new List <AccountLoan>
                {
                    accountLoan1, accountLoan3
                },
                Transactions = new List <TransactionsHistory>
                {
                    transaction
                },
                AccountDeposits = new List <AccountDeposit>
                {
                    accountDeposit3
                },
            }
                );

            _context.Accounts.Add(
                new Account()
            {
                UserId        = (await _userManager.FindByNameAsync("Jimmy")).Id,
                AccountNumber = "123456789",
                AccountName   = "JimmyAcc",
                Balance       = 10000,
                Cards         = new List <Card>
                {
                    new Card()
                    {
                        CardNumber = _encryptionService.Encrypt("5987458511365478"),
                        CCV        = 123,
                        CreatedAt  = DateTime.Now,
                        ExpireDate = DateTime.Now.AddYears(3),
                        Status     = CardStatus.Pending.ToString(),
                        CardType   = CardTypes.MasterCard.ToString()
                    },
                    new Card()
                    {
                        CardNumber = _encryptionService.Encrypt("5987458511365478"),
                        CCV        = 339,
                        CreatedAt  = DateTime.Now,
                        ExpireDate = DateTime.Now.AddYears(3),
                        Status     = CardStatus.Pending.ToString(),
                        CardType   = CardTypes.Visa.ToString()
                    },
                },
                AccountLoans = new List <AccountLoan>
                {
                    accountLoan1, accountLoan2
                },
                AccrueAccountLoans = new List <AccountLoan>
                {
                    accountLoan1, accountLoan3
                },
                Transactions = new List <TransactionsHistory>
                {
                    transaction
                },
                AccountDeposits = new List <AccountDeposit>
                {
                    accountDeposit3
                },
            }
                );

            _context.Accounts.Add(
                new Account()
            {
                UserId        = (await _userManager.FindByNameAsync("John")).Id,
                AccountNumber = "555666111222",
                AccountName   = "johnAcc",
                Balance       = 200,
                Cards         = new List <Card>
                {
                    new Card()
                    {
                        AccountId  = 1,
                        CardNumber = _encryptionService.Encrypt("2589854785986525"),
                        CCV        = 229,
                        CreatedAt  = DateTime.Now,
                        ExpireDate = DateTime.Now.AddYears(3),
                        Status     = CardStatus.Active.ToString(),
                        CardType   = "Visa"
                    }
                },
                AccountDeposits = new List <AccountDeposit>
                {
                    accountDeposit1, accountDeposit2
                },
                MoneyTransfers = new List <TransactionsHistory>
                {
                    transaction
                },
                AccountLoans = new List <AccountLoan>
                {
                    accountLoan3
                },
                AccrueAccountLoans = new List <AccountLoan>
                {
                    accountLoan2
                },
            }
                );

            _context.Loans.Add(new Loan()
            {
                Name              = "TestLoan1",
                Percentage        = 18,
                ServiceFee        = 2,
                AccidentInsurance = 0,
                InsuranceLoan     = 0,
                AccountLoans      = new List <AccountLoan>
                {
                    accountLoan1
                },
                Currency          = "USD",
                InterestRate      = 3,
                LoanInterestRate  = 3,
                RepaymentSchedule = "Monthly",
                AdvancedPayment   = "Without paying commission",
                MinAmount         = 2000,
                MaxAmount         = 5000,
                Term    = typeof(Term).GetValues().ToArray()[0],
                Purpose = typeof(LoanPurposes).GetValues().ToArray()[0]
            });

            _context.Loans.Add(new Loan()
            {
                Name              = "TestLoan2",
                Percentage        = 18,
                ServiceFee        = 2,
                AccidentInsurance = 0,
                InsuranceLoan     = 200,
                AccountLoans      = new List <AccountLoan>
                {
                    accountLoan2
                },
                Currency          = "USD",
                InterestRate      = 10,
                LoanInterestRate  = 10,
                RepaymentSchedule = "Monthly",
                AdvancedPayment   = "Without paying commission",
                MinAmount         = 3000,
                MaxAmount         = 6000,
                Term    = typeof(Term).GetValues().ToArray()[1],
                Purpose = typeof(LoanPurposes).GetValues().ToArray()[1]
            });

            _context.Loans.Add(new Loan()
            {
                Name              = "TestLoan3",
                Percentage        = 18,
                ServiceFee        = 2,
                AccidentInsurance = 0,
                InsuranceLoan     = 156,
                AccountLoans      = new List <AccountLoan>
                {
                    accountLoan3
                },
                Currency          = "USD",
                InterestRate      = 20,
                LoanInterestRate  = 20,
                RepaymentSchedule = "Monthly",
                AdvancedPayment   = "Without paying commission",
                MinAmount         = 5000,
                MaxAmount         = 100000,
                Term    = typeof(Term).GetValues().ToArray()[2],
                Purpose = typeof(LoanPurposes).GetValues().ToArray()[2]
            });

            await _context.SaveChangesAsync();
        }
示例#31
0
 /// <summary>
 /// Creates the specified value.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="encryptionService">The encryption service.</param>
 /// <returns></returns>
 public static EncryptedString Create(string value, IEncryptionService encryptionService)
 {
     return new EncryptedString(encryptionService.Encrypt(value));
 }