Exemple #1
0
        public void GlobalSettingsHasHigherPriority()
        {
            // arrange
            var currentIdentity           = new CurrentIdentity();
            IGigyaModuleSettings settings = new GigyaModuleSettings
            {
                SessionTimeout   = 10,
                Language         = "abc",
                GlobalParameters = "{ \"sessionExpiration\": 123, \"lang\": \"override\", \"jkglobal\": \"hello\" }"
            };

            var pathUtility = new Mock <IPathUtilities>();

            pathUtility.Setup(i => i.ToAbsolute(It.IsAny <string>())).Returns(string.Empty);
            var settingsHelper = new Gigya.Umbraco.Module.Helpers.GigyaSettingsHelper();

            settingsHelper.PathUtilities = pathUtility.Object;

            var viewModel = settingsHelper.ViewModel(settings, null, currentIdentity);

            Assert.AreEqual(123, viewModel.Settings.sessionExpiration, "sessionExpiration doesn't match global params");

            Assert.AreEqual("override", viewModel.Settings.lang, "lang doesn't match global params");
            Assert.AreEqual("hello", viewModel.Settings.jkglobal, "global param doesn't exist or match in settings object");
        }
Exemple #2
0
 public bool Load(string dataSource)
 {
     try
     {
         loaded = true;
         deletedRows.Clear();
         sales.Clear();
         salePoss.Clear();
         saleId               = CurrentIdentity.Get(dataSource, "Sale");
         salePosId            = CurrentIdentity.Get(dataSource, "SalePos");
         csBuilder.DataSource = dataSource;
         goodRepository.Connect(dataSource);
         saleDataAdapter    = new SqlDataAdapter(@"select * from Sale", csBuilder.ConnectionString);
         salePosDataAdapter = new SqlDataAdapter(@"select * from SalePos", csBuilder.ConnectionString);
         SqlCommandBuilder builder = new SqlCommandBuilder(saleDataAdapter);
         builder = new SqlCommandBuilder(salePosDataAdapter);
         saleDataAdapter.Fill(sales);
         salePosDataAdapter.Fill(salePoss);
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
        public async Task <IHttpActionResult> DeleteShopConfiguration(long id)
        {
            CurrentIdentity identity = getIdentity();

            if (identity.role == "Admin")
            {
            }
            else
            {
                Shop shop = await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId);

                if (shop == null)
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
                }

                if (shop.Id != id)
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
                }
            }

            ShopConfiguration shopConfiguration = await db.ShopConfigurations.FindAsync(id);

            if (shopConfiguration == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            db.ShopConfigurations.Remove(shopConfiguration);
            await db.SaveChangesAsync();

            return(Ok(shopConfiguration));
        }
        public async Task <IHttpActionResult> GetOrder(long id)
        {
            CurrentIdentity identity = getIdentity();

            Order order = await db.Orders.FindAsync(id);

            if (order == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            if (identity.role == "Admin")
            {
                return(Ok(order));
            }
            else
            {
                long shopId = ((Shop)await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId)).Id;
                if (order.ShopId == shopId)
                {
                    return(Ok(order));
                }
                else
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
                }
            }
        }
        public async Task <IHttpActionResult> DeleteCustomer(long id)
        {
            CurrentIdentity identity = getIdentity();
            Customer        customer = await db.Customers.FindAsync(id);

            if (customer == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            if (identity.role == "Admin")
            {
                db.Customers.Remove(customer);
                await db.SaveChangesAsync();

                return(Ok(customer));
            }
            else
            {
                long shopId = ((Shop)await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId)).Id;
                if (customer.ShopId == shopId)
                {
                    db.Customers.Remove(customer);
                    await db.SaveChangesAsync();

                    return(Ok(customer));
                }
                else
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
                }
            }
        }
        public virtual ActionResult Index()
        {
            var settings = _settingsHelper.GetForCurrentSite();

            if (!settings.EnableRaas)
            {
                if (settings.DebugMode)
                {
                    _logger.Debug("RaaS disabled so GigyaSettings not added to page.");
                }
                return(new EmptyResult());
            }

            if (string.IsNullOrEmpty(settings.ApiKey))
            {
                _logger.Error("Gigya API key not specified. Umbraco -> Gigya");
                return(new EmptyResult());
            }

            var currentIdentity = new CurrentIdentity
            {
                IsAuthenticated = User.Identity.IsAuthenticated,
                Name            = User.Identity.Name
            };

            var viewModel = _settingsHelper.ViewModel(settings, Url, currentIdentity);

            // umbraco doesn't use web forms so the script will always be rendered inline
            viewModel.RenderScript = true;

            var viewPath = "~/Views/GigyaSettings/Index.cshtml";

            return(View(viewPath, viewModel));
        }
        public async Task <IHttpActionResult> GetCustomerOrders(long id)
        {
            CurrentIdentity identity = getIdentity();

            if (identity.role == "Admin")
            {
                return(Ok(await db.Orders.Where(p => p.CustomerId == id).ToListAsync()));
            }
            else
            {
                Customer customer = await db.Customers.FindAsync(id);

                if (customer == null)
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
                }
                long shopId = ((Shop)await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId)).Id;
                if (customer.ShopId == shopId)
                {
                    List <Order> orders = new List <Order>();
                    orders = await db.Orders.Where(p => p.CustomerId == id).ToListAsync();

                    return(Ok(orders));
                }
                else
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
                }
            }
        }
Exemple #8
0
        public override bool CanExecute(object data)
        {
            var result = CurrentIdentity != null && CurrentIdentity.IsAdmininistrator();

            this.Reason = result ? CommonCommandsResources.ElevatedModeCommand_Error : string.Empty;
            return(result);
        }
        protected virtual void UpdateSessionExpirationCookie(HttpContext context, CurrentIdentity currentIdentity, bool isLoggingIn)
        {
            if (!IsDynamicSessionExtensionRequired(context, isLoggingIn))
            {
                return;
            }

            var gigyaAuthCookie = context.Request.Cookies["glt_" + _settings.ApiKey];

            if (gigyaAuthCookie == null || string.IsNullOrEmpty(gigyaAuthCookie.Value))
            {
                if (currentIdentity.IsAuthenticated)
                {
                    // not logged into gigya so sign out of CMS
                    _membershipHelper.Logout();
                }
                return;
            }

            var cookie            = new HttpCookie("gltexp_" + _settings.ApiKey);
            var sessionExpiration = _settingsHelper.SessionExpiration(_settings);

            cookie.Expires = DateTime.UtcNow.AddYears(10);

            var gigyaAuthCookieSplit = HttpUtility.UrlDecode(gigyaAuthCookie.Value).Split('|');
            var loginToken           = gigyaAuthCookieSplit[0];

            cookie.Value = GigyaSignatureHelpers.GetDynamicSessionSignatureUserSigned(loginToken, sessionExpiration, _settings.ApplicationKey, _settings.ApplicationSecret);
            cookie.Path  = "/";
            context.Response.Cookies.Set(cookie);
        }
Exemple #10
0
        public void FallbackLanguageUsedForAutoButUnsupportedLanguage()
        {
            // arrange
            var culture = new CultureInfo("tt");

            Thread.CurrentThread.CurrentUICulture = culture;

            var currentIdentity           = new CurrentIdentity();
            IGigyaModuleSettings settings = new GigyaModuleSettings
            {
                SessionTimeout   = 10,
                Language         = "auto",
                LanguageFallback = "fr"
            };

            var pathUtility = new Mock <IPathUtilities>();

            pathUtility.Setup(i => i.ToAbsolute(It.IsAny <string>())).Returns(string.Empty);
            var settingsHelper = new Gigya.Umbraco.Module.Helpers.GigyaSettingsHelper();

            settingsHelper.PathUtilities = pathUtility.Object;

            var viewModel = settingsHelper.ViewModel(settings, null, currentIdentity);

            Assert.AreEqual("fr", viewModel.Settings.lang, "Language should be fr");
        }
Exemple #11
0
        public async Task <IHttpActionResult> GetOwnShopProducts()
        {
            CurrentIdentity identity = getIdentity();
            Shop            shop     = await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId);

            if (shop == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            ShopProducts shopOut = new ShopProducts();

            shopOut.Id              = shop.Id;
            shopOut.UserId          = shop.UserId;
            shopOut.Title           = shop.Title;
            shopOut.Description     = shop.Description;
            shopOut.DescriptionFull = shop.DescriptionFull;
            shopOut.Views           = shop.Views;
            shopOut.IsActive        = shop.IsActive;
            shopOut.CreatedAt       = shop.CreatedAt;
            shopOut.UpdatedAt       = shop.UpdatedAt;

            shopOut.Products = new List <ProductOut>();
            IList <Product> productsInShop = new List <Product>();

            productsInShop = await db.Products.Where(p => p.ShopId == shop.Id).ToListAsync();

            foreach (var product in productsInShop)
            {
                shopOut.Products.Add(await GetProductsForShop(product.Id));
            }

            return(Ok(shopOut));
        }
        /// <summary>
        /// Logs a user into Gigya by calling NotifyLogin.
        /// </summary>
        /// <param name="currentIdentity"></param>
        public override void LoginToGigyaIfRequired()
        {
            if (!_settings.EnableRaas)
            {
                _logger.Error("RaaS not enabled.");
                return;
            }

            if (_settings.SessionProvider != GigyaSessionProvider.CMS)
            {
                return;
            }

            var identity        = ClaimsManager.GetCurrentIdentity();
            var currentIdentity = new CurrentIdentity
            {
                IsAuthenticated = identity.IsAuthenticated,
                Name            = identity.Name,
                UID             = identity.Name
            };

            var cookieName = "glt_" + _settings.ApiKey;

            if (!currentIdentity.IsAuthenticated || HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                // user not logged in
                return;
            }

            // get UID if not the username
            var uidMapping = _settings.MappedMappingFields.FirstOrDefault(i => i.GigyaFieldName == Constants.GigyaFields.UserId && !string.IsNullOrEmpty(i.CmsFieldName));

            if (uidMapping != null && uidMapping.CmsFieldName != Constants.SitefinityFields.UserId)
            {
                // get member to find UID field
                var userManager = UserManager.GetManager();
                var currentUser = userManager.GetUser(identity.UserId);
                if (currentUser == null)
                {
                    _logger.Error(string.Format("Couldn't find member with username of {0} so couldn't sign them in.", currentIdentity.Name));
                    return;
                }

                var profileManager = UserProfileManager.GetManager();
                var profile        = profileManager.GetUserProfile <SitefinityProfile>(currentUser);
                if (profile == null)
                {
                    _logger.Error(string.Format("Couldn't find profile for member with username of {0} so couldn't sign them in.", currentIdentity.Name));
                    return;
                }

                currentIdentity.UID = profile.GetValue <string>(uidMapping.CmsFieldName);
            }

            // user logged into Umbraco but not Gigya so call notifyLogin to sign in
            LoginToGigya(currentIdentity);
        }
Exemple #13
0
        public async Task <IHttpActionResult> DeleteShop(long id)
        {
            CurrentIdentity identity = getIdentity();
            Shop            shop     = await db.Shops.FindAsync(id);

            if (shop == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }


            if (identity.userId == shop.UserId || identity.role == "Admin")
            {
                List <Product> products = await db.Products.Where(p => p.ShopId == id).ToListAsync();

                //Delete all products in shop
                if (products != null)
                {
                    foreach (var product in products)
                    {
                        IList <Image> images = await db.Images.Where(p => p.ProductId == product.Id).ToListAsync();

                        IList <ProductsToCategory> categories = await db.ProductsToCategories.Where(p => p.ProductId == product.Id).ToListAsync();

                        ShopConfiguration shopConfig = await db.ShopConfigurations.FindAsync(id);

                        //Delete shop config if it exsists
                        if (shopConfig != null)
                        {
                            db.ShopConfigurations.Remove(shopConfig);
                            await db.SaveChangesAsync();
                        }

                        db.Products.Remove(product);
                        await db.SaveChangesAsync();

                        foreach (var image in images)
                        {
                            db.Images.Remove(image);
                        }
                        foreach (var category in categories)
                        {
                            db.ProductsToCategories.Remove(category);
                        }
                        await db.SaveChangesAsync();
                    }
                }

                db.Shops.Remove(shop);
                await db.SaveChangesAsync();

                return(Ok(shop));
            }
            return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
        }
Exemple #14
0
        public async Task <IHttpActionResult> GetOwnShop()
        {
            CurrentIdentity identity = getIdentity();
            Shop            shop     = await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId);

            if (shop == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            return(Ok(shop));
        }
        private CurrentIdentity getIdentity()
        {
            var identity = (ClaimsIdentity)User.Identity;
            IEnumerable <Claim> claims  = identity.Claims;
            string          userId      = claims.FirstOrDefault(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
            string          role        = claims.FirstOrDefault(p => p.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Value;
            CurrentIdentity identityOut = new CurrentIdentity();

            identityOut.userId = userId;
            identityOut.role   = role;
            return(identityOut);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            var service = new Controller();
//            UserDto userDto = service.login("nguyenbh", "nguyenbh");
//            Console.Out.WriteLine("login message: " + userDto.Message);
//            userDto = service.login("nguyenbh", "123456");
//            Console.Out.WriteLine("login Name: " + userDto.UserName);
//            string result = service.changePassword("nguyenbh", "nguyenbh", "123456", "123456");
//            Console.Out.WriteLine("changePassword code: " + result);
//            result = service.changePassword("nguyenbh", "123456", "123456", "123456");
//            Console.Out.WriteLine("changePassword code: " + result);
//            result = service.changePassword("nguyenbh", "123456", "nguyenbh", "nguyenbh");
//            Console.Out.WriteLine("changePassword code: " + result);
//            result = service.changePassword("nguyenbh", "nguyenbh", "123456", "123456");
//            Console.Out.WriteLine("changePassword code: " + result);
//            result = service.CreateUserAdmin("NGUYENHAIMINH03", "Nguyen Hai Minh", "QTHT", "NGUYENBH");
//            Console.Out.WriteLine("CreateUserAdmin code: " + result);
//            var test = "nguyenvana";
//            test = test + Char.ToString((char) ('a' + 1));
//            Console.Out.WriteLine("  " + test);
//            var strThang = DateUtil.GetDateTimeAsStringWithEnProvider(DateTime.Now, ConstUtil.MONTH_FORMAT);
//            Console.Out.WriteLine("  " + strThang);
//            var result = service.SearchBangKeExt(2, DateTime.Now.AddMonths(-2), DateTime.Now);
//            Console.Out.WriteLine("SearchBangKe code: " + result);
//            var text = String.Format("{0:yyyyMMddHHmmssfff}", DateTime.Now);
//            Console.Out.WriteLine("  " + text);
//            var allMemberInfos = service.RetrieveAll<MemberInfo>();
//            foreach (var memberInfo in allMemberInfos)
//            {
//                memberInfo.HoTenKd = VnStringHelper.toEnglish(memberInfo.HoTen);
//                service.Save(memberInfo);
//            }
//            var returnCode = service.CreateUser("", "", "Trần Thị Hương", null, "011405182", null, "", "", "", "", "",
//                                                "", "NGUYENBH");
//            Console.Out.WriteLine("CreateUser code: " + returnCode);
//            var result = service.SearchMemberNodeDto("");
//            Console.Out.WriteLine("SearchBangKe code: " + result);

//            long intervalTime;
//            if (!long.TryParse(ParameterUtil.GetParameter("IntervalTime"), out intervalTime))
//            {
//                intervalTime = 300000; //every 10 minutes
//            }
//            service.CalculateAccountLog();
//            service.CalculateBonusOfAccountTree();
//            service.CalculateBonusOfManagerTree();
//            Thread.Sleep((int) intervalTime);
//            Console.Out.Write(".");
            CurrentIdentity currentIdentity = service.GetCurrentIdentity("ACCOUNT");

            Console.Out.WriteLine("CurrentIdentity: " + currentIdentity);
        }
        public async Task <IHttpActionResult> PostShopConfiguration(ShopConfiguration shopConfiguration)
        {
            CurrentIdentity identity = getIdentity();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (identity.role == "Admin")
            {
            }
            else
            {
                Shop shop = await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId);

                if (shop == null)
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
                }

                if (shop.Id != shopConfiguration.ShopId)
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
                }
            }

            if (shopConfiguration.LayoutId < 0)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.BadRequest)));
            }

            db.ShopConfigurations.Add(shopConfiguration);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ShopConfigurationExists(shopConfiguration.ShopId))
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Conflict)));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("WSApi", new { id = shopConfiguration.ShopId }, shopConfiguration));
        }
        public virtual ActionResult Index()
        {
            if (SystemManager.IsDesignMode || SystemManager.IsPreviewMode)
            {
                return(new EmptyResult());
            }

            var settings = _settingsHelper.GetForCurrentSite(true);

            if (!settings.EnableRaas)
            {
                if (settings.DebugMode)
                {
                    _logger.Debug("RaaS disabled so GigyaSettings not added to page.");
                }
                return(new EmptyResult());
            }

            if (string.IsNullOrEmpty(settings.ApiKey))
            {
                _logger.Error("Gigya API key not specified. Check settings on Administration -> Settings -> Gigya");
                return(new EmptyResult());
            }

            // check if Sitefinity is the session leader and sign in if required
            GigyaAccountHelper.ProcessRequestChecks(System.Web.HttpContext.Current, settings);

            var identity        = ClaimsManager.GetCurrentIdentity();
            var currentIdentity = new CurrentIdentity
            {
                IsAuthenticated = identity.IsAuthenticated,
                Name            = identity.Name
            };

            var viewModel = _settingsHelper.ViewModel(settings, Url, currentIdentity);

            viewModel.ErrorMessage = Res.Get(Constants.Resources.ClassId, Constants.Resources.ErrorMessage);
            Page pageHandler = HttpHandlerExtensions.GetPageHandler(HttpContext.CurrentHandler);

            // check if the widget is being rendered through Sitefinity or directly from the Razor view
            viewModel.RenderScript = pageHandler == null || pageHandler.Header == null || pageHandler.Header.Controls == null;

            if (!viewModel.RenderScript)
            {
                var script = this.GetScript(viewModel);
                pageHandler.Header.Controls.Add((Control) new LiteralControl(script));
            }

            var viewPath = FileHelper.GetPath("~/Mvc/Views/GigyaSettings/Index.cshtml", ModuleClass.ModuleVirtualPath + "Gigya.Module.Mvc.Views.GigyaSettings.Index.cshtml");

            return(View(viewPath, viewModel));
        }
Exemple #19
0
        public async Task <IHttpActionResult> PostShop(Shop shop)
        {
            if (ShopTitleExists(shop.Title))
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.Conflict)));
            }

            CurrentIdentity identity = getIdentity();

            if ((await db.Shops.CountAsync(p => p.UserId == identity.userId)) > 0)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.Forbidden)));
            }

            Shop newShop = new Shop();

            newShop.UserId          = identity.userId;
            newShop.Title           = shop.Title;
            newShop.Description     = shop.Description;
            newShop.DescriptionFull = shop.DescriptionFull;
            newShop.Views           = 0;
            newShop.IsActive        = 0;
            DateTime now = DateTime.Now;

            newShop.CreatedAt = now;
            newShop.UpdatedAt = now;

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Shops.Add(newShop);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ShopExists(newShop.Id))
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Conflict)));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("WSApi", new { id = newShop.Id }, newShop));
        }
Exemple #20
0
        // GET: /Shops
        public IQueryable <Shop> GetShops()
        {
            CurrentIdentity identity = getIdentity();

            if (identity.role == "Admin")
            {
                return(db.Shops);
            }
            else
            {
                return(db.Shops.Where(p => p.IsActive == 1));
            }
        }
        // GET: /Categories
        public IQueryable <Category> GetCategories()
        {
            CurrentIdentity identity = getIdentity();

            if (identity.role == "Admin")
            {
                return(db.Categories);
            }
            else
            {
                return(db.Categories.Where(p => p.IsActive == 1));
            }
        }
Exemple #22
0
        /// <summary>
        ///     Überprüft, ob der übergebene Domain-Nutzer der aktuell am System angemeldete Nutzer ist.
        ///     TODO: Was wenn Impersonifizierung aktiv ist?
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool IsCurrentUser(User user)
        {
            if (user == null)
            {
                return(false);
            }

            if (CurrentIdentity == null)
            {
                return(false);
            }

            return(user.BusinessId.ToString() == CurrentIdentity.GetUserId <string>());
        }
Exemple #23
0
        public async Task Ban(
            [Summary("title", "The title of the modcase")] string title,
            [Summary("user", "User to punish")] IUser user,
            [Choice("None", 0)]
            [Choice("1 Hour", 1)]
            [Choice("1 Day", 24)]
            [Choice("1 Week", 168)]
            [Choice("1 Month", 672)]
            [Summary("hours", "How long the punishment should be")] long punishedForHours             = 0,
            [Summary("description", "The description of the modcase")] string description             = "",
            [Summary("dm-notification", "Whether to send a dm notification")] bool sendDmNotification = true,
            [Summary("public-notification", "Whether to send a public webhook notification")] bool sendPublicNotification    = true,
            [Summary("execute-punishment", "Whether to execute the punishment or just register it.")] bool executePunishment = true)
        {
            await Context.Interaction.DeferAsync(ephemeral : !sendPublicNotification);

            ModCase modCase = new()
            {
                Title   = title,
                GuildId = Context.Guild.Id,
                UserId  = user.Id,
                ModId   = CurrentIdentity.GetCurrentUser().Id
            };

            if (string.IsNullOrEmpty(description))
            {
                modCase.Description = title;
            }
            else
            {
                modCase.Description = description;
            }
            modCase.PunishmentType   = PunishmentType.Ban;
            modCase.PunishmentActive = executePunishment;
            modCase.PunishedUntil    = DateTime.UtcNow.AddHours(punishedForHours);
            if (punishedForHours == 0)
            {
                modCase.PunishedUntil = null; // Permanent ban.
            }
            modCase.CreationType = CaseCreationType.ByCommand;

            ModCase created = await ModCaseRepository.CreateDefault(ServiceProvider, CurrentIdentity).CreateModCase(modCase, executePunishment, sendPublicNotification, sendDmNotification);

            string url = $"{Config.GetBaseUrl()}/guilds/{created.GuildId}/cases/{created.CaseId}";
            await Context.Interaction.ModifyOriginalResponseAsync((MessageProperties msg) =>
            {
                msg.Content = Translator.T().CmdPunish(created.CaseId, url);
            });;
        }
    }
        public IQueryable <Order> GetOrders()
        {
            CurrentIdentity identity = getIdentity();

            if (identity.role == "Admin")
            {
                return(db.Orders);
            }
            else
            {
                long shopId = ((Shop)db.Shops.FirstOrDefault(p => p.UserId == identity.userId)).Id;
                return(db.Orders.Where(p => p.ShopId == shopId));
            }
        }
        public async Task <IHttpActionResult> GetOwnOrders()
        {
            CurrentIdentity identity = getIdentity();
            long            shopId   = (await db.Shops.Where(p => p.UserId == identity.userId).FirstOrDefaultAsync()).Id;

            List <Order> orders = await db.Orders.Where(p => p.ShopId == shopId).ToListAsync();

            if (orders == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            return(Ok(orders));
        }
Exemple #26
0
        private void ExtractUserInfo(string authHeader)
        {
            var token = authHeader.Split(' ')[1];                // gets the token from the header

            var dictionary = JWTokenHelper.DecodeJWToken(token); //

            int tmp;

            CurrentIdentity = new CurrentIdentity
            {
                Email    = dictionary["Email"].ToString(),
                Username = dictionary["Username"].ToString(),
                UserId   = int.TryParse(dictionary["UserId"].ToString(), out tmp) ? tmp : (int?)null
            };
        }
        public async Task <IHttpActionResult> ActivateProduct(long productId, ProductIn product)
        {
            CurrentIdentity identity = getIdentity();

            Product productCurrent = await db.Products.FindAsync(productId);

            if (productCurrent == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            string userId = (await db.Shops.FindAsync(productCurrent.ShopId)).UserId;

            if (identity.userId == userId || identity.role == "Admin")
            {
                if (productCurrent.IsActive == 0)
                {
                    productCurrent.IsActive = 1;
                }
                else
                {
                    productCurrent.IsActive = 0;
                }

                db.Entry(productCurrent).State = EntityState.Modified;

                try
                {
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductExists(productId))
                    {
                        return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
                    }
                    else
                    {
                        throw;
                    }
                }
                return(StatusCode(HttpStatusCode.NoContent));
            }
            return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
        }
        public async Task <IHttpActionResult> GetProductOwnDetails()
        {
            CurrentIdentity identity = getIdentity();
            long            shopId   = (await db.Shops.Where(p => p.UserId == identity.userId).FirstOrDefaultAsync()).Id;
            List <Product>  products = await db.Products.Where(p => p.ShopId == shopId).ToListAsync();

            if (products == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            List <ProductOut> productsOut = new List <ProductOut>();

            foreach (var product in products)
            {
                IList <Image> images = await db.Images.Where(p => p.ProductId == product.Id).ToListAsync();

                IList <ProductsToCategory> productToCategories = await db.ProductsToCategories.Where(p => p.ProductId == product.Id).ToListAsync();

                IList <Category> categories = new List <Category>();

                foreach (var categoryEach in productToCategories)
                {
                    categories.Add(await db.Categories.FirstOrDefaultAsync(p => p.Id == categoryEach.CategoryId));
                }

                ProductOut productOut = new ProductOut();
                productOut.Id              = product.Id;
                productOut.Title           = product.Title;
                productOut.Description     = product.Description;
                productOut.DescriptionFull = product.DescriptionFull;
                productOut.Views           = product.Views;
                productOut.IsActive        = product.IsActive;
                productOut.CreatedAt       = product.CreatedAt;
                productOut.UpdatedAt       = product.UpdatedAt;
                productOut.ShopId          = product.ShopId;
                productOut.Images          = images;
                productOut.Categories      = categories;
                productOut.Stock           = product.Stock;
                productOut.Price           = product.Price;
                productsOut.Add(productOut);
            }

            return(Ok(productsOut));
        }
        public async Task <IHttpActionResult> GetOrderProducts(long id)
        {
            CurrentIdentity identity = getIdentity();

            Order order = await db.Orders.FindAsync(id);

            if (order == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            if (identity.role != "Admin")
            {
                if (order.ShopId != (await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId)).Id)
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
                }
            }

            OrderProducts orderOut = new OrderProducts();

            orderOut.Id              = order.Id;
            orderOut.CustomerId      = order.CustomerId;
            orderOut.ShippingAddress = order.ShippingAddress;
            orderOut.BillingAddress  = order.BillingAddress;
            orderOut.CreatedAt       = order.CreatedAt;
            orderOut.UpdatedAt       = order.UpdatedAt;
            orderOut.Status          = order.Status;
            orderOut.ShopId          = order.ShopId;
            orderOut.Amount          = order.Amount;


            orderOut.Products = new List <ProductOutOrder>();
            IList <OrdersToProduct> productsInOrder = new List <OrdersToProduct>();

            productsInOrder = await db.OrdersToProducts.Where(p => p.OrderId == id).ToListAsync();

            foreach (var product in productsInOrder)
            {
                orderOut.Products.Add(await GetProductsForOrder(product.ProductId, product.Quantity));
            }

            return(Ok(orderOut));
        }
        public async Task <IHttpActionResult> PutCustomer(long id, CustomerIn customerIn)
        {
            CurrentIdentity identity = getIdentity();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Customer customerCurrent = await db.Customers.FindAsync(id);

            if (customerCurrent == null)
            {
                return(ResponseMessage(getHttpResponse(HttpStatusCode.NotFound)));
            }

            if (identity.role != "Admin")
            {
                if (customerCurrent.ShopId != (await db.Shops.FirstOrDefaultAsync(p => p.UserId == identity.userId)).Id)
                {
                    return(ResponseMessage(getHttpResponse(HttpStatusCode.Unauthorized)));
                }
            }

            customerCurrent.Name    = (customerIn.Name != null) ? customerIn.Name : customerCurrent.Name;
            customerCurrent.Phone   = (customerIn.Phone != null) ? customerIn.Phone : customerCurrent.Phone;
            customerCurrent.Email   = (customerIn.Email != null) ? customerIn.Email : customerCurrent.Email;
            customerCurrent.Address = (customerIn.Address != null) ? customerIn.Address : customerCurrent.Address;
            customerCurrent.Zip     = (customerIn.Zip != null) ? customerIn.Zip : customerCurrent.Zip;
            customerCurrent.City    = (customerIn.City != null) ? customerIn.City : customerCurrent.City;
            customerCurrent.Country = (customerIn.Country != null) ? customerIn.Country : customerCurrent.Country;
            customerCurrent.ShopId  = customerCurrent.ShopId;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }