Files
2020-06-30 16:35:24 +02:00

172 lines
5.3 KiB
C#

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Security.OAuth;
using Microsoft.Owin.StaticFiles;
using Microsoft.Owin.StaticFiles.ContentTypes;
using Newtonsoft.Json;
using Owin;
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Web.Http;
using Thermo.Active.Core;
using Thermo.Active.Provider;
using Thermo.Active.Utils;
using static Thermo.Active.Config.ServerConfig;
using static Thermo.Active.Model.Constants;
[assembly: OwinStartup(typeof(Thermo.Active.App_Start.Startup))]
namespace Thermo.Active.App_Start
{
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions;
public void Configuration(IAppBuilder app)
{
if (NcConfig.NcVendor.ToUpper() == NC_VENDOR.SIEMENS && NcConfig.ShowNcHMI)
ThreadSiemensHmi.InitWindow();
// aggiunto x CORSe accesso remote al progetto
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// Configure HTTP
HttpConfiguration config = new HttpConfiguration();
// Register Web API config
WebApiConfig.Register(config);
// Register Swagger config
SwaggerConfig.Register(config);
// Configure api authentication
ConfigureWebApiOAuth(app);
app.UseWebApi(config);
// SignalR config & startup
SignalRConfig(app);
var directoryBrowsing = ConfigurationManager.AppSettings["enableDirectoryBrowsing"] == "true";
// Check if web site directory exists
if (!Directory.Exists(WEBSITE_DIRECTORY))
ExceptionManager.ManageError(ERROR_LEVEL.FATAL, "Main window directory not found!");
var options = new FileServerOptions()
{
EnableDefaultFiles = !directoryBrowsing,
EnableDirectoryBrowsing = directoryBrowsing,
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem(WEBSITE_DIRECTORY),
};
options.StaticFileOptions.ServeUnknownFileTypes = true;
options.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider();
((FileExtensionContentTypeProvider)options.StaticFileOptions.ContentTypeProvider).Mappings.Remove(".json");
((FileExtensionContentTypeProvider)options.StaticFileOptions.ContentTypeProvider).Mappings.Add("json", "application/json");
((FileExtensionContentTypeProvider)options.StaticFileOptions.ContentTypeProvider).Mappings.Remove(".ttf");
((FileExtensionContentTypeProvider)options.StaticFileOptions.ContentTypeProvider).Mappings.Add(".ttf", "font/ttf");
//// Setup configuration sources.
//Configuration = new Configuration().AddJsonFile("config.json").AddEnvironmentVariables();
//contentProvider.Mappings.Add(".woff2", "application/font-woff2");
app.UseFileServer(options);
if (!ServerPortIsAvailable(ServerStartupConfig.ServerPort))
{
ExceptionManager.ManageError(ERROR_LEVEL.FATAL, "Server port is already in use by another process");
}
}
private void ConfigureWebApiOAuth(IAppBuilder app)
{
// Create new authorization options
OAuthOptions = new OAuthAuthorizationServerOptions
{
// Login and Token generation end point
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(),
// Bearer token expiration time
AccessTokenExpireTimeSpan = TimeSpan.FromDays(365),
//TODO: In modalit di produzione impostare AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Set authorization options
app.UseOAuthAuthorizationServer(OAuthOptions);
// Set bearer oAuth as authentication method
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { AuthenticationType = AUTHENTICATION_TYPE });
}
public void SignalRConfig(IAppBuilder app)
{
// Set CamelCase json configuration
var settings = new JsonSerializerSettings
{
ContractResolver = new SignalRContractResolver()
};
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
// Set up signalR config
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new SignalROAuthBearerProvider(),
AuthenticationType = AUTHENTICATION_TYPE
});
var hubConfiguration = new HubConfiguration
{
Resolver = GlobalHost.DependencyResolver,
EnableDetailedErrors = true
};
map.RunSignalR(hubConfiguration);
});
//app.MapSignalR();
}
private bool ServerPortIsAvailable(int port)
{
bool isAvailable = true;
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
foreach (IPEndPoint endPoint in ipEndPoints)
{
if (endPoint.Port == port)
{
isAvailable = false;
break;
}
}
return isAvailable;
}
}
}
//app.Map("/signalr", map =>
//{
// map.UseCors(CorsOptions.AllowAll);
// // Debug
// HubConfiguration hubConfiguration = new HubConfiguration
// {
// EnableDetailedErrors = true
// };
// // Create an istance of custom authorize attribute
// SignalRAuthorizeAttribute authorizer = new SignalRAuthorizeAttribute();
// AuthorizeModule module = new AuthorizeModule(authorizer, authorizer);
// GlobalHost.HubPipeline.AddModule(module);
// map.RunSignalR();
//});