Ejemplo n.º 1
0
        public void EditLastNameOfUserShouldChangeLastName()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new BookStoreDbContext(options);

            var testUser = new BookStoreUser()
            {
                UserName = "******",
                LastName = "Simeonova"
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();



            var userServices = new UserServices(dbContext);
            var editLastName = "miss Simeonova";

            userServices.EditLastName(testUser, editLastName);

            Assert.Equal(editLastName, testUser.LastName);
        }
Ejemplo n.º 2
0
        public void GetUserOrderByIdShouldReturnOrderById()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            //

            var dbContext = new BookStoreDbContext(options);

            var _userServices = new Mock <IUserServices>();

            var user = new BookStoreUser
            {
                Id       = "2200A9B3-2622-44C3-A42F-6EBE640FFE74",
                UserName = "******"
            };

            dbContext.BookStoreUsers.Add(user);
            dbContext.SaveChanges();

            _userServices.Setup(x => x.GetUserByUsername(user.UserName)).Returns(user);
            var orderService = new OrderServices(_userServices.Object, dbContext);


            var createdOrder = orderService.CreateOrder(user.UserName);

            var getOrderByUsername = orderService.GetUserOrderById(createdOrder.Id, user.UserName);

            Assert.True(getOrderByUsername != null);
            Assert.True(getOrderByUsername.BookStoreUser.UserName == user.UserName);
        }
Ejemplo n.º 3
0
        public void CreateOrderShouldCreateOrder()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            //

            var dbContext = new BookStoreDbContext(options);

            var _userServices = new Mock <IUserServices>();


            var user = new BookStoreUser
            {
                Id       = "2200A9B3-2622-44C3-A42F-6EBE640FFE74",
                UserName = "******"
            };

            _userServices.Setup(x => x.GetUserByUsername(user.UserName)).Returns(user);

            var orderService = new OrderServices(_userServices.Object, dbContext);

            var isCreateOrder = orderService.CreateOrder(user.UserName);

            Assert.True(isCreateOrder != null);
            Assert.True(isCreateOrder.Status == OrderStatus.Processing);
        }
Ejemplo n.º 4
0
        public void TestDecriptDataShoulDecriptUcn()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            //

            var dbContext = new BookStoreDbContext(options);

            var userServices = new UserServices(dbContext);

            var testUser = new BookStoreUser()
            {
                UserName = "******",
                //For tests are use automate generate UCN from this site => https://georgi.unixsol.org/programs/egn.php?a=gen&s=0&d=0&m=0&y=0&n=5&r=0
                UCN = userServices.EncryptData("6602100531")
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();
            var userFromDbUcn = dbContext.BookStoreUsers.SingleOrDefault(x => x.UserName == "DesiUser")?.UCN;

            var isMatchrUcn = userServices.DecryptData(userFromDbUcn) == "6602100531";


            Assert.True(isMatchrUcn);
        }
Ejemplo n.º 5
0
        public void EditUsernameOfUserShouldChangeUsername()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new BookStoreDbContext(options);

            var testUser = new BookStoreUser()
            {
                UserName    = "******",
                PhoneNumber = "0897000607"
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();



            var userServices = new UserServices(dbContext);
            var editUsername = "******";

            userServices.EditUsername(testUser, editUsername);

            Assert.Equal(editUsername, testUser.UserName);
        }
Ejemplo n.º 6
0
        public void GetUserByUsernameShouldReturnNull()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new BookStoreDbContext(options);

            var testUser = new BookStoreUser()
            {
                UserName    = "******",
                PhoneNumber = "0897000607"
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();



            var userServices = new UserServices(dbContext);
            var testUsername = "******";

            var currentUser = userServices.GetUserByUsername(testUsername);

            Assert.Null(currentUser);
        }
Ejemplo n.º 7
0
        public void EditEmailOfUserShouldChangeEmail()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new BookStoreDbContext(options);

            var testUser = new BookStoreUser()
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();



            var userServices = new UserServices(dbContext);
            var editEmail    = "*****@*****.**";

            userServices.EditEmail(testUser, editEmail);

            Assert.Equal(editEmail, testUser.Email);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new BookStoreUser
                {
                    UserName     = Input.Username,
                    Email        = Input.Email,
                    ShoppingCart = new ShoppingCart()
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 9
0
        public void TestToDeleteUcnShouldSetUcnToNull()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            //

            var dbContext = new BookStoreDbContext(options);

            var userServices = new UserServices(dbContext);

            var testUser = new BookStoreUser()
            {
                UserName = "******",
                //For tests are use automate generate UCN from this site => https://georgi.unixsol.org/programs/egn.php?a=gen&s=0&d=0&m=0&y=0&n=5&r=0
                UCN = userServices.EncryptData("6602100531")
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();

            userServices.DeleteUCN(testUser);

            var isUcnOnUserIsSetToNull = testUser.UCN == null;

            Assert.True(isUcnOnUserIsSetToNull);
        }
Ejemplo n.º 10
0
        public void TestToGetUserByEncryptUcn()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            //

            var dbContext = new BookStoreDbContext(options);

            var userServices = new UserServices(dbContext);

            var testUser = new BookStoreUser()
            {
                UserName = "******",
                //For tests are use automate generate UCN from this site => https://georgi.unixsol.org/programs/egn.php?a=gen&s=0&d=0&m=0&y=0&n=5&r=0
                UCN = userServices.EncryptData("6602100531")
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();

            var testEncrUcn = "VAkZJfsiMFxQGlolWk7hBA==";
            var tempUcnB    = testUser.UCN;

            var temp = userServices.GetUserByUcn(tempUcnB);

            Assert.Equal(tempUcnB, testEncrUcn);
            Assert.True(temp != null && temp.UserName.Contains("DesiUser"));
        }
Ejemplo n.º 11
0
        public void EditLastName(BookStoreUser user, string lastName)
        {
            if (user == null)
            {
                return;
            }

            user.LastName = lastName;
            this.context.SaveChanges();
        }
Ejemplo n.º 12
0
        public void EditEmail(BookStoreUser user, string email)
        {
            if (user == null)
            {
                return;
            }

            user.Email = email;
            this.context.SaveChanges();
        }
Ejemplo n.º 13
0
        public void EditUsername(BookStoreUser user, string userName)
        {
            if (user == null)
            {
                return;
            }

            user.UserName = userName;
            this.context.SaveChanges();
        }
Ejemplo n.º 14
0
        public void EditUCN(BookStoreUser user, string ucn)
        {
            if (user == null)
            {
                return;
            }

            user.UCN = ucn;
            this.context.SaveChanges();
        }
Ejemplo n.º 15
0
        public void EditPhonenumber(BookStoreUser user, string phonenumber)
        {
            if (user == null)
            {
                return;
            }

            user.PhoneNumber = phonenumber;
            this.context.SaveChanges();
        }
Ejemplo n.º 16
0
        public static IApplicationBuilder UseDatabaseMigration(this IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetService <BookStoreDbContext>().Database.Migrate();

                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <BookStoreUser> >();

                Task
                .Run(async() =>
                {
                    var adminName = WebConstants.AdministratorRole;

                    var roleExists = await roleManager.RoleExistsAsync(adminName);

                    if (!roleExists)
                    {
                        await roleManager.CreateAsync(new IdentityRole
                        {
                            Name = adminName
                        });
                    }


                    var adminUser = await userManager.FindByNameAsync(adminName);

                    if (adminUser == null)
                    {
                        adminUser = new BookStoreUser
                        {
                            UserName     = "******",
                            Email        = "*****@*****.**",
                            ShoppingCart = new ShoppingCart()
                        };

                        var result = await userManager.CreateAsync(adminUser, "123456");

                        if (result.Succeeded)
                        {
                            await userManager.AddToRoleAsync(adminUser, WebConstants.AdministratorRole);
                        }
                    }
                })
                .GetAwaiter()
                .GetResult();
            }
            return(app);
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new BookStoreUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 18
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(BookStoreUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            //if (!IsValidUCN(Input.UCN))
            //{
            //    return BadRequest("ЕГН което въвеждаш е невалидно! Опитай пак с валидни данни.");
            //}
            if (ModelState.IsValid)
            {
                var isRoot = !_userManager.Users.Any();
                var user   = new BookStoreUser
                {
                    UserName    = Input.Username,
                    Email       = Input.Email,
                    FirstName   = Input.Firstname,
                    LastName    = Input.Lastname,
                    PhoneNumber = Input.Phonenumber,
                    //UCN = _userServices.EncryptData(Input.UCN)
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    if (isRoot)
                    {
                        await _userManager.AddToRoleAsync(user, "Admin");
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "User");
                    }
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 20
0
        public void AddAddressToUserShouldAddData()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            //
            var dbContext = new BookStoreDbContext(options);

            var user = new BookStoreUser()
            {
                FirstName = "Emo", UserName = "******"
            };

            dbContext.BookStoreUsers.Add(user);
            dbContext.SaveChanges();

            var userService = new UserServices(dbContext);

            var addressServices = new AddressesServices(dbContext, userService);

            var address = new Address()
            {
                Street         = "Beli Lom",
                Description    = "13A",
                BuildingNumber = "AA",
                City           = new City()
                {
                    Name     = "Razgrad",
                    Postcode = "7200"
                },
                Country = "BG",
            };

            addressServices.AddAddressToUser("Jaivant", address);

            var userFromDb = dbContext.BookStoreUsers.FirstOrDefault(x => x.UserName == "Jaivant")?.Addresses;
            var cityName   = userFromDb?.Select(x => x.City).ToList()[0].Name;

            Debug.Assert(cityName != null, nameof(cityName) + " != null");
            Assert.Equal(userFromDb.Count, 1);
            Assert.Equal(cityName, "Razgrad");
        }
Ejemplo n.º 21
0
        public IActionResult EditAdmin(EditUserFromDbView editUser)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = new BookStoreUser()
            {
                Email           = editUser.Email,
                NormalizedEmail = editUser.Email,

                FirstName   = editUser.FirstName,
                LastName    = editUser.Lastname,
                PhoneNumber = editUser.Phonenumber
            };


            return(this.Redirect("/Users/AllUsers"));
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new BookStoreUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Ejemplo n.º 23
0
        public void DeleteUserShouldSetUsernameFirstNameLastNameUcnPhonenumberEmailToXXX()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new BookStoreDbContext(options);

            var testUser = new BookStoreUser()
            {
                UserName    = "******",
                PhoneNumber = "0897000607",
                FirstName   = "Desi",
                LastName    = "Simeonova",
                UCN         = "VAkZJfsiMFxQGlolWk7hBA==",
                Email       = "*****@*****.**"
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();


            var userServices = new UserServices(dbContext);


            userServices.DeleteUser(testUser.Id);

            var username        = testUser.UserName == "xxx";
            var firstName       = testUser.FirstName == "xxx";
            var lastName        = testUser.LastName == "xxx";
            var phonenumberName = testUser.PhoneNumber == "xxx";
            var ucn             = testUser.UCN == "xxx";
            var email           = testUser.Email == "xxx";

            Assert.True(username);
            Assert.True(firstName);
            Assert.True(lastName);
            Assert.True(phonenumberName);
            Assert.True(ucn);
            Assert.True(email);
        }
Ejemplo n.º 24
0
        public void TestClientMetricIsReturnCorrectNotValidUcnData()
        {
            var options = new DbContextOptionsBuilder <BookStoreDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            //

            var dbContext = new BookStoreDbContext(options);

            var userServices = new UserServices(dbContext);

            //insert user in Db and Encrypt his data
            var testUser = new BookStoreUser()
            {
                UserName = "******",
                //For tests are use automate generate UCN from this site => https://georgi.unixsol.org/programs/egn.php?a=gen&s=0&d=0&m=0&y=0&n=5&r=0
                //insert not valid ucn
                UCN = userServices.EncryptData("3008015552")
            };

            dbContext.Users.Add(testUser);
            dbContext.SaveChanges();
            //Get User from Db, special her encrypt UCN
            var userFromDbUcn = dbContext.BookStoreUsers.SingleOrDefault(x => x.UserName == "DesiUser")?.UCN;
            //Decrypt ucn
            var clearUcn = userServices.DecryptData(userFromDbUcn);
            //
            var clientInfo = userServices.ClientMetric(clearUcn);

            var isValidUcn = clientInfo[0].IsValidUCN == false;
            var gender     = clientInfo[0].Gender == "n";
            var year       = clientInfo[0].Year == "n";
            var month      = clientInfo[0].Month == "n";
            var region     = clientInfo[0].Region == "n";

            Assert.True(isValidUcn);
            Assert.True(gender);
            Assert.True(year);
            Assert.True(month);
            Assert.True(region);
        }
Ejemplo n.º 25
0
        public bool EditAdmin(BookStoreUser user)
        {
            var id = user.Id;

            if (user == null)
            {
                return(false);
            }
            var userFromDn = this.context.BookStoreUsers.FirstOrDefault(x => x.Id == id);

            userFromDn.FirstName   = user.FirstName;
            userFromDn.LastName    = user.LastName;
            userFromDn.Email       = user.Email;
            userFromDn.PhoneNumber = user.PhoneNumber;



            this.context.BookStoreUsers.Update(user);
            this.context.SaveChanges();



            return(true);
        }
Ejemplo n.º 26
0
 public void DeleteUCN(BookStoreUser user)
 {
     user.UCN = null;
     this.context.SaveChanges();
 }
Ejemplo n.º 27
0
        private List <Order> GetTestOrders()
        {
            var user = new BookStoreUser
            {
                UserName     = "******",
                Email        = "*****@*****.**",
                ShoppingCart = new ShoppingCart()
            };

            return(new List <Order>()
            {
                new Order
                {
                    User = user,
                    Status = OrderStatus.Completed,
                    CompletionDate = DateTime.UtcNow.AddDays(-10),
                    OrderBooks = new List <OrderBook>
                    {
                        new OrderBook
                        {
                            Book = new Book
                            {
                                Title = "Под Игото",
                                Author = new Author
                                {
                                    FirstName = "Иван",
                                    LastName = "Вазов"
                                },
                                Publisher = new Publisher
                                {
                                    Name = "Култура"
                                },

                                Language = "български",
                                Description = "описание",
                                Image = "image",
                                Price = 6.99M,
                                CreatedOn = DateTime.UtcNow.AddDays(-10)
                            }
                        },
                        new OrderBook
                        {
                            Book = new Book
                            {
                                Title = "Науката на успеха",
                                Author = new Author
                                {
                                    FirstName = "Наполеон",
                                    LastName = "Хил"
                                },
                                Publisher = new Publisher
                                {
                                    Name = "Култура"
                                },

                                Language = "български",
                                Description = "описание",
                                Image = "image",
                                Price = 5.99M,
                                CreatedOn = DateTime.UtcNow.AddDays(-20)
                            }
                        }
                    }
                },
                new Order
                {
                    User = user,
                    Status = OrderStatus.Completed,
                    CompletionDate = DateTime.UtcNow.AddDays(-15),
                    OrderBooks = new List <OrderBook>
                    {
                        new OrderBook
                        {
                            Book = new Book
                            {
                                Title = "Под Игото",
                                Author = new Author
                                {
                                    FirstName = "Иван",
                                    LastName = "Вазов"
                                },
                                Publisher = new Publisher
                                {
                                    Name = "Култура"
                                },

                                Language = "български",
                                Description = "описание",
                                Image = "image",
                                Price = 6.99M,
                                CreatedOn = DateTime.UtcNow.AddDays(-10)
                            }
                        },
                    }
                }
            });
        }