示例#1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, [FromServices] DbGallery db)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            db.Database.EnsureDeleted();    // wipe out existing database
            db.Database.EnsureCreated();    // our database is created after this line

            new DbSeedData(db).Init();      // seed our database with data
        }
        public IActionResult Index(int productid, int rating, string review, [FromServices] DbGallery db)
        {
            string sessionId = HttpContext.Session.GetString("SessionId");

            if (sessionId == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            Session session = db.Sessions.FirstOrDefault(x => x.SessionId == sessionId);
            User    user    = db.Users.FirstOrDefault(x => x.Id == session.UserId);

            ViewData["SessionId"] = sessionId;

            db.Review.Add(new Review
            {
                UserName     = user.Name,
                MainReview   = review,
                Rating       = rating,
                DateReviewed = DateTime.Now.ToString(),
                ProductId    = productid
            });

            db.SaveChanges();

            return(RedirectToAction("Index", "ProductPg", new { productid = productid }));
        }
        public async Task Invoke(HttpContext context, DbGallery db)
        {
            string  sessionId = context.Request.Cookies["sessionId"];
            Session session   = db.Sessions.FirstOrDefault(x => x.Id.ToString() == sessionId);

            if (session != null && session.User != null)
            {
                Session currentSession = db.Sessions.FirstOrDefault(x => x.Id == Guid.Parse(sessionId));
                long    oldTimestamp   = currentSession.Timestamp;
                long    newTimestamp   = DateTimeOffset.Now.ToUnixTimeSeconds();
                if (newTimestamp - oldTimestamp > 5) // change it to 1200!!!!!!!!!!!!!!!!!!!!!!!
                {
                    db.Sessions.Remove(currentSession);
                    db.SaveChanges();
                    context.Response.Cookies.Delete("sessionId");
                    context.Response.Redirect("/Login/Index");
                    return;
                }
                else
                {
                    currentSession.Timestamp = newTimestamp;
                    db.SaveChanges();
                }
            }
            else if (session != null)
            {
                session.Timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                db.SaveChanges();
            }

            await next(context);
        }
示例#4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, DbGallery db)
        {
            app.UseDeveloperExceptionPage();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            //app.UseMiddleware<SessionChecker>();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            //!!!WARNING!!!: This is used to delete the DB if you want a clean slate
            db.Database.EnsureDeleted();

            //this makes sure that the Db is create and available on your machine/server
            db.Database.EnsureCreated();

            //this is to clean off all the ShoppingCart record that is added by Guest
            List <ShoppingCartDetail> GuestRecord = db.ShoppingCart.Where(x => x.UserId == null).ToList();

            foreach (ShoppingCartDetail item in GuestRecord)
            {
                db.ShoppingCart.Remove(item);
            }
            db.SaveChanges();

            //this is too seed data when DB is newly created and empty
            new DbSeedData(db).Init();
        }
示例#5
0
        public IActionResult Logout([FromServices] DbGallery db)
        {
            // Remove the SessionId from database
            string  guid    = HttpContext.Session.GetString("SessionId");
            Session session = db.Sessions.FirstOrDefault(x => x.SessionId == guid);

            db.Sessions.Remove(session);
            db.SaveChanges();

            // Remove the SessionId from Session Object
            HttpContext.Session.Clear();
            ViewData["SessionId"] = null;

            return(RedirectToAction("Index", "Login"));
        }
示例#6
0
        public IActionResult Auth(string email, string password, [FromServices] DbGallery db)
        {
            Debug.WriteLine($"email: {email} password: {password}");
            User user = db.Users.FirstOrDefault(x =>
                                                x.Email == email && x.Password == password);

            if (user == null)
            {
                ViewData["errMsg"] = "Email or incorrect password.";
                return(View("Index"));
            }
            else
            {
                // session goes here
                HttpContext.Session.SetString("LoggedIn", "YES");
                return(RedirectToAction("index", "home"));
            }
        }
示例#7
0
 public CheckoutController(DbGallery db)
 {
     this.db = db;
 }
示例#8
0
 public ProductPgController(DbGallery db)
 {
     this.db = db;
 }
示例#9
0
 public LoginController(DbGallery db)
 {
     this.db = db;
 }
示例#10
0
 public HomeController(ILogger <HomeController> logger, DbGallery db)
 {
     _logger = logger;
     this.db = db;
 }
示例#11
0
 public ShoppingCart(DbGallery db)
 {
     this.db = db;
 }
示例#12
0
 public RegisterController(DbGallery db)
 {
     this.db = db;
 }
示例#13
0
 public ShoppingCartController(DbGallery db)
 {
     this.db = db;
 }
示例#14
0
        public IActionResult CreateUser(string name, string email, string password, string confirmPassword, [FromServices] DbGallery db)
        {
            if (password == confirmPassword)
            {
                db.Users.Add(new User {
                    Name     = name,
                    Email    = email,
                    Password = BC.HashPassword(password)
                });

                db.SaveChanges();

                HttpContext.Session.SetString("RegisterSuccessful", "true");

                return(RedirectToAction("Index", "Login", new { FromCheckout = "false" }));
            }
            else
            {
                ViewData["RegErrMsg"] = "Password does not match";
                return(View("Index"));
            }
        }
        public IActionResult Index([FromServices] DbGallery db)
        {
            string sessionId = HttpContext.Session.GetString("SessionId");

            if (sessionId == null)
            {
                return(RedirectToAction("Index", "Login"));
            }

            Session session = db.Sessions.FirstOrDefault(x => x.SessionId == sessionId);
            User    user    = db.Users.FirstOrDefault(x => x.Id == session.UserId);

            ViewData["SessionId"] = sessionId;

            List <Order> orders = db.Orders.Where(x => x.UserId == user.Id && x.IsPaid == true).ToList();

            if (orders.Count < 0)
            {
                ViewData["acLookup"] = new Dictionary <Product, List <ActivationCode> >();
                return(View());
            }

            List <ActivationCode> acList = new List <ActivationCode>();

            foreach (Order order in orders)
            {
                List <ActivationCode> acs = db.ActivationCode.Where(x => x.OrderId == order.Id && x.IsSold == true).ToList();
                acList.AddRange(acs);
            }

            Dictionary <Order, List <Cart> > cartLookUp = new Dictionary <Order, List <Cart> >();

            foreach (Order order in orders)
            {
                List <Cart> cart = db.Cart.Where(x => x.OrderId == order.Id).ToList();
                cartLookUp.Add(order, cart);
            }

            Dictionary <Product, List <ActivationCode> > acLookUp = new Dictionary <Product, List <ActivationCode> >();

            foreach (ActivationCode ac in acList)
            {
                if (acLookUp.ContainsKey(ac.Product))
                {
                    acLookUp[ac.Product].Add(ac);
                }
                else
                {
                    acLookUp.Add(ac.Product, new List <ActivationCode> {
                        ac
                    });
                }
            }

            ViewData["Order"]      = orders;
            ViewData["acLookup"]   = acLookUp;
            ViewData["cartLookup"] = cartLookUp;

            // Display bubble using user's cart
            int   userId      = db.Sessions.FirstOrDefault(x => x.SessionId == sessionId).UserId;
            Order orderBubble = db.Orders.FirstOrDefault(x => x.UserId == userId && x.IsPaid == false);

            if (orderBubble != null)
            {
                List <Cart> cart = db.Cart.Where(x => x.OrderId == orderBubble.Id).ToList();
                ViewData["Cart"] = cart;
            }
            else
            {
                ViewData["Cart"] = null;
            }

            return(View());
        }
 public HomeController(DbGallery db)
 {
     this.db = db;
 }
示例#17
0
 public HistoryController(DbGallery db)
 {
     this.db = db;
 }
示例#18
0
        public IActionResult Auth(string email, string password, [FromServices] DbGallery db)
        {
            Debug.WriteLine($"email: {email} password: {password}");
            User user = db.Users.FirstOrDefault(x => x.Email == email);

            if (user == null)
            {
                ViewData["errMsg"] = "Email or incorrect password.";
                return(View("Index"));
            }
            string hashPassword = user.Password;
            bool   verified     = BC.Verify(password, hashPassword);

            if (verified == true)
            {
                // Give User a new SessionId
                string guid = Guid.NewGuid().ToString();
                db.Sessions.Add(new Session()
                {
                    SessionId = guid,
                    UserId    = user.Id
                });

                db.SaveChanges();

                // Get the Temp Cart
                List <string> items = new List <string>();
                int           j     = 0;
                string        item  = "initiate";
                do
                {
                    item = HttpContext.Session.GetString("Product" + Convert.ToString(j));
                    if (item == null)
                    {
                        break;
                    }
                    items.Add(item);
                    j++;
                } while (item != null);

                List <Cart> tempCart = new List <Cart>();
                foreach (string x in items)
                {
                    if (x != "removed product")
                    {
                        string[] xx = x.Split(',');
                        Cart     y  = new Cart();
                        y.ProductId = Convert.ToInt32(xx[0]);
                        y.Quantity  = Convert.ToInt32(xx[1]);
                        tempCart.Add(y);
                    }
                }

                // Get the unpaid order if it exist
                Order order = db.Orders.FirstOrDefault(x => x.UserId == user.Id && x.IsPaid == false);

                // Create new order is user don't have any order yet
                if (order == null && tempCart.Count > 0)
                {
                    db.Orders.Add(new Order
                    {
                        UserId    = user.Id,
                        OrderDate = DateTime.Now.ToString()
                    });
                    db.SaveChanges();

                    Order newOrder = db.Orders.FirstOrDefault(x => x.UserId == user.Id && x.IsPaid == false);

                    foreach (Cart toAdd in tempCart)
                    {
                        db.Cart.Add(new Cart
                        {
                            OrderId   = newOrder.Id,
                            ProductId = toAdd.ProductId,
                            Quantity  = toAdd.Quantity
                        });
                        db.SaveChanges();
                    }
                }
                // Combine with unpaid order
                else if (tempCart.Count > 0)
                {
                    // Get the current unpaid order cart
                    List <Cart> cart = db.Cart.Where(x => x.OrderId == order.Id).ToList();

                    // Get a dictionary of unpaid order cart and the productID for easy lookup later
                    Dictionary <int, Cart> lookUpTable = new Dictionary <int, Cart>();
                    foreach (Cart cartItem in cart)
                    {
                        lookUpTable.Add(cartItem.ProductId, cartItem);
                    }

                    foreach (Cart toAdd in tempCart)
                    {
                        // See if the user already has the product in his cart
                        if (lookUpTable.ContainsKey(toAdd.ProductId))
                        {
                            Cart value = lookUpTable[toAdd.ProductId];
                            // Don't allow combination if the total count is more than our stock
                            int stockCount =
                                db.ActivationCode.Where(x => x.ProductId == value.ProductId && x.IsSold == false).Count();
                            if (value.Quantity + toAdd.Quantity <= stockCount)
                            {
                                value.Quantity += toAdd.Quantity;
                                db.SaveChanges();
                            }
                            else if (value.Quantity + toAdd.Quantity > stockCount)
                            {
                                value.Quantity = stockCount;
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            db.Cart.Add(new Cart
                            {
                                OrderId   = order.Id,
                                ProductId = toAdd.ProductId,
                                Quantity  = toAdd.Quantity
                            });
                            db.SaveChanges();
                        }
                    }
                }

                Debug.WriteLine(HttpContext.Session.GetString("FromCheckout"));
                string FromCheckout = HttpContext.Session.GetString("FromCheckout");

                // Clear the old session full of temp cart
                HttpContext.Session.Clear();
                // Add sessionId
                HttpContext.Session.SetString("SessionId", guid);
                ViewData["SessionId"] = guid;

                string updateCartMessage = "";

                // Check the user's current cart for sold out items
                Order prevOrder = db.Orders.FirstOrDefault(x => x.UserId == user.Id && x.IsPaid == false);
                if (prevOrder == null)
                {
                    updateCartMessage = "false";
                }
                else
                {
                    List <Cart> updateCart = db.Cart.Where(x => x.OrderId == prevOrder.Id).ToList();
                    // For each item in cart, check if we still have stock
                    foreach (Cart toUpdate in updateCart)
                    {
                        int currentStock =
                            db.ActivationCode.Where(x => x.ProductId == toUpdate.ProductId && x.IsSold == false).Count();

                        // Remove/change the quantity based on how much stock we have left
                        if (currentStock == 0)
                        {
                            db.Cart.Remove(toUpdate);
                            updateCartMessage = "true";
                        }
                        else if (toUpdate.Quantity > currentStock)
                        {
                            toUpdate.Quantity = currentStock;
                            updateCartMessage = "true";
                        }
                        db.SaveChanges();

                        // Check if cart is empty after removing items, remove the orderid
                        if (db.Cart.FirstOrDefault(x => x.OrderId == prevOrder.Id) == null)
                        {
                            db.Orders.Remove(prevOrder);
                            db.SaveChanges();
                            updateCartMessage = "true";
                        }
                    }
                }

                HttpContext.Session.SetString("updateCartMessage", updateCartMessage);

                //redirect to view cart page if checkout button was clicked in temp cart
                Debug.WriteLine(FromCheckout);


                if (FromCheckout == "true")
                {
                    return(RedirectToAction("Index", "ShoppingCart"));
                }
                else
                {
                    return(RedirectToAction("index", "home"));
                }
            }
            else
            {
                ViewData["errMsg"] = "Email or incorrect password.";
                return(View("Index"));
            }
        }