private T GetData <T>(string key)
        {
            if (CookieManager.Has(key))
            {
                return((T)CookieManager.Get(key));
            }

            return(default(T));
        }
Esempio n. 2
0
        public async Task <ActionResult <ResendEmailModel> > ResendEmailConfirmation()
        {
            if (User.Identity.IsAuthenticated && string.IsNullOrEmpty(CookieManager.Get(HttpContext, CookieManager.CookieKeys.JwtToken)))
            {
                await _signInManager.SignOutAsync();
            }

            return(View(new ResendEmailModel()));
        }
Esempio n. 3
0
        public async Task <ActionResult <ForgotPasswordModel> > ForgotPassword()
        {
            var model = new ForgotPasswordModel();

            if (User.Identity.IsAuthenticated && string.IsNullOrEmpty(CookieManager.Get(HttpContext, CookieManager.CookieKeys.JwtToken)))
            {
                await _signInManager.SignOutAsync();
            }

            return(View(model));
        }
Esempio n. 4
0
        public async Task <ActionResult <UserDto> > Register(string returnUrl = null)
        {
            var model = new UserDto
            {
                ReturnUrl = returnUrl ?? Url.Content("~/")
            };

            if (User.Identity.IsAuthenticated && string.IsNullOrEmpty(CookieManager.Get(HttpContext, CookieManager.CookieKeys.JwtToken)))
            {
                await _signInManager.SignOutAsync();
            }
            else if (User.Identity.IsAuthenticated)
            {
                return(Redirect(model.ReturnUrl));
            }

            return(View(model));
        }
Esempio n. 5
0
            public static Languages LangIsSeleted()
            {
                string lang = string.Empty;
                var    co   = CookieManager.Get(LangKey);

                if (co != null)
                {
                    lang = string.IsNullOrWhiteSpace(co) ? GetDefaultLanguage() : co;
                }
                else
                {
                    lang = GetDefaultLanguage();
                }

                var langSelected = AvailableLanguages.Where(a => a.LanguageCultureName == lang).FirstOrDefault();

                return(langSelected == null?AvailableLanguages.FirstOrDefault() : langSelected);
            }
Esempio n. 6
0
        public async Task <ActionResult <LoginModel> > Login(string returnUrl = null)
        {
            var model = new LoginModel
            {
                ReturnUrl = returnUrl ?? Url.Action("Index", "Home")
            };

            if (User.Identity.IsAuthenticated && string.IsNullOrEmpty(CookieManager.Get(HttpContext, CookieManager.CookieKeys.JwtToken)))
            {
                await _signInManager.SignOutAsync();
            }
            else if (User.Identity.IsAuthenticated)
            {
                return(Redirect(model.ReturnUrl));
            }

            model.ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            return(View(model));
        }
        /// <summary>
        /// Get the channel for wich the user accesed the site.
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns>The channel for wich the user accesed the site.</returns>
        private static string GetChannel(ControllerContext filterContext)
        {
            bool   isLoggedIn = filterContext.HttpContext.User.Identity.IsAuthenticated;
            string channel    = filterContext.HttpContext.Request.QueryString[qsChannel];

            if (!string.IsNullOrEmpty(channel) && !isLoggedIn)
            {
                CookieManager.Set(ckChannel, channel);
            }

            if (!isLoggedIn && CookieManager.Has(ckChannel))
            {
                channel = (string)CookieManager.Get(ckChannel);
            }
            else if (UserDataHelper.Data != null)
            {
                channel = UserDataHelper.Data.Channel;
            }

            return(channel);
        }
Esempio n. 8
0
        public async Task <ActionResult <ResetPasswordModel> > ResetPassword(string email, string code = null)
        {
            if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(email))
            {
                throw new BadRequestException("برای تغییر کلمه عبور کد لازم است!");
            }

            var model = new ResetPasswordModel
            {
                Email = email,
                Code  = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code))
            };

            if (User.Identity.IsAuthenticated ||
                string.IsNullOrEmpty(CookieManager.Get(HttpContext, CookieManager.CookieKeys.JwtToken)))
            {
                CookieManager.RemoveAllCookie(HttpContext);
                await _signInManager.SignOutAsync();
            }

            return(View(model));
        }
Esempio n. 9
0
        public IList <Cookie> LoadForRequest(HttpUrl httpUrl)
        {
            var headers       = new Dictionary <string, IList <string> >();
            var cookieHeaders = _cookieManager.Get(httpUrl.Uri(), headers);
            var cookies       = new List <Cookie>();

            if (cookieHeaders != null)
            {
                foreach (var entry in cookieHeaders)
                {
                    if ((entry.Key == "Cookie" || entry.Key == "Cookie2") && entry.Value != null)
                    {
                        foreach (var header in entry.Value)
                        {
                            var newCookies = DecodeHeader(httpUrl, header);
                            cookies.AddRange(newCookies);
                        }
                    }
                }
            }
            return(cookies);
        }
Esempio n. 10
0
        /// <summary>
        /// Effectue le pré-rendu du contrôle
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            var ck = CookieManager.Get(CookieName);

            if (ck != null && !string.IsNullOrEmpty(ck.Value))
            {
                this.Visible = false;
            }

            var c = this.Style["display"];

            if (c == null)
            {
                this.Style.Add("display", "none");
            }

            c = this.Attributes["data-e_cookiepanel"];
            if (c == null)
            {
                this.Attributes.Add("data-e_cookiepanel", CookieName);
            }

            base.OnPreRender(e);
        }
        /// <summary>
        /// This will Authorize User
        /// </summary>
        /// <returns></returns>
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (filterContext != null)
            {
                if (filterContext.Filters.Any(p => p is Microsoft.AspNetCore.Mvc.Authorization.AllowAnonymousFilter))
                {
                    return;
                }

                //var logger = (ILogger<CustomAuthorize>)filterContext.HttpContext.RequestServices.GetService(typeof(ILogger<CustomAuthorize>));
                var logger = filterContext.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(typeof(ILogger <CustomAuthorize>));
                if (string.IsNullOrEmpty(CookieManager.Get(filterContext.HttpContext, CookieManager.CookieKeys.JwtToken)))
                {
                    if (filterContext.HttpContext.Request.IsAjax())
                    {
                        //handle in ServiceCollectionExtensions->AddJwtAthuntication->OnTokenValidated

                        //throw new AppException(ApiResultStatusCode.UnAuthorized,
                        //                       "OnAuthorization Method :Not Authenticate,You are unauthorized to access this resource.",
                        //                       HttpStatusCode.Unauthorized);
                    }
                    else
                    {
                        logger.LogError("OnAuthorization Method : Jwt Session is null!");
                        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Login" }));
                    }
                }
                if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    if (roles.Length > 0)
                    {
                        var claimsIdentity = filterContext.HttpContext.User.Identity as ClaimsIdentity;
                        if (claimsIdentity.Claims?.Any() == true)
                        {
                            var userRoles = claimsIdentity.GetRoles();
                            if (userRoles == null || !userRoles.Any(role => roles.Contains(role)))
                            {
                                if (filterContext.HttpContext.Request.IsAjax())
                                {
                                    throw new AppException(ApiResultStatusCode.UnAuthorized,
                                                           "OnAuthorization Method : You are unauthorized to access this resource.",
                                                           HttpStatusCode.Unauthorized);
                                }
                                else
                                {
                                    logger.LogError("OnAuthorization Method : You are unauthorized to access this resource.");
                                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Login" }));
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (filterContext.HttpContext.Request.IsAjax())
                    {
                        throw new AppException(ApiResultStatusCode.UnAuthorized,
                                               "OnAuthorization Method :Not Authenticate,You are unauthorized to access this resource.",
                                               HttpStatusCode.Unauthorized);
                    }
                    else
                    {
                        logger.LogError("OnAuthorization Method : You are unauthorized to access this resource.");
                        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Login" }));
                    }
                }
            }
        }
        public async Task Invoke(HttpContext context)
        {
            string              message        = null;
            HttpStatusCode      httpStatusCode = HttpStatusCode.InternalServerError;
            ApiResultStatusCode apiStatusCode  = ApiResultStatusCode.ServerError;

            try
            {
                var isAjax            = context.Request.IsAjax();
                var isPostAjax        = context.Request.IsAjax("POST");
                var isSentFromPostMan = context.Request.Headers.ContainsKey("Postman-Token");
                if (isSentFromPostMan)
                {
                    var postManValue = context.Request.Headers["Postman-Token"];
                }

                if (isAjax && context.User.Identity.IsAuthenticated &&
                    !string.IsNullOrEmpty(CookieManager.Get(context, CookieManager.CookieKeys.JwtToken)) &&
                    !string.IsNullOrEmpty(context.Request.Headers["Authorization"]) &&
                    context.Request.Headers["Authorization"] != $"Bearer {CookieManager.Get(context, CookieManager.CookieKeys.JwtToken)}")
                {
                    throw new BadRequestException("Jwt token in Request not valid!");
                }

                await _next(context);
            }
            catch (AppException exception)
            {
                _logger.LogError(exception, exception.Message);
                httpStatusCode = exception.HttpStatusCode;
                apiStatusCode  = exception.ApiStatusCode;

                if (context.Request.IsAjax())
                {
                    if (_env.IsDevelopment())
                    {
                        var dic = new Dictionary <string, string>
                        {
                            ["Exception"]  = exception.Message,
                            ["StackTrace"] = exception.StackTrace,
                        };
                        if (exception.InnerException != null)
                        {
                            dic.Add("InnerException.Exception", exception.InnerException.Message);
                            dic.Add("InnerException.StackTrace", exception.InnerException.StackTrace);
                        }
                        if (exception.AdditionalData != null)
                        {
                            dic.Add("AdditionalData", JsonConvert.SerializeObject(exception.AdditionalData));
                        }

                        message = JsonConvert.SerializeObject(dic);
                    }
                    else
                    {
                        message = exception.Message;
                    }
                    await WriteToResponseAsync();
                }
                else
                {
                    if (httpStatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (context.User.Identity.IsAuthenticated)
                        {
                            context.Response.Redirect("/Home");
                        }
                        else
                        {
                            context.Response.Redirect("/Login");
                        }
                    }
                }
            }
            catch (SecurityTokenExpiredException exception)
            {
                _logger.LogError(exception, exception.Message);
                if (context.Request.IsAjax())
                {
                    SetUnAuthorizeResponse(exception);
                    await WriteToResponseAsync();
                }
                else
                {
                    if (httpStatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (context.User.Identity.IsAuthenticated)
                        {
                            context.Response.Redirect("/Home");
                        }
                        else
                        {
                            context.Response.Redirect("/Login");
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException exception)
            {
                _logger.LogError(exception, exception.Message);
                if (context.Request.IsAjax())
                {
                    SetUnAuthorizeResponse(exception);
                    await WriteToResponseAsync();
                }
                else
                {
                    if (httpStatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (context.User.Identity.IsAuthenticated)
                        {
                            context.Response.Redirect("/Home");
                        }
                        else
                        {
                            context.Response.Redirect("/Login");
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, exception.Message);
                if (context.Request.IsAjax())
                {
                    if (_env.IsDevelopment())
                    {
                        var dic = new Dictionary <string, string>
                        {
                            ["Exception"]  = exception.Message,
                            ["StackTrace"] = exception.StackTrace,
                        };
                        message = JsonConvert.SerializeObject(dic);
                    }
                    await WriteToResponseAsync();
                }
                else
                {
                    if (httpStatusCode == HttpStatusCode.Unauthorized)
                    {
                        if (context.User.Identity.IsAuthenticated)
                        {
                            context.Response.Redirect("/Home");
                        }
                        else
                        {
                            context.Response.Redirect("/Login");
                        }
                    }
                }
            }

            async Task WriteToResponseAsync()
            {
                if (context.Response.HasStarted)
                {
                    throw new InvalidOperationException("The response has already started, the http status code middleware will not be executed.");
                }

                var result = new ApiResult(false, apiStatusCode, message);
                var json   = JsonConvert.SerializeObject(result);

                context.Response.StatusCode  = (int)httpStatusCode;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(json);
            }

            void SetUnAuthorizeResponse(Exception exception)
            {
                httpStatusCode = HttpStatusCode.Unauthorized;
                apiStatusCode  = ApiResultStatusCode.UnAuthorized;

                if (_env.IsDevelopment())
                {
                    var dic = new Dictionary <string, string>
                    {
                        ["Exception"]  = exception.Message,
                        ["StackTrace"] = exception.StackTrace
                    };
                    if (exception is SecurityTokenExpiredException tokenException)
                    {
                        dic.Add("Expires", tokenException.Expires.ToString());
                    }

                    message = JsonConvert.SerializeObject(dic);
                }
            }
        }
Esempio n. 13
0
        public ActionResult Index()
        {
            var curentApplication = CurrentApplication;
            var applicationId     = curentApplication == null ? null : curentApplication.Id;
            var viewModel         = new DashboardViewModel();
            var applications      = Core.GetApplications();
            var preferences       = CookieManager.Get(WebConstants.CookieSettings.DashboardCookieKey);
            var pref = preferences.IsNullOrEmpty() || !preferences.Contains("|") ? null : preferences.Split('|');

            viewModel.ShowMe   = pref == null ? "1" : pref[0];
            viewModel.PageSize = pref == null ? 10 : int.Parse(pref[1]);

            if (applications.PagingStatus.TotalItems > 0)
            {
                viewModel.HasApplications = true;

                if (applications.Items.Count == 1)
                {
                    viewModel.SingleApplicationId    = applications.Items[0].Id;
                    viewModel.SingleApplicationToken = applications.Items[0].Token;
                }

                var showMe = DashboardViewModel.Sorting.FirstOrDefault(s => s.Id == viewModel.ShowMe) ?? new DashboardSort("1", "", true, "LastErrorUtc");

                if (showMe.Id == "5")
                {
                    var errors = _getApplicationErrorsQuery.Invoke(new GetApplicationErrorsRequest
                    {
                        Paging         = new PageRequestWithSort(1, viewModel.PageSize, "TimestampUtc", true),
                        OrganisationId = Core.AppContext.CurrentUser.OrganisationId,
                        ApplicationId  = applicationId
                    }).Errors;

                    viewModel.Errors = errors.Items.Select(e => new ErrorInstanceViewModel
                    {
                        Error           = e,
                        ApplicationName = GetApplicationName(applications.Items, e.ApplicationId),
                    }).ToList();

                    viewModel.ShowIntro = errors.PagingStatus.TotalItems <= 5 && applications.Items.Count == 1;
                }
                else
                {
                    var issues = _getApplicationIssuesQuery.Invoke(new GetApplicationIssuesRequest
                    {
                        Paging         = new PageRequestWithSort(1, viewModel.PageSize, showMe.SortField, showMe.SortDescending),
                        OrganisationId = Core.AppContext.CurrentUser.OrganisationId,
                        ApplicationId  = applicationId
                    }).Issues;

                    viewModel.TestIssueId = issues.Items.FirstOrDefault(i => i.TestIssue).IfPoss(i => i.Id);
                    viewModel.Issues      = IssueItemViewModel.ConvertSimple(issues.Items, Core.GetUsers().Items, Core.AppContext.CurrentUser.ActiveOrganisation.TimezoneId, showMe.Id != "2");
                    viewModel.ShowIntro   = issues.PagingStatus.TotalItems <= 3 && applications.Items.Count == 1;
                }

                var selectedApplication = applicationId.IsNotNullOrEmpty()
                    ? applications.Items.FirstOrDefault(a => a.FriendlyId == applicationId.GetFriendlyId())
                    : null;

                viewModel.SelectedApplicationId   = selectedApplication == null ? null : selectedApplication.FriendlyId;
                viewModel.SelectedApplicationName = selectedApplication == null ? null : selectedApplication.Name;
                viewModel.Applications            = applications.Items;
                viewModel.UrlGetter     = GetDashboardUrl;
                viewModel.ShowMeOptions = DashboardViewModel.Sorting.ToSelectList(s => s.Id, s => s.DisplayName, s => s.Id == viewModel.ShowMe);
                viewModel.PageSizes     = new List <SelectListItem>
                {
                    new SelectListItem {
                        Text = "10", Value = "10", Selected = viewModel.PageSize == 10
                    },
                    new SelectListItem {
                        Text = "20", Value = "20", Selected = viewModel.PageSize == 20
                    },
                    new SelectListItem {
                        Text = "30", Value = "30", Selected = viewModel.PageSize == 30
                    }
                };
            }
            else
            {
                ConfirmationNotification("You do not currently have any applications, please create an application to begin using Errordite.");
                return(Redirect(Url.AddApplication(false)));
            }

            return(View(viewModel));
        }