From 9b6b3194e4708eea70b49576996e1acfd4e08e0d Mon Sep 17 00:00:00 2001 From: "CMS4390\\marantalu" Date: Thu, 23 Nov 2017 16:56:17 +0100 Subject: [PATCH] Project refactor and added comments --- Step.UI/ServerControlWindow.Designer.cs | 99 ++++++++--------- Step.UI/ServerControlWindow.cs | 123 +++++++++++----------- Step/App_Start/Startup.cs | 8 +- Step/App_Start/WebApiConfig.cs | 2 - Step/CmsAuthorizationAttribute.cs | 19 ++++ Step/Controllers/LoginController.cs | 14 +-- Step/Provider/ApplicationOAuthProvider.cs | 12 +-- Step/program.cs | 47 ++++----- 8 files changed, 172 insertions(+), 152 deletions(-) create mode 100644 Step/CmsAuthorizationAttribute.cs diff --git a/Step.UI/ServerControlWindow.Designer.cs b/Step.UI/ServerControlWindow.Designer.cs index 347d8fda..36164a60 100644 --- a/Step.UI/ServerControlWindow.Designer.cs +++ b/Step.UI/ServerControlWindow.Designer.cs @@ -28,59 +28,62 @@ /// private void InitializeComponent() { - this.components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ServerControlWindow)); - this.button1 = new System.Windows.Forms.Button(); - this.button2 = new System.Windows.Forms.Button(); - this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components); - this.SuspendLayout(); - // - // button1 - // - this.button1.Location = new System.Drawing.Point(12, 12); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(177, 69); - this.button1.TabIndex = 0; - this.button1.Text = "Server Stop"; - this.button1.UseVisualStyleBackColor = true; - this.button1.Click += new System.EventHandler(this.button1_Click); - // - // button2 - // - this.button2.Location = new System.Drawing.Point(211, 12); - this.button2.Name = "button2"; - this.button2.Size = new System.Drawing.Size(177, 69); - this.button2.TabIndex = 1; - this.button2.Text = "Open UI"; - this.button2.UseVisualStyleBackColor = true; - this.button2.Click += new System.EventHandler(this.button2_Click); - // - // notifyIcon1 - // - this.notifyIcon1.BalloonTipText = "CMS"; - this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon"))); - this.notifyIcon1.Text = "CMS Server"; - this.notifyIcon1.Visible = true; - this.notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click); - // - // ServerControlWindow - // - this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 24F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(400, 93); - this.Controls.Add(this.button2); - this.Controls.Add(this.button1); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.Name = "ServerControlWindow"; - this.Text = "Step"; - this.ResumeLayout(false); + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ServerControlWindow)); + this.stopServerButton = new System.Windows.Forms.Button(); + this.openUiButton = new System.Windows.Forms.Button(); + this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components); + this.SuspendLayout(); + // + // stopServerButton + // + this.stopServerButton.Location = new System.Drawing.Point(7, 7); + this.stopServerButton.Margin = new System.Windows.Forms.Padding(2); + this.stopServerButton.Name = "stopServerButton"; + this.stopServerButton.Size = new System.Drawing.Size(97, 37); + this.stopServerButton.TabIndex = 0; + this.stopServerButton.Text = "Server Stop"; + this.stopServerButton.UseVisualStyleBackColor = true; + this.stopServerButton.Click += new System.EventHandler(this.StopServerButton_Click); + // + // openUiButton + // + this.openUiButton.Location = new System.Drawing.Point(115, 7); + this.openUiButton.Margin = new System.Windows.Forms.Padding(2); + this.openUiButton.Name = "openUiButton"; + this.openUiButton.Size = new System.Drawing.Size(97, 37); + this.openUiButton.TabIndex = 1; + this.openUiButton.Text = "Open UI"; + this.openUiButton.UseVisualStyleBackColor = true; + this.openUiButton.Click += new System.EventHandler(this.OpenUiButton_Click); + // + // notifyIcon1 + // + this.notifyIcon1.BalloonTipText = "CMS"; + this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon"))); + this.notifyIcon1.Text = "CMS Server"; + this.notifyIcon1.Visible = true; + this.notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click); + // + // ServerControlWindow + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(218, 50); + this.Controls.Add(this.openUiButton); + this.Controls.Add(this.stopServerButton); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Margin = new System.Windows.Forms.Padding(2); + this.Name = "ServerControlWindow"; + this.Text = "Step"; + this.ResumeLayout(false); } #endregion - private System.Windows.Forms.Button button1; - private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button stopServerButton; + private System.Windows.Forms.Button openUiButton; private System.Windows.Forms.NotifyIcon notifyIcon1; } } \ No newline at end of file diff --git a/Step.UI/ServerControlWindow.cs b/Step.UI/ServerControlWindow.cs index b84ba46e..a499c720 100644 --- a/Step.UI/ServerControlWindow.cs +++ b/Step.UI/ServerControlWindow.cs @@ -14,68 +14,69 @@ using TeamDev.SDK.MVVM; namespace Step.UI { - public partial class ServerControlWindow : Form - { - public ServerControlWindow() + public partial class ServerControlWindow : Form { - InitializeComponent(); - } - - private static ServerControlWindow ctrlwindow = null; - - public static void Start() - { - Thread th = new Thread(() => - { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - ctrlwindow = new ServerControlWindow(); - Application.Run(ctrlwindow); - }); - - th.SetApartmentState(ApartmentState.STA); - th.Start(); - } - - public static void Stop() - { - if (ctrlwindow != null) - { - ctrlwindow.Invoke((ThreadStart)delegate () + public ServerControlWindow() { - ctrlwindow._closing = true; - ctrlwindow.Close(); - ctrlwindow = null; - }); - } + InitializeComponent(); + } + + private static ServerControlWindow ctrlwindow = null; + + public static void Start() + { // Open WinForm + Thread th = new Thread(() => + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + ctrlwindow = new ServerControlWindow(); + Application.Run(ctrlwindow); + }); + + th.SetApartmentState(ApartmentState.STA); + th.Start(); + } + + public static void Stop() + { // Close WinForm + if (ctrlwindow != null) + { + ctrlwindow.Invoke((ThreadStart)delegate () + { + ctrlwindow._closing = true; + ctrlwindow.Close(); + ctrlwindow = null; + }); + } + } + + + private bool _closing = false; + + // Avoid closing the window + protected override void OnClosing(CancelEventArgs e) + { + if (!_closing) + { + e.Cancel = true; + this.Hide(); + } + } + + private void OpenUiButton_Click(object sender, EventArgs e) + { + Process.Start("http://localhost:9000/index.html"); + } + + private void StopServerButton_Click(object sender, EventArgs e) + { + // Send message to listeners and close server + MessageServices.Current.Publish("StopServer"); + } + + private void notifyIcon1_Click(object sender, EventArgs e) + { + this.Show(); + } } - - - private bool _closing = false; - - // Evito di chiudere la finestra - protected override void OnClosing(CancelEventArgs e) - { - if (!_closing) - { - e.Cancel = true; - this.Hide(); - } - } - - private void button2_Click(object sender, EventArgs e) - { - Process.Start("http://localhost:9000"); - } - - private void button1_Click(object sender, EventArgs e) - { - MessageServices.Current.Publish("StopServer"); - } - - private void notifyIcon1_Click(object sender, EventArgs e) - { - this.Show(); - } - } } diff --git a/Step/App_Start/Startup.cs b/Step/App_Start/Startup.cs index 209fe53b..be59a553 100644 --- a/Step/App_Start/Startup.cs +++ b/Step/App_Start/Startup.cs @@ -51,17 +51,19 @@ namespace Step.App_Start private void ConfigureOAuth(IAppBuilder app) { - OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions + OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions { + // Login and Token generation end point TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(), - AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), + // Bearer token expiration time AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), //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()); } } diff --git a/Step/App_Start/WebApiConfig.cs b/Step/App_Start/WebApiConfig.cs index 5024b3ef..d8b54148 100644 --- a/Step/App_Start/WebApiConfig.cs +++ b/Step/App_Start/WebApiConfig.cs @@ -11,8 +11,6 @@ namespace Step public static void Register(HttpConfiguration config) { // Web API configuration and services - - var form = config.Formatters.FormUrlEncodedFormatter; var xml = config.Formatters.XmlFormatter; var json = config.Formatters.JsonFormatter; diff --git a/Step/CmsAuthorizationAttribute.cs b/Step/CmsAuthorizationAttribute.cs new file mode 100644 index 00000000..353d1b6a --- /dev/null +++ b/Step/CmsAuthorizationAttribute.cs @@ -0,0 +1,19 @@ +using System.Linq; +using System.Security.Claims; +using System.Web.Http; +using System.Web.Http.Controllers; + +namespace Step +{ + class CmsAuthorizationAttribute : AuthorizeAttribute + { + public string Category; + public string Action; + protected override bool IsAuthorized(HttpActionContext actionContext) + { + ClaimsPrincipal principal = actionContext.RequestContext.Principal as ClaimsPrincipal; + var customClaimValue = principal.Claims.Where(c => c.Type == "role").Single().Value; + return base.IsAuthorized(actionContext); + } + } +} diff --git a/Step/Controllers/LoginController.cs b/Step/Controllers/LoginController.cs index 8cbf20eb..95cc9e6f 100644 --- a/Step/Controllers/LoginController.cs +++ b/Step/Controllers/LoginController.cs @@ -1,13 +1,6 @@ using Step.Model; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; using System.Web.Http; using Step.Database.Controllers; -using System.Web.Http.Controllers; -using System.Security.Claims; namespace Step.Controllers { @@ -25,5 +18,12 @@ namespace Step.Controllers if (model.Username == "utente" && model.Password == "finto") return Ok(); return Unauthorized(); } + + [CmsAuthorization(Category = "test", Action = "Write")] + [Route("test"), HttpGet] + public IHttpActionResult Test() + { + return Ok(); + } } } diff --git a/Step/Provider/ApplicationOAuthProvider.cs b/Step/Provider/ApplicationOAuthProvider.cs index ecf2fb6a..5b5f8785 100644 --- a/Step/Provider/ApplicationOAuthProvider.cs +++ b/Step/Provider/ApplicationOAuthProvider.cs @@ -14,28 +14,28 @@ namespace Step.Provider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { + // Validate client context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { - - context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); - using (UsersController usersController = new UsersController()) { + // Check if credentials are correct UserModel user = usersController.Find(context.UserName, context.Password); - + // If not if (user == null) { + // Return 401 bad request context.SetError("invalid_grant", "The user name or password is incorrect."); return; } - + // Create a new Identity and insert custom claims var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("username", user.Username)); identity.AddClaim(new Claim("role", user.Role.Level.ToString())); - + // Create Token with identity data context.Validated(identity); } } diff --git a/Step/program.cs b/Step/program.cs index 70d46d60..1301262e 100644 --- a/Step/program.cs +++ b/Step/program.cs @@ -11,37 +11,34 @@ using TeamDev.SDK.MVVM; namespace Step { - public class Application - { - - public static readonly ManualResetEvent StopRequest = new ManualResetEvent(false); - - public static int MessageService { get; private set; } - - public static void Main() + public class Application { - // Avvio dell'applicazione in selfhost - var configuredUri = ConfigurationManager.AppSettings["localHostServiceURI"]; - ServerControlWindow.Start(); + public static readonly ManualResetEvent StopRequest = new ManualResetEvent(false); - // Registro il messaggi di chiusura della applicazione. - MessageServices.Current.Subscribe("StopServer", (a, b) => - { - Application.StopRequest.Set(); - }); + public static int MessageService { get; private set; } + public static void Main() + { + // Start self host application + var configuredUri = ConfigurationManager.AppSettings["localHostServiceURI"]; - // Creo la finestra lato server che verrà visualizzata sulla SysTray + // Start WinForm + ServerControlWindow.Start(); + // Register listener to "close application" messages + MessageServices.Current.Subscribe("StopServer", (a, b) => + { + StopRequest.Set(); + }); - // Avvio il servizio del server. - using (WebApp.Start(url: configuredUri)) - { - StopRequest.WaitOne(); - } - - ServerControlWindow.Stop(); + // Start server services + using (WebApp.Start(url: configuredUri)) + { + StopRequest.WaitOne(); + } + // Close WinForm + ServerControlWindow.Stop(); + } } - } }