示例#1
0
        public async Task <bool> CheckPasswordAsync(ProfileModel model, string password)
        {
            try
            {
                var loggedInUserId = GetLoggedInUserId();
                var user           = await _userManager.FindByIdAsync(loggedInUserId);

                if (user.UserName != _cookieService.Get("username") ||
                    user.UserName != model.Username)
                {
                    return(false);
                }

                if (!await _userManager.CheckPasswordAsync(user, password))
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
                return(false);
            }

            return(true);
        }
        public async Task <IActionResult> Logout()
        {
            try
            {
                var userId = _cookieService.Get("user_id");

                if (userId != null)
                {
                    var protectorProvider = _provider.GetService <IDataProtectionProvider>();
                    var protector         = protectorProvider.CreateProtector(_dataProtectionKeys.ApplicationUserKey);
                    var unprotectedToken  = protector.Unprotect(userId);

                    var rt = _db.Tokens.FirstOrDefault(t => t.UserId == unprotectedToken);

                    // First remove the Token
                    if (rt != null)
                    {
                        _db.Tokens.Remove(rt);
                    }
                    await _db.SaveChangesAsync();

                    // Second remove all Cookies
                    _cookieService.DeleteAllCookies(cookiesToDelete);
                }
            }
            catch (Exception ex)
            {
                _cookieService.DeleteAllCookies(cookiesToDelete);
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }

            Log.Information("User logged out.");
            return(RedirectToLocal(null));
        }
示例#3
0
        public IActionResult Create()
        {   //https://localhost:44394/Trackers/Create?Place=Vision_College
            //only update place with teh query if there is something in the string
            string nullCheck = null;

            nullCheck = HttpContext.Request.Query["Place"].ToString();

            if (!string.IsNullOrEmpty(nullCheck))
            {
                Place = HttpContext.Request.Query["Place"].ToString();

                ViewData["Place"] = Place;
            }

            //get the cookies back
            var name      = _cookieService.Get <string>(c_NAMECOOKIENAME);               //sample
            var contrived = _cookieService.Get <ContrivedValues>(c_CONTRIVEDCOOKIENAME); //sample

            //  var contrived = _cookieService.GetOrSet<ContrivedValues>(c_CONTRIVEDCOOKIENAME, () => new ContrivedValues { Name = "n", Phone = "p", Place = Place });

            if (contrived != null)
            {
                var viewModel = new TrackerCookiesVM
                {//2 classes
                    Name      = name,
                    Contrived = contrived
                };

                ViewData["cookieName"]  = viewModel.Contrived.Name;
                ViewData["cookiePhone"] = viewModel.Contrived.Phone;
                ViewData["cookiePlace"] = viewModel.Contrived.Place;
            }
            else
            {
                ViewData["cookieName"]  = "Name";
                ViewData["cookiePhone"] = "";
                ViewData["cookiePlace"] = "";
            }


            return(View());
        }
示例#4
0
        public void StoreTokenData(TokenModel token)
        {
            if (token == null)
            {
                throw new ArgumentNullException(nameof(token));
            }

            var serialized = ProtectToken(JsonConvert.SerializeObject(token));

            var cookie = _cookieService.Get(AssistanceConstants.Cookies.AuthenticationTokenKey)
                         ?? new HttpCookie(AssistanceConstants.Cookies.AuthenticationTokenKey)
            {
                Secure   = false,   // Change this to true in production
                HttpOnly = true,
                Expires  = DateTime.UtcNow.AddDays(50)
            };

            cookie.Value = serialized;

            _cookieService.Add(cookie);
        }
示例#5
0
        public IActionResult Index()
        {
            var name      = _cookieService.Get <string>(c_NAMECOOKIENAME);
            var contrived = _cookieService.GetOrSet <ContrivedValues>("contrived", () => new ContrivedValues {
                Name = "Guest"
            });

            var viewModel = new HomeViewModel
            {
                Name      = name,
                Contrived = contrived
            };

            return(View(viewModel));
        }
示例#6
0
        public async Task <IActionResult> Index()
        {
            var model = _cookieService.Get <SearchViewModel>("search-model") ?? new SearchViewModel();

            model.Date = DateTime.Now.Date.AddDays(1);

            if (model.FromId <= 0 || model.ToId <= 0)
            {
                var result = await _mediator.Send(new GetBusLocationQuery());

                model.FromId   = result[0].Data;
                model.FromText = result[0].Value;
                model.ToId     = result[1].Data;
                model.ToText   = result[1].Value;
            }

            return(View(model));
        }
        private async Task <IActionResult> Edit(string viewName, bool partial, string formUrlSlug, string sectionUrlSlug)
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            var formModel = await _dynamicFormsPresentationService.CreateFormModelFromDbAsync(formUrlSlug, sectionUrlSlug, cts.Token);

            if (formModel == null)
            {
                return(BadRequest());
            }

            var formSubmissionId = _cookieService.Get(formUrlSlug);

            if (!(await _dynamicFormsPresentationService.IsValidSubmissionUrlAsync(formSubmissionId, formUrlSlug, sectionUrlSlug, ControllerName, cts.Token)))
            {
                return(BadRequest());
            }

            if (string.IsNullOrEmpty(_cookieService.Get(formUrlSlug)))
            {
                formSubmissionId = Guid.NewGuid().ToString();
                _cookieService.Set(formUrlSlug, formSubmissionId, 14);
            }
            else
            {
                if (sectionUrlSlug == null)
                {
                    sectionUrlSlug = await _dynamicFormsPresentationService.GetFirstSectionUrlSlugAsync(formUrlSlug, ControllerName);
                }

                await _dynamicFormsPresentationService.PopulateFormModelFromDbAsync(formModel, formSubmissionId, sectionUrlSlug);
            }

            var formContainer = await _dynamicFormsPresentationService.CreateFormContainerAsync(formModel, formUrlSlug, sectionUrlSlug, formSubmissionId, ControllerName, cts.Token);

            ViewBag.DetailsMode = false;
            ViewBag.PageTitle   = Title;
            ViewBag.Admin       = false;

            if (partial)
            {
                return(PartialView(viewName, formContainer));
            }
            else
            {
                return(View(viewName, formContainer));
            }
        }
 public T Get(string cookieName)
 {
     return(_cookieService.Get(_httpContextBase, cookieName));
 }
 public string GetToken()
 {
     return(_cookieService.Get(KEY));
 }
示例#10
0
        private OrderFilter GetFilter()
        {
            var filter = new OrderFilter
            {
                Keyword = _cookieService.Get(_KEYWORD)
            };

            var dateFromStr = _cookieService.Get(_DATEFROM);

            if (!string.IsNullOrEmpty(dateFromStr))
            {
                if (DateTime.TryParse(dateFromStr, out var dateFrom))
                {
                    filter.DateFrom = dateFrom;
                }
                else
                {
                    filter.DateFrom = null;
                }
            }

            var dateToStr = _cookieService.Get(_DATETO);

            if (!string.IsNullOrEmpty(dateToStr))
            {
                if (DateTime.TryParse(dateToStr, out var dateTo))
                {
                    filter.DateTo = dateTo;
                }
                else
                {
                    filter.DateTo = null;
                }
            }

            var priceFromStr = _cookieService.Get(_PRICEFROM);

            if (!string.IsNullOrEmpty(priceFromStr))
            {
                if (decimal.TryParse(priceFromStr, out var priceFrom))
                {
                    filter.PriceFrom = priceFrom;
                }
                else
                {
                    filter.PriceFrom = 0;
                }
            }

            var priceToStr = _cookieService.Get(_PRICETO);

            if (!string.IsNullOrEmpty(priceToStr))
            {
                if (decimal.TryParse(priceToStr, out var priceTo))
                {
                    filter.PriceTo = priceTo;
                }
                else
                {
                    filter.PriceTo = 0;
                }
            }

            var orderStatusStr = _cookieService.Get(_ORDERSTATUS);

            if (!string.IsNullOrEmpty(orderStatusStr))
            {
                if (int.TryParse(orderStatusStr, out var status))
                {
                    filter.OrderStatusId = status;
                }
                else
                {
                    filter.OrderStatusId = 0;
                }
            }

            filter.PurchaseOrderNumber = _cookieService.Get(_PURCHASENUMBER);
            filter.OrderGroupId        = _cookieService.Get(_ORDERGROUPID);
            filter.AddressId           = _cookieService.Get(_SHIPPINGADDRESS);

            return(filter);
        }
        private async Task SetAdminBaseViewModel()
        {
            var protectorProvider = _provider.GetService <IDataProtectionProvider>();
            var protector         = protectorProvider.CreateProtector(_dataProtectionKeys.ApplicationUserKey);
            var userProfile       = await _userService.GetUserProfileByIdAsync(protector.Unprotect(_cookieService.Get("user_id")));

            var resetPassword = new ResetPasswordViewModel();

            _adminBaseViewModel = new AdminBaseViewModel
            {
                Profile       = userProfile,
                ResetPassword = resetPassword,
            };
        }
        private async Task <TokenResponseModel> RefreshToken(TokenRequestModel model)
        {
            try
            {
                if (_appSettings.AllowSiteWideTokenRefresh)
                {
                    // STEP 1: Validate JWT Token
                    var jwtValidationResult = await ValidateAuthTokenAsync();

                    if (jwtValidationResult.IsValid && jwtValidationResult.Message == "Token Expired")
                    {
                        // check if there's an user with the refresh token's userId
                        var user = await _userManager.FindByEmailAsync(model.Email);

                        // also check if user is not admin / using admin cookie
                        if (user == null || user.UserRole == "Administrator")
                        {
                            // UserId not found or invalid
                            return(CreateErrorResponseToken("Request Not Supported", HttpStatusCode.Unauthorized));
                        }

                        // check if the received refreshToken exists for the given clientId
                        var rt = _db.Tokens.FirstOrDefault(t =>
                                                           t.ClientId == _appSettings.ClientId &&
                                                           t.UserId == user.Id);

                        if (rt == null)
                        {
                            return(CreateErrorResponseToken("Request Not Supported", HttpStatusCode.Unauthorized));
                        }

                        // check if refresh token is expired
                        if (rt.ExpiryTime < DateTime.UtcNow)
                        {
                            _cookieSvc.DeleteCookie("access_token");
                            _cookieSvc.DeleteCookie("refreshToken");
                            _cookieSvc.DeleteCookie("loginStatus");
                            _cookieSvc.DeleteCookie("username");
                            _cookieSvc.DeleteCookie("userRole");
                            return(CreateErrorResponseToken("Request Not Supported", HttpStatusCode.Unauthorized));
                        }
                        /* Get the Data protection service instance */
                        var protectorProvider = _provider.GetService <IDataProtectionProvider>();
                        /* Create a protector instance */
                        var protectorRt      = protectorProvider.CreateProtector(rt.EncryptionKeyRt);
                        var unprotectedToken = protectorRt.Unprotect(_cookieSvc.Get("refreshToken"));
                        var decryptedToken   = unprotectedToken.ToString();

                        if (rt.Value != decryptedToken)
                        {
                            return(CreateErrorResponseToken("Request Not Supported", HttpStatusCode.Unauthorized));
                        }

                        var accessToken = await CreateAccessToken(user);

                        var expireTime             = accessToken.Expiration.Subtract(DateTime.UtcNow).TotalMinutes;
                        var refreshTokenExpireTime = accessToken.RefreshTokenExpiration.Subtract(DateTime.UtcNow).TotalMinutes;
                        // set cookie for jwt and refresh token
                        // Expiry time for cookie - When Refresh token expires all other cookies should expire
                        // therefor set all the cookie expiry time to refresh token expiry time
                        _cookieSvc.SetCookie("access_token", accessToken.Token.ToString(), Convert.ToInt32(refreshTokenExpireTime));
                        _cookieSvc.SetCookie("refreshToken", accessToken.RefreshToken, Convert.ToInt32(refreshTokenExpireTime));
                        _cookieSvc.SetCookie("loginStatus", "1", Convert.ToInt32(refreshTokenExpireTime), false, false);
                        _cookieSvc.SetCookie("username", user.UserName, Convert.ToInt32(refreshTokenExpireTime), false, false);
                        _cookieSvc.SetCookie("userRole", user.UserRole, Convert.ToInt32(refreshTokenExpireTime), false, false);
                        _cookieSvc.SetCookie("user_id", accessToken.UserId, Convert.ToInt32(refreshTokenExpireTime));
                        accessToken.Principal = validateToken;
                        return(accessToken);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
                return(CreateErrorResponseToken($"Error => {ex.Message}", HttpStatusCode.Unauthorized));
            }

            return(CreateErrorResponseToken("Request Not Supported", HttpStatusCode.Unauthorized));
        }
示例#13
0
        public IActionResult Index(BudgetingPage currentPage)
        {
            var selectedOrgId    = _cookieService.Get(Constant.Fields.SelectedOrganization);
            var isSubOrgSelected = !string.IsNullOrEmpty(selectedOrgId);
            var selectedOrg      = isSubOrgSelected
                ? _organizationService.GetFoundationOrganizationById(selectedOrgId)
                : _organizationService.GetCurrentFoundationOrganization();

            var viewModel = new BudgetingPageViewModel
            {
                CurrentContent           = currentPage,
                IsSubOrganization        = isSubOrgSelected,
                OrganizationBudgets      = new List <BudgetViewModel>(),
                SubOrganizationsBudgets  = new List <BudgetViewModel>(),
                PurchasersSpendingLimits = new List <BudgetViewModel>()
            };

            if (selectedOrg != null)
            {
                var currentBudget = _budgetService.GetCurrentOrganizationBudget(selectedOrg.OrganizationId);
                if (currentBudget != null)
                {
                    viewModel.CurrentBudgetViewModel = new BudgetViewModel(currentBudget);
                }

                var budgets = _budgetService.GetOrganizationBudgets(selectedOrg.OrganizationId);
                if (budgets != null)
                {
                    viewModel.OrganizationBudgets.AddRange(
                        budgets.Select(budget => new BudgetViewModel(budget)
                    {
                        OrganizationName = selectedOrg.Name,
                        IsCurrentBudget  = currentBudget?.BudgetId == budget.BudgetId
                    })
                        );
                }

                if (selectedOrg.SubOrganizations != null)
                {
                    foreach (var subOrg in selectedOrg.SubOrganizations)
                    {
                        var budget = _budgetService.GetCurrentOrganizationBudget(subOrg.OrganizationId);
                        if (budget != null)
                        {
                            viewModel.SubOrganizationsBudgets.Add(new BudgetViewModel(budget)
                            {
                                OrganizationName = subOrg.Name
                            });
                        }
                    }
                }

                var purchasersBudgets = _budgetService.GetOrganizationPurchasersBudgets(selectedOrg.OrganizationId);
                if (purchasersBudgets != null)
                {
                    viewModel.PurchasersSpendingLimits.AddRange(purchasersBudgets.Select(purchaserBudget => new BudgetViewModel(purchaserBudget)));
                }
            }
            viewModel.IsAdmin = CustomerContext.Current.CurrentContact.Properties[Constant.Fields.UserRole].Value.ToString() == Constant.UserRoles.Admin;

            return(View(viewModel));
        }
 private string getCookieValue(HttpRequest request)
 {
     return(_cookieService.Get(KinabaluConstants.cookieName, request));
 }
        public IViewComponentResult Invoke(MyAccountPageType id)
        {
            var referenceSettings = _settingsService.GetSiteSettings <ReferencePageSettings>();
            var layoutsettings    = _settingsService.GetSiteSettings <LayoutSettings>();

            if (referenceSettings == null || layoutsettings == null)
            {
                return(new ViewViewComponentResult());
            }

            var selectedSubNav        = _cookieService.Get(Constant.Fields.SelectedNavOrganization);
            var organization          = _organizationService.GetCurrentFoundationOrganization();
            var canSeeOrganizationNav = _customerService.CanSeeOrganizationNav();

            var model = new MyAccountNavigationViewModel
            {
                Organization        = canSeeOrganizationNav ? _organizationService.GetOrganizationModel(organization) : null,
                CurrentOrganization = canSeeOrganizationNav ? !string.IsNullOrEmpty(selectedSubNav) ?
                                      _organizationService.GetOrganizationModel(_organizationService.GetSubFoundationOrganizationById(selectedSubNav)) :
                                      _organizationService.GetOrganizationModel(organization) : null,
                CurrentPageType     = id,
                OrganizationPage    = referenceSettings.OrganizationMainPage,
                SubOrganizationPage = referenceSettings.SubOrganizationPage,
                MenuItemCollection  = new LinkItemCollection()
            };

            var menuItems = layoutsettings.MyAccountCmsMenu;

            if (menuItems == null)
            {
                return(View("_ProfileSidebar.cshtml", model));
            }

            var wishlist = _contentLoader.Get <PageData>(referenceSettings.WishlistPage);

            menuItems = menuItems.CreateWritableClone();

            if (model.Organization != null)
            {
                if (wishlist != null)
                {
                    var url  = wishlist.LinkURL.Contains("?") ? wishlist.LinkURL.Split('?').First() : wishlist.LinkURL;
                    var item = menuItems.FirstOrDefault(x => x.Href.Substring(1).Equals(url));
                    if (item != null)
                    {
                        menuItems.Remove(item);
                    }
                }
                menuItems.Add(new LinkItem
                {
                    Href = _urlResolver.GetUrl(referenceSettings.QuickOrderPage),
                    Text = _localizationService.GetString("/Dashboard/Labels/QuickOrder", "Quick Order")
                });
            }
            else if (organization != null)
            {
                if (wishlist != null)
                {
                    var url  = wishlist.LinkURL.Contains("?") ? wishlist.LinkURL.Split('?').First() : wishlist.LinkURL;
                    var item = menuItems.FirstOrDefault(x => x.Href.Substring(1).Equals(url));
                    if (item != null)
                    {
                        item.Text = _localizationService.GetString("/Dashboard/Labels/OrderPad", "Order Pad");
                    }
                }
            }

            model.MenuItemCollection.AddRange(menuItems);

            return(View("_ProfileSidebar.cshtml", model));
        }