예제 #1
0
        public IHttpResponse FinishOrder(IHttpRequest req)
        {
            var shoppingCart = req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey);

            int  userId = req.Session.Get <int>(SessionStore.CurrentUserKey);
            User user   = default(User);

            int orderId = -10;

            HashSet <Product>      products     = shoppingCart.Orders.ToHashSet();
            HashSet <ProductOrder> mappingTable = new HashSet <ProductOrder>();

            using (var db = new ByTheCakeContext())
            {
                user = db.Users.FirstOrDefault(x => x.Id == userId);

                if (user == default(User))
                {
                    this.ViewData["error"]       = "Nice try to hack me.";
                    this.ViewData["showError"]   = "block";
                    this.ViewData["authDisplay"] = "none";

                    return(this.FileViewResponse(@"account\register"));
                }

                DateTime exactTime = DateTime.UtcNow;

                Order order = new Order()
                {
                    UserId       = user.Id,
                    User         = user,
                    CreationDate = exactTime
                };

                db.Orders.Add(order);
                db.SaveChanges();
                orderId = order.Id;

                foreach (var product in products)
                {
                    int     productId = product.Id;
                    Product productDb = db.Products.FirstOrDefault(x => x.Id == productId);

                    ProductOrder productOrder = new ProductOrder()
                    {
                        OrderId   = orderId,
                        ProductId = productId
                    };
                    order.Products.Add(productOrder);
                    productDb.Orders.Add(productOrder);
                    db.SaveChanges();
                }
            }

            req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey).Orders.Clear();

            return(this.FileViewResponse(@"shopping\finish-order"));
        }
        public IHttpResponse Add(IHttpRequest req)
        {
            string  name     = req.FormData["name"];
            decimal price    = decimal.Parse(req.FormData["price"]);
            string  imageUrl = req.FormData["imageUrl"];

            var product = new Product
            {
                Name     = name,
                Price    = price,
                ImageUrl = imageUrl
            };

            using (var context = new ByTheCakeContext())
            {
                context.Products.Add(product);
                context.SaveChanges();
            }

            this.ViewData["name"]       = name;
            this.ViewData["price"]      = price.ToString("f2");
            this.ViewData["imageUrl"]   = imageUrl;
            this.ViewData["showResult"] = "block";

            return(this.FileViewResponse(@"cakes\add"));
        }
예제 #3
0
        public IHttpResponse Register(IHttpRequest req)
        {
            const string formNameKey            = "name";
            const string formUsernameKey        = "username";
            const string formPasswordKey        = "password";
            const string formConfirmPasswordKey = "confirmpassword";

            if (!req.FormData.ContainsKey(formNameKey) ||
                !req.FormData.ContainsKey(formUsernameKey) ||
                !req.FormData.ContainsKey(formPasswordKey) ||
                !req.FormData.ContainsKey(formConfirmPasswordKey))
            {
                RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }

            var name            = req.FormData[formNameKey];
            var username        = req.FormData[formUsernameKey];
            var password        = req.FormData[formPasswordKey];
            var confirmpassword = req.FormData[formConfirmPasswordKey];

            if (string.IsNullOrWhiteSpace(name) ||
                string.IsNullOrWhiteSpace(username) ||
                string.IsNullOrWhiteSpace(password) ||
                string.IsNullOrWhiteSpace(confirmpassword))
            {
                RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }

            if (name.Length < 3 || username.Length < 3)
            {
                RejectLoginAttempt(NAME_AND_USERNAME_VALIDATION_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }


            if (password != confirmpassword)
            {
                RejectLoginAttempt(PASSWORD_MATCH_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }

            User user = new User()
            {
                Name               = name,
                Username           = username,
                PasswordHash       = PasswordUtilities.GenerateHash256(password),
                DateOfRegistration = DateTime.UtcNow
            };

            using (var context = new ByTheCakeContext())
            {
                context.Users.Add(user);
                context.SaveChanges();
            }

            return(LoginUser(req, user));
        }
        public IHttpResponse FinishOrder(IHttpRequest req)
        {
            //Register order in the database


            var currentUserId = req.Session.Get <int>(SessionStore.CurrentUserKey);

            //purvo slagame ordera
            using (var context = new ByTheCakeContext())
            {
                User currentUser  = context.Users.Find(currentUserId);
                var  shoppingCart = req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey);

                List <int> itemsIds = shoppingCart
                                      .Orders
                                      .Select(i => i.Id).ToList();

                List <Product> productItems = new List <Product>();

                foreach (var id in itemsIds)
                {
                    Product product = context.Products.Find(id);

                    productItems.Add(product);
                }


                //Suzdavam nov order
                Order order = new Order
                {
                    DateOfCreation = DateTime.UtcNow,
                    UserId         = currentUserId
                };

                context.Orders.Add(order);

                //za vseki produkt v karta suzdavam nov ProductOrder
                foreach (int id in itemsIds)
                {
                    Product item = context.Products.Find(id);

                    ProductOrder productOrder = new ProductOrder
                    {
                        Order   = order,
                        Product = item
                    };

                    context.ProductOrders.Add(productOrder);
                }

                context.SaveChanges();
            }



            req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey).Orders.Clear();

            return(this.FileViewResponse(@"shopping\finish-order"));
        }
        // Post
        public IHttpResponse Register(IHttpRequest request)
        {
            const string formNameKey            = "name";
            const string formUsernameKey        = "username";
            const string formPasswordKey        = "password";
            const string formConfirmPasswordKey = "confirm-password";

            if (!request.FormData.ContainsKey(formNameKey) ||
                !request.FormData.ContainsKey(formUsernameKey) ||
                !request.FormData.ContainsKey(formPasswordKey) ||
                !request.FormData.ContainsKey(formConfirmPasswordKey))
            {
                return(new BadRequestResponse());
            }

            string name            = request.FormData[formNameKey];
            string username        = request.FormData[formUsernameKey];
            string password        = request.FormData[formPasswordKey];
            string confirmPassword = request.FormData[formConfirmPasswordKey];

            if ((string.IsNullOrEmpty(name) || name.Length < 3) ||
                (string.IsNullOrEmpty(username) || username.Length < 3) ||
                string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(confirmPassword) ||
                password != confirmPassword)
            {
                return(new RedirectResponse("/register"));
            }

            User user = null;

            using (var context = new ByTheCakeContext())
            {
                if (context.Users.Any(u => u.Username == username))
                {
                    return(new RedirectResponse("/register"));
                }

                user = new User()
                {
                    Name             = name,
                    Username         = username,
                    PasswordHash     = PasswordUtilities.ComputeHash(password),
                    RegistrationDate = DateTime.UtcNow
                };

                context.Users.Add(user);
                context.SaveChanges();
            }

            return(CompleteLogin(request, user.Id));
        }
예제 #6
0
        public IHttpResponse AddToCart(IHttpRequest req)
        {
            if (!req.UrlParameters.ContainsKey("id"))
            {
                return(new NotFoundResponse());
            }

            var id = int.Parse(req.UrlParameters["id"]);

            using (var context = new ByTheCakeContext())
            {
                Product cake = context.Products.Find(id);

                if (cake == null)
                {
                    return(new NotFoundResponse());
                }

                var userId = req.Session.Get <int>(SessionStore.CurrentUserKey);

                var user = context.Users.Find(userId);

                var order = new Order()
                {
                    User           = user,
                    DateOfCreation = DateTime.UtcNow
                };

                var productOrder = new ProductOrder()
                {
                    Order   = order,
                    Product = cake
                };

                order.Products.Add(productOrder);
                cake.Orders.Add(productOrder);
                user.Orders.Add(order);

                context.SaveChanges();
            }

            var redirectUrl = "/search";

            const string searchTermKey = "searchTerm";

            if (req.UrlParameters.ContainsKey(searchTermKey))
            {
                redirectUrl = $"{redirectUrl}?{searchTermKey}={req.UrlParameters[searchTermKey]}";
            }

            return(new RedirectResponse(redirectUrl));
        }
        public void Create(string name, decimal price, string imageUrl)
        {
            using (var db = new ByTheCakeContext())
            {
                var product = new Product
                {
                    Name     = name,
                    Price    = price,
                    ImageUrl = imageUrl
                };

                db.Add(product);
                db.SaveChanges();
            }
        }
예제 #8
0
        internal IHttpResponse FinishOrder(IHttpRequest req)
        {
            using (var context = new ByTheCakeContext())
            {
                var userId = req.Session.Get <int>(SessionStore.CurrentUserKey);

                var orders = context.Orders
                             .Where(o => o.UserId == userId);

                var productOrders = context.ProductOrders
                                    .Where(po => orders.Any(o => o.Id == po.OrderId));

                context.Orders.RemoveRange(orders);
                context.ProductOrders.RemoveRange(productOrders);
                context.SaveChanges();
            }

            return(this.FileViewResponse(@"shopping\finish-order"));
        }
예제 #9
0
        public void CreateOrder(int userId, IEnumerable <int> productIds)
        {
            using (var db = new ByTheCakeContext())
            {
                var order = new Order
                {
                    UserId       = userId,
                    CreationDate = DateTime.UtcNow,
                    Products     = productIds
                                   .Select(id => new OrderProduct
                    {
                        ProductId = id
                    })
                                   .ToList()
                };

                db.Add(order);
                db.SaveChanges();
            }
        }
예제 #10
0
        public bool Create(string username, string password)
        {
            using (var db = new ByTheCakeContext())
            {
                if (db.Users.Any(u => u.Username == username))
                {
                    return(false);
                }

                var user = new User
                {
                    Username         = username,
                    Password         = password,
                    RegistrationDate = DateTime.UtcNow
                };

                db.Add(user);
                db.SaveChanges();

                return(true);
            }
        }
예제 #11
0
        public IHttpResponse Add(IHttpRequest req)
        {
            if (!req.FormData.ContainsKey("name") ||
                !req.FormData.ContainsKey("price"))
            {
                this.ViewData["showResult"] = "none";
                this.ViewData["error"]      = "Cakes are supposed to have name and price.";
                this.ViewData["showError"]  = "block";

                return(this.FileViewResponse(@"cakes\add"));
            }

            string  name  = req.FormData["name"];
            decimal price = decimal.Parse(req.FormData["price"]);
            string  path  = string.Empty;

            using (var db = new ByTheCakeContext())
            {
                Product cakeNameCheck = db.Products.FirstOrDefault(x => x.Name.Equals(name));

                if (cakeNameCheck != default(Product))
                {
                    this.ViewData["showResult"] = "none";
                    this.ViewData["error"]      = "Cakes must be unique.";
                    this.ViewData["showError"]  = "block";

                    return(this.FileViewResponse(@"cakes\add"));
                }
            }

            if (req.FormData.ContainsKey("path"))
            {
                path = req.FormData["path"];
            }

            var cake = new Product
            {
                Name  = name,
                Price = price
            };

            if (path != string.Empty)
            {
                cake.ImageURL = path;
            }

            using (var db = new ByTheCakeContext())
            {
                db.Products.Add(cake);
                db.SaveChanges();
            };

            this.ViewData["showResult"]  = "block";
            this.ViewData["name"]        = name;
            this.ViewData["price"]       = price.ToString("F2");
            this.ViewData["authDisplay"] = "none";
            this.ViewData["showError"]   = "none";


            return(this.FileViewResponse(@"cakes\add"));
        }
        public IHttpResponse Register(IHttpRequest req)
        {
            //slagame imenata na inputite ot formata v konstanti zashtoto  po dobre
            const string formNameKey            = "name";
            const string formUsernameKey        = "username";
            const string formPasswordKey        = "password";
            const string formConfirmPasswordKey = "confirmpassword";


            //Proverqvame dali FormData sudurja nashite kluchove ot formichkata
            if (!req.FormData.ContainsKey(formNameKey) ||
                !req.FormData.ContainsKey(formUsernameKey) ||
                !req.FormData.ContainsKey(formPasswordKey) ||
                !req.FormData.ContainsKey(formConfirmPasswordKey))
            {
                RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }

            //AKO GI IMA TRQBVA DA SUZDADEM USER V BAZATA DANNI.

            //Vzimame si stoinostite ot formichkata
            var name            = req.FormData[formNameKey];
            var username        = req.FormData[formUsernameKey];
            var password        = req.FormData[formPasswordKey];
            var confirmpassword = req.FormData[formConfirmPasswordKey];

            //Proverqvame dali ne sa null ili ""
            if (string.IsNullOrWhiteSpace(name) ||
                string.IsNullOrWhiteSpace(username) ||
                string.IsNullOrWhiteSpace(password) ||
                string.IsNullOrWhiteSpace(confirmpassword))
            {
                //Ako e tuka slagame greshkite i se redirektvame kum /register
                RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }

            if (name.Length < 3 || username.Length < 3)
            {
                RejectLoginAttempt(NAME_AND_USERNAME_VALIDATION_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }


            //Proverqvame dali parolite suvpadat
            if (password != confirmpassword)
            {
                RejectLoginAttempt(PASSWORD_MATCH_ERROR_MESSAGE);
                return(this.FileViewResponse(@"account\register"));
            }


            //Trqbva da keshirame parolata predi da registrirame daden user

            User user = new User()
            {
                Name               = name,
                Username           = username,
                PasswordHash       = PasswordUtilities.GenerateHash256(password), //keshirame parolata kato polzvame PaswordUtilities klasa
                DateOfRegistration = DateTime.UtcNow
            };


            //TRQBVA DA SLOJIM  USERA V BAZATA, POLZVAME KONTEXTA:
            using (var context = new ByTheCakeContext())
            {
                context.Users.Add(user);
                context.SaveChanges();
            }


            //Ako vsichko mine dobre, avtomatichno se logvame s imeto si kato suzdavame sesiq
            return(LoginUser(req, user));
        }
예제 #13
0
        public IHttpResponse Register(IHttpRequest req)
        {
            const string formNameKey            = "name";
            const string formUsernameKey        = "username";
            const string formPasswordKey        = "password";
            const string formConfirmPasswordKey = "confirmpassword";

            if (!req.FormData.ContainsKey(formNameKey) ||
                !req.FormData.ContainsKey(formPasswordKey) ||
                !req.FormData.ContainsKey(formConfirmPasswordKey) ||
                !req.FormData.ContainsKey(formUsernameKey))
            {
                return(new BadRequestResponse());
            }

            var name            = req.FormData[formNameKey];
            var username        = req.FormData[formUsernameKey];
            var password        = req.FormData[formPasswordKey];
            var confirmPassword = req.FormData[formConfirmPasswordKey];

            if (string.IsNullOrWhiteSpace(name) ||
                string.IsNullOrWhiteSpace(password) ||
                string.IsNullOrWhiteSpace(confirmPassword) ||
                string.IsNullOrWhiteSpace(username))
            {
                this.ViewData["error"]       = "You have empty fields";
                this.ViewData["showError"]   = "block";
                this.ViewData["authDisplay"] = "none";

                return(this.FileViewResponse(@"account\register"));
            }

            int userId = 0;

            using (ByTheCakeContext context = new ByTheCakeContext())
            {
                bool userExists = context.Users.Any(x => x.Username == username);
                if (userExists)
                {
                    this.ViewData["error"]       = "The username is taken.";
                    this.ViewData["showError"]   = "block";
                    this.ViewData["authDisplay"] = "none";

                    return(this.FileViewResponse(@"account\register"));
                }

                bool passwordsMatch = password.Equals(confirmPassword);
                if (!passwordsMatch)
                {
                    this.ViewData["error"]       = "Password do not match.";
                    this.ViewData["showError"]   = "block";
                    this.ViewData["authDisplay"] = "none";

                    return(this.FileViewResponse(@"account\register"));
                }

                User userToRegister = new User()
                {
                    Name             = name,
                    Username         = username,
                    PasswordHash     = PasswordUtilities.GenerateHash(password),
                    RegistrationDate = DateTime.Now
                };

                context.Users.Add(userToRegister);
                context.SaveChanges();

                userId = userToRegister.Id;
            }

            req.Session.Add(SessionStore.CurrentUserKey, userId);
            req.Session.Add(ShoppingCart.SessionKey, new ShoppingCart());

            return(new RedirectResponse("/"));
        }