private void ValidateRequestHeader(HttpRequestMessage request)
        {
            string cookieToken = String.Empty;
            string formToken   = String.Empty;

            IEnumerable <string> tokenHeaders;

            if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
            {
                string tokenValue = tokenHeaders.FirstOrDefault();
                if (!String.IsNullOrEmpty(tokenValue))
                {
                    string[] tokens = tokenValue.Split(':');
                    if (tokens.Length == 2)
                    {
                        cookieToken = tokens[0].Trim();
                        formToken   = tokens[1].Trim();
                    }
                }
            }

            AntiForgery.Validate(cookieToken, formToken);
        }
Ejemplo n.º 2
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (ConfigurationManager.AppSettings.AllKeys.Contains(ApiAntiForgeryConfig.AntiForgerySkipValidationAppSettingsName))
            {
                if (Convert.ToBoolean(ConfigurationManager.AppSettings[ApiAntiForgeryConfig.AntiForgerySkipValidationAppSettingsName]))
                {
                    return(true);
                }
            }

            var headers = actionContext.Request.Headers;

            string headerToken = headers.Contains(ApiAntiForgeryConfig.AntiForgeryHeaderName)
                ? headers.GetValues(ApiAntiForgeryConfig.AntiForgeryHeaderName).FirstOrDefault()
                : null;

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

            var cookieToken = headers
                              .GetCookies()
                              .Select(c => c[AntiForgeryConfig.CookieName])
                              .FirstOrDefault();

            try
            {
                AntiForgery.Validate(cookieToken?.Value, headerToken);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 3
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            //  Only validate POSTs
            if (request.HttpMethod == WebRequestMethods.Http.Post)
            {
                //  Ajax POSTs and normal form posts have to be treated differently when it comes
                //  to validating the AntiForgeryToken
                if (request.IsAjaxRequest())
                {
                    var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];

                    var cookieValue = antiForgeryCookie != null
                        ? antiForgeryCookie.Value
                        : null;
                    if (request.Headers["__RequestVerificationToken"] != null)
                    {
                        AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
                    }
                    else
                    {
                        filterContext.Result = new ViewResult
                        {
                            ViewName = "~/Error/InternalError",
                            ViewData = filterContext.Controller.ViewData,
                            TempData = filterContext.Controller.TempData
                        };
                    }
                }
                else
                {
                    new ValidateAntiForgeryTokenAttribute()
                    .OnAuthorization(filterContext);
                }
            }
        }
Ejemplo n.º 4
0
        public System.Web.Mvc.ActionResult HttpPost(Page_Context context, PagePositionContext positionContext)
        {
            AntiForgery.Validate();

            try
            {
                var httpContext = context.ControllerContext.HttpContext;
                var repository  = Repository.Current;
                var textFolder  = new TextFolder(repository, "Members");
                var values      = new NameValueCollection(httpContext.Request.Form);
                values["Published"] = true.ToString();

                var member = textFolder.CreateQuery().WhereEquals("UserName", values["username"]).FirstOrDefault();
                if (member != null)
                {
                    context.ControllerContext.Controller.ViewData.ModelState.AddModelError("UserName", "The user already exists.".RawLabel().ToString());
                }
                else
                {
                    values["PasswordSalt"] = MemberAuth.GenerateSalt();
                    values["Password"]     = MemberAuth.EncryptPassword(values["Password"], values["PasswordSalt"]);

                    var textContext = ServiceFactory.TextContentManager.Add(repository, textFolder, null, null,
                                                                            values, httpContext.Request.Files, null, httpContext.User.Identity.Name);

                    MemberAuth.SetAuthCookie(textContext["UserName"].ToString(), false);

                    return(new RedirectResult(context.Url.FrontUrl().PageUrl("Dashboard").ToString()));
                }
            }
            catch (Exception e)
            {
                context.ControllerContext.Controller.ViewData.ModelState.AddModelError("", e);
                Kooboo.HealthMonitoring.Log.LogException(e);
            }
            return(null);
        }
Ejemplo n.º 5
0
        public ActionResult Abandon(string password = null)
        {
            try
            {
                if (Session["userIndex"] == null || password == null)
                {
                    throw new HttpAntiForgeryException();
                }
                AntiForgery.Validate();
            }
            catch (HttpAntiForgeryException)
            {
                Session.Abandon();
                ViewBag.Message = "잘못된 접근입니다.";
                return(View());
            }

            using (var handler = new DataHandler())
            {
                handler.CreateCommand("DELETE FROM cherrybbs_users WHERE useridx=@code, password=@password",
                                      new Parameter[] {
                    new Parameter("@code", Session["userIndex"]),
                    new Parameter("@password", DataHandler.HashString(ref password))
                });

                if (handler.ExecuteNonQuery() == 0)
                {
                    ViewBag.Message = "비밀번호가 옳지 않습니다.";
                    return(View());
                }
                else
                {
                    ViewBag.AbandonFlag = true;
                    return(View());
                }
            }
        }
Ejemplo n.º 6
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (IsPostBack)
            {
                // will throw exception if invalid
                AntiForgery.Validate();
            }

            SiteHosts            = GetSiteHosts();
            ShowLanguageDropDown = ShouldShowLanguageDropDown();

            LanguageBranches = LanguageBranchRepository.Service.ListEnabled().Select(x => new LanguageBranchData
            {
                DisplayName = x.URLSegment,
                Language    = x.Culture.Name
            }).ToList();

            LanguageBranches.Insert(0, new LanguageBranchData
            {
                DisplayName = "*",
                Language    = ""
            });

            if (!PrincipalInfo.HasAdminAccess)
            {
                AccessDenied();
            }

            if (!IsPostBack)
            {
                BindList();
            }

            SystemPrefixControl.Heading = "Search engine sitemap settings";
        }
 public Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation)
 {
     try {
         var formToken = actionContext.Request.Headers
                         .GetValues("__RequestVerificationToken")
                         .FirstOrDefault();
         var cookieToken = actionContext.Request.Headers
                           .GetCookies()
                           .SelectMany(e => e.Cookies)
                           .FirstOrDefault(e => e.Name == "__RequestVerificationToken")
                           ?.Value;
         if (formToken != null && cookieToken != null)
         {
             AntiForgery.Validate(cookieToken, formToken);
         }
     } catch {
         actionContext.Response = new HttpResponseMessage {
             StatusCode     = HttpStatusCode.Forbidden,
             RequestMessage = actionContext.ControllerContext.Request
         };
         return(FromResult(actionContext.Response));
     }
     return(continuation());
 }
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <exception cref="System.ArgumentNullException">The filterContext parameter is null.</exception>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException(nameof(filterContext));
            }

            var request          = filterContext.HttpContext.Request;
            var headerTokenValue = request.Headers[RequestVerificationTokenHttpHeaderName];

            // Ajax POSTs using jquery have a header set that defines the token.
            // However using unobtrusive ajax the token is still submitted normally in the form.
            // if the header is present then use it, else fall back to processing the form like normal.
            if (headerTokenValue != null)
            {
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
                var cookieValue       = antiForgeryCookie == null ? null : antiForgeryCookie.Value;
                AntiForgery.Validate(cookieValue, headerTokenValue);
            }
            else
            {
                AntiForgery.Validate();
            }
        }
Ejemplo n.º 9
0
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string cookieToken = "";
        string formToken   = "";

        if (filterContext.HttpContext.Request.Headers["RequestVerificationToken"] != null)
        {
            string[] tokens = filterContext.HttpContext.Request.Headers["RequestVerificationToken"].Split(':');
            if (tokens.Length == 2)
            {
                cookieToken = tokens[0].Trim();
                formToken   = tokens[1].Trim();
            }
        }
        try
        {
            AntiForgery.Validate(cookieToken, formToken);
            base.OnActionExecuting(filterContext);
        }
        catch
        {
            filterContext.Result = new HttpNotFoundResult();
        }
    }
Ejemplo n.º 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                AntiForgery.Validate();
            }

            string filters = "*.jpg;*.png;*.gif;*.jpeg";
            string Path    = ConfigurationManager.AppSettings["FilePath"].ToString();

            List <String> images = new List <string>();

            foreach (string filter in filters.Split(';'))
            {
                FileInfo[] fit = new DirectoryInfo(this.Server.MapPath(Path)).GetFiles(filter);
                foreach (FileInfo fi in fit)
                {
                    images.Add(String.Format(Path + "/{0}", fi));
                }
            }

            RepeaterImages.DataSource = images;
            RepeaterImages.DataBind();
        }
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var headers     = actionContext.Request.Headers;
            var headerToken = headers.Contains("__RequestVerificationToken")
                ? headers.GetValues("__RequestVerificationToken").FirstOrDefault()
                : null;
            var cookieToken = headers.GetCookies().Select(x => x[AntiForgeryConfig.CookieName]).FirstOrDefault();

            if (headerToken == null || cookieToken == null)
            {
                return(false);
            }

            try
            {
                AntiForgery.Validate(cookieToken.Value, headerToken);
            }
            catch
            {
                return(false);
            }

            return(base.IsAuthorized(actionContext));
        }
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            try
            {
                var headerToken = actionContext
                                  .Request
                                  .Headers
                                  .GetValues("__RequestVerificationToken")
                                  .FirstOrDefault();
                ;

                var cookieToken = actionContext
                                  .Request
                                  .Headers
                                  .GetCookies()
                                  .Select(c => c[AntiForgeryConfig.CookieName])
                                  .FirstOrDefault();

                // check for missing cookie or header
                if (cookieToken == null || headerToken == null)
                {
                    return(false);
                }

                // ensure that the cookie matches the header

                AntiForgery.Validate(cookieToken.Value, headerToken);
            }
            catch
            {
                return(false);
            }


            return(!_authorize || base.IsAuthorized(actionContext));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// On Authorozation Event
        /// </summary>
        /// <param name="filterContext">Filter Context</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var httpContext = filterContext.HttpContext;

            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            // only POST requests
            if (!string.Equals(filterContext.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(NoAntiForgeryCheckAttribute), true).Length > 0)
            {
                return;
            }

            // don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
                AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
            }
            else
            {
                new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
            }
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            if (request.HttpMethod == WebRequestMethods.Http.Post)
            {
                if (request.IsAjaxRequest())
                {
                    var antiForgeryCookie = request.Cookies[cookiesName];
                    var cookieValue       = antiForgeryCookie != null
                     ? antiForgeryCookie.Value
                     : null;
                    //从cookies 和 Headers 中 验证防伪标记
                    //这里可以加try-catch
                    try
                    {
                        AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
                    }
                    catch (Exception ex)
                    {
                        filterContext.Result = new JsonResult()
                        {
                            Data = new JsonModel()
                            {
                                Success = false, Msg = ex.Message
                            }
                        };
                    }
                }
                else
                {
                    new ValidateAntiForgeryTokenAttribute()
                    .OnAuthorization(filterContext);
                }
            }
        }
Ejemplo n.º 15
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext != null)
            {
                var request = filterContext.HttpContext.Request;

                //  Only validate POSTs
                if (request.HttpMethod == WebRequestMethods.Http.Post)
                {
                    //  Ajax POSTs and normal form posts have to be treated differently when it comes
                    //  to validating the AntiForgeryToken
                    if (request.IsAjaxRequest())
                    {
                        var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];

                        var cookieValue = antiForgeryCookie != null
                            ? antiForgeryCookie.Value
                            : null;

                        AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login")
            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            var provider = new Auth0.Owin.Auth0AuthenticationProvider
            {
                OnTokenExchangeFailed = (context) =>
                {
                },
                OnReturnEndpoint = (context) =>
                {
                    // xsrf validation
                    if (context.Request.Query["state"] != null && context.Request.Query["state"].Contains("xsrf="))
                    {
                        var state = HttpUtility.ParseQueryString(context.Request.Query["state"]);
                        AntiForgery.Validate(context.Request.Cookies["__RequestVerificationToken"], state["xsrf"]);
                    }

                    return(System.Threading.Tasks.Task.FromResult(0));
                }
            };

            app.UseAuth0Authentication(
                clientId: System.Configuration.ConfigurationManager.AppSettings["auth0:ClientId"],
                clientSecret: System.Configuration.ConfigurationManager.AppSettings["auth0:ClientSecret"],
                domain: System.Configuration.ConfigurationManager.AppSettings["auth0:Domain"],
                provider: provider);
        }
Ejemplo n.º 17
0
    public void ProcessRequest(HttpContext context)
    {
        AntiForgery.Validate();

        if (!WebUser.IsAuthenticated)
        {
            throw new HttpException(401, "You must login !");
        }


        if (!WebUser.HasRole(UserRoles.Admin))
        {
            throw new HttpException(401, "You do not have permission to do this");
        }

        //treba nam mode jer cemo u zavisnosti od njega, ako je edit da ispravljamo post ako je new da pravimo novi...
        var mode = context.Request.Form["mode"];

        var name = context.Request.Form["roleName"];
        var id   = context.Request.Form["roleId"];

        if (mode == "edit")
        {
            Edit(Convert.ToInt32(id), name);
        }
        else if (mode == "new")
        {
            Create(name);
        }
        else if (mode == "delete")
        {
            Delete(name);
        }

        context.Response.Redirect("~/admin/role/");
    }
        private void ValidateRequestHeader(HttpRequestMessage request)
        {
            var headers = request.Headers;
            var cookie  = headers
                          .GetCookies()
                          .Select(c => c[AntiForgeryConfig.CookieName])
                          .FirstOrDefault();

            IEnumerable <string> xXsrfHeaders;

            if (headers.TryGetValues("X-XSRF-Token", out xXsrfHeaders))
            {
                var rvt = xXsrfHeaders.FirstOrDefault();

                if (cookie == null)
                {
                    throw new InvalidOperationException(String.Format("Missing {0} cookie", AntiForgeryConfig.CookieName));
                }

                AntiForgery.Validate(cookie.Value, rvt);
            }
            else
            {
                var headerBuilder = new StringBuilder();

                headerBuilder.AppendLine("Missing X-XSRF-Token HTTP header:");

                foreach (var header in headers)
                {
                    headerBuilder.AppendFormat("- [{0}] = {1}", header.Key, header.Value);
                    headerBuilder.AppendLine();
                }

                throw new InvalidOperationException(headerBuilder.ToString());
            }
        }
Ejemplo n.º 19
0
        public override void Execute()
        {
            WriteLiteral("\r\n\r\n");



            #line 4 "..\..\Register.cshtml"

            Page.Title = AdminResources.RegisterTitle;
            var adminPath = SiteAdmin.AdminVirtualPath.TrimStart('~');
            Page.Desc = String.Format(CultureInfo.CurrentCulture, AdminResources.RegisterDesc, Html.Encode(adminPath));

            // If the password is already set the redirect to login
            if (AdminSecurity.HasAdminPassword())
            {
                SiteAdmin.RedirectToLogin(Response);
                return;
            }

            if (IsPost)
            {
                AntiForgery.Validate();

                var password          = Request.Form["password"];
                var reenteredPassword = Request.Form["repassword"];
                if (password.IsEmpty())
                {
                    ModelState.AddError("password", AdminResources.Validation_PasswordRequired);
                }
                else if (password != reenteredPassword)
                {
                    ModelState.AddError("repassword", AdminResources.Validation_PasswordsDoNotMatch);
                }

                if (ModelState.IsValid)
                {
                    // Save the admin password
                    if (AdminSecurity.SaveTemporaryPassword(password))
                    {
                        // Get the return url
                        var returnUrl = SiteAdmin.GetReturnUrl(Request) ?? SiteAdmin.AdminVirtualPath;

                        // Redirect to the return url
                        Response.Redirect(returnUrl);
                    }
                    else
                    {
                        // Add a validation error since creating the password.txt failed
                        ModelState.AddFormError(AdminResources.AdminModuleRequiresAccessToAppData);
                    }
                }
            }



            #line default
            #line hidden
            WriteLiteral("\r\n<br/>\r\n\r\n");



            #line 47 "..\..\Register.cshtml"
            Write(Html.ValidationSummary());


            #line default
            #line hidden
            WriteLiteral("\r\n\r\n<form method=\"post\" action=\"\">\r\n");



            #line 50 "..\..\Register.cshtml"
            Write(AntiForgery.GetHtml());


            #line default
            #line hidden
            WriteLiteral("\r\n<fieldset>\r\n    <ol>\r\n        <li class=\"password\">\r\n            <label for=\"pa" +
                         "ssword\">");



            #line 54 "..\..\Register.cshtml"
            Write(AdminResources.EnterPassword);


            #line default
            #line hidden
            WriteLiteral("</label>\r\n            ");



            #line 55 "..\..\Register.cshtml"
            Write(Html.Password("password"));


            #line default
            #line hidden
            WriteLiteral(" ");



            #line 55 "..\..\Register.cshtml"
            Write(Html.ValidationMessage("password", "*"));


            #line default
            #line hidden
            WriteLiteral("\r\n        </li>\r\n        <li class=\"password\">\r\n            <label>");



            #line 58 "..\..\Register.cshtml"
            Write(AdminResources.ReenterPassword);


            #line default
            #line hidden
            WriteLiteral("</label>\r\n            ");



            #line 59 "..\..\Register.cshtml"
            Write(Html.Password("repassword"));


            #line default
            #line hidden
            WriteLiteral(" ");



            #line 59 "..\..\Register.cshtml"
            Write(Html.ValidationMessage("repassword", "*"));


            #line default
            #line hidden
            WriteLiteral("\r\n        </li>\r\n    </ol>\r\n    <p class=\"form-actions\">\r\n        <input type=\"su" +
                         "bmit\" value=\"");



            #line 63 "..\..\Register.cshtml"
            Write(AdminResources.CreatePassword);


            #line default
            #line hidden
            WriteLiteral("\" class=\"long-input\" />\r\n    </p>\r\n</fieldset>\r\n</form>\r\n");
        }
Ejemplo n.º 20
0
        public object Any(AntiForgeryTest request)
        {
            AntiForgery.Validate();

            return(request);
        }
Ejemplo n.º 21
0
        public override void Execute()
        {
            WriteLiteral("\r\n\r\n");



            #line 4 "..\..\Login.cshtml"

            Page.Title = AdminResources.LoginTitle;

            // No admin password has been registered so redirect
            if (!AdminSecurity.HasAdminPassword())
            {
                SiteAdmin.RedirectToRegister(Response);
                return;
            }

            if (IsPost)
            {
                AntiForgery.Validate();
                var password = Request.Form["password"];

                if (AdminSecurity.CheckPassword(password))
                {
                    // Get the return url
                    var returnUrl = SiteAdmin.GetReturnUrl(Request) ?? SiteAdmin.AdminVirtualPath;

                    // Set the admin auth cookie
                    AdminSecurity.SetAuthCookie(Response);

                    // Redirect to the return url
                    Response.Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddError("password", AdminResources.Validation_PasswordIncorrect);
                }
            }



            #line default
            #line hidden
            WriteLiteral("\r\n");


            DefineSection("Head", () => {
                WriteLiteral("\r\n    <script type=\"text/javascript\">\r\n    function showForgotPasswordInfo(){\r\n  " +
                             "      document.getElementById(\'forgotPasswordInfo\').style.display = \'\';\r\n    }\r\n" +
                             "    </script>\r\n");
            });

            WriteLiteral("\r\n\r\n");



            #line 41 "..\..\Login.cshtml"
            Write(Html.ValidationSummary());


            #line default
            #line hidden
            WriteLiteral("\r\n<br />\r\n\r\n<form method=\"post\" action=\"\">\r\n    ");



            #line 45 "..\..\Login.cshtml"
            Write(AntiForgery.GetHtml());


            #line default
            #line hidden
            WriteLiteral("\r\n    <fieldset>\r\n    <ol>\r\n        <li class=\"password\">\r\n            <label for" +
                         "=\"password\">");



            #line 49 "..\..\Login.cshtml"
            Write(AdminResources.Password);


            #line default
            #line hidden
            WriteLiteral(":</label>\r\n            ");



            #line 50 "..\..\Login.cshtml"
            Write(Html.Password("password"));


            #line default
            #line hidden
            WriteLiteral(" ");



            #line 50 "..\..\Login.cshtml"
            Write(Html.ValidationMessage("password", "*"));


            #line default
            #line hidden
            WriteLiteral("\r\n    </ol>\r\n    <p class=\"form-actions\">\r\n        <input type=\"submit\" value=\"");



            #line 53 "..\..\Login.cshtml"
            Write(AdminResources.Login);


            #line default
            #line hidden
            WriteLiteral("\" />\r\n    </p>\r\n    </fieldset>\r\n    <p>\r\n        <a href=\"#\" onclick=\"showForgot" +
                         "PasswordInfo(); return false;\">");



            #line 57 "..\..\Login.cshtml"
            Write(AdminResources.ForgotPassword);


            #line default
            #line hidden
            WriteLiteral("</a>\r\n    </p>\r\n</form>\r\n<br />\r\n");



            #line 61 "..\..\Login.cshtml"

            var passwordFileLocation = AdminSecurity.AdminPasswordFile.TrimStart('~', '/');
            var forgotPasswordHelp   = String.Format(CultureInfo.CurrentCulture, AdminResources.AdminPasswordChangeInstructions, Html.Encode(passwordFileLocation));



            #line default
            #line hidden
            WriteLiteral("<span id=\"forgotPasswordInfo\" style=\"display: none\">");



            #line 65 "..\..\Login.cshtml"
            Write(Html.Raw(forgotPasswordHelp));


            #line default
            #line hidden
            WriteLiteral("</span>");
        }
        public override void Execute()
        {
            WriteLiteral("\r\n\r\n");



            #line 4 "..\..\packages\PackageSources.cshtml"

            // Setup layout
            var currentPage = Href(PageUtils.GetPageVirtualPath("PackageSources"));
            PageData["BreadCrumbs"].Add(Tuple.Create(PackageManagerResources.ManageSourcesTitle, currentPage));
            Page.Desc         = PackageManagerResources.ManageSourcesDesc;
            Page.SectionTitle = PackageManagerResources.ManageSourcesTitle;

            if (IsPost)
            {
                AntiForgery.Validate();
                var action     = Request.Form["action"];
                var sourceUrl  = Request.Form["sourceUrl"];
                var sourceName = Request.Form["sourceName"];
                try {
                    if (action.Equals(PackageManagerResources.AddPackageSourceLabel, StringComparison.OrdinalIgnoreCase))
                    {
                        ModelState.SetModelValue("sourceName", sourceName);
                        ModelState.SetModelValue("sourceUrl", sourceUrl);

                        Uri url;
                        if (!Uri.TryCreate(sourceUrl, UriKind.Absolute, out url))
                        {
                            ModelState.AddError("sourceUrl", PackageManagerResources.Validation_InvalidPackageSourceUrl);
                        }
                        else if (!PackageManagerModule.AddPackageSource(source: sourceUrl, name: sourceName))
                        {
                            ModelState.AddError("sourceName", PackageManagerResources.Validation_PackageSourceAlreadyExists);
                        }
                        else
                        {
                            // The feed was successfully added. Clear the model state.
                            ModelState.Clear();
                        }
                    }
                    else if (action.Equals(PackageManagerResources.DeleteLabel, StringComparison.OrdinalIgnoreCase))
                    {
                        PackageManagerModule.RemovePackageSource(sourceName);
                    }
                    else if (action.Equals(PackageManagerResources.RestoreDefaultSources, StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (var packageSource in PackageManagerModule.DefaultSources)
                        {
                            PackageManagerModule.AddPackageSource(packageSource);
                        }
                    }
                } catch (UnauthorizedAccessException) {
            #line default
            #line hidden
                    WriteLiteral("            <div class=\"message error\">\r\n                ");



            #line 42 "..\..\packages\PackageSources.cshtml"
                    Write(String.Format(CultureInfo.CurrentCulture, PackageManagerResources.PackageSourceFileInstructions, PackageManagerModule.PackageSourceFilePath));


            #line default
            #line hidden
                    WriteLiteral("\r\n            </div>\r\n");



            #line 44 "..\..\packages\PackageSources.cshtml"
                }
            }

            var numSources = PackageManagerModule.PackageSources.Count();



            #line default
            #line hidden
            WriteLiteral("\r\n");



            #line 50 "..\..\packages\PackageSources.cshtml"
            Write(Html.ValidationSummary(excludeFieldErrors: true));


            #line default
            #line hidden
            WriteLiteral("\r\n\r\n<table id=\"feeds\">\r\n<thead>\r\n    <tr>\r\n        <th scope=\"col\">");



            #line 55 "..\..\packages\PackageSources.cshtml"
            Write(PackageManagerResources.SourceNameLabel);


            #line default
            #line hidden
            WriteLiteral("</th>\r\n        <th scope=\"col\">");



            #line 56 "..\..\packages\PackageSources.cshtml"
            Write(PackageManagerResources.SourceUrlLabel);


            #line default
            #line hidden
            WriteLiteral("</th>\r\n        <th></th>\r\n    </tr>\r\n</thead>\r\n<tbody>     \r\n");



            #line 61 "..\..\packages\PackageSources.cshtml"
            foreach (var source in PackageManagerModule.PackageSources)
            {
            #line default
            #line hidden
                WriteLiteral("    <tr>\r\n        <td>");



            #line 63 "..\..\packages\PackageSources.cshtml"
                Write(source.Name);


            #line default
            #line hidden
                WriteLiteral("</td>\r\n        <td><a href=\"");



            #line 64 "..\..\packages\PackageSources.cshtml"
                Write(source.Source);


            #line default
            #line hidden
                WriteLiteral("\">");



            #line 64 "..\..\packages\PackageSources.cshtml"
                Write(source.Source);


            #line default
            #line hidden
                WriteLiteral("</a></td>\r\n        <td>\r\n");



            #line 66 "..\..\packages\PackageSources.cshtml"
                if (numSources > 1)
                {
            #line default
            #line hidden
                    WriteLiteral("                <form method=\"post\" action=\"\">\r\n                    <input type=\"" +
                                 "hidden\" name=\"sourceName\" value=\"");



            #line 68 "..\..\packages\PackageSources.cshtml"
                    Write(source.Name);


            #line default
            #line hidden
                    WriteLiteral("\" />\r\n                    <input type=\"submit\" name=\"action\" value=\"");



            #line 69 "..\..\packages\PackageSources.cshtml"
                    Write(PackageManagerResources.DeleteLabel);


            #line default
            #line hidden
                    WriteLiteral("\" />\r\n                    ");



            #line 70 "..\..\packages\PackageSources.cshtml"
                    Write(AntiForgery.GetHtml());


            #line default
            #line hidden
                    WriteLiteral("\r\n                </form>\r\n");



            #line 72 "..\..\packages\PackageSources.cshtml"
                }


            #line default
            #line hidden
                WriteLiteral("        </td>\r\n    </tr>\r\n");



            #line 75 "..\..\packages\PackageSources.cshtml"
            }


            #line default
            #line hidden
            WriteLiteral("</tbody>\r\n</table>\r\n<br />\r\n<form method=\"post\" action=\"\">\r\n");



            #line 80 "..\..\packages\PackageSources.cshtml"
            Write(AntiForgery.GetHtml());


            #line default
            #line hidden
            WriteLiteral("\r\n<fieldset>\r\n    <legend>");



            #line 82 "..\..\packages\PackageSources.cshtml"
            Write(PackageManagerResources.AddPackageSourceLabel);


            #line default
            #line hidden
            WriteLiteral("</legend>\r\n    <ol>\r\n        <li>\r\n            <label for=\"feedName\">");



            #line 85 "..\..\packages\PackageSources.cshtml"
            Write(PackageManagerResources.SourceNameLabel);


            #line default
            #line hidden
            WriteLiteral(":</label>\r\n            ");



            #line 86 "..\..\packages\PackageSources.cshtml"
            Write(Html.TextBox("sourceName"));


            #line default
            #line hidden
            WriteLiteral(" ");



            #line 86 "..\..\packages\PackageSources.cshtml"
            Write(Html.ValidationMessage("sourceName"));


            #line default
            #line hidden
            WriteLiteral("\r\n        </li>\r\n        <li>\r\n            <label for=\"feedUrl\">");



            #line 89 "..\..\packages\PackageSources.cshtml"
            Write(PackageManagerResources.SourceUrlLabel);


            #line default
            #line hidden
            WriteLiteral(":</label>\r\n            ");



            #line 90 "..\..\packages\PackageSources.cshtml"
            Write(Html.TextBox("sourceUrl"));


            #line default
            #line hidden
            WriteLiteral(" ");



            #line 90 "..\..\packages\PackageSources.cshtml"
            Write(Html.ValidationMessage("sourceUrl"));


            #line default
            #line hidden
            WriteLiteral("\r\n        </li>\r\n    </ol>\r\n    <p class=\"form-actions\">\r\n        \r\n    <input ty" +
                         "pe=\"submit\" name=\"action\" class=\"long-input\" value=\"");



            #line 95 "..\..\packages\PackageSources.cshtml"
            Write(PackageManagerResources.AddPackageSourceLabel);


            #line default
            #line hidden
            WriteLiteral("\" />\r\n    </p>\r\n</fieldset>\r\n</form>\r\n\r\n");



            #line 100 "..\..\packages\PackageSources.cshtml"

            if (PackageManagerModule.DefaultSources.Intersect(PackageManagerModule.PackageSources).Count() != PackageManagerModule.DefaultSources.Count())
            {
            #line default
            #line hidden
                WriteLiteral("    <p>\r\n        <form method=\"post\" action=\"\">\r\n            ");



            #line 104 "..\..\packages\PackageSources.cshtml"
                Write(AntiForgery.GetHtml());


            #line default
            #line hidden
                WriteLiteral("\r\n            <fieldset class=\"no-border\">  \r\n                <input type=\"submit" +
                             "\" name=\"action\" class=\"long-input\"  value=\"");



            #line 106 "..\..\packages\PackageSources.cshtml"
                Write(PackageManagerResources.RestoreDefaultSources);


            #line default
            #line hidden
                WriteLiteral("\" />\r\n            </fieldset>\r\n        </form>\r\n    </p>\r\n");



            #line 110 "..\..\packages\PackageSources.cshtml"
            }



            #line default
            #line hidden
        }
Ejemplo n.º 23
0
    public void ProcessRequest(HttpContext context)
    {
        AntiForgery.Validate();

        if (!WebUser.IsAuthenticated)
        {
            throw new HttpException(401, "You must login to do this");
        }

        if (!WebUser.HasRole(UserRoles.Admin))
        {
            throw new HttpException(401, "You do not have permission to do this");
        }

        var mode                = context.Request.Form["mode"];
        var username            = context.Request.Form["accountName"];
        var password1           = context.Request.Form["accountPassword1"];
        var password2           = context.Request.Form["accountPassword2"];
        var id                  = context.Request.Form["accountId"];
        var email               = context.Request.Form["accountEmail"];
        var userRoles           = context.Request.Form["accountRoles"];
        var resourceItem        = context.Request.Form["resourceItem"];
        IEnumerable <int> roles = new int[] { };

        if (!string.IsNullOrEmpty(userRoles))
        {
            roles = userRoles.Split(',').Select(v => Convert.ToInt32(v));
        }


        if (mode == "delete")
        {
            Delete(username ?? resourceItem);
        }
        else
        {
            if (password1 != password2)
            {
                throw new Exception("Passwords do not match");
            }
            if (string.IsNullOrWhiteSpace(email))
            {
                throw new Exception("Email cannot be blank");
            }
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new Exception("Username cannot be blank");
            }
            if (mode == "edit")
            {
                Edit(Convert.ToInt32(id), username, password1, email, roles);
            }
            else if (mode == "new")
            {
                Create(username, password1, email, roles);
            }
        }

        if (string.IsNullOrEmpty(resourceItem))
        {
            context.Response.Redirect("~/admin/account");
        }
    }
Ejemplo n.º 24
0
        public ActionResult Edit(int id)
        {
            Election election = db.Elections.Find(id);

            if (election == null)
            {
                return(HttpNotFound());
            }

            CouncilElectionData councilData = null;
            CouncilElectionForm councilForm = null;
            ElectionForm        form;

            if (election.Type == ElectionType.StudentCouncil)
            {
                councilData = db.CouncilElectionData.First(data => data.ElectionId == election.Id);
                form        = councilForm = GenerateFormForCouncil(election, councilData);
            }
            else
            {
                form = GenerateFormForCourseRep(election);
            }

            ModelFieldsAccessibility fieldsInfo = ElectionLifecycleInfo.GetWhatCanBeEditedCouncil(election);

            ViewData[FormConstants.FieldsInfoKey] = fieldsInfo;
            ViewBag.Election = election;

            fieldsInfo.EnsureAllowedDefaultKind(
                ModelFieldsAccessibility.Kind.Editable,
                nameof(AdminElectionsController) + "." + nameof(Edit)
                );

            if (Request.HttpMethod.ToUpper() != "POST")
            {
                // Just show the template
                return(View("Edit", form));
            }

            AntiForgery.Validate();

            // Update the form based on data that we received
            // ReSharper disable once ConvertIfStatementToNullCoalescingExpression - we need the compiler to specify different generic arguments
            if (councilForm != null)
            {
                TryUpdateModel(councilForm);
            }
            else
            {
                TryUpdateModel(form);
            }

            // Get the original form so that we use old values for uneditable fields
            CouncilElectionForm councilOriginalForm = null;
            ElectionForm        originalForm;

            if (councilForm != null)
            {
                originalForm = councilOriginalForm = GenerateFormForCouncil(election, councilData);
            }
            else
            {
                originalForm = GenerateFormForCourseRep(election);
            }

            // Replace all uneditable values with old ones
            fieldsInfo.ReplaceUneditableWithOldValues(form, originalForm);

            // As the role IDs are sent from user, we need to make sure that they weren't changed
            if (councilForm != null && fieldsInfo.CanBeChangedByUser(nameof(CouncilElectionForm.Roles)))
            {
                IEnumerable <int?> initialRoleIds = councilOriginalForm.Roles.Select(role => role.Id);
                IEnumerable <int?> newRoleIds     = councilForm.Roles.Select(role => role.Id);

                if (!initialRoleIds.SequenceEqual(newRoleIds))
                {
                    throw new Exception("The IDs of roles were changed by user input");
                }
            }

            // Validate again (since some rules are relative to other fields and can be affected by operations above)
            TryValidateModel(form);

            // Ignore the failures from uneditable fields
            this.RemoveIgnoredErrors(fieldsInfo);

            if (!ModelState.IsValid)
            {
                // The validation failed so we just display the form again
                return(View("Edit", form));
            }

            // Record the admin action
            AdminActionRecord actionRecord = CreateActionRecord(election, AdminActionRecord.RecordType.Edit);

            actionRecord.SetFormChangeSet(FormChangeSet.Generate(form, originalForm));
            db.AdminActionRecords.Add(actionRecord);

            // Validation passed with the fields that are allowed to change. Persist the changes
            Mapper.Map(form, election);
            if (councilData != null)
            {
                Mapper.Map(form, councilData);
            }

            db.SaveChanges();

            BackgroundJob.Enqueue <SynchronizeDelayedJobsJob>(job => job.Execute(election.Id));
            AuditLogManager.RecordElectionEdit(User, election);

            return(RedirectToAction("Details", new { id }));
        }
Ejemplo n.º 25
0
    public void ProcessRequest(HttpContext context)
    {
        AntiForgery.Validate();

        if (!WebUser.IsAuthenticated)
        {
            throw new HttpException(401, "You must login to do this.");
        }

        if (!WebUser.HasRole(UserRoles.Admin) &&
            !WebUser.HasRole(UserRoles.Editor) &&
            !WebUser.HasRole(UserRoles.Author))
        {
            throw new HttpException(401, "You do not have permission to do that.");
        }

        var mode          = context.Request.Form["mode"];
        var title         = context.Request.Form["postTitle"];
        var content       = context.Request.Form["postContent"];
        var slug          = context.Request.Form["postSlug"];
        var id            = context.Request.Form["postId"];
        var datePublished = context.Request.Form["postDatePublished"];
        var postTags      = context.Request.Form["postTags"];
        var authorId      = context.Request.Form["postAuthorId"];
        var resourceItem  = context.Request.Form["resourceItem"];

        IEnumerable <int> tags = new int[] { };

        if (!string.IsNullOrEmpty(postTags))
        {
            tags = postTags.Split(',').Select(v => Convert.ToInt32(v));
        }

        if ((mode == "edit" || mode == "delete") && WebUser.HasRole(UserRoles.Author))
        {
            if (WebUser.UserId != Convert.ToInt32(authorId))
            {
                throw new HttpException(401, "You do not have permission to do that.");
            }
        }

        if (mode == "delete")
        {
            DeletePost(slug ?? resourceItem);
        }
        else
        {
            if (string.IsNullOrWhiteSpace(slug))
            {
                slug = CreateSlug(title);
            }

            if (mode == "edit")
            {
                EditPost(Convert.ToInt32(id), title, content, slug, datePublished, Convert.ToInt32(authorId), tags);
            }
            else if (mode == "new")
            {
                CreatePost(title, content, slug, datePublished, WebUser.UserId, tags);
            }
        }

        if (string.IsNullOrEmpty(resourceItem))
        {
            context.Response.Redirect("~/admin/post/");
        }
    }
Ejemplo n.º 26
0
 public static void ValidateToken(HttpContext context)
 {
     AntiForgery.Validate();
 }
Ejemplo n.º 27
0
        public async Task <ActionResult> Index(string author, bool?showTemplates, string selectedAuthor, string selectedLanguage, int?selectedCategoryId, string search)
        {
            ApplicationUser user = null;

            string selectedAuthor2 = selectedAuthor;

            if (User.Identity.IsAuthenticated)
            {
                user = await db.Users.FirstOrDefaultAsync(u => u.UserName == User.Identity.Name);

                if (Request.HttpMethod == "POST")
                {
                    AntiForgery.Validate();

                    // Update user.
                    if (!string.IsNullOrEmpty(author) && showTemplates != null &&
                        (user.Author != author || user.ShowTemplates != showTemplates))
                    {
                        // Fix selectedAuthor if same as author which is being modified.
                        if (selectedAuthor2 == user.Author)
                        {
                            selectedAuthor2 = author;
                        }

                        // Update db.
                        user.Author        = author;
                        user.ShowTemplates = showTemplates.GetValueOrDefault();
                        await db.SaveChangesAsync();
                    }
                }
                else
                {
                    // On GET, initialize selectedUser to the current user.  On POST, user
                    // could have changed it.
                    selectedAuthor2 = user.Author;
                }
            }

            // Then do search.
            search = search?.Trim();

            // base query
            IQueryable <MvvmTemplate> templates;

            if (user == null)
            {
                templates = from t in db.MvvmTemplates
                            where t.Enabled && t.ApplicationUser.ShowTemplates
                            select t;
            }
            else
            {
                // If logged in, also show all templates for the current user no matter
                // the user's ShowTemplates flag or Enabled flags on the templates.
                templates = from t in db.MvvmTemplates
                            where t.ApplicationUserId == user.Id ||
                            user.UserName == Secrets.AdminUserName ||
                            (t.Enabled && t.ApplicationUser.ShowTemplates)
                            select t;
            }
            // add author condition
            if (!string.IsNullOrEmpty(selectedAuthor2))
            {
                templates = templates.Where(t => t.ApplicationUser.Author == selectedAuthor2);
            }
            // add language condition
            if (!string.IsNullOrEmpty(selectedLanguage))
            {
                templates = templates.Where(t => t.Language == selectedLanguage);
            }
            // add category condition
            if (selectedCategoryId != null)
            {
                templates = templates.Where(t => t.MvvmTemplateCategoryId == selectedCategoryId);
            }
            // add search text condition
            if (!string.IsNullOrWhiteSpace(search))
            {
                templates = templates.Where(
                    t => t.Name.ToLower().Contains(search.ToLower()) ||
                    t.View.ToLower().Contains(search.ToLower()) ||
                    t.ViewModel.ToLower().Contains(search));
            }
            // Leave off view and view model text fields since they won't be needed on the client.
            var query = templates.Select(t => new Template
            {
                Author   = t.ApplicationUser.Author,
                Name     = t.Name,
                Id       = t.Id,
                Category = db.MvvmTemplateCategories.FirstOrDefault(c => c.Id == t.MvvmTemplateCategoryId).Name,
                Language = t.Language,
                Enabled  = t.Enabled
            });

            string curUserName  = user?.UserName;
            var    authorsQuery = from u in db.Users
                                  where (u.ShowTemplates && u.MvvmTemplates.Any(t => t.Enabled)) ||
                                  (curUserName != null && u.UserName == curUserName) ||
                                  (string.IsNullOrEmpty(selectedAuthor2) && u.Author == selectedAuthor2)
                                  select u;
            var authorsList = await authorsQuery.ToListAsync();

            // Generate model.
            var model = new TemplateIndexViewModel(
                user?.Author,
                user != null && user.ShowTemplates,
                await query.ToListAsync(),
                authorsList,
                selectedAuthor2,
                selectedCategoryId.GetValueOrDefault(),
                await db.MvvmTemplateCategories.ToListAsync(),
                string.IsNullOrWhiteSpace(selectedLanguage) ? null : selectedLanguage,
                string.IsNullOrWhiteSpace(search) ? null : search);

            return(View(model));
        }
 private void ValidateToken(string cookieToken, string formToken)
 {
     AntiForgery.Validate(cookieToken, formToken);
 }
Ejemplo n.º 29
0
        public ActionResult PlayWithUnifiedGroups(PlayWithUsersViewModel model)
        {
            AntiForgery.Validate();

            var groups         = UsersGroupsHelper.ListUnifiedGroups(100);
            var group          = UsersGroupsHelper.GetGroup(groups[0].Id);
            var owners         = UsersGroupsHelper.ListGroupOwners(group.Id);
            var members        = UsersGroupsHelper.ListGroupMembers(group.Id);
            var photo          = UsersGroupsHelper.GetGroupPhoto(group.Id);
            var calendar       = UnifiedGroupsHelper.GetUnifiedGroupCalendar(group.Id);
            var calendarEvents = UnifiedGroupsHelper.ListUnifiedGroupEvents(group.Id);
            var events         = UnifiedGroupsHelper.ListUnifiedGroupEvents(group.Id, DateTime.Now,
                                                                            DateTime.Now.AddMonths(1), 0);

            var conversations      = UnifiedGroupsHelper.ListUnifiedGroupConversations(group.Id);
            var threads            = UnifiedGroupsHelper.ListUnifiedGroupThreads(group.Id);
            var postsOfThread      = UnifiedGroupsHelper.ListUnifiedGroupThreadPosts(group.Id, threads[0].Id);
            var singlePostOfThread = UnifiedGroupsHelper.GetUnifiedGroupThreadPost(group.Id, threads[0].Id, postsOfThread[0].Id);

            UnifiedGroupsHelper.ReplyToUnifiedGroupThread(group.Id, threads[0].Id,
                                                          new Models.ConversationThreadPost
            {
                Body = new Models.ItemBody
                {
                    Type    = Models.BodyType.Html,
                    Content = "<html><body><div>This is the body of a post created via the Microsoft Graph API!</div></body></html>",
                },
                NewParticipants = new List <Models.UserInfoContainer>(
                    new Models.UserInfoContainer[] {
                    new Models.UserInfoContainer {
                        Recipient = new Models.UserInfo {
                            Name    = model.MailSendToDescription,
                            Address = model.MailSendTo,
                        }
                    }
                }),
            });

            var drive = UnifiedGroupsHelper.GetUnifiedGroupDrive(group.Id);

            var newUnifiedGroup = UnifiedGroupsHelper.AddUnifiedGroup(
                new Models.Group
            {
                DisplayName     = "Created via API",
                MailEnabled     = true,
                SecurityEnabled = false,
                GroupTypes      = new List <String>(new String[] { "Unified" }),
                MailNickname    = "APICreated",
            });

            // Wait for a while to complete Office 365 Group creation
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(30));

            MemoryStream memPhoto = new MemoryStream();

            using (FileStream fs = new FileStream(Server.MapPath("~/AppIcon.png"), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Byte[] newPhoto = new Byte[fs.Length];
                fs.Read(newPhoto, 0, (Int32)(fs.Length - 1));
                memPhoto.Write(newPhoto, 0, newPhoto.Length);
                memPhoto.Position = 0;
            }

            try
            {
                if (memPhoto.Length > 0)
                {
                    UnifiedGroupsHelper.UpdateUnifiedGroupPhoto(newUnifiedGroup.Id, memPhoto);
                }
            }
            catch (Exception ex)
            {
                // Handle the exception
            }

            UnifiedGroupsHelper.DeleteUnifiedGroup(newUnifiedGroup.Id);

            return(View("Index"));
        }
Ejemplo n.º 30
0
        public ActionResult PlayWithUsers(PlayWithUsersViewModel model)
        {
            AntiForgery.Validate();

            var users                     = UsersGroupsHelper.ListUsers(600);
            var externalUsers             = UsersGroupsHelper.ListExternalUsers(600);
            var usersWithCustomAttributes = UsersGroupsHelper.ListUsers(
                new String[] { "id", "userPrincipalName", "mail",
                               "department", "country", "preferredLanguage",
                               "onPremisesImmutableId", "onPremisesSecurityIdentifier",
                               "onPremisesSyncEnabled", "userType" },
                600);

            try
            {
                var usersWorkingInIT = UsersGroupsHelper.ListUsersByDepartment("IT", 100);
                var oneUser          = UsersGroupsHelper.GetUser(model.UserPrincipalName);

                oneUser.City = "Brescia";
                UsersGroupsHelper.UpdateUser(oneUser);
            }
            catch (Exception)
            {
                // Something wrong while getting the thumbnail,
                // We will have to handle it properly ...
            }

            try
            {
                var newUser = UsersGroupsHelper.AddUser(
                    new Models.User
                {
                    AccountEnabled  = true,
                    DisplayName     = "API Created",
                    PasswordProfile = new Models.PasswordProfile
                    {
                        ForceChangePasswordNextSignIn = true,
                        Password = "******",
                    },
                    UserPrincipalName = $"api-created@{model.UserPrincipalName.Substring(model.UserPrincipalName.IndexOf("@") + 1)}",
                }
                    );
            }
            catch (Exception)
            {
                // Something wrong while getting the thumbnail,
                // We will have to handle it properly ...
            }

            try
            {
                var oneUserManager = UsersGroupsHelper.GetUserManager(model.UserPrincipalName);
                var oneUserManagerDirectReports = UsersGroupsHelper.GetUserDirectReports(oneUserManager.UserPrincipalName);
            }
            catch (Exception)
            {
                // Something wrong while getting the thumbnail,
                // We will have to handle it properly ...
            }

            return(View("Index"));
        }