Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc().AddJsonOptions(opt =>
            {
                opt.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
            services.AddLogging(builder => builder
                                .AddConsole()
                                .AddFilter(level => level >= Microsoft.Extensions.Logging.LogLevel.Trace)
                                );
            loggerFactory = services.BuildServiceProvider().GetService <ILoggerFactory>();
            AppLogger     = loggerFactory.CreateLogger <ConsoleLoggerProvider>();

            services.AddIdentity <User, IdentityRole>().AddEntityFrameworkStores <ApplicationDbContext>().AddDefaultTokenProviders();
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 1;
                options.SignIn.RequireConfirmedEmail    = false;
                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = true;
            });

            //services.ConfigureApplicationCookie(options =>
            //{
            //    // Cookie settings
            //    options.Cookie.HttpOnly = true;
            //    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

            //    options.LoginPath = "/api/Login";
            //    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            //    options.SlidingExpiration = true;
            //});

            //services.AddAuthentication(options =>
            //{
            //    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //})
            //.AddCookie(options =>
            //{
            //    options.LoginPath = "/api/login";
            //    options.LogoutPath = "/auth/logout";
            //});

            services.AddAuthentication().AddFacebook(facebookOptions =>
            {
                facebookOptions.AppId     = Configuration["Authentication:Facebook:AppId"];
                facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            }).AddJwtBearer(
                options => options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateActor            = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = "yourdomain.com",
                ValidAudience    = "yourdomain.com",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["secret_key"])),
                ClockSkew        = TimeSpan.MinValue
            }
                );
            services.AddSignalR();
            services.AddSingleton <NotificationsHub>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddDbContextPool <ApplicationDbContext>(
                optionsAction => optionsAction.UseSqlServer(Configuration.GetConnectionString("MyDatabase")));

            //var scopeFactory = services.BuildServiceProvider()
            //               .GetRequiredService<IServiceScopeFactory>();
            //using (var scope = scopeFactory.CreateScope())
            //{
            //    using (var context = scope.ServiceProvider
            //                              .GetRequiredService<ApplicationDbContext>())
            //    {
            //        var loggerFactory = context.GetInfrastructure()
            //                                   .GetService<ILoggerFactory>();
            //        loggerFactory.AddProvider(new ConsoleLoggerProvider((_, __) => true, true));
            //    }
            //}
            var vapidDetails = new VapidDetails(
                Configuration.GetValue <string>("VapidDetails:Subject"),
                Configuration.GetValue <string>("VapidDetails:PublicKey"),
                Configuration.GetValue <string>("VapidDetails:PrivateKey"));

            services.AddTransient(c => vapidDetails);

            services.Configure <PushNotificationsOptions>(Configuration.GetSection("PushNotifications"));

            services.AddResponseCompression(options =>
            {
                options.EnableForHttps = true;
                options.MimeTypes      = ResponseCompressionDefaults.MimeTypes.Concat(new[]
                {
                    "image/svg+xml",
                    "application/atom+xml"
                });;
                options.Providers.Add <GzipCompressionProvider>();
            });
            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "PrintFramer API",
                    Description    = "Calculates the cost of a picture frame based on its dimensions.",
                    TermsOfService = "None",
                    Contact        = new Contact
                    {
                        Name  = "Your name",
                        Email = string.Empty,
                        Url   = "https://www.microsoft.com/learn"
                    }
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }
Пример #2
0
 private BAL()
 {
     _keys = VapidHelper.GenerateVapidKeys();
 }
Пример #3
0
 public PushService(HttpClient httpClient, VapidDetails vapid)
 {
     this._vapid   = vapid;
     this._webpush = new WebPushClient(httpClient);
 }
Пример #4
0
        public async Task Send()
        {
            var vapidDetails  = new VapidDetails(_webPushNotificationSettings.Subject, _webPushNotificationSettings.PublicKey, _webPushNotificationSettings.PrivateKey);
            var webPushClient = new WebPushClient();

            foreach (var pushUser in _pushUsers)
            {
                var pushSubscription = pushUser.PushSubscription;
                var subscription     = new WebPush.PushSubscription(pushSubscription.Endpoint, pushSubscription.Keys.P256dh, pushSubscription.Keys.Auth);

                foreach (var roadWay in pushUser.RoadWays)
                {
                    var previousRoadWay = _lastSentNotifications.FirstOrDefault(l => l.PushSubscription.Endpoint == pushUser.PushSubscription.Endpoint).RoadWays.FirstOrDefault(r => r.HmLocation == roadWay.HmLocation);
                    if (JsonConvert.SerializeObject(roadWay) == JsonConvert.SerializeObject(previousRoadWay))
                    {
                        continue;
                    }

                    foreach (var subscribedVms in roadWay.VariableMessageSigns)
                    {
                        var id = subscribedVms.Id;

                        var liveVms = _liveData.SingleOrDefault(l => l.Id == id);
                        var sign    = liveVms != null ? liveVms.Sign : "unknown";
                        subscribedVms.Sign = Reformat(id, sign);
                    }

                    var    body  = string.Join(' ', roadWay.VariableMessageSigns);
                    string image = null;

                    var lastSign       = roadWay.VariableMessageSigns.Last().Sign;
                    var isLaneSpecific = !(lastSign.StartsWith("TP|") || lastSign.StartsWith("live/"));
                    if (!isLaneSpecific)
                    {
                        if (lastSign.StartsWith("TP|"))
                        {
                            body = lastSign;
                        }
                        else if (lastSign.StartsWith("live/"))
                        {
                            image = string.Format("{0}/{1}", _webUrl, lastSign);
                        }
                    }

                    var notification = new Notification
                    {
                        Title = roadWay.HmLocation,
                        Icon  = "images/xanland.png",
                        Body  = isLaneSpecific || lastSign.StartsWith("TP|") ? body : "Klik op de afbeelding voor de volledige beeldstand.",
                        Image = isLaneSpecific ? null : image,
                        Tag   = isLaneSpecific ? string.Format("{0}={1}@{2}", roadWay.HmLocation, DateTime.UtcNow.Hour, DateTime.UtcNow.Day) : roadWay.HmLocation,
                        Data  = new NotificationData
                        {
                            CoordinatesUrl = roadWay.Coordinates != null?string.Format("{0}/?lat={1}&lon={2}&zoom=17", _webUrl, roadWay.Coordinates.X.ToString().Replace(',', '.'), roadWay.Coordinates.Y.ToString().Replace(',', '.')) : null,
                        },
                        Actions = new List <NotificationAction>
                        {
                            new NotificationAction
                            {
                                Action = "go-to-location",
                                Icon   = "images/xanland.png",
                                Title  = "Open locatie"
                            }
                        },
                        HmLocation     = roadWay.HmLocation,
                        LanesShownSign = string.Join(' ', roadWay.VariableMessageSigns),
                        DripShownSign  = false
                    };

                    try
                    {
                        await webPushClient.SendNotificationAsync(subscription, JsonConvert.SerializeObject(notification, new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        }), vapidDetails);
                    }
                    catch (Exception) { }
                }
            }

            PostProcess();
        }