Esempio n. 1
0
        public static void MockUser(this TestApplication app)
        {
            var userRepo       = app.GetService <IRepository <User> >();
            var passwordHasher = app.GetService <IPasswordHasher <User> >();

            var user = new User
            {
                CreatedAtUtc   = DateTime.UtcNow.AddDays(-1),
                UserName       = "******",
                DisplayName    = "FancyUser",
                HashedPassword = passwordHasher.HashPassword(null, "111111")
            };

            userRepo.Save(user);

            var lastSigninTime = DateTime.UtcNow.AddMinutes(-30);
            var claims         = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.Integer32),
                new Claim(ClaimTypes.Name, user.UserName, ClaimValueTypes.String),
                new Claim("SigninTime", lastSigninTime.Ticks.ToString(), ClaimValueTypes.Integer64)
            };
            var identity = new ClaimsIdentity(claims, IdentityConstants.ApplicationScheme);

            app.User = new ClaimsPrincipal(identity);
        }
Esempio n. 2
0
        public static AntiForgeryRequestTokens GetFromApplication(TestApplication app)
        {
            var homeResponseTask = app.Server.CreateRequest("/").GetAsync();

            homeResponseTask.ConfigureAwait(false);
            homeResponseTask.Wait();

            var homeRes = homeResponseTask.Result;

            if (!homeRes.Headers.TryGetValues(HeaderNames.SetCookie, out var cookies))
            {
                cookies = Enumerable.Empty <string>();
            }
            var antiForgeryCookie = SetCookieHeaderValue.ParseList(cookies.ToList()).FirstOrDefault(cookie => cookie.Name.ToString().StartsWith(".AspNetCore.Antiforgery"));

            if (antiForgeryCookie == null)
            {
                throw new InvalidOperationException("无法从服务器获取 AntiForgery Cookie");
            }

            var          htmlContent      = homeRes.ReadAllContent();
            const string tokenStart       = "window.__RequestVerificationToken";
            var          tokenHtmlContent = htmlContent.Substring(htmlContent.LastIndexOf(tokenStart));
            var          tokenPattern     = new Regex(@"^window\.__RequestVerificationToken[^']+'(?<token>[^']+)';");

            var token     = tokenPattern.Match(tokenHtmlContent).Groups["token"].Value;
            var reqCookie = new Cookie(antiForgeryCookie.Name.ToString(), antiForgeryCookie.Value.ToString());

            return(new AntiForgeryRequestTokens
            {
                VerificationToken = token,
                Cookie = reqCookie
            });
        }
Esempio n. 3
0
        public static ModelStateDictionary ValidateModel(this TestApplication app, object model)
        {
            var validator     = app.GetService <IObjectModelValidator>();
            var actionContext = new ActionContext();

            validator.Validate(actionContext, null, string.Empty, model);

            return(actionContext.ModelState);
        }
Esempio n. 4
0
        public static TestApplication BuildApplication(TestApplication testApp, string environmentName = "Production", Action <IWebHostBuilder> configureHost = null)
        {
            testApp.LoggerProvider = new StubLoggerProvider();
            testApp.User           = new ClaimsPrincipal(new ClaimsIdentity());

            var hostBuilder = new WebHostBuilder();

            configureHost?.Invoke(hostBuilder);
            hostBuilder.ConfigureServices(services =>
            {
                services.AddTransient <HttpContextFactory>();
                services.AddTransient <IHttpContextFactory>((sp) =>
                {
                    var defaultContextFactory = sp.GetService <HttpContextFactory>();
                    var httpContextFactory    = new WrappedHttpContextFactory(defaultContextFactory);
                    httpContextFactory.ConfigureFeatureWithContext((features, httpCtx) =>
                    {
                        features.Set <IHttpAuthenticationFeature>(new HttpAuthenticationFeature {
                            User = testApp.User
                        });
                        features.Set <IServiceProvidersFeature>(new RequestServicesFeature(httpCtx, testApp.ServiceReplacer.CreateScopeFactory()));
                    });
                    return(httpContextFactory);
                });
            });

            Environment.SetEnvironmentVariable("DOTNETCLUB_sqliteConnectionString", " ");
            Environment.SetEnvironmentVariable("DOTNETCLUB_Logging:Console:LogLevel:Default", "Warning");
            Configuration.ConfigureHost(hostBuilder);

            hostBuilder.ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                loggingBuilder.AddProvider(testApp.LoggerProvider);
            });
            hostBuilder
            .UseContentRoot(WebProjectPath())
            .UseEnvironment(environmentName)
            .UseStartup <Startup>();

            testApp.Server = new TestServer(hostBuilder);
            testApp.ApplicationServices = testApp.Server.Host.Services;
            testApp.ServiceReplacer     = new ReplacableServiceProvider(testApp.ApplicationServices);

            return(testApp);
        }
Esempio n. 5
0
        public static RequestBuilder RequestAntiForgeryForm(this TestApplication app, string path, Dictionary <string, string> obj = null)
        {
            var tokens  = app.GetAntiForgeryTokens();
            var request = app.Server.CreateRequest(path);

            return(request.And(req =>
            {
                if (obj == null)
                {
                    obj = new Dictionary <string, string>();
                }

                obj["__RequestVerificationToken"] = tokens.VerificationToken;
                req.Content = new FormUrlEncodedContent(obj);
            })
                   .WithCookie(tokens.Cookie));
        }
Esempio n. 6
0
        public static T CreateController <T>(this TestApplication app) where T : Controller
        {
            var httpContext = app.GetService <IHttpContextFactory>().Create(new DefaultHttpContext().Features);

            httpContext.User = app.User;

            var actionContext = new ActionContext(
                httpContext,
                new RouteData(),
                new ControllerActionDescriptor
            {
                ControllerTypeInfo = typeof(T).GetTypeInfo()
            });

            return(app.GetService <IControllerFactory>()
                   .CreateController(new ControllerContext(actionContext)) as T);
        }
        public static User CreateUser(this TestApplication app, string username, string password = null, string displayName = null)
        {
            var actualPassword = string.IsNullOrEmpty(password) ? Guid.NewGuid().ToString("N").Substring(4, 8) : password;
            var userManager    = app.GetService <UserManager <User> >();
            var user           = new User
            {
                UserName     = username,
                DisplayName  = string.IsNullOrEmpty(displayName) ? username : displayName,
                CreatedAtUtc = DateTime.UtcNow
            };

            var task = userManager.CreateAsync(user, actualPassword);

            task.ConfigureAwait(false);
            task.Wait();

            return(user);
        }
Esempio n. 8
0
        public static User GetDiscussionUser(this TestApplication app)
        {
            var userRepo = app.GetService <IRepository <User> >();

            return(app.User.ToDiscussionUser(userRepo));
        }
Esempio n. 9
0
 public static T GetService <T>(this TestApplication app) where T : class
 {
     return(app.ApplicationServices.GetService <T>());
 }
Esempio n. 10
0
        public static IEnumerable <StubLoggerProvider.LogItem> GetLogs(this TestApplication app)
        {
            var loggerProvider = app.ApplicationServices.GetRequiredService <ILoggerProvider>() as StubLoggerProvider;

            return(loggerProvider?.LogItems);
        }