diff --git a/Step.Config/StartupConfig.cs b/Step.Config/ServerConfig.cs similarity index 77% rename from Step.Config/StartupConfig.cs rename to Step.Config/ServerConfig.cs index 81e98325..79d6803e 100644 --- a/Step.Config/StartupConfig.cs +++ b/Step.Config/ServerConfig.cs @@ -4,13 +4,15 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Step.Model.ConfigModels; +using Step.Model.DatabaseModels; namespace Step.Config { - public static class StartupConfig + public static class ServerConfig { - public static ServerConfigModel ServerConfig; + public static ServerConfigModel ServerStartupConfig; public static NcConfigModel NcConfig; + public static MachineModel MachineConfig; public static AreasConfigModel ProductionConfig; public static AreasConfigModel ToolingConfig; diff --git a/Step.Config/StartupConfigController.cs b/Step.Config/ServerConfigController.cs similarity index 95% rename from Step.Config/StartupConfigController.cs rename to Step.Config/ServerConfigController.cs index d886abba..4a8ff988 100644 --- a/Step.Config/StartupConfigController.cs +++ b/Step.Config/ServerConfigController.cs @@ -2,7 +2,7 @@ using System.Xml.Schema; using System.Xml.Linq; using System.Linq; -using static Step.Config.StartupConfig; +using static Step.Config.ServerConfig; using Step.Model.ConfigModels; using static Step.Utils.Constants; using Step.Utils; @@ -10,7 +10,7 @@ using System.Collections.Generic; namespace Step.Config { - public static class StartupConfigController + public static class ServerConfigController { public static void ReadStartupConfig() { @@ -34,11 +34,12 @@ namespace Step.Config NcVendor = x.Element("ncVendor").Value, showNcHMI = Convert.ToBoolean(x.Element("showNcHMI").Value), NcIpAddress = x.Element("ncIpAddress").Value, - NcPort = Convert.ToUInt16(x.Element("ncPort").Value) + NcPort = Convert.ToUInt16(x.Element("ncPort").Value), + NcName = x.Element("ncName").Value }).FirstOrDefault(); // Read server config with LINQ and save into static config - ServerConfig = xmlConfigFile + ServerConfig.ServerStartupConfig = xmlConfigFile .Descendants(SERVER_CONFIG_KEY) .Select(x => new ServerConfigModel() { // Set server config model data diff --git a/Step.Config/Step.Config.csproj b/Step.Config/Step.Config.csproj index f4063b53..7ccc228e 100644 --- a/Step.Config/Step.Config.csproj +++ b/Step.Config/Step.Config.csproj @@ -43,8 +43,8 @@ - - + + diff --git a/Step.Config/serverConfig.xml b/Step.Config/serverConfig.xml index c26fb05a..e384e1ab 100644 --- a/Step.Config/serverConfig.xml +++ b/Step.Config/serverConfig.xml @@ -5,6 +5,7 @@ true 10.69.36.33 8193 + Ares 9000 diff --git a/Step.Config/serverConfigValidator.xsd b/Step.Config/serverConfigValidator.xsd index 131961c1..f2e4610b 100644 --- a/Step.Config/serverConfigValidator.xsd +++ b/Step.Config/serverConfigValidator.xsd @@ -10,6 +10,7 @@ + diff --git a/Step.Database/Controllers/MachineController.cs b/Step.Database/Controllers/MachineController.cs new file mode 100644 index 00000000..b1d09b51 --- /dev/null +++ b/Step.Database/Controllers/MachineController.cs @@ -0,0 +1,55 @@ +using Step.Model.DatabaseModels; +using System; +using System.Linq; +using static Step.Config.ServerConfig; + +namespace Step.Database.Controllers +{ + public class MachineController : IDisposable + { + private DatabaseContext dbCtx; + + public MachineController() + { + // Initialize database context + dbCtx = new DatabaseContext(); + } + + public void Dispose() + { + // Clear database context + dbCtx.Dispose(); + } + + public MachineModel GetMachineById(int id) + { + return dbCtx + .Machines + .Where(x => x.MachineId == id) + .SingleOrDefault(); + } + + public MachineModel GetMachineByUniqueId(string uniqueId) + { + return dbCtx + .Machines + .Where(x => x.UniqueId == uniqueId) + .SingleOrDefault(); + } + + public MachineModel Create( string uniqueId) + { + MachineModel machine= new MachineModel() + { + MachineId = 1, + Name = NcConfig.NcName, + UniqueId = uniqueId + }; + + dbCtx.Machines.Add(machine); + dbCtx.SaveChanges(); + + return machine; + } + } +} diff --git a/Step.Database/Controllers/MachinesUsersController.cs b/Step.Database/Controllers/MachinesUsersController.cs new file mode 100644 index 00000000..2c469e46 --- /dev/null +++ b/Step.Database/Controllers/MachinesUsersController.cs @@ -0,0 +1,36 @@ +using Step.Model.DatabaseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Step.Database.Controllers +{ + public class MachinesUsersController : IDisposable + { + private DatabaseContext dbCtx; + + public MachinesUsersController() + { + // Initialize database context + dbCtx = new DatabaseContext(); + } + + public void Dispose() + { + // Clear database context + dbCtx.Dispose(); + } + + public MachinesUsersModel FindByUserId(int machineId, int userId) + { + return dbCtx + .MachinesUsers + .Include("Role") + .Where(x => x.MachineId == machineId && x.UserId == userId) + .FirstOrDefault(); + + } + } +} diff --git a/Step.Database/Controllers/UsersController.cs b/Step.Database/Controllers/UsersController.cs index ec0880a7..3775fd16 100644 --- a/Step.Database/Controllers/UsersController.cs +++ b/Step.Database/Controllers/UsersController.cs @@ -1,4 +1,5 @@ using System; +using System.Data.Entity.Migrations; using System.Globalization; using System.Linq; using System.Web.Helpers; @@ -23,16 +24,16 @@ namespace Step.Database.Controllers dbCtx.Dispose(); } - public void Create(string username, string password, string firstName, string lastName, int roleId, CultureInfo language) + public void Create(string username, string password, string firstName, string lastName, CultureInfo language) { - UserModel user = CreateUserModel(username, password, firstName, lastName, roleId, language); + UserModel user = CreateUserModel(username, password, firstName, lastName, 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) + public static UserModel CreateUserModel(int id, string username, string password, string firstName, string lastName, CultureInfo language) { // Create a new user model with params return new UserModel() @@ -42,20 +43,19 @@ namespace Step.Database.Controllers Password = Crypto.HashPassword(password), FirstName = firstName, LastName = lastName, - RoleId = roleId, SecurityStamp = Guid.NewGuid().ToString(), Language = language }; } - public static UserModel CreateUserModel(string username, string password, string firstName, string lastName, int roleId, CultureInfo language) + public static UserModel CreateUserModel(string username, string password, string firstName, string lastName, CultureInfo language) { - return CreateUserModel(0, username, password, firstName, lastName, roleId, language); + return CreateUserModel(0, username, password, firstName, lastName, language); } public DTOUserModel GetUserInfo(int id) { // Find user by Id with Role object included - UserModel userDatabaseModel = dbCtx.Users.Include("Role").Where(u => u.UserId == id).FirstOrDefault(); + UserModel userDatabaseModel = dbCtx.Users.Where(u => u.UserId == id).FirstOrDefault(); return new DTOUserModel() { @@ -64,20 +64,19 @@ namespace Step.Database.Controllers FirstName = userDatabaseModel.FirstName, LastName = userDatabaseModel.LastName, Language = userDatabaseModel.Language, - RoleId = userDatabaseModel.RoleId }; } public UserModel FindById(int id) { // Find user by Id with Role object included - return dbCtx.Users.Include("Role").Where(u => u.UserId == id).FirstOrDefault(); + return dbCtx.Users.Where(u => u.UserId == id).FirstOrDefault(); } private UserModel FindByUsername(string username) { // Find user by Id with Role object included - return dbCtx.Users.Include("Role").Where(u => u.Username == username).FirstOrDefault(); + return dbCtx.Users.Where(u => u.Username == username).FirstOrDefault(); } public UserModel FindByUsernameAndPassword(string username, string password) @@ -96,5 +95,20 @@ namespace Step.Database.Controllers return user; } + + public void CreateCmsDefaultUserIfNotExists() + { + dbCtx.Users.AddOrUpdate + ( + CreateUserModel(1, "cms", "cms", "cms", "cms", new CultureInfo("en")) + ); + + dbCtx.MachinesUsers.AddOrUpdate( + new MachinesUsersModel() { MachineId = 1, UserId = 1, RoleId = 1 } + ); + + // Commit changes + dbCtx.SaveChanges(); + } } } diff --git a/Step.Database/DatabaseContext.cs b/Step.Database/DatabaseContext.cs index 1be7ca57..6be06eb3 100644 --- a/Step.Database/DatabaseContext.cs +++ b/Step.Database/DatabaseContext.cs @@ -1,11 +1,14 @@ using System; -using System.Collections.Generic; using System.Data.Entity; using Step.Model.DatabaseModels; using MySql.Data.Entity; using static Step.Utils.ExceptionManager; using static Step.Utils.Constants; using Step.Database.Migrations; +using System.IO; +using Step.Database.Controllers; +using static Step.Config.ServerConfig; +using Microsoft.Win32; namespace Step.Database { @@ -13,6 +16,8 @@ namespace Step.Database public class DatabaseContext : DbContext { public DbSet Users { get; set; } + public DbSet Machines { get; set; } + public DbSet MachinesUsers { get; set; } public DbSet Roles { get; set; } public DbSet FunctionsAccess { get; set; } @@ -21,6 +26,11 @@ namespace Step.Database { } + public static DatabaseContext Create() + { + return new DatabaseContext(); + } + public static void TestDatabaseConnection() { System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion()); @@ -29,8 +39,7 @@ namespace Step.Database { try { - dbContext.Database.Connection.Open(); - dbContext.Database.Connection.Close(); + FindOrCreateMachineUniqueId(); } catch (MySql.Data.MySqlClient.MySqlException ex) { @@ -47,7 +56,81 @@ namespace Step.Database Manage(ERROR_LEVEL.ERROR, ex); } } + catch (Exception ex) + { + Manage(ERROR_LEVEL.FATAL, ex); + } } } + + public static void FindOrCreateMachineUniqueId() + { + // Find machine unique id in the register + string uniqueId = ReadUniqueIdFromRegister(); + + // If not found + if (uniqueId == null || uniqueId == "") + { + if (!File.Exists("uniqueid.txt")) + { + uniqueId = Guid.NewGuid().ToString(); + // Save uinique id into file + File.WriteAllText("uniqueid.txt", uniqueId); + // Save uinique id in the registry + WriteUniqueIdIntoRegister(uniqueId); + } + else + { + // Find machine unique id in the storage file + uniqueId = File.ReadAllText("uniqueid.txt"); + + // If null or empty + if (uniqueId == null || uniqueId == "") + { + // Delete empty file and recreate + File.Delete(uniqueId); + FindOrCreateMachineUniqueId(); + return; + } + else + { + WriteUniqueIdIntoRegister(uniqueId); + } + } + } + // Set machine info into static server config + using (MachineController machineController = new MachineController()) + { + MachineConfig = machineController.GetMachineByUniqueId(uniqueId); + if (MachineConfig == null) + { + MachineConfig = machineController.Create(uniqueId); + using (UsersController usersController = new UsersController()) + { + usersController.CreateCmsDefaultUserIfNotExists(); + } + } + } + } + + private static void WriteUniqueIdIntoRegister(string uniqueId) + { + // Get path to the HKEY_LOCAL_MACHINE/SOFTWARE + RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); + // Create or get ..//CMS/Step subkey + key = key.CreateSubKey("Cms").CreateSubKey("Step"); + // Set machine unique id Key + key.SetValue(REGISTER_MACHINE_ID_KEY_NAME, uniqueId); + } + + private static string ReadUniqueIdFromRegister() + { + // Get path to the HKEY_LOCAL_MACHINE/SOFTWARE + RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); + // Get ..//CMS/Step subkey + key = key.CreateSubKey("Cms").CreateSubKey("Step"); + // Return value + return (string)key.GetValue(REGISTER_MACHINE_ID_KEY_NAME); + } } } diff --git a/Step.Database/Migrations/201801101327160_InizialCreate.Designer.cs b/Step.Database/Migrations/201801161604529_InitCreate.Designer.cs similarity index 80% rename from Step.Database/Migrations/201801101327160_InizialCreate.Designer.cs rename to Step.Database/Migrations/201801161604529_InitCreate.Designer.cs index a0dab130..d94b4cc4 100644 --- a/Step.Database/Migrations/201801101327160_InizialCreate.Designer.cs +++ b/Step.Database/Migrations/201801161604529_InitCreate.Designer.cs @@ -7,13 +7,13 @@ namespace Step.Database.Migrations using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] - public sealed partial class InizialCreate : IMigrationMetadata + public sealed partial class InitCreate : IMigrationMetadata { - private readonly ResourceManager Resources = new ResourceManager(typeof(InizialCreate)); + private readonly ResourceManager Resources = new ResourceManager(typeof(InitCreate)); string IMigrationMetadata.Id { - get { return "201801101327160_InizialCreate"; } + get { return "201801161604529_InitCreate"; } } string IMigrationMetadata.Source diff --git a/Step.Database/Migrations/201801101327160_InizialCreate.cs b/Step.Database/Migrations/201801161604529_InitCreate.cs similarity index 56% rename from Step.Database/Migrations/201801101327160_InizialCreate.cs rename to Step.Database/Migrations/201801161604529_InitCreate.cs index 68996621..20883b37 100644 --- a/Step.Database/Migrations/201801101327160_InizialCreate.cs +++ b/Step.Database/Migrations/201801161604529_InitCreate.cs @@ -3,7 +3,7 @@ namespace Step.Database.Migrations using System; using System.Data.Entity.Migrations; - public partial class InizialCreate : DbMigration + public partial class InitCreate : DbMigration { public override void Up() { @@ -20,6 +20,32 @@ namespace Step.Database.Migrations }) .PrimaryKey(t => t.id); + CreateTable( + "dbo.machine", + c => new + { + id = c.Int(nullable: false, identity: true), + name = c.String(unicode: false), + unique_id = c.String(unicode: false), + }) + .PrimaryKey(t => t.id); + + CreateTable( + "dbo.machines_users", + c => new + { + machine_id = c.Int(nullable: false), + user_id = c.Int(nullable: false), + role_id = c.Int(nullable: false), + }) + .PrimaryKey(t => new { t.machine_id, t.user_id, t.role_id }) + .ForeignKey("dbo.machine", t => t.machine_id, cascadeDelete: true) + .ForeignKey("dbo.roles", t => t.role_id, cascadeDelete: true) + .ForeignKey("dbo.users", t => t.user_id, cascadeDelete: true) + .Index(t => t.machine_id) + .Index(t => t.user_id) + .Index(t => t.role_id); + CreateTable( "dbo.roles", c => new @@ -43,18 +69,22 @@ namespace Step.Database.Migrations 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); + .PrimaryKey(t => t.id); } public override void Down() { - DropForeignKey("dbo.users", "role_id", "dbo.roles"); - DropIndex("dbo.users", new[] { "role_id" }); + DropForeignKey("dbo.machines_users", "user_id", "dbo.users"); + DropForeignKey("dbo.machines_users", "role_id", "dbo.roles"); + DropForeignKey("dbo.machines_users", "machine_id", "dbo.machine"); + DropIndex("dbo.machines_users", new[] { "role_id" }); + DropIndex("dbo.machines_users", new[] { "user_id" }); + DropIndex("dbo.machines_users", new[] { "machine_id" }); DropTable("dbo.users"); DropTable("dbo.roles"); + DropTable("dbo.machines_users"); + DropTable("dbo.machine"); DropTable("dbo.functions_access"); } } diff --git a/Step.Database/Migrations/201801101327160_InizialCreate.resx b/Step.Database/Migrations/201801161604529_InitCreate.resx similarity index 66% rename from Step.Database/Migrations/201801101327160_InizialCreate.resx rename to Step.Database/Migrations/201801161604529_InitCreate.resx index 38e05804..21384366 100644 --- a/Step.Database/Migrations/201801101327160_InizialCreate.resx +++ b/Step.Database/Migrations/201801161604529_InitCreate.resx @@ -118,7 +118,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - H4sIAAAAAAAEAO1abW/bNhD+PmD/QdDHI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8Lkn3TBxXyS/WpFq0v8+CUYqZml1J6GTs1YqRJHq/01yFLAUzWxbaYfR58jwcvF+v5lyxNvp/+OEM+m3DV4wJgfwkJzfLe9tv9t4165t2pLXYI8ZAi3uspMK4vnVYaX6ZNfwrfLxOYPrdvb4LeMG8uZutRiFfZC2YFopNnlaIjQV9DdZox0XAkIJTiDp0YrFfa3oUhepIy2+9UKjCE2MQEaEwV6gDjd3nziu6tLruib8v10r+4ok7CIku5iHPswcep/Vc67Mg6/2NRjdyzrmJ2dh9ZB9bfxstfztJMej5slOjSaGai82EGogdUJX7f2wUGEqv7+o/0AbV934atq1ih3d5aQGKkMHLpwIaAokZN21CcZngwdnr1irShOKpzaOv1Znn2cxvlXl3JpNEFGWOqHtpeFHTOB2tcfYOW1E4HYxcrxIRE/bPXaO0ey7qeIneFYq3vGDtZ3CWUcTx7edXu8avrUXRX+NUe9DxXXZachm95se545NGsvMrex6a2dxcyRuTXfZGpX4C8ikuvrqpNcP2zSmJQVCqZFHD1iKt16hBK0kCuf5LCldBV7aWSFCtLcVSFYG0ChG8qAeoZbLlOrDYXOSVtVsHTXgqkrpHbsWIwiTyN5N0LMMbmir4kojdyXtsyhkFxl5yQYJeA8N+nsLuI+KsKgv9nKhi6teO/7HOOl2FxDTU0Kro0c/WQAo/dDccx9ZfApewzP6jTf4z0GaCEdTkN7qB3jq8SGiWUTRkGd6j2r+D4bdYlP61gq+s8uYrSe2ETU2Bq+mwK8Ap/SHzklXqfKWLNFgh+TeavF3wtKX/FWK1LpMuweaO0AeXmK2/3WxhEiIGRKzwHD3CIboyAH+EKuOsirdQO0r8QdbNPTnywikFAcoxqPPuVcdgLHt/9D3M/E91FSAAA dbo diff --git a/Step.Database/Migrations/Configuration.cs b/Step.Database/Migrations/Configuration.cs index 6b5a18da..ebdb1c8a 100644 --- a/Step.Database/Migrations/Configuration.cs +++ b/Step.Database/Migrations/Configuration.cs @@ -8,11 +8,17 @@ namespace Step.Database.Migrations using System.Globalization; using System.Linq; - public sealed class Configuration : DbMigrationsConfiguration + public sealed class Configuration : DbMigrationsConfiguration { + private readonly bool _pendingMigrations; + public Configuration() { AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = true; + ContextKey = "Step.Database.DatabaseContext"; + + } protected override void Seed(DatabaseContext context) @@ -22,6 +28,7 @@ namespace Step.Database.Migrations 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 = "userData", Area = "production", Enabled = true, WriteLevelMin = 1, ReadLevelMin = 1 }, @@ -29,10 +36,7 @@ namespace Step.Database.Migrations new FunctionAccessModel() { FunctionAccessId = 4, Name = "functionAccess", Area = "production", Enabled = true, WriteLevelMin = 100, ReadLevelMin = 1 } ); - context.Users.AddOrUpdate - ( - UsersController.CreateUserModel(1, "cms", "cms", "cms", "cms", 1, new CultureInfo("en")) - ); + context.SaveChanges(); } } } diff --git a/Step.Database/Step.Database.csproj b/Step.Database/Step.Database.csproj index 56be13cc..ace2c400 100644 --- a/Step.Database/Step.Database.csproj +++ b/Step.Database/Step.Database.csproj @@ -68,11 +68,13 @@ + + - - - 201801101327160_InizialCreate.cs + + + 201801161604529_InitCreate.cs @@ -108,8 +110,8 @@ - - 201801101327160_InizialCreate.cs + + 201801161604529_InitCreate.cs diff --git a/Step.Model/ConfigModels/NcConfigModel.cs b/Step.Model/ConfigModels/NcConfigModel.cs index 63f2faae..0919844e 100644 --- a/Step.Model/ConfigModels/NcConfigModel.cs +++ b/Step.Model/ConfigModels/NcConfigModel.cs @@ -12,5 +12,7 @@ namespace Step.Model.ConfigModels public bool showNcHMI { get; set; } public string NcIpAddress { get; set; } public ushort NcPort { get; set; } + public string NcUniqueId { get; set; } + public string NcName { get; set; } } } diff --git a/Step.Model/DatabaseModels/MachineModel.cs b/Step.Model/DatabaseModels/MachineModel.cs new file mode 100644 index 00000000..8ca48b10 --- /dev/null +++ b/Step.Model/DatabaseModels/MachineModel.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Step.Model.DatabaseModels +{ + [Table("machine")] + public class MachineModel + { + [Key] + [Column("id")] + public int MachineId { get; set; } + [Column("name")] + public string Name { get; set; } + [Column("unique_id")] + public string UniqueId { get; set; } + } +} diff --git a/Step.Model/DatabaseModels/MachinesUsersModel.cs b/Step.Model/DatabaseModels/MachinesUsersModel.cs new file mode 100644 index 00000000..e22d4189 --- /dev/null +++ b/Step.Model/DatabaseModels/MachinesUsersModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Step.Model.DatabaseModels +{ + [Table("machines_users")] + public class MachinesUsersModel + { + + [Key, Column(name:"machine_id", Order = 1)] + public int MachineId { get; set; } + [ForeignKey("MachineId")] + public MachineModel Machine { get; set; } + + [Key, Column(name: "user_id", Order = 2)] + public int UserId { get; set; } + [ForeignKey("UserId")] + public UserModel User { get; set; } + + [Key, Column(name: "role_id", Order = 3)] + public int RoleId { get; set; } + [ForeignKey("RoleId")] + public RoleModel Role { get; set; } + } +} diff --git a/Step.Model/DatabaseModels/UserModel.cs b/Step.Model/DatabaseModels/UserModel.cs index fbd0bf2b..40fc65f0 100644 --- a/Step.Model/DatabaseModels/UserModel.cs +++ b/Step.Model/DatabaseModels/UserModel.cs @@ -45,7 +45,5 @@ namespace Step.Model.DatabaseModels [Column("role_id")] public int RoleId { get; set; } - [ForeignKey("RoleId")] - public RoleModel Role { get; set; } } } diff --git a/Step.Model/Step.Model.csproj b/Step.Model/Step.Model.csproj index 449036fd..201fd7a5 100644 --- a/Step.Model/Step.Model.csproj +++ b/Step.Model/Step.Model.csproj @@ -62,10 +62,12 @@ + DtsGenerator RoleModel.cs.d.ts + diff --git a/Step.NC/NcHandler.cs b/Step.NC/NcHandler.cs index 815e424d..b4b3ec71 100644 --- a/Step.NC/NcHandler.cs +++ b/Step.NC/NcHandler.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using static Step.Utils.Constants; -using static Step.Config.StartupConfig; +using static Step.Config.ServerConfig; using CMS_CORE; using CMS_CORE.Demo; using CMS_CORE.Fanuc; diff --git a/Step.Tasks/ThreadsFunctions.cs b/Step.Tasks/ThreadsFunctions.cs index b10f5053..69774080 100644 --- a/Step.Tasks/ThreadsFunctions.cs +++ b/Step.Tasks/ThreadsFunctions.cs @@ -16,7 +16,7 @@ public static class ThreadsFunctions private static long ReadAlarmsTimer = 0, ReadAlarmsTimes = 0; private static long ReadNcGenericInfoTimer = 0, ReadNcGenericInfoTimes = 0; private static long ReadAxesTimer = 0, ReadAxesTimes = 0; - + public static void Read_Alarms() { @@ -148,7 +148,7 @@ public static class ThreadsFunctions { ManageLibraryError(cmsError); } - else if ( cmsError.errorCode != CMS_ERROR_CODES.OK) + else if (cmsError.errorCode != CMS_ERROR_CODES.OK) ncHandler.Dispose(); Thread.Sleep(1000); @@ -205,17 +205,17 @@ public static class ThreadsFunctions case CMS_ERROR_CODES.SIEMENS_HMI_NOT_RUNNING: Manage(ERROR_LEVEL.FATAL, cmsError.message); break; - } + } } internal static void StatThread() { - while(true) + while (true) { if (ThreadsHandler.RunningThreadStatus.ContainsKey("Read_Alarms") && ReadAlarmsTimes != 0) { - ThreadsHandler.RunningThreadStatus["Read_Alarms"] = (ReadAlarmsTimer/ReadAlarmsTimes) + " mS"; + ThreadsHandler.RunningThreadStatus["Read_Alarms"] = (ReadAlarmsTimer / ReadAlarmsTimes) + " mS"; ReadAlarmsTimer = 0; ReadAlarmsTimes = 0; } @@ -240,15 +240,15 @@ public static class ThreadsFunctions } } - + private static void StatReset() { - ReadAlarmsTimer = 0; - ReadAlarmsTimes = 0; - ReadNcGenericInfoTimer = 0; - ReadNcGenericInfoTimes = 0; - ReadAxesTimer = 0; - ReadAxesTimes = 0; + ReadAlarmsTimer = 0; + ReadAlarmsTimes = 0; + ReadNcGenericInfoTimer = 0; + ReadNcGenericInfoTimes = 0; + ReadAxesTimer = 0; + ReadAxesTimes = 0; } } diff --git a/Step.Tasks/ThreadsHandler.cs b/Step.Tasks/ThreadsHandler.cs index 985e21a5..9e9d9423 100644 --- a/Step.Tasks/ThreadsHandler.cs +++ b/Step.Tasks/ThreadsHandler.cs @@ -10,7 +10,7 @@ using CMS_CORE.Fanuc; using CMS_CORE.Osai; using CMS_CORE.Siemens; using Step.NC; -using static Step.Config.StartupConfig; +using static Step.Config.ServerConfig; using static Step.Utils.Constants; using TeamDev.SDK.MVVM; using System.Diagnostics; @@ -23,7 +23,8 @@ namespace Step.Core { ThreadsFunctions.Read_Alarms, ThreadsFunctions.Read_Nc_Generic_Info, - ThreadsFunctions.Read_Axes + ThreadsFunctions.Read_Axes, + ThreadsFunctions.StatThread }; private static List RunningThreadsList = new List(); internal static Dictionary RunningThreadStatus = new Dictionary(); @@ -36,51 +37,40 @@ namespace Step.Core public static void StartWorkers() { - lock (RunningThreadsList) + + RunningThreadStatus.Clear(); + + // For each function run in the list a thread + ThreadFunctionsList.ForEach(threadFunction => { - RunningThreadStatus.Clear(); + // Run new Thread in the list + Thread t = new Thread(() => + threadFunction() + ); + t.Start(); + // Add thread to running threads list + RunningThreadsList.Add(t); - // For each function run in the list a thread - ThreadFunctionsList.ForEach(threadFunction => - { - // Run new Thread in the list - Thread t = new Thread(() => - threadFunction() - ); - t.Start(); - // Add thread to running threads list - RunningThreadsList.Add(t); - - RunningThreadStatus.Add(threadFunction.Method.Name, "---"); - }); - - MessageServices.Current.Publish(MVVM_NC_THREADS, null, RunningThreadStatus); - StatThread = new Thread(() => ThreadsFunctions.StatThread()); - StatThread.Start(); - } + RunningThreadStatus.Add(threadFunction.Method.Name, "---"); + }); + MessageServices.Current.Publish(MVVM_NC_THREADS, null, RunningThreadStatus); } public static void Stop() - { + { // Stop each thread RunningThreadsList.ForEach(thread => { thread.Abort(); }); - if(StatThread != null) - StatThread.Abort(); - // No running status + + // Remove threads from running status RunningThreadsList.Clear(); - - lock (RunningThreadsList) - { - RunningThreadStatus.Clear(); - RunningThreadStatus.Add("TryNcConnection", "---"); - MessageServices.Current.Publish(MVVM_NC_THREADS, null, RunningThreadStatus); - } - + RunningThreadStatus.Clear(); + RunningThreadStatus.Add("TryNcConnection", "---"); + MessageServices.Current.Publish(MVVM_NC_THREADS, null, RunningThreadStatus); } } } diff --git a/Step.UI/ServerControlWindow.cs b/Step.UI/ServerControlWindow.cs index 40269987..49325f68 100644 --- a/Step.UI/ServerControlWindow.cs +++ b/Step.UI/ServerControlWindow.cs @@ -8,7 +8,7 @@ using System.Threading; using System.Windows.Forms; using Step.Model; using TeamDev.SDK.MVVM; -using static Step.Config.StartupConfig; +using static Step.Config.ServerConfig; using static Step.Utils.Constants; using Step.Model.DTOModels; @@ -23,8 +23,8 @@ namespace Step.UI { InitializeComponent(); - HomePageUI = "http://localhost:" + ServerConfig.ServerPort.ToString() + "/index.html"; - TestJSPageUI = "http://localhost:" + ServerConfig.ServerPort.ToString() + "/Testjavascript//index.html"; + HomePageUI = "http://localhost:" + ServerStartupConfig.ServerPort.ToString() + "/index.html"; + TestJSPageUI = "http://localhost:" + ServerStartupConfig.ServerPort.ToString() + "/Testjavascript//index.html"; InitializeMessageListeners(); } diff --git a/Step.Utils/Constants.cs b/Step.Utils/Constants.cs index 904ddb66..c7c15df8 100644 --- a/Step.Utils/Constants.cs +++ b/Step.Utils/Constants.cs @@ -27,8 +27,11 @@ namespace Step.Utils public const string SIEMENS = "SIEMENS"; public const string OSAI = "OSAI"; } + // Registry key + public const string REGISTER_MACHINE_ID_KEY_NAME = "MachineUniqueId"; // Token fields Keys + public const string MACHINE_ID_KEY = "machineId"; public const string ROLE_LEVEL_KEY = "roleLevel"; public const string USERNAME_KEY = "username"; public const string USER_ID_KEY = "id"; diff --git a/Step/App_Start/Startup.cs b/Step/App_Start/Startup.cs index 39b5971e..e195c368 100644 --- a/Step/App_Start/Startup.cs +++ b/Step/App_Start/Startup.cs @@ -12,7 +12,7 @@ using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Step.Attributes; using Step.Utils; -using static Step.Config.StartupConfig; +using static Step.Config.ServerConfig; using System.IO; using System.Net.NetworkInformation; using System.Net; @@ -56,7 +56,7 @@ namespace Step.App_Start }; app.UseFileServer(options); - if (!ServerPortIsAvailable(ServerConfig.ServerPort)) + if (!ServerPortIsAvailable(ServerStartupConfig.ServerPort)) { ExceptionManager.Manage(Constants.ERROR_LEVEL.FATAL, "Server port is already in use by another process"); } diff --git a/Step/Attributes/SignalRAuthorizeAttribute.cs b/Step/Attributes/SignalRAuthorizeAttribute.cs index 418ec0a2..053bb814 100644 --- a/Step/Attributes/SignalRAuthorizeAttribute.cs +++ b/Step/Attributes/SignalRAuthorizeAttribute.cs @@ -7,7 +7,7 @@ using Step.Config; using Step.Database.Controllers; using Step.Model.DatabaseModels; using static Step.Utils.Constants; -using Step.Utils; +using static Step.Config.ServerConfig; namespace Step.Attributes { @@ -24,51 +24,52 @@ namespace Step.Attributes // Get user level stored in the bearer token ClaimsIdentity identity = user.Identity as ClaimsIdentity; var userRoleLevel = identity.Claims.Where(c => c.Type == ROLE_LEVEL_KEY).SingleOrDefault(); + + // Get machine unique id stored in the bearer token + var machineUniqueId = identity.Claims.Where(c => c.Type == MACHINE_ID_KEY).SingleOrDefault(); + // User data not found -> not authorized - if (userRoleLevel == null) + if (userRoleLevel == null || machineUniqueId == null) return false; // check authorization - if (!CheckAuthorization(Convert.ToInt32(userRoleLevel.Value), FunctionAccess)) + if (!CheckAuthorization(machineUniqueId.ToString(), Convert.ToInt32(userRoleLevel.Value), FunctionAccess)) return false; - return true; + return true; } - private bool CheckAuthorization(int userLevel, string functionName) + private bool CheckAuthorization(string machineUniqueId, int userLevel, string functionName) { - try + using (FunctionAccessController acController = new FunctionAccessController()) { - using (FunctionAccessController acController = new FunctionAccessController()) - { + // Check if the machine is the same where the user logged in + if (machineUniqueId != MachineConfig.UniqueId) + return false; - // Read from db category levels - FunctionAccessModel functionAccess = acController.FindEnabledFunctionByName(functionName); - if (functionAccess != null && StartupConfigController.CheckAreaStatus(functionAccess.Area)) - { - if (Action == ACTIONS.READ) - { // Check read permissions - if (functionAccess.ReadLevelMin > userLevel) - return false; // Not authorized - } - else - { // Check write permissions - if (functionAccess.WriteLevelMin > userLevel) - return false; // Not authorized - } + // Read from db category levels + FunctionAccessModel functionAccess = acController.FindEnabledFunctionByName(functionName); + if (functionAccess != null && ServerConfigController.CheckAreaStatus(functionAccess.Area)) + { + if (Action == ACTIONS.READ) + { // Check read permissions + if (functionAccess.ReadLevelMin > userLevel) + return false; // Not authorized } else - { - return false; + { // Check write permissions + if (functionAccess.WriteLevelMin > userLevel) + return false; // Not authorized } } + else + { + return false; + } } - catch (Exception ex) - { - ExceptionManager.Manage(ex); - } + // Authorized return true; - } } + } } diff --git a/Step/Attributes/WebApiAuthorizeAttribute.cs b/Step/Attributes/WebApiAuthorizeAttribute.cs index 644cb987..33ddc45c 100644 --- a/Step/Attributes/WebApiAuthorizeAttribute.cs +++ b/Step/Attributes/WebApiAuthorizeAttribute.cs @@ -7,6 +7,7 @@ using Step.Database.Controllers; using Step.Config; using static Step.Utils.Constants; using Step.Model.DatabaseModels; +using static Step.Config.ServerConfig; namespace Step { @@ -22,24 +23,32 @@ namespace Step // Get user level stored in the bearer token ClaimsPrincipal principal = actionContext.RequestContext.Principal as ClaimsPrincipal; var userRoleLevel = principal.Claims.Where(c => c.Type == ROLE_LEVEL_KEY).SingleOrDefault(); + + // Get machine unique id stored in the bearer token + var machineUniqueId = principal.Claims.Where(c => c.Type == MACHINE_ID_KEY).SingleOrDefault(); + // User data not found -> not authorized - if (userRoleLevel == null) + if (userRoleLevel == null || machineUniqueId == null) return false; // check authorization - if (!CheckAuthorization(Convert.ToInt32(userRoleLevel.Value), FunctionAccess)) + if (!CheckAuthorization(machineUniqueId.Value.ToString(), Convert.ToInt32(userRoleLevel.Value), FunctionAccess)) return false; return true; } - private bool CheckAuthorization(int userLevel, string functionName) + private bool CheckAuthorization(string machineUniqueId, int userLevel, string functionName) { using (FunctionAccessController acController = new FunctionAccessController()) { + // Check if the machine is the same where the user logged in + if (machineUniqueId != MachineConfig.UniqueId) + return false; + // Read from db category levels FunctionAccessModel functionAccess = acController.FindEnabledFunctionByName(functionName); - if (functionAccess != null && StartupConfigController.CheckAreaStatus(functionAccess.Area)) + if (functionAccess != null && ServerConfigController.CheckAreaStatus(functionAccess.Area)) { if (Action == ACTIONS.READ) { // Check read permissions diff --git a/Step/Controllers/WebApi/ConfigurationController.cs b/Step/Controllers/WebApi/ConfigurationController.cs index 4230736b..56bf075d 100644 --- a/Step/Controllers/WebApi/ConfigurationController.cs +++ b/Step/Controllers/WebApi/ConfigurationController.cs @@ -1,6 +1,6 @@ using Step.Model.DTOModels; using System.Web.Http; -using static Step.Config.StartupConfig; +using static Step.Config.ServerConfig; namespace Step.Controllers.WebApi { diff --git a/Step/Controllers/WebApi/UserController.cs b/Step/Controllers/WebApi/UserController.cs index 13b99d16..adf72a30 100644 --- a/Step/Controllers/WebApi/UserController.cs +++ b/Step/Controllers/WebApi/UserController.cs @@ -15,7 +15,7 @@ namespace Step.Controllers.WebApi public IHttpActionResult CreateUser(UserModel model) { UsersController users = new UsersController(); - users.Create(model.Username, model.Password, model.FirstName, model.LastName, model.RoleId, model.Language); + users.Create(model.Username, model.Password, model.FirstName, model.LastName, model.Language); return Ok(); } diff --git a/Step/Provider/ApplicationOAuthProvider.cs b/Step/Provider/ApplicationOAuthProvider.cs index 14ac3a3b..fd8abcb4 100644 --- a/Step/Provider/ApplicationOAuthProvider.cs +++ b/Step/Provider/ApplicationOAuthProvider.cs @@ -1,10 +1,11 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using Microsoft.Owin.Security.OAuth; using Step.Database.Controllers; using Step.Model.DatabaseModels; using System.Security.Claims; using static Step.Utils.Constants; -using System; +using static Step.Config.ServerConfig; namespace Step.Provider { @@ -27,26 +28,54 @@ namespace Step.Provider // If not if (user == null) { - // Return 401 bad request + // Return 401 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())); + + // Add claims to token identity.AddClaim(new Claim(USER_ID_KEY, user.UserId.ToString())); + + using (MachinesUsersController machinesUsersController = new MachinesUsersController()) + { + // Check if user can access to the machine + MachinesUsersModel machineUser = machinesUsersController.FindByUserId(MachineConfig.MachineId, user.UserId); + + if (machineUser == null) + { + // Return 401 bad request + context.SetError("invalid_grant", "User has no access to this machine"); + return; + } + + // Find machine unique id + using (MachineController machineController = new MachineController()) + { + MachineModel machineModel = machineController.GetMachineById(machineUser.MachineId); + // Add machine id + identity.AddClaim(new Claim(MACHINE_ID_KEY, machineModel.UniqueId)); + } + + // Add Role level key id + identity.AddClaim(new Claim(ROLE_LEVEL_KEY, machineUser.Role.Level.ToString())); + } + // Create Token with identity data context.Validated(identity); await base.GrantResourceOwnerCredentials(context); + return; } - catch(Exception ex) + catch (Exception ex) { - + // Return 401 bad request + context.SetError("invalid_grant", ex.Message); + return; } - + } } } diff --git a/Step/Step.csproj b/Step/Step.csproj index 6c067403..3570ac38 100644 --- a/Step/Step.csproj +++ b/Step/Step.csproj @@ -30,6 +30,7 @@ prompt 4 false + true true diff --git a/Step/program.cs b/Step/program.cs index b69fe881..d768bb96 100644 --- a/Step/program.cs +++ b/Step/program.cs @@ -3,7 +3,7 @@ using Step.UI; using System.Threading; using TeamDev.SDK.MVVM; using Step.Config; -using static Step.Config.StartupConfig; +using static Step.Config.ServerConfig; using static Step.Utils.StepLogger; using static Step.Utils.Constants; using Step.Database; @@ -23,12 +23,12 @@ namespace Step public static void Main() { LogInfo("Application started"); - StartupConfigController.ReadStartupConfig(); + ServerConfigController.ReadStartupConfig(); DatabaseContext.TestDatabaseConnection(); // Start self host application - string configuredUri = "http://localhost:" + ServerConfig.ServerPort.ToString(); + string configuredUri = "http://localhost:" + ServerStartupConfig.ServerPort.ToString(); // Register listener to "close application" messages MessageServices.Current.Subscribe(MVVM_STOP_SERVER, (a, b) =>