Update first char for every dto variables + add password utils (hash password)

This commit is contained in:
Thomas Fransolet 2021-07-25 00:53:47 +02:00
parent ed1e08f443
commit 62aa7453c0
23 changed files with 418 additions and 201 deletions

View File

@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging; using Manager.Framework.Helpers;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -10,6 +11,11 @@ namespace Manager.Framework.Business
{ {
private readonly ILogger<ProfileLogic> _logger; private readonly ILogger<ProfileLogic> _logger;
/// <summary>
/// Scrypt algorithm pepper
/// </summary>
private const string PasswordsPepper = "m6rOay9Sg8pDGFRyHVWBWLZ8DahGdYgX";
public ProfileLogic(ILogger<ProfileLogic> logger) public ProfileLogic(ILogger<ProfileLogic> logger)
: base() : base()
{ {
@ -31,5 +37,15 @@ namespace Manager.Framework.Business
return true; return true;
} }
/// <summary>
/// Hash a password
/// </summary>
/// <param name="password">Password to hash</param>
/// <returns>Hashed password</returns>
public string HashPassword(string password)
{
return PasswordUtils.Encode(password, PasswordsPepper);
}
} }
} }

View File

@ -0,0 +1,170 @@
using Scrypt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace Manager.Framework.Helpers
{
/// <summary>
/// Password utils
/// </summary>
public static class PasswordUtils
{
private const int DefaultIterationCount = 16384;
private const int DefaultBlockSize = 8;
private const int DefaultThreadCount = 1;
private static readonly Random s_random = new Random((int)(DateTimeOffset.Now.Ticks % 100000));
#region Secure password management
/// <summary>
/// Generate a random key of the specified length (source: https://stackoverflow.com/a/31959204/249000)
/// </summary>
/// <param name="length">Length of the resulting key</param>
/// <param name="chars">Allowed characters for the resulting key</param>
/// <returns></returns>
public static string GetUniqueKey(int length = 32, string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
using (var crypto = new RNGCryptoServiceProvider())
{
var data = new byte[length];
// If chars.Length isn't a power of 2 then there is a bias if
// we simply use the modulus operator. The first characters of
// chars will be more probable than the last ones.
// buffer used if we encounter an unusable random byte. We will
// regenerate it in this buffer
byte[] smallBuffer = null;
// Maximum random number that can be used without introducing a
// bias
int maxRandom = byte.MaxValue - ((byte.MaxValue + 1) % chars.Length);
crypto.GetBytes(data);
var result = new char[length];
for (int i = 0; i < length; i++)
{
byte v = data[i];
while (v > maxRandom)
{
if (smallBuffer == null)
{
smallBuffer = new byte[1];
}
crypto.GetBytes(smallBuffer);
v = smallBuffer[0];
}
result[i] = chars[v % chars.Length];
}
return new string(result);
}
}
/// <summary>
/// Encode the specified password with the specified pepper with the scrypt algorithm
/// </summary>
/// <param name="password">Password to encode</param>
/// <param name="pepper">Pepper to use</param>
/// <param name="iterationCount">scrypt algorithm iteration count</param>
/// <param name="blockSize">scrypt algorithm block size</param>
/// <param name="threadCount">scrypt algorithm thread count</param>
/// <returns>Encoded password</returns>
public static string Encode(string password, string pepper = "", int iterationCount = DefaultIterationCount, int blockSize = DefaultBlockSize, int threadCount = DefaultThreadCount)
{
var encoder = new ScryptEncoder(iterationCount, blockSize, threadCount);
return encoder.Encode(pepper + password);
}
/// <summary>
/// Compare the specified encoded password with the specified password with the specified pepper with the scrypt algorithm
/// </summary>
/// <param name="hashedPassword">Hashed password</param>
/// <param name="password">Password to compare</param>
/// <param name="pepper">Pepper to use</param>
/// <param name="iterationCount">scrypt algorithm iteration count</param>
/// <param name="blockSize">scrypt algorithm block size</param>
/// <param name="threadCount">scrypt algorithm thread count</param>
/// <returns></returns>
public static bool Compare(string hashedPassword, string password, string pepper = "", int iterationCount = DefaultIterationCount, int blockSize = DefaultBlockSize, int threadCount = DefaultThreadCount)
{
var encoder = new ScryptEncoder(iterationCount, blockSize, threadCount);
return encoder.Compare(pepper + password, hashedPassword);
}
/// <summary>
/// Generate a random password
/// </summary>
/// <param name="pepper">Pepper to use</param>
/// <param name="iterationCount">scrypt algorithm iteration count</param>
/// <param name="blockSize">scrypt algorithm block size</param>
/// <param name="threadCount">scrypt algorithm thread count</param>
/// <returns>Generated password</returns>
public static string Generate(string pepper = "", int iterationCount = DefaultIterationCount, int blockSize = DefaultBlockSize, int threadCount = DefaultThreadCount)
{
return Encode(GetUniqueKey(), pepper, iterationCount, blockSize, threadCount);
}
#endregion
/// <summary>
/// Get a random string of the specified length
/// </summary>
/// <param name="length">Number of characters</param>
/// <returns>Random string of the specified length</returns>
public static string GetRandomString(int length)
{
string pass = "";
for (int i = 0; i < length; i++)
{
int r = s_random.Next(10 + 26 + 26);
char c;
if (r < 10) c = (char)(r + 48);
else if (r < 10 + 26) c = (char)((r - 10) + 65);
else c = (char)((r - 10 - 26) + 97);
pass += c;
}
return pass;
}
/// <summary>
/// Get a random number with the specified maximum number of digits
/// </summary>
/// <param name="maxDigits">Maximum number of digits</param>
/// <returns>Random number with the specified maximum number of digits</returns>
public static int GetRandomNumber(int maxDigits)
{
return s_random.Next((int)Math.Pow(10, maxDigits));
}
/// <summary>
/// Calculate the MD5 sum of the specified byte array and remove potential dashes
/// </summary>
/// <param name="source">Source array</param>
/// <returns>Source array MD5 sum</returns>
public static string MD5Sum(byte[] source)
{
return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(source)).Replace("-", "").ToLower();
}
/// <summary>
/// Calculate the MD5 sum of the specified string and remove potential dashes
/// </summary>
/// <param name="source">Source string</param>
/// <returns>Source string MD5 sum</returns>
public static string MD5Sum(string source)
{
return MD5Sum(Encoding.ASCII.GetBytes(source));
}
}
}

View File

@ -6,6 +6,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" />
<PackageReference Include="Scrypt.NET" Version="1.3.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -6,11 +6,11 @@ namespace Manager.Interfaces.DTO
{ {
public class ConfigurationDTO public class ConfigurationDTO
{ {
public string Id { get; set; } public string id { get; set; }
public string Label { get; set; } public string label { get; set; }
public string PrimaryColor { get; set; } public string primaryColor { get; set; }
public string SecondaryColor { get; set; } public string secondaryColor { get; set; }
public List<string> Languages { get; set; } // fr, en, de, nl => Sélection dans une liste déjà établie dans l'application ! public List<string> languages { get; set; } // fr, en, de, nl => Sélection dans une liste déjà établie dans l'application !
public DateTime DateCreation { get; set; } public DateTime dateCreation { get; set; }
} }
} }

View File

@ -6,23 +6,23 @@ namespace Manager.Interfaces.DTO
{ {
public class DeviceDTO public class DeviceDTO
{ {
public string Id { get; set; } public string id { get; set; }
public string Identifier { get; set; } public string identifier { get; set; }
public string Name { get; set; } public string name { get; set; }
public string IpAddressWLAN { get; set; } public string ipAddressWLAN { get; set; }
public string IpAddressETH { get; set; } public string ipAddressETH { get; set; }
public string ConfigurationId { get; set; } public string configurationId { get; set; }
public string Configuration { get; set; } public string configuration { get; set; }
public bool Connected{ get; set; } public bool connected{ get; set; }
public DateTime DateCreation{ get; set; } public DateTime dateCreation{ get; set; }
public DateTime DateUpdate { get; set; } public DateTime dateUpdate { get; set; }
} }
public class DeviceDetailDTO : DeviceDTO public class DeviceDetailDTO : DeviceDTO
{ {
public string ConnectionLevel { get; set; } public string connectionLevel { get; set; }
public DateTime LastConnectionLevel { get; set; } public DateTime lastConnectionLevel { get; set; }
public string BatteryLevel { get; set; } public string batteryLevel { get; set; }
public DateTime LastBatteryLevel { get; set; } public DateTime lastBatteryLevel { get; set; }
} }
} }

View File

@ -2,7 +2,7 @@ namespace Manager.Interfaces.DTO
{ {
public class LoginDTO public class LoginDTO
{ {
public string Email { get; set; } public string email { get; set; }
public string Password { get; set; } public string password { get; set; }
} }
} }

View File

@ -7,9 +7,9 @@ namespace Manager.Interfaces.DTO
{ {
public class ResourceDTO public class ResourceDTO
{ {
public string Id { get; set; } public string id { get; set; }
public ResourceType Type { get; set; } public ResourceType type { get; set; }
public string Label { get; set; } public string label { get; set; }
public string Data { get; set; } public string data { get; set; }
} }
} }

View File

@ -7,10 +7,10 @@ namespace Manager.Interfaces.DTO
{ {
public class ResourceDetailDTO public class ResourceDetailDTO
{ {
public string Id { get; set; } public string id { get; set; }
public ResourceType Type { get; set; } public ResourceType type { get; set; }
public string Label { get; set; } public string label { get; set; }
public DateTime DateCreation { get; set; } public DateTime dateCreation { get; set; }
public string Data { get; set; } public string data { get; set; }
} }
} }

View File

@ -7,18 +7,18 @@ namespace Manager.Interfaces.DTO
{ {
public class SectionDTO public class SectionDTO
{ {
public string Id { get; set; } public string id { get; set; }
public string Label { get; set; } // use in manager public string label { get; set; } // use in manager
public List<TranslationDTO> Title { get; set; } public List<TranslationDTO> title { get; set; }
public List<TranslationDTO> Description { get; set; } public List<TranslationDTO> description { get; set; }
public string ImageId { get; set; } // == ResourceId public string imageId { get; set; } // == ResourceId
public string ImageSource { get; set; } // == Image url public string imageSource { get; set; } // == Image url
public string ConfigurationId { get; set; } public string configurationId { get; set; }
public bool IsSubSection { get; set; } // true if part of menu type public bool isSubSection { get; set; } // true if part of menu type
public string ParentId { get; set; } // only if it's an subsection public string parentId { get; set; } // only if it's an subsection
public SectionType Type { get; set; } // !! If IsSubSection == true => Type can't not be menu ! public SectionType type { get; set; } // !! If IsSubSection == true => Type can't not be menu !
public string Data { get; set; } // == Include section type info public string data { get; set; } // == Include section type info
public DateTime DateCreation { get; set; } // == Include section type info public DateTime dateCreation { get; set; } // == Include section type info
public int Order { get; set; } // Order to show public int order { get; set; } // Order to show
} }
} }

View File

@ -6,7 +6,7 @@ namespace Manager.Interfaces.DTO
{ {
public class TranslationDTO public class TranslationDTO
{ {
public string Language { get; set; } public string language { get; set; }
public string Value { get; set; } public string value { get; set; }
} }
} }

View File

@ -6,9 +6,9 @@ namespace Manager.Interfaces.DTO
{ {
public class UserDetailDTO public class UserDetailDTO
{ {
public string Id { get; set; } public string id { get; set; }
public string Email { get; set; } public string email { get; set; }
public string FirstName { get; set; } public string firstName { get; set; }
public string LastName { get; set; } public string lastName { get; set; }
} }
} }

View File

@ -38,12 +38,12 @@ namespace Manager.Interfaces.Models
{ {
return new ConfigurationDTO() return new ConfigurationDTO()
{ {
Id = Id, id = Id,
Label = Label, label = Label,
DateCreation = DateCreation, dateCreation = DateCreation,
PrimaryColor = PrimaryColor, primaryColor = PrimaryColor,
Languages = Languages, languages = Languages,
SecondaryColor = SecondaryColor secondaryColor = SecondaryColor
}; };
} }
} }

View File

@ -65,16 +65,16 @@ namespace Manager.Interfaces.Models
{ {
return new DeviceDTO() return new DeviceDTO()
{ {
Id = Id, id = Id,
Identifier = Identifier, identifier = Identifier,
Name = Name, name = Name,
IpAddressWLAN = IpAddressWLAN, ipAddressWLAN = IpAddressWLAN,
IpAddressETH = IpAddressETH, ipAddressETH = IpAddressETH,
Connected = Connected, connected = Connected,
Configuration = Configuration, configuration = Configuration,
ConfigurationId = ConfigurationId, configurationId = ConfigurationId,
DateUpdate = DateUpdate, dateUpdate = DateUpdate,
DateCreation = DateCreation dateCreation = DateCreation
}; };
} }
@ -82,20 +82,20 @@ namespace Manager.Interfaces.Models
{ {
return new DeviceDetailDTO() return new DeviceDetailDTO()
{ {
Id = Id, id = Id,
Identifier = Identifier, identifier = Identifier,
Name = Name, name = Name,
IpAddressWLAN = IpAddressWLAN, ipAddressWLAN = IpAddressWLAN,
IpAddressETH = IpAddressETH, ipAddressETH = IpAddressETH,
Connected = Connected, connected = Connected,
Configuration = Configuration, configuration = Configuration,
ConfigurationId = ConfigurationId, configurationId = ConfigurationId,
ConnectionLevel = ConnectionLevel, connectionLevel = ConnectionLevel,
LastConnectionLevel = LastConnectionLevel, lastConnectionLevel = LastConnectionLevel,
BatteryLevel = BatteryLevel, batteryLevel = BatteryLevel,
LastBatteryLevel = LastBatteryLevel, lastBatteryLevel = LastBatteryLevel,
DateUpdate = DateUpdate, dateUpdate = DateUpdate,
DateCreation = DateCreation dateCreation = DateCreation
}; };
} }
} }

View File

@ -35,10 +35,10 @@ namespace Manager.Interfaces.Models
{ {
return new ResourceDTO() return new ResourceDTO()
{ {
Id = Id, id = Id,
Label = Label, label = Label,
Type = Type, type = Type,
Data = Type != ResourceType.Image ? Data : null, data = Type != ResourceType.Image ? Data : null,
}; };
} }
@ -46,11 +46,11 @@ namespace Manager.Interfaces.Models
{ {
return new ResourceDetailDTO() return new ResourceDetailDTO()
{ {
Id = Id, id = Id,
Label = Label, label = Label,
Type = Type, type = Type,
Data = Data, data = Data,
DateCreation = DateCreation dateCreation = DateCreation
}; };
} }

View File

@ -65,19 +65,19 @@ namespace Manager.Interfaces.Models
{ {
return new SectionDTO() return new SectionDTO()
{ {
Id = Id, id = Id,
Label = Label, label = Label,
Title = Title.OrderBy(t => t.Language).ToList(), title = Title.OrderBy(t => t.language).ToList(),
Description = Description.OrderBy(d => d.Language).ToList(), description = Description.OrderBy(d => d.language).ToList(),
Order = Order, order = Order,
Type = Type, type = Type,
ImageId = ImageId, imageId = ImageId,
ImageSource = ImageSource, imageSource = ImageSource,
ConfigurationId = ConfigurationId, configurationId = ConfigurationId,
IsSubSection = IsSubSection, isSubSection = IsSubSection,
ParentId = ParentId, parentId = ParentId,
Data = Data, data = Data,
DateCreation = DateCreation dateCreation = DateCreation
}; };
} }
} }

View File

@ -42,10 +42,10 @@ namespace Manager.Interfaces.Models
{ {
return new UserDetailDTO() return new UserDetailDTO()
{ {
Id = Id, id = Id,
Email = Email, email = Email,
FirstName = FirstName, firstName = FirstName,
LastName = LastName, lastName = LastName,
}; };
} }

View File

@ -105,7 +105,7 @@ namespace ManagerService.Service.Controllers
[ProducesResponseType(typeof(string), (int)HttpStatusCode.InternalServerError)] [ProducesResponseType(typeof(string), (int)HttpStatusCode.InternalServerError)]
public ObjectResult AuthenticateWithJson([FromBody] LoginDTO login) public ObjectResult AuthenticateWithJson([FromBody] LoginDTO login)
{ {
return Authenticate(login.Email.ToLower(), login.Password); return Authenticate(login.email.ToLower(), login.password);
} }
} }
} }

View File

@ -99,9 +99,9 @@ namespace ManagerService.Controllers
// Todo add some verification ? // Todo add some verification ?
Configuration configuration = new Configuration(); Configuration configuration = new Configuration();
configuration.Label = newConfiguration.Label; configuration.Label = newConfiguration.label;
configuration.PrimaryColor = newConfiguration.PrimaryColor; configuration.PrimaryColor = newConfiguration.primaryColor;
configuration.SecondaryColor = newConfiguration.SecondaryColor; configuration.SecondaryColor = newConfiguration.secondaryColor;
configuration.Languages = new List<string> { "FR", "NL", "EN", "DE" }; // by default all languages configuration.Languages = new List<string> { "FR", "NL", "EN", "DE" }; // by default all languages
configuration.DateCreation = DateTime.Now; configuration.DateCreation = DateTime.Now;
@ -140,18 +140,18 @@ namespace ManagerService.Controllers
if (updatedConfiguration == null) if (updatedConfiguration == null)
throw new ArgumentNullException("configuration param is null"); throw new ArgumentNullException("configuration param is null");
Configuration configuration = _configurationService.GetById(updatedConfiguration.Id); Configuration configuration = _configurationService.GetById(updatedConfiguration.id);
if (configuration == null) if (configuration == null)
throw new KeyNotFoundException("Configuration does not exist"); throw new KeyNotFoundException("Configuration does not exist");
// Todo add some verification ? // Todo add some verification ?
configuration.Label = updatedConfiguration.Label; configuration.Label = updatedConfiguration.label;
configuration.PrimaryColor = updatedConfiguration.PrimaryColor; configuration.PrimaryColor = updatedConfiguration.primaryColor;
configuration.SecondaryColor = updatedConfiguration.SecondaryColor; configuration.SecondaryColor = updatedConfiguration.secondaryColor;
configuration.Languages = updatedConfiguration.Languages; configuration.Languages = updatedConfiguration.languages;
Configuration configurationModified = _configurationService.Update(updatedConfiguration.Id, configuration); Configuration configurationModified = _configurationService.Update(updatedConfiguration.id, configuration);
MqttClientService.PublishMessage($"config/{configurationModified.Id}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true })); MqttClientService.PublishMessage($"config/{configurationModified.Id}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));

View File

@ -103,36 +103,36 @@ namespace ManagerService.Controllers
if (newDevice == null) if (newDevice == null)
throw new ArgumentNullException("Device param is null"); throw new ArgumentNullException("Device param is null");
var configuration = _configurationService.GetById(newDevice.ConfigurationId); var configuration = _configurationService.GetById(newDevice.configurationId);
if (configuration == null) if (configuration == null)
throw new KeyNotFoundException("Configuration does not exist"); throw new KeyNotFoundException("Configuration does not exist");
Device device = new Device(); Device device = new Device();
if (_deviceService.IsExistIdentifier(newDevice.Identifier)) if (_deviceService.IsExistIdentifier(newDevice.identifier))
{ {
// Update info // Update info
device = _deviceService.GetByIdentifier(newDevice.Identifier); device = _deviceService.GetByIdentifier(newDevice.identifier);
device.DateUpdate = DateTime.Now; device.DateUpdate = DateTime.Now;
} }
else { else {
// Creation // Creation
device.Identifier = newDevice.Identifier; device.Identifier = newDevice.identifier;
device.DateCreation = DateTime.Now; device.DateCreation = DateTime.Now;
} }
device.Name = newDevice.Name; device.Name = newDevice.name;
device.Configuration = configuration.Label; device.Configuration = configuration.Label;
device.ConfigurationId = newDevice.ConfigurationId; device.ConfigurationId = newDevice.configurationId;
device.IpAddressETH = newDevice.IpAddressETH; device.IpAddressETH = newDevice.ipAddressETH;
device.IpAddressWLAN = newDevice.IpAddressWLAN; device.IpAddressWLAN = newDevice.ipAddressWLAN;
device.Connected = newDevice.Connected; device.Connected = newDevice.connected;
device.ConnectionLevel = newDevice.ConnectionLevel; device.ConnectionLevel = newDevice.connectionLevel;
device.LastConnectionLevel = newDevice.LastConnectionLevel; device.LastConnectionLevel = newDevice.lastConnectionLevel;
device.BatteryLevel = newDevice.BatteryLevel; device.BatteryLevel = newDevice.batteryLevel;
device.LastBatteryLevel = newDevice.LastBatteryLevel; device.LastBatteryLevel = newDevice.lastBatteryLevel;
Device deviceCreated = _deviceService.IsExistIdentifier(newDevice.Identifier) ? _deviceService.Update(device.Id, device) : _deviceService.Create(device); Device deviceCreated = _deviceService.IsExistIdentifier(newDevice.identifier) ? _deviceService.Update(device.Id, device) : _deviceService.Create(device);
return new OkObjectResult(deviceCreated.ToDTO()); return new OkObjectResult(deviceCreated.ToDTO());
} }
@ -171,23 +171,23 @@ namespace ManagerService.Controllers
if (updatedDevice == null) if (updatedDevice == null)
throw new ArgumentNullException("Device param is null"); throw new ArgumentNullException("Device param is null");
Device device = _deviceService.GetById(updatedDevice.Id); Device device = _deviceService.GetById(updatedDevice.id);
if (device == null) if (device == null)
throw new KeyNotFoundException("Device does not exist"); throw new KeyNotFoundException("Device does not exist");
// Todo add some verification ? // Todo add some verification ?
device.Name = updatedDevice.Name; device.Name = updatedDevice.name;
device.Identifier = updatedDevice.Identifier; device.Identifier = updatedDevice.identifier;
device.IpAddressWLAN = updatedDevice.IpAddressWLAN; device.IpAddressWLAN = updatedDevice.ipAddressWLAN;
device.IpAddressETH = updatedDevice.IpAddressETH; device.IpAddressETH = updatedDevice.ipAddressETH;
device.Connected = updatedDevice.Connected; device.Connected = updatedDevice.connected;
device.ConnectionLevel = updatedDevice.ConnectionLevel; device.ConnectionLevel = updatedDevice.connectionLevel;
device.LastConnectionLevel = updatedDevice.LastConnectionLevel; device.LastConnectionLevel = updatedDevice.lastConnectionLevel;
device.BatteryLevel = updatedDevice.BatteryLevel; device.BatteryLevel = updatedDevice.batteryLevel;
device.LastBatteryLevel = updatedDevice.LastBatteryLevel; device.LastBatteryLevel = updatedDevice.lastBatteryLevel;
Device deviceModified = _deviceService.Update(updatedDevice.Id, device); Device deviceModified = _deviceService.Update(updatedDevice.id, device);
return new OkObjectResult(deviceModified.ToDTO()); return new OkObjectResult(deviceModified.ToDTO());
} }
@ -221,21 +221,21 @@ namespace ManagerService.Controllers
if (deviceIn == null) if (deviceIn == null)
throw new ArgumentNullException("Device param is null"); throw new ArgumentNullException("Device param is null");
Device device = _deviceService.GetById(deviceIn.Id); Device device = _deviceService.GetById(deviceIn.id);
if (device == null) if (device == null)
throw new KeyNotFoundException("Device does not exist"); throw new KeyNotFoundException("Device does not exist");
var configuration = _configurationService.GetById(deviceIn.ConfigurationId); var configuration = _configurationService.GetById(deviceIn.configurationId);
if (configuration == null) if (configuration == null)
throw new KeyNotFoundException("Configuration does not exist"); throw new KeyNotFoundException("Configuration does not exist");
// Todo add some verification ? // Todo add some verification ?
device.Name = deviceIn.Name; device.Name = deviceIn.name;
device.Connected = deviceIn.Connected; device.Connected = deviceIn.connected;
device.Configuration = configuration.Label; device.Configuration = configuration.Label;
device.ConfigurationId = deviceIn.ConfigurationId; device.ConfigurationId = deviceIn.configurationId;
Device deviceModified = _deviceService.Update(device.Id, device); Device deviceModified = _deviceService.Update(device.Id, device);

View File

@ -144,8 +144,8 @@ namespace ManagerService.Controllers
/*if (uploadResource == null) /*if (uploadResource == null)
throw new ArgumentNullException("Resource param is null");*/ throw new ArgumentNullException("Resource param is null");*/
ResourceDetailDTO uploadResource = new ResourceDetailDTO(); ResourceDetailDTO uploadResource = new ResourceDetailDTO();
uploadResource.Type = (ResourceType) Enum.Parse(typeof(ResourceType), type); uploadResource.type = (ResourceType) Enum.Parse(typeof(ResourceType), type);
uploadResource.Label = label; uploadResource.label = label;
var file = Request.Form.Files[0]; var file = Request.Form.Files[0];
@ -163,8 +163,8 @@ namespace ManagerService.Controllers
} }
// Todo add some verification ? // Todo add some verification ?
Resource resource = new Resource(); Resource resource = new Resource();
resource.Label = uploadResource.Label; resource.Label = uploadResource.label;
resource.Type = uploadResource.Type; resource.Type = uploadResource.type;
resource.DateCreation = DateTime.Now; resource.DateCreation = DateTime.Now;
resource.Data = stringResult; resource.Data = stringResult;
Resource resourceCreated = _resourceService.Create(resource); Resource resourceCreated = _resourceService.Create(resource);
@ -207,10 +207,10 @@ namespace ManagerService.Controllers
// Todo add some verification ? // Todo add some verification ?
Resource resource = new Resource(); Resource resource = new Resource();
resource.Label = newResource.Label; resource.Label = newResource.label;
resource.Type = newResource.Type; resource.Type = newResource.type;
resource.DateCreation = DateTime.Now; resource.DateCreation = DateTime.Now;
resource.Data = newResource.Data; resource.Data = newResource.data;
Resource resourceCreated = _resourceService.Create(resource); Resource resourceCreated = _resourceService.Create(resource);
@ -247,17 +247,17 @@ namespace ManagerService.Controllers
if (updatedResource == null) if (updatedResource == null)
throw new ArgumentNullException("Resource param is null"); throw new ArgumentNullException("Resource param is null");
Resource resource = _resourceService.GetById(updatedResource.Id); Resource resource = _resourceService.GetById(updatedResource.id);
if (resource == null) if (resource == null)
throw new KeyNotFoundException("Resource does not exist"); throw new KeyNotFoundException("Resource does not exist");
// Todo add some verification ? // Todo add some verification ?
resource.Label = updatedResource.Label; resource.Label = updatedResource.label;
resource.Type = updatedResource.Type; resource.Type = updatedResource.type;
resource.Data = updatedResource.Data; resource.Data = updatedResource.data;
Resource resourceModified = _resourceService.Update(updatedResource.Id, resource); Resource resourceModified = _resourceService.Update(updatedResource.id, resource);
return new OkObjectResult(resourceModified.ToDTO()); return new OkObjectResult(resourceModified.ToDTO());
} }

View File

@ -216,25 +216,25 @@ namespace ManagerService.Controllers
if (newSection == null) if (newSection == null)
throw new ArgumentNullException("Section param is null"); throw new ArgumentNullException("Section param is null");
if (newSection.ConfigurationId == null) if (newSection.configurationId == null)
throw new ArgumentNullException("Configuration param is null"); throw new ArgumentNullException("Configuration param is null");
if (!_configurationService.IsExist(newSection.ConfigurationId) ) if (!_configurationService.IsExist(newSection.configurationId) )
throw new KeyNotFoundException("Configuration does not exist"); throw new KeyNotFoundException("Configuration does not exist");
// Todo add some verification ? // Todo add some verification ?
Section section = new Section(); Section section = new Section();
section.Label = newSection.Label; section.Label = newSection.label;
section.ImageId = newSection.ImageId; section.ImageId = newSection.imageId;
section.ImageSource = newSection.ImageSource; section.ImageSource = newSection.imageSource;
section.ConfigurationId = newSection.ConfigurationId; section.ConfigurationId = newSection.configurationId;
section.DateCreation = DateTime.Now; section.DateCreation = DateTime.Now;
section.IsSubSection = newSection.IsSubSection; section.IsSubSection = newSection.isSubSection;
section.ParentId = newSection.ParentId; section.ParentId = newSection.parentId;
section.Type = newSection.Type; section.Type = newSection.type;
section.Title = new List<TranslationDTO>(); section.Title = new List<TranslationDTO>();
section.Description = new List<TranslationDTO>(); section.Description = new List<TranslationDTO>();
section.Order = _sectionService.GetAllFromConfiguration(newSection.ConfigurationId).Count; section.Order = _sectionService.GetAllFromConfiguration(newSection.configurationId).Count;
// Preparation // Preparation
List<string> languages = new List<string> { "FR", "NL", "EN", "DE" };//_configurationService.GetById(newSection.ConfigurationId).Languages; List<string> languages = new List<string> { "FR", "NL", "EN", "DE" };//_configurationService.GetById(newSection.ConfigurationId).Languages;
@ -245,35 +245,35 @@ namespace ManagerService.Controllers
{ {
TranslationDTO title = new TranslationDTO(); TranslationDTO title = new TranslationDTO();
TranslationDTO description = new TranslationDTO(); TranslationDTO description = new TranslationDTO();
title.Language = language.ToUpper(); title.language = language.ToUpper();
description.Language = language.ToUpper(); description.language = language.ToUpper();
switch (language.ToUpper()) switch (language.ToUpper())
{ {
case "FR": case "FR":
title.Value = "Titre en français"; title.value = "Titre en français";
description.Value = "Description en français"; description.value = "Description en français";
break; break;
case "EN": case "EN":
title.Value = "Title in english"; title.value = "Title in english";
description.Value = "Description en anglais"; description.value = "Description en anglais";
break; break;
case "NL": case "NL":
title.Value = "Titre in dutch"; title.value = "Titre in dutch";
description.Value = "Description en néerlandais"; description.value = "Description en néerlandais";
break; break;
case "DE": case "DE":
title.Value = "Titre en allemand"; title.value = "Titre en allemand";
description.Value = "Description en allemand"; description.value = "Description en allemand";
break; break;
} }
section.Title.Add(title); section.Title.Add(title);
section.Description.Add(description); section.Description.Add(description);
} }
section.Title = section.Title.OrderBy(t => t.Language).ToList(); section.Title = section.Title.OrderBy(t => t.language).ToList();
section.Description = section.Description.OrderBy(d => d.Language).ToList(); section.Description = section.Description.OrderBy(d => d.language).ToList();
switch (newSection.Type) { switch (newSection.type) {
case SectionType.Map: case SectionType.Map:
mapDTO = new MapDTO(); mapDTO = new MapDTO();
mapDTO.mapType = MapTypeApp.hybrid; mapDTO.mapType = MapTypeApp.hybrid;
@ -316,6 +316,30 @@ namespace ManagerService.Controllers
case SectionType.Menu: case SectionType.Menu:
MenuDTO menuDTO = new MenuDTO(); MenuDTO menuDTO = new MenuDTO();
menuDTO.sections = new List<SectionDTO>(); menuDTO.sections = new List<SectionDTO>();
/*SectionDTO section0DTO = new SectionDTO();
section0DTO.IsSubSection = true;
section0DTO.Label = newSection.Label;
section0DTO.ImageId = newSection.ImageId;
section0DTO.ConfigurationId = newSection.ConfigurationId;
section0DTO.DateCreation = DateTime.Now;
section0DTO.ParentId = null;
section0DTO.Type = SectionType.Map;
section0DTO.Data = JsonConvert.SerializeObject(mapDTO);
SectionDTO section1DTO = new SectionDTO();
section0DTO.IsSubSection = true;
section0DTO.Label = newSection.Label;
section0DTO.ImageId = newSection.ImageId;
section0DTO.ConfigurationId = newSection.ConfigurationId;
section0DTO.DateCreation = DateTime.Now;
section0DTO.ParentId = null;
section0DTO.Type = SectionType.Slider;
section1DTO.IsSubSection = true;
section1DTO.Data = JsonConvert.SerializeObject(sliderDTO);*/
/*menuDTO.Sections.Add(section0DTO);
menuDTO.Sections.Add(section1DTO);*/
section.Data = JsonConvert.SerializeObject(menuDTO); // Include all info from specific section as JSON section.Data = JsonConvert.SerializeObject(menuDTO); // Include all info from specific section as JSON
break; break;
} }
@ -406,24 +430,24 @@ namespace ManagerService.Controllers
if (updatedSection == null) if (updatedSection == null)
throw new ArgumentNullException("Section param is null"); throw new ArgumentNullException("Section param is null");
Section section = _sectionService.GetById(updatedSection.Id); Section section = _sectionService.GetById(updatedSection.id);
if (section == null) if (section == null)
throw new KeyNotFoundException("Section does not exist"); throw new KeyNotFoundException("Section does not exist");
// Todo add some verification ? // Todo add some verification ?
section.Label = updatedSection.Label; section.Label = updatedSection.label;
section.Title = updatedSection.Title; section.Title = updatedSection.title;
section.Description = updatedSection.Description; section.Description = updatedSection.description;
section.Type = updatedSection.Type; section.Type = updatedSection.type;
section.ImageId = updatedSection.ImageId; section.ImageId = updatedSection.imageId;
section.ImageSource = updatedSection.ImageSource; section.ImageSource = updatedSection.imageSource;
section.ConfigurationId = updatedSection.ConfigurationId; section.ConfigurationId = updatedSection.configurationId;
section.IsSubSection = updatedSection.IsSubSection; section.IsSubSection = updatedSection.isSubSection;
section.ParentId = updatedSection.ParentId; section.ParentId = updatedSection.parentId;
section.Data = updatedSection.Data; section.Data = updatedSection.data;
Section sectionModified = _sectionService.Update(updatedSection.Id, section); Section sectionModified = _sectionService.Update(updatedSection.id, section);
MqttClientService.PublishMessage($"config/{sectionModified.ConfigurationId}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true })); MqttClientService.PublishMessage($"config/{sectionModified.ConfigurationId}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
@ -461,20 +485,20 @@ namespace ManagerService.Controllers
foreach (var section in updatedSectionsOrder) foreach (var section in updatedSectionsOrder)
{ {
if (!_sectionService.IsExist(section.Id)) if (!_sectionService.IsExist(section.id))
throw new KeyNotFoundException($"Section {section.Label} with id {section.Id} does not exist"); throw new KeyNotFoundException($"Section {section.label} with id {section.id} does not exist");
} }
foreach (var updatedSection in updatedSectionsOrder) foreach (var updatedSection in updatedSectionsOrder)
{ {
Section section = _sectionService.GetById(updatedSection.Id); Section section = _sectionService.GetById(updatedSection.id);
section.Order = updatedSection.Order; section.Order = updatedSection.order;
_sectionService.Update(section.Id, section); _sectionService.Update(section.Id, section);
} }
if (updatedSectionsOrder.Count > 0) { if (updatedSectionsOrder.Count > 0) {
MqttClientService.PublishMessage($"config/{updatedSectionsOrder[0].ConfigurationId}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true })); MqttClientService.PublishMessage($"config/{updatedSectionsOrder[0].configurationId}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
} }
return new ObjectResult("Sections order has been successfully modified") { StatusCode = 200 }; return new ObjectResult("Sections order has been successfully modified") { StatusCode = 200 };

View File

@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Manager.Framework.Business;
using Manager.Interfaces.DTO; using Manager.Interfaces.DTO;
using Manager.Interfaces.Models; using Manager.Interfaces.Models;
using Manager.Services; using Manager.Services;
@ -21,12 +22,14 @@ namespace ManagerService.Controllers
private UserDatabaseService _userService; private UserDatabaseService _userService;
private TokensService _tokenService; private TokensService _tokenService;
private readonly ILogger<UserController> _logger; private readonly ILogger<UserController> _logger;
private readonly ProfileLogic _profileLogic;
public UserController(ILogger<UserController> logger, UserDatabaseService userService, TokensService tokenService) public UserController(ILogger<UserController> logger, UserDatabaseService userService, TokensService tokenService, ProfileLogic profileLogic)
{ {
_logger = logger; _logger = logger;
_userService = userService; _userService = userService;
_tokenService = tokenService; _tokenService = tokenService;
_profileLogic = profileLogic;
} }
/// <summary> /// <summary>
@ -104,6 +107,8 @@ namespace ManagerService.Controllers
if (users.Select(u => u.Email).Contains(newUser.Email)) if (users.Select(u => u.Email).Contains(newUser.Email))
throw new InvalidOperationException("This Email is already used"); throw new InvalidOperationException("This Email is already used");
newUser.Password = _profileLogic.HashPassword(newUser.Password);
User userCreated = _userService.Create(newUser); User userCreated = _userService.Create(newUser);
return new OkObjectResult(userCreated.ToDTO()); return new OkObjectResult(userCreated.ToDTO());

View File

@ -64,7 +64,8 @@ namespace Mqtt.Client.AspNetCore.Services
{ {
var deserialized = JsonConvert.DeserializeObject<Dictionary<string, object>>(payload); var deserialized = JsonConvert.DeserializeObject<Dictionary<string, object>>(payload);
switch (topic.Split("/")[0]) { switch (topic.Split("/")[0])
{
case "player": case "player":
var test = topic.Split("/")[1]; // Get device id var test = topic.Split("/")[1]; // Get device id