From 796801f7ee40e7da58956804613e67f615b826bb Mon Sep 17 00:00:00 2001 From: Lucio Maranta Date: Wed, 10 Jan 2018 17:21:40 +0100 Subject: [PATCH] + Added migration + Added STATIC data into Database (Roles functions and users) + Configuration controller and startupConfig API * Refactor api names --- Step.Database/Controllers/UsersController.cs | 19 ++- Step.Database/DatabaseContext.cs | 9 +- .../201801101327160_InizialCreate.Designer.cs | 29 ++++ .../201801101327160_InizialCreate.cs | 61 +++++++++ .../201801101327160_InizialCreate.resx | 126 ++++++++++++++++++ Step.Database/Migrations/Configuration.cs | 37 +++++ Step.Database/Step.Database.csproj | 10 ++ .../DTOModels/DTOStartupConfigurationModel.cs | 20 +++ Step.Model/Step.Model.csproj | 1 + .../WebApi/AuthorizationController.cs | 36 +++++ .../WebApi/ConfigurationController.cs | 41 +++--- Step/Controllers/WebApi/LoginController.cs | 20 +-- Step/Controllers/WebApi/NcApiController.cs | 2 +- Step/Provider/ApplicationOAuthProvider.cs | 37 +++-- Step/Step.csproj | 1 + 15 files changed, 380 insertions(+), 69 deletions(-) create mode 100644 Step.Database/Migrations/201801101327160_InizialCreate.Designer.cs create mode 100644 Step.Database/Migrations/201801101327160_InizialCreate.cs create mode 100644 Step.Database/Migrations/201801101327160_InizialCreate.resx create mode 100644 Step.Database/Migrations/Configuration.cs create mode 100644 Step.Model/DTOModels/DTOStartupConfigurationModel.cs create mode 100644 Step/Controllers/WebApi/AuthorizationController.cs diff --git a/Step.Database/Controllers/UsersController.cs b/Step.Database/Controllers/UsersController.cs index bc38996f..9d49289f 100644 --- a/Step.Database/Controllers/UsersController.cs +++ b/Step.Database/Controllers/UsersController.cs @@ -23,9 +23,18 @@ namespace Step.Database.Controllers } public void Create(string username, string password, string firstName, string lastName, int roleId, CultureInfo language) + { + UserModel user = CreateUserModel(username, password, firstName, lastName, roleId, language); + // Add to database + dbCtx.Users.Add(user); + // Commit changes + dbCtx.SaveChanges(); + } + + public static UserModel CreateUserModel(int id, string username, string password, string firstName, string lastName, int roleId, CultureInfo language) { // Create a new user model with params - UserModel user = new UserModel() + return new UserModel() { Username = username, Password = Crypto.HashPassword(password), @@ -35,10 +44,10 @@ namespace Step.Database.Controllers SecurityStamp = Guid.NewGuid().ToString(), Language = language }; - // Add to database - dbCtx.Users.Add(user); - // Commit changes - dbCtx.SaveChanges(); + } + public static UserModel CreateUserModel(string username, string password, string firstName, string lastName, int roleId, CultureInfo language) + { + return CreateUserModel(0, username, password, firstName, lastName, roleId, language); } public UserModel Find(int id) diff --git a/Step.Database/DatabaseContext.cs b/Step.Database/DatabaseContext.cs index a4491052..1be7ca57 100644 --- a/Step.Database/DatabaseContext.cs +++ b/Step.Database/DatabaseContext.cs @@ -5,6 +5,7 @@ using Step.Model.DatabaseModels; using MySql.Data.Entity; using static Step.Utils.ExceptionManager; using static Step.Utils.Constants; +using Step.Database.Migrations; namespace Step.Database { @@ -22,6 +23,8 @@ namespace Step.Database public static void TestDatabaseConnection() { + System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion()); + using (DatabaseContext dbContext = new DatabaseContext()) { try @@ -33,7 +36,7 @@ namespace Step.Database { if (ex.Number == 0) { - dbContext.Database.CreateIfNotExists(); + dbContext.Database.Initialize(true); } else if (ex.Number == 1042) // Can't find MySQLServer { @@ -46,9 +49,5 @@ namespace Step.Database } } } - protected override void OnModelCreating(DbModelBuilder modelBuilder) - { - System.Data.Entity.Database.SetInitializer(null); - } } } diff --git a/Step.Database/Migrations/201801101327160_InizialCreate.Designer.cs b/Step.Database/Migrations/201801101327160_InizialCreate.Designer.cs new file mode 100644 index 00000000..a0dab130 --- /dev/null +++ b/Step.Database/Migrations/201801101327160_InizialCreate.Designer.cs @@ -0,0 +1,29 @@ +// +namespace Step.Database.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] + public sealed partial class InizialCreate : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(InizialCreate)); + + string IMigrationMetadata.Id + { + get { return "201801101327160_InizialCreate"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Step.Database/Migrations/201801101327160_InizialCreate.cs b/Step.Database/Migrations/201801101327160_InizialCreate.cs new file mode 100644 index 00000000..68996621 --- /dev/null +++ b/Step.Database/Migrations/201801101327160_InizialCreate.cs @@ -0,0 +1,61 @@ +namespace Step.Database.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class InizialCreate : DbMigration + { + public override void Up() + { + CreateTable( + "dbo.functions_access", + c => new + { + id = c.Int(nullable: false, identity: true), + name = c.String(unicode: false), + write_level_min = c.Int(nullable: false), + read_level_min = c.Int(nullable: false), + area = c.String(unicode: false), + enabled = c.Boolean(nullable: false), + }) + .PrimaryKey(t => t.id); + + CreateTable( + "dbo.roles", + c => new + { + id = c.Int(nullable: false, identity: true), + name = c.String(unicode: false), + level = c.Int(nullable: false), + }) + .PrimaryKey(t => t.id); + + CreateTable( + "dbo.users", + c => new + { + id = c.Int(nullable: false, identity: true), + username = c.String(nullable: false, unicode: false), + first_name = c.String(unicode: false), + last_name = c.String(unicode: false), + password = c.String(unicode: false), + security_stamp = c.String(unicode: false), + language = c.String(unicode: false), + role_id = c.Int(nullable: false), + }) + .PrimaryKey(t => t.id) + .ForeignKey("dbo.roles", t => t.role_id, cascadeDelete: true) + .Index(t => t.role_id); + + } + + public override void Down() + { + DropForeignKey("dbo.users", "role_id", "dbo.roles"); + DropIndex("dbo.users", new[] { "role_id" }); + DropTable("dbo.users"); + DropTable("dbo.roles"); + DropTable("dbo.functions_access"); + } + } +} diff --git a/Step.Database/Migrations/201801101327160_InizialCreate.resx b/Step.Database/Migrations/201801101327160_InizialCreate.resx new file mode 100644 index 00000000..38e05804 --- /dev/null +++ b/Step.Database/Migrations/201801101327160_InizialCreate.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO1abW/bNhD+PmD/QdDHIbWSFgW2wG6ROskQrE6COO32zaCls0OMojSSSm0M+2X7sJ+0v7CjXilKtmXlrSiGAkXCl+eOx7vj3aP8+/c/w/erkDn3ICSN+Mg9Ghy6DnA/CihfjtxELV796L5/9/13w7MgXDmfi3Vv9DrcyeXIvVMqPvY86d9BSOQgpL6IZLRQAz8KPRJE3uvDw5+8oyMPEMJFLMcZ3iRc0RDSX/DXccR9iFVC2CQKgMl8HGemKapzSUKQMfFh5E4VxINTosicSHCdE0YJKjEFtnAdwnmkiEIVjz9JmCoR8eU0xgHCbtcx4LoFYXpXqvpxtbzrKQ5f61N41cYCyk+kisI9AY/e5Gbx7O29jOuWZkPDnaGB1VqfOjXeyD1PuK+hT3wfpEzt7Dq23OMxE3pPbuZ0VWns7G4GLUAHTrX8oPQSdCb978AZJ0wlAkYcEiUIrrhO5oz6v8D6Nvod+IgnjJnKo/o4VxvAoWsRxSDU+gYWrUe6CFzHq6N4NkwJshEhO/0FV29eu84lKkbmDEq/MSw1VZGAn4GDIAqCa6IUCLz2iwBSyzd0sSTr/wtp6KgYbq4zIauPwJfqbuTij65zTlcQFCO5Bp84xejETUoksEvIr4Iq+Aj3wCaU7zrbdqgbIMHjIJ0IIE9+8jOuNSrv80MUMSB8h65Dr4qarbF0g2gPiKBy+wvFjZbfJ1qKfd9UjKROvY9Hd/YSfILEA7yk3P5CXqLl9/GSYt9zeYmWxx/HU/bMZOdUSPU8TkqeSdA1kfJLJIInFzQFP8HXaT1VJIyfXNqMEb5MyPLpDdgtR1oYl+SeLtNg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FBm/rLLskjH7kbydhG6vRZ2N8mwRYNz63xtZ243SzKnTkBvMI7z/3/YIjm5GcH+7A/G6Sasy1yRKt1GcbMbxJgDHXJiBp42efnDduWMSiRDrxxQ2euZ0DfxSeuNnHoFcbf7KGMSXpsoLQf8DGwa/5c7nmgi+iIq4sjYolVhKfgCIBOvuJUHRBfIXT2vPSD5afCUs05RbOIbjgV4mKE4VHhnDOal/KdXhuk5+S4XWdh1dx6uiPcQRUk+IR4Ip/SCgLSr3PW16SDRA67vOaRt+l0rXNcl0iXUa8I1BuvjJd3UIYMwSTV3xK7qGPbuh/H2FJ/HXRjW4G2X0RdbMPTylZChLKHKPaj7+iDwfh6t1/prASybkpAAA= + + + dbo + + \ No newline at end of file diff --git a/Step.Database/Migrations/Configuration.cs b/Step.Database/Migrations/Configuration.cs new file mode 100644 index 00000000..113665ad --- /dev/null +++ b/Step.Database/Migrations/Configuration.cs @@ -0,0 +1,37 @@ +namespace Step.Database.Migrations +{ + using Step.Database.Controllers; + using Step.Model.DatabaseModels; + using System; + using System.Data.Entity; + using System.Data.Entity.Migrations; + using System.Globalization; + using System.Linq; + + public sealed class Configuration : DbMigrationsConfiguration + { + public Configuration() + { + AutomaticMigrationsEnabled = true; + + } + + protected override void Seed(DatabaseContext context) + { + // This method will be called after migrating to the latest version. + context.Roles.AddOrUpdate( + new RoleModel() { RoleId = 1, Level = 10, Name = "Admin" }, + new RoleModel() { RoleId = 2, Level = 1, Name = "Guest" } + ); + context.FunctionsAccess.AddOrUpdate( + new FunctionAccessModel() { FunctionAccessId = 1, Name = "test", Area = "production", Enabled = true, WriteLevelMin = 7, ReadLevelMin = 1 }, + new FunctionAccessModel() { FunctionAccessId = 2, Name = "ncData", Area = "production", Enabled = true, WriteLevelMin = 100, ReadLevelMin = 1 }, + new FunctionAccessModel() { FunctionAccessId = 3, Name = "functionAccess", Area = "production", Enabled = true, WriteLevelMin = 100, ReadLevelMin = 1 } + ); + context.Users.AddOrUpdate + ( + UsersController.CreateUserModel("cms", "cms", "cms", "cms", 1, new CultureInfo("en")) + ); + } + } +} diff --git a/Step.Database/Step.Database.csproj b/Step.Database/Step.Database.csproj index 301db284..56be13cc 100644 --- a/Step.Database/Step.Database.csproj +++ b/Step.Database/Step.Database.csproj @@ -70,6 +70,11 @@ + + + 201801101327160_InizialCreate.cs + + @@ -102,5 +107,10 @@ + + + 201801101327160_InizialCreate.cs + + \ No newline at end of file diff --git a/Step.Model/DTOModels/DTOStartupConfigurationModel.cs b/Step.Model/DTOModels/DTOStartupConfigurationModel.cs new file mode 100644 index 00000000..986175b1 --- /dev/null +++ b/Step.Model/DTOModels/DTOStartupConfigurationModel.cs @@ -0,0 +1,20 @@ +using Step.Model.ConfigModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Step.Model.DTOModels +{ + public class DTOStartupConfigurationModel + { + public AreasConfigModel ProductionConfig; + public AreasConfigModel ToolingConfig; + public AreasConfigModel ReportConfig; + public AreasConfigModel AlarmsConfig; + public AreasConfigModel MaintenanceConfig; + public AreasConfigModel UtilitiesConfig; + public AreasConfigModel ScadaConfig; + } +} diff --git a/Step.Model/Step.Model.csproj b/Step.Model/Step.Model.csproj index 07c60cdd..fd55ba3c 100644 --- a/Step.Model/Step.Model.csproj +++ b/Step.Model/Step.Model.csproj @@ -70,6 +70,7 @@ + diff --git a/Step/Controllers/WebApi/AuthorizationController.cs b/Step/Controllers/WebApi/AuthorizationController.cs new file mode 100644 index 00000000..976e6a5e --- /dev/null +++ b/Step/Controllers/WebApi/AuthorizationController.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Web.Http; +using Step.Database.Controllers; +using Step.Model.DTOModels; +using static Step.Utils.Constants; + +namespace Step.Controllers.WebApi +{ + + [RoutePrefix("api/authorization")] + public class AuthorizationController : ApiController + { + [Route("functions"), HttpGet] + [WebApiAuthorize(FunctionAccess = "functionAccess", Action = ACTIONS.READ)] + public IHttpActionResult GetFunctionsConfig() + { + using (FunctionAccessController functionController = new FunctionAccessController()) + { + var identity = User.Identity as ClaimsIdentity; + + var userRoleLevel = identity.Claims.Where(c => c.Type == ROLE_LEVEL_KEY).SingleOrDefault(); + + + List functionsList = functionController.GetFunctionAccess(Convert.ToInt32(userRoleLevel.Value)); + + if (functionsList == null) + return NotFound(); + + return Ok(functionsList); + } + } + } +} diff --git a/Step/Controllers/WebApi/ConfigurationController.cs b/Step/Controllers/WebApi/ConfigurationController.cs index 104342c0..3ee1b876 100644 --- a/Step/Controllers/WebApi/ConfigurationController.cs +++ b/Step/Controllers/WebApi/ConfigurationController.cs @@ -1,36 +1,27 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; +using Step.Model.DTOModels; using System.Web.Http; -using Step.Database.Controllers; -using Step.Model.DTOModels; -using static Step.Utils.Constants; +using static Step.Config.StartupConfig; namespace Step.Controllers.WebApi { - - [RoutePrefix("api/config")] + [RoutePrefix("api/configuration")] public class ConfigurationController : ApiController { - [Route("functions"), HttpGet] - [WebApiAuthorize(FunctionAccess = "test", Action = ACTIONS.READ)] - public IHttpActionResult GetFunctionsConfig() - { - using (FunctionAccessController functionController = new FunctionAccessController()) + [Route("base"), HttpGet] + public IHttpActionResult GetStartupConfiguration() + { + DTOStartupConfigurationModel startupConfiguration = new DTOStartupConfigurationModel() { - var identity = User.Identity as ClaimsIdentity; + ProductionConfig = ProductionConfig, + AlarmsConfig = AlarmsConfig, + ScadaConfig = ScadaConfig, + MaintenanceConfig = MaintenanceConfig, + ReportConfig = ReportConfig, + ToolingConfig = ToolingConfig, + UtilitiesConfig = UtilitiesConfig + }; - var userRoleLevel = identity.Claims.Where(c => c.Type == ROLE_LEVEL_KEY).SingleOrDefault(); - - - List functionsList = functionController.GetFunctionAccess(Convert.ToInt32(userRoleLevel.Value)); - - if (functionsList == null) - return NotFound(); - - return Ok(functionsList); - } + return Ok(startupConfiguration); } } } diff --git a/Step/Controllers/WebApi/LoginController.cs b/Step/Controllers/WebApi/LoginController.cs index 45a6443c..bd8fa793 100644 --- a/Step/Controllers/WebApi/LoginController.cs +++ b/Step/Controllers/WebApi/LoginController.cs @@ -6,27 +6,9 @@ using Step.Model.DatabaseModels; namespace Step.Controllers.WebApi { - [RoutePrefix("api/login")] + [RoutePrefix("api/user")] public class LoginController : ApiController { - - - - [WebApiAuthorize(FunctionAccess = "test", Action = ACTIONS.WRITE)] - [Route("test"), HttpGet] - public IHttpActionResult Test() - { - return Ok(); - } - - [WebApiAuthorize(FunctionAccess = "test", Action = ACTIONS.WRITE)] - [Route("crash"), HttpGet] - public IHttpActionResult Crash() - { - UsersController users = new UsersController(); - return Ok(users.Find(13)); - } - [Route("register"), HttpPost] public IHttpActionResult CreateUser(UserModel model) { diff --git a/Step/Controllers/WebApi/NcApiController.cs b/Step/Controllers/WebApi/NcApiController.cs index eb44f26c..1a4e8e3e 100644 --- a/Step/Controllers/WebApi/NcApiController.cs +++ b/Step/Controllers/WebApi/NcApiController.cs @@ -16,7 +16,7 @@ namespace Step.Controllers.WebApi public class NcApiController : ApiController { [Route("generic_data"), HttpGet] - [WebApiAuthorize(FunctionAccess = "test", Action = ACTIONS.READ)] + [WebApiAuthorize(FunctionAccess = "ncData", Action = ACTIONS.READ)] public IHttpActionResult GetNcGenericData() { DTONcGenericDataModel genericData = new DTONcGenericDataModel(); diff --git a/Step/Provider/ApplicationOAuthProvider.cs b/Step/Provider/ApplicationOAuthProvider.cs index 0b171e7d..e15edc0a 100644 --- a/Step/Provider/ApplicationOAuthProvider.cs +++ b/Step/Provider/ApplicationOAuthProvider.cs @@ -4,6 +4,7 @@ using Step.Database.Controllers; using Step.Model.DatabaseModels; using System.Security.Claims; using static Step.Utils.Constants; +using System; namespace Step.Provider { @@ -19,24 +20,32 @@ namespace Step.Provider { using (UsersController usersController = new UsersController()) { - // Check if credentials are correct - UserModel user = usersController.Find(context.UserName, context.Password); - // If not - if (user == null) + try { - // Return 401 bad request - context.SetError("invalid_grant", "The user name or password is incorrect."); + // 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_KEY, user.Username)); + identity.AddClaim(new Claim(ROLE_LEVEL_KEY, user.Role.Level.ToString())); + // Create Token with identity data + context.Validated(identity); + + await base.GrantResourceOwnerCredentials(context); return; } - // Create a new Identity and insert custom claims - var identity = new ClaimsIdentity(context.Options.AuthenticationType); - identity.AddClaim(new Claim(USERNAME_KEY, user.Username)); - identity.AddClaim(new Claim(ROLE_LEVEL_KEY, user.Role.Level.ToString())); - // Create Token with identity data - context.Validated(identity); + catch(Exception ex) + { - await base.GrantResourceOwnerCredentials(context); - return; + } + } } } diff --git a/Step/Step.csproj b/Step/Step.csproj index c8cd2398..1d76f637 100644 --- a/Step/Step.csproj +++ b/Step/Step.csproj @@ -165,6 +165,7 @@ +