diff --git a/MyCore.Framework/Business/ProfileLogic.cs b/MyCore.Framework/Business/ProfileLogic.cs new file mode 100644 index 0000000..c6abd14 --- /dev/null +++ b/MyCore.Framework/Business/ProfileLogic.cs @@ -0,0 +1,37 @@ +using MyCore.Framework.Models; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Framework.Business +{ + public class ProfileLogic + { + private readonly ILogger _logger; + + public ProfileLogic(ILogger logger) + : base() + { + _logger = logger; + } + + public bool Authenticate(string email, string password) + { + if (string.IsNullOrWhiteSpace(email)) + { + _logger.LogError($"Authenticate error: No e-mail provided"); + throw new RequestException(StatusCodes.Status401Unauthorized, "Authentication error"); + } + if (string.IsNullOrEmpty(password)) + { + _logger.LogError($"Authenticate error: No password provided"); + throw new RequestException(StatusCodes.Status401Unauthorized, "Authentication error"); + } + + return true; + } + } +} diff --git a/MyCore.Framework/Models/Exceptions/RequestException.cs b/MyCore.Framework/Models/Exceptions/RequestException.cs new file mode 100644 index 0000000..54d47b0 --- /dev/null +++ b/MyCore.Framework/Models/Exceptions/RequestException.cs @@ -0,0 +1,26 @@ +using System.Text.Json; + +namespace MyCore.Framework.Models +{ + [System.Serializable] + public class RequestException : System.Exception + { + public int StatusCode { get; set; } + + public object Payload {get;set;} + + protected RequestException() { } + + public RequestException(int statusCode) : this() { StatusCode = statusCode; } + public RequestException(int statusCode, string message) : base(message) { StatusCode = statusCode; } + public RequestException(int statusCode, string message, System.Exception inner) : base(message, inner) { StatusCode = statusCode; } + protected RequestException( + System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) : base(info, context) { } + + public string GetJson() + { + return JsonSerializer.Serialize(new { StatusCode, Message, Payload }); + } + } +} \ No newline at end of file diff --git a/MyCore.Framework/MyCore.Framework.csproj b/MyCore.Framework/MyCore.Framework.csproj new file mode 100644 index 0000000..c205ef2 --- /dev/null +++ b/MyCore.Framework/MyCore.Framework.csproj @@ -0,0 +1,12 @@ + + + + netcoreapp3.1 + + + + + + + + diff --git a/MyCore/DTO/Common/ConnectionStatus.cs b/MyCore.Interfaces/DTO/Common/ConnectionStatus.cs similarity index 86% rename from MyCore/DTO/Common/ConnectionStatus.cs rename to MyCore.Interfaces/DTO/Common/ConnectionStatus.cs index c7021f1..b63d3fa 100644 --- a/MyCore/DTO/Common/ConnectionStatus.cs +++ b/MyCore.Interfaces/DTO/Common/ConnectionStatus.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.Common +namespace MyCore.Interfaces.DTO { public enum ConnectionStatus { diff --git a/MyCore/DTO/Common/DeviceType.cs b/MyCore.Interfaces/DTO/Common/DeviceType.cs similarity index 90% rename from MyCore/DTO/Common/DeviceType.cs rename to MyCore.Interfaces/DTO/Common/DeviceType.cs index 6d260a8..f207d9b 100644 --- a/MyCore/DTO/Common/DeviceType.cs +++ b/MyCore.Interfaces/DTO/Common/DeviceType.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.Common +namespace MyCore.Interfaces.DTO { public enum DeviceType // TO BE Continued { diff --git a/MyCore/DTO/Common/MeansOfCommunication.cs b/MyCore.Interfaces/DTO/Common/MeansOfCommunication.cs similarity index 87% rename from MyCore/DTO/Common/MeansOfCommunication.cs rename to MyCore.Interfaces/DTO/Common/MeansOfCommunication.cs index 6804a77..4fc3f99 100644 --- a/MyCore/DTO/Common/MeansOfCommunication.cs +++ b/MyCore.Interfaces/DTO/Common/MeansOfCommunication.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.Common +namespace MyCore.Interfaces.DTO { public enum MeansOfCommunication { diff --git a/MyCore/DTO/Common/RequestParam.cs b/MyCore.Interfaces/DTO/Common/RequestParam.cs similarity index 94% rename from MyCore/DTO/Common/RequestParam.cs rename to MyCore.Interfaces/DTO/Common/RequestParam.cs index 19b6817..5f3af87 100644 --- a/MyCore/DTO/Common/RequestParam.cs +++ b/MyCore.Interfaces/DTO/Common/RequestParam.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO +namespace MyCore.Interfaces.DTO { public class RequestParam { diff --git a/MyCore/DTO/Common/ViewBy.cs b/MyCore.Interfaces/DTO/Common/ViewBy.cs similarity index 85% rename from MyCore/DTO/Common/ViewBy.cs rename to MyCore.Interfaces/DTO/Common/ViewBy.cs index 485d442..3f9677e 100644 --- a/MyCore/DTO/Common/ViewBy.cs +++ b/MyCore.Interfaces/DTO/Common/ViewBy.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.Energy +namespace MyCore.Interfaces.DTO { public enum ViewBy { diff --git a/MyCore.Interfaces/DTO/LoginDTO.cs b/MyCore.Interfaces/DTO/LoginDTO.cs new file mode 100644 index 0000000..707506e --- /dev/null +++ b/MyCore.Interfaces/DTO/LoginDTO.cs @@ -0,0 +1,8 @@ +namespace MyCore.Interfaces.DTO +{ + public class LoginDTO + { + public string Email { get; set; } + public string Password { get; set; } + } +} diff --git a/MyCore/DTO/MyControlPanel/AutomationDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/AutomationDTO.cs similarity index 86% rename from MyCore/DTO/MyControlPanel/AutomationDTO.cs rename to MyCore.Interfaces/DTO/MyControlPanel/AutomationDTO.cs index adcd09b..fb0f0d4 100644 --- a/MyCore/DTO/MyControlPanel/AutomationDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/AutomationDTO.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.MyControlPanel +namespace MyCore.Interfaces.DTO { public class AutomationDTO { diff --git a/MyCore/DTO/MyControlPanel/DeviceDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/DeviceDTO.cs similarity index 94% rename from MyCore/DTO/MyControlPanel/DeviceDTO.cs rename to MyCore.Interfaces/DTO/MyControlPanel/DeviceDTO.cs index b3f2b60..cd2bde8 100644 --- a/MyCore/DTO/MyControlPanel/DeviceDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/DeviceDTO.cs @@ -1,11 +1,9 @@ -using MyCore.DTO.Common; -using MyCore.Models.MyControlPanel; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.MyControlPanel +namespace MyCore.Interfaces.DTO { public class DeviceSummaryDTO { diff --git a/MyCore/DTO/MyControlPanel/GroupDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/GroupDTO.cs similarity index 88% rename from MyCore/DTO/MyControlPanel/GroupDTO.cs rename to MyCore.Interfaces/DTO/MyControlPanel/GroupDTO.cs index a857fdc..06519f7 100644 --- a/MyCore/DTO/MyControlPanel/GroupDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/GroupDTO.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.MyControlPanel +namespace MyCore.Interfaces.DTO { public class GroupDTO { diff --git a/MyCore/DTO/MyControlPanel/LocationDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/LocationDTO.cs similarity index 86% rename from MyCore/DTO/MyControlPanel/LocationDTO.cs rename to MyCore.Interfaces/DTO/MyControlPanel/LocationDTO.cs index b1a779f..331de58 100644 --- a/MyCore/DTO/MyControlPanel/LocationDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/LocationDTO.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.MyControlPanel +namespace MyCore.Interfaces.DTO { public class LocationDTO { diff --git a/MyCore/DTO/MyControlPanel/ProviderDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/ProviderDTO.cs similarity index 93% rename from MyCore/DTO/MyControlPanel/ProviderDTO.cs rename to MyCore.Interfaces/DTO/MyControlPanel/ProviderDTO.cs index a3d917c..5f5c1e5 100644 --- a/MyCore/DTO/MyControlPanel/ProviderDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/ProviderDTO.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.DTO.MyControlPanel +namespace MyCore.Interfaces.DTO { public class ProviderDTO { diff --git a/MyCore.Interfaces/DTO/Odd.cs b/MyCore.Interfaces/DTO/Odd.cs new file mode 100644 index 0000000..62df32a --- /dev/null +++ b/MyCore.Interfaces/DTO/Odd.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Interfaces +{ + public class Odd + { + public string Sport_nice { get; set; } + public List Teams { get; set; } + public int Commence_time { get; set; } + public string Home_team { get; set; } + public List Sites { get; set; } + + } + + public class OddSite + { + public string Site_key { get; set; } + public string Site_nice { get; set; } + public int Last_update { get; set; } + public OddMatch Odds { get; set; } + } + + public class OddMatch + { + public IEnumerable H2h { get; set; } + } + + public class OddH2H + { + public double HomeOdd { get; set; } + public double DrawOdd { get; set; } + public double VisitOdd { get; set; } + } + + public class OddNice + { + public List Teams { get; set; } + public int Commence_time { get; set; } + public string Home_team { get; set; } + public OddH2H Odds { get; set; } + } +} diff --git a/MyCore.Interfaces/DTO/SwaggerTokenRequest.cs b/MyCore.Interfaces/DTO/SwaggerTokenRequest.cs new file mode 100644 index 0000000..8d60f46 --- /dev/null +++ b/MyCore.Interfaces/DTO/SwaggerTokenRequest.cs @@ -0,0 +1,14 @@ +namespace MyCore.Interfaces.DTO +{ + /// + /// Swagger test client authentication data + /// + public class SwaggerTokenRequest + { + public string grant_type { get; set; } + public string username { get; set; } + public string password { get; set; } + public string client_id { get; set; } + public string client_secret { get; set; } + } +} diff --git a/MyCore.Interfaces/DTO/TokenDTO.cs b/MyCore.Interfaces/DTO/TokenDTO.cs new file mode 100644 index 0000000..b510559 --- /dev/null +++ b/MyCore.Interfaces/DTO/TokenDTO.cs @@ -0,0 +1,14 @@ +using System; + +namespace MyCore.Interfaces.DTO +{ + public class TokenDTO + { + public string access_token { get; set; } + public string refresh_token { get; set; } + public string scope { get; set; } + public string token_type { get; set; } + public int expires_in { get; set; } + public DateTimeOffset expiration { get; set; } + } +} diff --git a/MyCore/Models/Book.cs b/MyCore.Interfaces/Models/Book.cs similarity index 94% rename from MyCore/Models/Book.cs rename to MyCore.Interfaces/Models/Book.cs index 6914ad6..6efe7ae 100644 --- a/MyCore/Models/Book.cs +++ b/MyCore.Interfaces/Models/Book.cs @@ -5,7 +5,7 @@ using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class Book { diff --git a/MyCore/Models/Common/LightState.cs b/MyCore.Interfaces/Models/Common/LightState.cs similarity index 84% rename from MyCore/Models/Common/LightState.cs rename to MyCore.Interfaces/Models/Common/LightState.cs index 2d16653..61d1f45 100644 --- a/MyCore/Models/Common/LightState.cs +++ b/MyCore.Interfaces/Models/Common/LightState.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public enum LightState { diff --git a/MyCore/Models/Common/LogDatabase.cs b/MyCore.Interfaces/Models/Common/LogDatabase.cs similarity index 94% rename from MyCore/Models/Common/LogDatabase.cs rename to MyCore.Interfaces/Models/Common/LogDatabase.cs index 26ee35f..d05f338 100644 --- a/MyCore/Models/Common/LogDatabase.cs +++ b/MyCore.Interfaces/Models/Common/LogDatabase.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Common +namespace MyCore.Interfaces.Models { public class LogDatabase // TODO { diff --git a/MyCore/Models/MyControlPanel/Database/Automation.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Automation.cs similarity index 92% rename from MyCore/Models/MyControlPanel/Database/Automation.cs rename to MyCore.Interfaces/Models/MyControlPanel/Database/Automation.cs index 69f2d73..6774cbb 100644 --- a/MyCore/Models/MyControlPanel/Database/Automation.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Automation.cs @@ -1,11 +1,10 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -using MyCore.DTO.Common; -using MyCore.DTO.MyControlPanel; +using MyCore.Interfaces.DTO; using System; using System.Collections.Generic; -namespace MyCore.Models.MyControlPanel.Database +namespace MyCore.Interfaces.Models { /// /// Automation diff --git a/MyCore/Models/MyControlPanel/Database/Device.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Device.cs similarity index 95% rename from MyCore/Models/MyControlPanel/Database/Device.cs rename to MyCore.Interfaces/Models/MyControlPanel/Database/Device.cs index bd7fcff..ba5c73c 100644 --- a/MyCore/Models/MyControlPanel/Database/Device.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Device.cs @@ -1,14 +1,12 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -using MyCore.DTO.Common; -using MyCore.DTO.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; -using MyCore.Services.MyControlPanel; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; using System; using System.Collections.Generic; using System.Linq; -namespace MyCore.Models.MyControlPanel.Database +namespace MyCore.Interfaces.Models { /// /// Group of devices diff --git a/MyCore/Models/MyControlPanel/Database/Group.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Group.cs similarity index 86% rename from MyCore/Models/MyControlPanel/Database/Group.cs rename to MyCore.Interfaces/Models/MyControlPanel/Database/Group.cs index 6b04f14..a1ed510 100644 --- a/MyCore/Models/MyControlPanel/Database/Group.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Group.cs @@ -1,10 +1,9 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -using MyCore.DTO.Common; -using MyCore.DTO.MyControlPanel; +using MyCore.Interfaces.DTO; using System; using System.Collections.Generic; -namespace MyCore.Models.MyControlPanel.Database +namespace MyCore.Interfaces.Models { /// /// Group of devices diff --git a/MyCore/Models/MyControlPanel/Database/Location.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Location.cs similarity index 87% rename from MyCore/Models/MyControlPanel/Database/Location.cs rename to MyCore.Interfaces/Models/MyControlPanel/Database/Location.cs index f50cdd2..3041e62 100644 --- a/MyCore/Models/MyControlPanel/Database/Location.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Location.cs @@ -1,8 +1,8 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -using MyCore.DTO.MyControlPanel; +using MyCore.Interfaces.DTO; -namespace MyCore.Models.MyControlPanel.Database +namespace MyCore.Interfaces.Models { /// /// Location of a device (Room name, garden, ..) diff --git a/MyCore/Models/MyControlPanel/Database/Provider.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Provider.cs similarity index 92% rename from MyCore/Models/MyControlPanel/Database/Provider.cs rename to MyCore.Interfaces/Models/MyControlPanel/Database/Provider.cs index 08dca9c..e0a631f 100644 --- a/MyCore/Models/MyControlPanel/Database/Provider.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Provider.cs @@ -1,11 +1,10 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -using MyCore.DTO.Common; -using MyCore.DTO.MyControlPanel; +using MyCore.Interfaces.DTO; using System; using System.Collections.Generic; -namespace MyCore.Models.MyControlPanel.Database +namespace MyCore.Interfaces.Models { /// /// Provider of a device (provider of informations) - e.g. : Meross, Arlo, IoThomas, ... diff --git a/MyCore/Models/MyControlPanel/Database/UserInfo.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/UserInfo.cs similarity index 93% rename from MyCore/Models/MyControlPanel/Database/UserInfo.cs rename to MyCore.Interfaces/Models/MyControlPanel/Database/UserInfo.cs index 4293bd7..3a91ed5 100644 --- a/MyCore/Models/MyControlPanel/Database/UserInfo.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/UserInfo.cs @@ -2,17 +2,17 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using AspNetCore.Security.Jwt; +//using AspNetCore.Security.Jwt; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -using MyCore.Models.MyControlPanel; +using MyCore.Interfaces.Models; -namespace MyCore.Models.MyControlPanel.Database +namespace MyCore.Interfaces.Models { /// /// User Information /// - public class UserInfo : IAuthenticationUser + public class UserInfo //: IAuthenticationUser // TODO ! { [BsonId] [BsonRepresentation(BsonType.ObjectId)] diff --git a/MyCore/Models/MyControlPanel/Layout/PanelSection.cs b/MyCore.Interfaces/Models/MyControlPanel/Layout/PanelSection.cs similarity index 95% rename from MyCore/Models/MyControlPanel/Layout/PanelSection.cs rename to MyCore.Interfaces/Models/MyControlPanel/Layout/PanelSection.cs index f55faeb..0915fa9 100644 --- a/MyCore/Models/MyControlPanel/Layout/PanelSection.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Layout/PanelSection.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Layout +namespace MyCore.Interfaces.Models { public class PanelSection { diff --git a/MyCore.Interfaces/Models/Policy.cs b/MyCore.Interfaces/Models/Policy.cs new file mode 100644 index 0000000..1e0b78a --- /dev/null +++ b/MyCore.Interfaces/Models/Policy.cs @@ -0,0 +1,8 @@ +namespace MyCore.Interfaces.Models +{ + public class Policy + { + public string Name { get; set; } + public string[] Claims { get; set; } + } +} diff --git a/MyCore/Models/Providers/Arlo/ArloDevice.cs b/MyCore.Interfaces/Models/Providers/Arlo/ArloDevice.cs similarity index 98% rename from MyCore/Models/Providers/Arlo/ArloDevice.cs rename to MyCore.Interfaces/Models/Providers/Arlo/ArloDevice.cs index 52d8dde..aaf6c26 100644 --- a/MyCore/Models/Providers/Arlo/ArloDevice.cs +++ b/MyCore.Interfaces/Models/Providers/Arlo/ArloDevice.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Arlo +namespace MyCore.Interfaces.Models { public class ArloDevice { diff --git a/MyCore/Models/Providers/Arlo/UserLocation.cs b/MyCore.Interfaces/Models/Providers/Arlo/UserLocation.cs similarity index 82% rename from MyCore/Models/Providers/Arlo/UserLocation.cs rename to MyCore.Interfaces/Models/Providers/Arlo/UserLocation.cs index 3d2f084..3ccb0c8 100644 --- a/MyCore/Models/Providers/Arlo/UserLocation.cs +++ b/MyCore.Interfaces/Models/Providers/Arlo/UserLocation.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Arlo +namespace MyCore.Interfaces.Models { public class UserLocation { diff --git a/MyCore/Models/Providers/Arlo/UserMedia.cs b/MyCore.Interfaces/Models/Providers/Arlo/UserMedia.cs similarity index 97% rename from MyCore/Models/Providers/Arlo/UserMedia.cs rename to MyCore.Interfaces/Models/Providers/Arlo/UserMedia.cs index 8a01a64..adc3132 100644 --- a/MyCore/Models/Providers/Arlo/UserMedia.cs +++ b/MyCore.Interfaces/Models/Providers/Arlo/UserMedia.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Arlo +namespace MyCore.Interfaces.Models { public class UserMedia { diff --git a/MyCore/Models/Providers/IoThomas/Energy/ElectricityProduction.cs b/MyCore.Interfaces/Models/Providers/IoThomas/Energy/ElectricityProduction.cs similarity index 95% rename from MyCore/Models/Providers/IoThomas/Energy/ElectricityProduction.cs rename to MyCore.Interfaces/Models/Providers/IoThomas/Energy/ElectricityProduction.cs index 081ee49..105d3b7 100644 --- a/MyCore/Models/Providers/IoThomas/Energy/ElectricityProduction.cs +++ b/MyCore.Interfaces/Models/Providers/IoThomas/Energy/ElectricityProduction.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Energy +namespace MyCore.Interfaces.Models { public class ElectricityProduction { diff --git a/MyCore/Models/Providers/IoThomas/SmartGardenMessage.cs b/MyCore.Interfaces/Models/Providers/IoThomas/SmartGardenMessage.cs similarity index 96% rename from MyCore/Models/Providers/IoThomas/SmartGardenMessage.cs rename to MyCore.Interfaces/Models/Providers/IoThomas/SmartGardenMessage.cs index b393dde..d0e001e 100644 --- a/MyCore/Models/Providers/IoThomas/SmartGardenMessage.cs +++ b/MyCore.Interfaces/Models/Providers/IoThomas/SmartGardenMessage.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class SmartGardenMessage { diff --git a/MyCore/Models/Providers/IoThomas/SmartPrinterMessage.cs b/MyCore.Interfaces/Models/Providers/IoThomas/SmartPrinterMessage.cs similarity index 95% rename from MyCore/Models/Providers/IoThomas/SmartPrinterMessage.cs rename to MyCore.Interfaces/Models/Providers/IoThomas/SmartPrinterMessage.cs index 5ab02a1..dbfe001 100644 --- a/MyCore/Models/Providers/IoThomas/SmartPrinterMessage.cs +++ b/MyCore.Interfaces/Models/Providers/IoThomas/SmartPrinterMessage.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class SmartPrinterMessage { diff --git a/MyCore/Models/Providers/Meross/DevicesAbilities.cs b/MyCore.Interfaces/Models/Providers/Meross/DevicesAbilities.cs similarity index 98% rename from MyCore/Models/Providers/Meross/DevicesAbilities.cs rename to MyCore.Interfaces/Models/Providers/Meross/DevicesAbilities.cs index 805df46..e04f54b 100644 --- a/MyCore/Models/Providers/Meross/DevicesAbilities.cs +++ b/MyCore.Interfaces/Models/Providers/Meross/DevicesAbilities.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Meross +namespace MyCore.Interfaces.Models { public class DeviceAbilities { diff --git a/MyCore/Models/Providers/Meross/MerossDevice.cs b/MyCore.Interfaces/Models/Providers/Meross/MerossDevice.cs similarity index 96% rename from MyCore/Models/Providers/Meross/MerossDevice.cs rename to MyCore.Interfaces/Models/Providers/Meross/MerossDevice.cs index 37ff9f7..7245586 100644 --- a/MyCore/Models/Providers/Meross/MerossDevice.cs +++ b/MyCore.Interfaces/Models/Providers/Meross/MerossDevice.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Meross +namespace MyCore.Interfaces.Models { public class MerossDevice { diff --git a/MyCore/Models/Providers/Zigbee/Aqara/AqaraCube.cs b/MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraCube.cs similarity index 82% rename from MyCore/Models/Providers/Zigbee/Aqara/AqaraCube.cs rename to MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraCube.cs index 7e21e7e..ecf6b93 100644 --- a/MyCore/Models/Providers/Zigbee/Aqara/AqaraCube.cs +++ b/MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraCube.cs @@ -1,12 +1,12 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -using MyCore.Models.Providers.Zigbee.Aqara; +using MyCore.Interfaces.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Aqara +namespace MyCore.Interfaces.Models { public class AqaraCube : AqaraDevice { diff --git a/MyCore/Models/Providers/Zigbee/Aqara/AqaraDevice.cs b/MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraDevice.cs similarity index 85% rename from MyCore/Models/Providers/Zigbee/Aqara/AqaraDevice.cs rename to MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraDevice.cs index f2212f1..de8abf2 100644 --- a/MyCore/Models/Providers/Zigbee/Aqara/AqaraDevice.cs +++ b/MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraDevice.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Providers.Zigbee.Aqara +namespace MyCore.Interfaces.Models { public class AqaraDevice { diff --git a/MyCore/Models/Providers/Zigbee/Aqara/AqaraSwitch.cs b/MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraSwitch.cs similarity index 89% rename from MyCore/Models/Providers/Zigbee/Aqara/AqaraSwitch.cs rename to MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraSwitch.cs index 6f4bf13..e12530d 100644 --- a/MyCore/Models/Providers/Zigbee/Aqara/AqaraSwitch.cs +++ b/MyCore.Interfaces/Models/Providers/Zigbee/Aqara/AqaraSwitch.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Providers.Zigbee.Aqara +namespace MyCore.Interfaces.Models { public class AqaraSwitch : AqaraDevice { diff --git a/MyCore/Models/Providers/Zigbee/Ikea/LightBulb.cs b/MyCore.Interfaces/Models/Providers/Zigbee/Ikea/LightBulb.cs similarity index 86% rename from MyCore/Models/Providers/Zigbee/Ikea/LightBulb.cs rename to MyCore.Interfaces/Models/Providers/Zigbee/Ikea/LightBulb.cs index 3d949b0..abf37b8 100644 --- a/MyCore/Models/Providers/Zigbee/Ikea/LightBulb.cs +++ b/MyCore.Interfaces/Models/Providers/Zigbee/Ikea/LightBulb.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Ikea +namespace MyCore.Interfaces.Models { public class LightBulb { diff --git a/MyCore/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs b/MyCore.Interfaces/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs similarity index 94% rename from MyCore/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs rename to MyCore.Interfaces/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs index 4f26c7d..9990265 100644 --- a/MyCore/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs +++ b/MyCore.Interfaces/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models.Providers.Zigbee.Zigbee2Mqtt +namespace MyCore.Interfaces.Models { public class Zigbee2MqttDevice { diff --git a/MyCore/Models/Screen/ScreenConfiguration.cs b/MyCore.Interfaces/Models/Screen/ScreenConfiguration.cs similarity index 95% rename from MyCore/Models/Screen/ScreenConfiguration.cs rename to MyCore.Interfaces/Models/Screen/ScreenConfiguration.cs index b70fc6b..407a369 100644 --- a/MyCore/Models/Screen/ScreenConfiguration.cs +++ b/MyCore.Interfaces/Models/Screen/ScreenConfiguration.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class ScreenConfiguration { diff --git a/MyCore/Models/Screen/ScreenDevice.cs b/MyCore.Interfaces/Models/Screen/ScreenDevice.cs similarity index 95% rename from MyCore/Models/Screen/ScreenDevice.cs rename to MyCore.Interfaces/Models/Screen/ScreenDevice.cs index 1b32c39..9ded88c 100644 --- a/MyCore/Models/Screen/ScreenDevice.cs +++ b/MyCore.Interfaces/Models/Screen/ScreenDevice.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class ScreenDevice { diff --git a/MyCore/Models/Screen/Widgets/Widget.cs b/MyCore.Interfaces/Models/Screen/Widgets/Widget.cs similarity index 97% rename from MyCore/Models/Screen/Widgets/Widget.cs rename to MyCore.Interfaces/Models/Screen/Widgets/Widget.cs index 5044ea4..e40055d 100644 --- a/MyCore/Models/Screen/Widgets/Widget.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/Widget.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class Widget { diff --git a/MyCore/Models/Screen/Widgets/WidgetAgenda.cs b/MyCore.Interfaces/Models/Screen/Widgets/WidgetAgenda.cs similarity index 92% rename from MyCore/Models/Screen/Widgets/WidgetAgenda.cs rename to MyCore.Interfaces/Models/Screen/Widgets/WidgetAgenda.cs index 4388938..52f706f 100644 --- a/MyCore/Models/Screen/Widgets/WidgetAgenda.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/WidgetAgenda.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class WidgetAgenda : Widget { diff --git a/MyCore/Models/Screen/Widgets/WidgetHourAndDate.cs b/MyCore.Interfaces/Models/Screen/Widgets/WidgetHourAndDate.cs similarity index 89% rename from MyCore/Models/Screen/Widgets/WidgetHourAndDate.cs rename to MyCore.Interfaces/Models/Screen/Widgets/WidgetHourAndDate.cs index 746acef..b22c121 100644 --- a/MyCore/Models/Screen/Widgets/WidgetHourAndDate.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/WidgetHourAndDate.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class WidgetHourAndDate : Widget { diff --git a/MyCore/Models/Screen/Widgets/WidgetMessage.cs b/MyCore.Interfaces/Models/Screen/Widgets/WidgetMessage.cs similarity index 94% rename from MyCore/Models/Screen/Widgets/WidgetMessage.cs rename to MyCore.Interfaces/Models/Screen/Widgets/WidgetMessage.cs index 113b3db..8721192 100644 --- a/MyCore/Models/Screen/Widgets/WidgetMessage.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/WidgetMessage.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class WidgetMessage : Widget { diff --git a/MyCore/Models/Screen/Widgets/WidgetNews.cs b/MyCore.Interfaces/Models/Screen/Widgets/WidgetNews.cs similarity index 92% rename from MyCore/Models/Screen/Widgets/WidgetNews.cs rename to MyCore.Interfaces/Models/Screen/Widgets/WidgetNews.cs index 0350ff4..148aaac 100644 --- a/MyCore/Models/Screen/Widgets/WidgetNews.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/WidgetNews.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class WidgetNews : Widget { diff --git a/MyCore/Models/Screen/Widgets/WidgetRadio.cs b/MyCore.Interfaces/Models/Screen/Widgets/WidgetRadio.cs similarity index 90% rename from MyCore/Models/Screen/Widgets/WidgetRadio.cs rename to MyCore.Interfaces/Models/Screen/Widgets/WidgetRadio.cs index 44570bf..7d37d99 100644 --- a/MyCore/Models/Screen/Widgets/WidgetRadio.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/WidgetRadio.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class WidgetRadio : Widget { diff --git a/MyCore/Models/Screen/Widgets/WidgetTraffic.cs b/MyCore.Interfaces/Models/Screen/Widgets/WidgetTraffic.cs similarity index 94% rename from MyCore/Models/Screen/Widgets/WidgetTraffic.cs rename to MyCore.Interfaces/Models/Screen/Widgets/WidgetTraffic.cs index 5be66c8..7aad064 100644 --- a/MyCore/Models/Screen/Widgets/WidgetTraffic.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/WidgetTraffic.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class WidgetTraffic : Widget { diff --git a/MyCore/Models/Screen/Widgets/WidgetWeather.cs b/MyCore.Interfaces/Models/Screen/Widgets/WidgetWeather.cs similarity index 93% rename from MyCore/Models/Screen/Widgets/WidgetWeather.cs rename to MyCore.Interfaces/Models/Screen/Widgets/WidgetWeather.cs index 4e43d66..db13a10 100644 --- a/MyCore/Models/Screen/Widgets/WidgetWeather.cs +++ b/MyCore.Interfaces/Models/Screen/Widgets/WidgetWeather.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace MyCore.Models +namespace MyCore.Interfaces.Models { public class WidgetWeather : Widget { diff --git a/MyCore.Interfaces/Models/TokensSettings.cs b/MyCore.Interfaces/Models/TokensSettings.cs new file mode 100644 index 0000000..33ad693 --- /dev/null +++ b/MyCore.Interfaces/Models/TokensSettings.cs @@ -0,0 +1,18 @@ +namespace MyCore.Interfaces.Models +{ + public class TokensSettings + { + /// + /// Application secret for tokens generation + /// + public string Secret { get; set; } + /// + /// Access token expiration in minutes + /// + public int AccessTokenExpiration { get; set; } = 30; + /// + /// Refresh token expiration in minutes + /// + public int RefreshTokenExpiration { get; set; } = 4 * 60; + } +} diff --git a/MyCore.Interfaces/MyCore.Interfaces.csproj b/MyCore.Interfaces/MyCore.Interfaces.csproj new file mode 100644 index 0000000..6df2fe4 --- /dev/null +++ b/MyCore.Interfaces/MyCore.Interfaces.csproj @@ -0,0 +1,11 @@ + + + + netcoreapp3.1 + + + + + + + diff --git a/MyCore.sln b/MyCore.sln index fd470d6..c844221 100644 --- a/MyCore.sln +++ b/MyCore.sln @@ -5,7 +5,9 @@ VisualStudioVersion = 16.0.29709.97 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyCore", "MyCore\MyCore.csproj", "{017065F0-FC61-4566-A432-F414FC217AAA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyCore.Devices", "MyCore.Devices\MyCore.Devices.csproj", "{7B9FE719-FBF7-42D5-BCF5-BDA31B05D66D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyCore.Interfaces", "MyCore.Interfaces\MyCore.Interfaces.csproj", "{6FD8EE93-D8BD-43AD-A126-A8ECBF4451E4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyCore.Framework", "MyCore.Framework\MyCore.Framework.csproj", "{AA56B2F3-A871-4C99-89FB-038F957399F2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -17,10 +19,14 @@ Global {017065F0-FC61-4566-A432-F414FC217AAA}.Debug|Any CPU.Build.0 = Debug|Any CPU {017065F0-FC61-4566-A432-F414FC217AAA}.Release|Any CPU.ActiveCfg = Release|Any CPU {017065F0-FC61-4566-A432-F414FC217AAA}.Release|Any CPU.Build.0 = Release|Any CPU - {7B9FE719-FBF7-42D5-BCF5-BDA31B05D66D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7B9FE719-FBF7-42D5-BCF5-BDA31B05D66D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7B9FE719-FBF7-42D5-BCF5-BDA31B05D66D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7B9FE719-FBF7-42D5-BCF5-BDA31B05D66D}.Release|Any CPU.Build.0 = Release|Any CPU + {6FD8EE93-D8BD-43AD-A126-A8ECBF4451E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6FD8EE93-D8BD-43AD-A126-A8ECBF4451E4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6FD8EE93-D8BD-43AD-A126-A8ECBF4451E4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6FD8EE93-D8BD-43AD-A126-A8ECBF4451E4}.Release|Any CPU.Build.0 = Release|Any CPU + {AA56B2F3-A871-4C99-89FB-038F957399F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AA56B2F3-A871-4C99-89FB-038F957399F2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AA56B2F3-A871-4C99-89FB-038F957399F2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AA56B2F3-A871-4C99-89FB-038F957399F2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/MyCore/Controllers/AuthenticationController.cs b/MyCore/Controllers/AuthenticationController.cs new file mode 100644 index 0000000..375b0ce --- /dev/null +++ b/MyCore/Controllers/AuthenticationController.cs @@ -0,0 +1,91 @@ +using MyCore.Interfaces.DTO; +using MyCore.Service.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Microsoft.Net.Http.Headers; +using NSwag.Annotations; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; + +namespace MyCore.Service.Controllers +{ + /// + /// Authentication controller + /// + [ApiController, Route("api/[controller]")] + [Authorize] + [OpenApiTag("Authentication", Description = "Authentication management")] + public class AuthenticationController : ControllerBase + { + private readonly ILogger _logger; + private readonly TokensService _tokensService; + + /// + /// Constructor + /// + /// Logger + /// Tokens service + public AuthenticationController(ILogger logger, TokensService tokensService) + { + _logger = logger; + _tokensService = tokensService; + } + + private ActionResult Authenticate(string email, string password) + { + try + { + var token = _tokensService.Authenticate(email.ToLower(), password); + + return Ok(token); + } + /*catch (UnauthorizedAccessException ex) + { + _logger?.LogError(ex, $"Authentication error for user '{email}': unauthorized access"); + return Unauthorized(ex); + }*/ + catch (Exception ex) + { + _logger?.LogError(ex, $"Authenticate error for user '{email}'"); + return Problem($"Authenticate error for user '{email}': {ex.Message}"); + } + } + + /// + /// Authenticate with form parameters (used by Swagger test client) + /// + /// Swagger token request + /// Token descriptor + [AllowAnonymous] + [HttpPost("Token")] + [Consumes("application/x-www-form-urlencoded")] + [SwaggerResponse(HttpStatusCode.OK, typeof(LoginDTO), Description = "Success")] + [SwaggerResponse(HttpStatusCode.Unauthorized, typeof(string), Description = "Invalid credentials")] + [SwaggerResponse(HttpStatusCode.InternalServerError, typeof(string), Description = "Error")] + public ActionResult AuthenticateWithForm([FromForm] SwaggerTokenRequest tokenRequest) + { + return Authenticate(tokenRequest.username, tokenRequest.password); + } + + /// + /// Authenticate with Json parameters (used by most clients) + /// + /// Login DTO + /// Token descriptor + [AllowAnonymous] + [HttpPost("Authenticate")] + [Consumes("application/json")] + [SwaggerResponse(HttpStatusCode.OK, typeof(LoginDTO), Description = "Success")] + [SwaggerResponse(HttpStatusCode.Unauthorized, typeof(string), Description = "Invalid credentials")] + [SwaggerResponse(HttpStatusCode.InternalServerError, typeof(string), Description = "Error")] + public ActionResult AuthenticateWithJson([FromBody] LoginDTO login) + { + return Authenticate(login.Email.ToLower(), login.Password); + } + } +} diff --git a/MyCore/Controllers/BooksController.cs b/MyCore/Controllers/BooksController.cs index bdb7599..f16c601 100644 --- a/MyCore/Controllers/BooksController.cs +++ b/MyCore/Controllers/BooksController.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; -using MyCore.Models; using MyCore.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; +using MyCore.Interfaces.Models; namespace MyCore.Controllers { - [Authorize(Roles = "Admin")] + [Authorize] [Route("api/books")] [ApiController] public class BooksController : ControllerBase diff --git a/MyCore/Controllers/Devices/DeviceController.cs b/MyCore/Controllers/Devices/DeviceController.cs index 0c2a149..1faf8a7 100644 --- a/MyCore/Controllers/Devices/DeviceController.cs +++ b/MyCore/Controllers/Devices/DeviceController.cs @@ -8,18 +8,15 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; -using MyCore.DTO.Common; -using MyCore.DTO.MyControlPanel; -using MyCore.Models; -using MyCore.Models.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; using MyCore.Services; using MyCore.Services.Devices; using MyCore.Services.MyControlPanel; namespace MyCore.Controllers.Devices { - [Authorize(Roles = "Admin")] + [Authorize] // TODO Add ROLES (Roles = "Admin") [Route("api/device")] [ApiController] public class DeviceController : ControllerBase diff --git a/MyCore/Controllers/Devices/IoThomas/EnergyController.cs b/MyCore/Controllers/Devices/IoThomas/EnergyController.cs index f965c5f..4190eb3 100644 --- a/MyCore/Controllers/Devices/IoThomas/EnergyController.cs +++ b/MyCore/Controllers/Devices/IoThomas/EnergyController.cs @@ -7,15 +7,14 @@ using Microsoft.AspNetCore.Mvc; using MQTTnet; using MQTTnet.Client; using MQTTnet.Server; -using MyCore.DTO.Energy; -using MyCore.Models; -using MyCore.Models.Energy; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; using MyCore.Services; using static MyCore.Services.OddService; namespace MyCore.Controllers { - [Authorize(Roles = "Admin")] + [Authorize] // TODO Add ROLES (Roles = "Admin") [Route("api/energy")] [ApiController] public class EnergyController : ControllerBase diff --git a/MyCore/Controllers/Devices/IoThomas/IOTController.cs b/MyCore/Controllers/Devices/IoThomas/IOTController.cs index 0a2604f..5a1d647 100644 --- a/MyCore/Controllers/Devices/IoThomas/IOTController.cs +++ b/MyCore/Controllers/Devices/IoThomas/IOTController.cs @@ -6,12 +6,12 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; -using MyCore.Models; +using MyCore.Interfaces.Models; using MyCore.Services; namespace MyCore.Controllers { - [Authorize(Roles = "Admin")] + [Authorize] // TODO Add ROLES (Roles = "Admin") [Route("api/iot")] [ApiController] public class IOTController : ControllerBase diff --git a/MyCore/Controllers/Devices/IoThomas/OddController.cs b/MyCore/Controllers/Devices/IoThomas/OddController.cs index 54b29c0..39dc109 100644 --- a/MyCore/Controllers/Devices/IoThomas/OddController.cs +++ b/MyCore/Controllers/Devices/IoThomas/OddController.cs @@ -4,23 +4,33 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using MQTTnet; using MQTTnet.Client; using MQTTnet.Server; -using MyCore.DTO; -using MyCore.Models; +using MyCore.Interfaces; +using MyCore.Interfaces.Models; using MyCore.Services; using static MyCore.Services.OddService; + namespace MyCore.Controllers { - [Authorize(Roles = "Admin")] + [Authorize] // TODO Add ROLES Authorize(Roles = "Admin") [Route("api/odd")] [ApiController] public class OddController : ControllerBase { private OddService oddService = new OddService(OddService.RegionOdd.UK); + private readonly ILogger _logger; + + public OddController(ILogger logger) : base() + { + _logger = logger; + } + + /// /// Get odds for one country and one odd value maximum /// @@ -46,7 +56,7 @@ namespace MyCore.Controllers var result = await GetOddsForCountry(id, oddRequest); - return new OkObjectResult(result); + return Ok(result); } catch (Exception e) { @@ -60,7 +70,6 @@ namespace MyCore.Controllers /// Get odds for one country and one odd value maximum /// /// Odd Maximum value - [AllowAnonymous] [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] @@ -80,7 +89,7 @@ namespace MyCore.Controllers } } - return new OkObjectResult(oddToSend); + return Ok(oddToSend); } catch (Exception e) { diff --git a/MyCore/Controllers/Devices/ProviderController.cs b/MyCore/Controllers/Devices/ProviderController.cs index a8ea451..02a0eb8 100644 --- a/MyCore/Controllers/Devices/ProviderController.cs +++ b/MyCore/Controllers/Devices/ProviderController.cs @@ -6,11 +6,8 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; -using MyCore.DTO.Common; -using MyCore.DTO.MyControlPanel; -using MyCore.Models; -using MyCore.Models.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; using MyCore.Services; using MyCore.Services.Devices; using MyCore.Services.MyControlPanel; diff --git a/MyCore/Controllers/Devices/ScreenDeviceController.cs b/MyCore/Controllers/Devices/ScreenDeviceController.cs index 3bf828f..01c390f 100644 --- a/MyCore/Controllers/Devices/ScreenDeviceController.cs +++ b/MyCore/Controllers/Devices/ScreenDeviceController.cs @@ -6,12 +6,12 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; -using MyCore.Models; +using MyCore.Interfaces.Models; using MyCore.Services; namespace MyCore.Controllers { - [Authorize(Roles = "Admin")] + [Authorize] // TODO Add ROLES (Roles = "Admin") [Route("api/device/screen")] [ApiController] public class ScreenDeviceController : ControllerBase diff --git a/MyCore/Controllers/Helpers/MQTTController.cs b/MyCore/Controllers/Helpers/MQTTController.cs index 26006f8..b10e1b7 100644 --- a/MyCore/Controllers/Helpers/MQTTController.cs +++ b/MyCore/Controllers/Helpers/MQTTController.cs @@ -16,7 +16,7 @@ namespace MyCore.Controllers [ApiController] public class MQTTController : ControllerBase { - private string _mqttServer = "192.168.0.8"; + private string _mqttServer = "192.168.31.140"; /// /// It's a mqtt publish test ! :) /// diff --git a/MyCore/Controllers/MyControlPanel/LayoutController.cs b/MyCore/Controllers/MyControlPanel/LayoutController.cs index 480cca1..4132549 100644 --- a/MyCore/Controllers/MyControlPanel/LayoutController.cs +++ b/MyCore/Controllers/MyControlPanel/LayoutController.cs @@ -7,14 +7,13 @@ using Microsoft.AspNetCore.Mvc; using MQTTnet; using MQTTnet.Client; using MQTTnet.Server; -using MyCore.Models; -using MyCore.Models.Layout; +using MyCore.Interfaces.Models; using MyCore.Services; using static MyCore.Services.OddService; namespace MyCore.Controllers { - [Authorize(Roles = "User")] + [Authorize] // TODO Add ROLES (Roles = "User") [Route("api/layout")] [ApiController] public class LayoutController : ControllerBase diff --git a/MyCore/Controllers/MyControlPanel/TokenController.cs b/MyCore/Controllers/MyControlPanel/TokenController.cs index ed1f059..d12908b 100644 --- a/MyCore/Controllers/MyControlPanel/TokenController.cs +++ b/MyCore/Controllers/MyControlPanel/TokenController.cs @@ -10,9 +10,9 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; -using MyCore.DTO; -using MyCore.Models; -using MyCore.Models.MyControlPanel.Database; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; +using MyCore.Service.Services; using MyCore.Services; namespace MyCore.Controllers @@ -22,10 +22,10 @@ namespace MyCore.Controllers [ApiController] public class TokenController : ControllerBase { - private TokenService _tokenService; + private TokensService _tokenService; private UserDatabaseService _userService; - public TokenController(TokenService tokenService, UserDatabaseService userService) + public TokenController(TokensService tokenService, UserDatabaseService userService) { _tokenService = tokenService; _userService = userService; @@ -33,14 +33,14 @@ namespace MyCore.Controllers [AllowAnonymous] [HttpPost] - public ActionResult ConnectUser([FromBody] TokenDTO tokenDTO) + public ActionResult ConnectUser([FromBody] LoginDTO loginDTO) { //string test = _TokenService.GenerateSHA256String(password); - if (IsValidUserAndPasswordCombination(tokenDTO.Email, tokenDTO.Password)) + if (IsValidUserAndPasswordCombination(loginDTO.Email, loginDTO.Password)) { - UserInfo user = _userService.GetByEmail(tokenDTO.Email); - user.Token = _tokenService.GenerateToken(tokenDTO.Email).ToString(); + UserInfo user = _userService.GetByEmail(loginDTO.Email); + user.Token = _tokenService.GenerateToken(loginDTO.Email).ToString(); return user; } diff --git a/MyCore/Controllers/MyControlPanel/UserController.cs b/MyCore/Controllers/MyControlPanel/UserController.cs index d513300..61028a7 100644 --- a/MyCore/Controllers/MyControlPanel/UserController.cs +++ b/MyCore/Controllers/MyControlPanel/UserController.cs @@ -7,21 +7,21 @@ using Microsoft.AspNetCore.Mvc; using MQTTnet; using MQTTnet.Client; using MQTTnet.Server; -using MyCore.Models; -using MyCore.Models.MyControlPanel.Database; +using MyCore.Interfaces.Models; +using MyCore.Service.Services; using MyCore.Services; namespace MyCore.Controllers { - [Authorize(Roles = "Admin")] + [Authorize] // TODO Add ROLES (Roles = "Admin") [Route("api/user")] [ApiController] public class UserController : ControllerBase { private UserDatabaseService _userService; - private TokenService _tokenService; + private TokensService _tokenService; - public UserController(UserDatabaseService userService, TokenService tokenService) + public UserController(UserDatabaseService userService, TokensService tokenService) { _userService = userService; _tokenService = tokenService; diff --git a/MyCore/Controllers/ValuesController.cs b/MyCore/Controllers/ValuesController.cs index 1a44654..f9f3a24 100644 --- a/MyCore/Controllers/ValuesController.cs +++ b/MyCore/Controllers/ValuesController.cs @@ -7,13 +7,13 @@ using Microsoft.AspNetCore.Mvc; using MQTTnet; using MQTTnet.Client; using MQTTnet.Server; -using MyCore.Models; +using MyCore.Interfaces.Models; using MyCore.Services; using static MyCore.Services.OddService; namespace MyCore.Controllers { - [Authorize(Roles = "Admin")] + [Authorize] // TODO Add ROLES (Roles = "Admin") [Route("api/test")] [ApiController] public class ValuesController : ControllerBase diff --git a/MyCore/DTO/MyControlPanel/TokenDTO.cs b/MyCore/DTO/MyControlPanel/TokenDTO.cs deleted file mode 100644 index a339c17..0000000 --- a/MyCore/DTO/MyControlPanel/TokenDTO.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace MyCore.DTO -{ - public class TokenDTO - { - public string Email { get; set; } - public string Password { get; set; } - } -} diff --git a/MyCore/DTO/Odd.cs b/MyCore/DTO/Odd.cs deleted file mode 100644 index 29603a5..0000000 --- a/MyCore/DTO/Odd.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace MyCore.DTO -{ - public class Odd - { - public string Sport_nice; - public List Teams; - public int Commence_time; - public string Home_team; - public List Sites; - - } - - public class OddSite - { - public string Site_key; - public string Site_nice; - public int Last_update; - public OddMatch Odds; - } - - public class OddMatch - { - public IEnumerable H2h; - } - - public class OddH2H - { - public double HomeOdd; - public double DrawOdd; - public double VisitOdd; - } - - public class OddNice - { - public List Teams; - public int Commence_time; - public string Home_team; - public OddH2H Odds; - } -} diff --git a/MyCore/MyCore.csproj b/MyCore/MyCore.csproj index ecb61a8..1d335f0 100644 --- a/MyCore/MyCore.csproj +++ b/MyCore/MyCore.csproj @@ -1,7 +1,7 @@  - netcoreapp2.1 + netcoreapp3.1 Linux 6d53b0c4-74d6-41aa-8816-2ec3cf42767a @@ -9,6 +9,8 @@ true $(NoWarn);1591 + MyCore.Service + MyCore.Service @@ -25,9 +27,15 @@ + + + + + + diff --git a/MyCore/Program.cs b/MyCore/Program.cs index 0407776..f5be552 100644 --- a/MyCore/Program.cs +++ b/MyCore/Program.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MyCore @@ -14,11 +15,14 @@ namespace MyCore { public static void Main(string[] args) { - CreateWebHostBuilder(args).Build().Run(); + CreateHostBuilder(args).Build().Run(); } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); } } diff --git a/MyCore/Properties/launchSettings.json b/MyCore/Properties/launchSettings.json index f31f4ba..05f3a87 100644 --- a/MyCore/Properties/launchSettings.json +++ b/MyCore/Properties/launchSettings.json @@ -4,7 +4,7 @@ "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:25049", - "sslPort": 0 + "sslPort": 44341 } }, "$schema": "http://json.schemastore.org/launchsettings.json", diff --git a/MyCore/Security.cs b/MyCore/Security.cs new file mode 100644 index 0000000..71a3fbe --- /dev/null +++ b/MyCore/Security.cs @@ -0,0 +1,60 @@ +using MyCore.Interfaces.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Service +{ + internal static class Security + { + public const string Scope = "MyCore-api"; + + /// + /// Permissions + /// + private class Permissions + { + /// + /// Dpos admin access + /// + public const string Admin = "MyCore.admin"; + } + + /// + /// Custom claims types + /// + public class ClaimTypes + { + public const string Permission = "Permission"; + } + + /// + /// Permissions for each type of profile + /// + public static readonly Dictionary ProfilesConfiguration = new Dictionary() + { + // An admin has access to everything + //{ typeof(AdminProfile), new[] { Permissions.Admin} }, + }; + + /// + /// Policies names + /// + public class Policies + { + /// + /// Administration + /// + public const string Admin = "MyCore.Administration"; + } + + /// + /// Policies + /// + public static readonly Policy[] PoliciesConfiguration = new[] + { + new Policy() { Name = Policies.Admin, Claims = new[] { Permissions.Admin} } + }; + } +} \ No newline at end of file diff --git a/MyCore/Services/BookService.cs b/MyCore/Services/BookService.cs index 93e445b..3d3202c 100644 --- a/MyCore/Services/BookService.cs +++ b/MyCore/Services/BookService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; diff --git a/MyCore/Services/Devices/DeviceService.cs b/MyCore/Services/Devices/DeviceService.cs index 77c5b0e..00cfa33 100644 --- a/MyCore/Services/Devices/DeviceService.cs +++ b/MyCore/Services/Devices/DeviceService.cs @@ -1,8 +1,6 @@ using Microsoft.AspNetCore.Mvc; -using MyCore.DTO.Common; -using MyCore.DTO.MyControlPanel; -using MyCore.Models.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; using MyCore.Services.MyControlPanel; using System; using System.Collections.Generic; @@ -86,11 +84,11 @@ namespace MyCore.Services.Devices switch (provider.Name) { case "Arlo": - List arloDevices = new ArloService(provider.Username, provider.Password).GetAllDevices(); + List arloDevices = new ArloService(provider.Username, provider.Password).GetAllDevices(); createdDevice = CreateArloDevices(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, arloDevices, provider); break; case "Meross": - List merossDevices = new MerossService(provider.Username, provider.Password).GetMerossDevices(); + List merossDevices = new MerossService(provider.Username, provider.Password).GetMerossDevices(); createdDevice = CreateMerossDevices(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, merossDevices, provider); break; case "Yeelight": @@ -131,7 +129,7 @@ namespace MyCore.Services.Devices return createdDevice; } - public static List CreateArloDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List arloDevices, Provider provider) + public static List CreateArloDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List arloDevices, Provider provider) { List createdArloDevices = new List(); @@ -181,7 +179,7 @@ namespace MyCore.Services.Devices return createdArloDevices; } - public static List CreateMerossDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List merossDevices, Provider provider) + public static List CreateMerossDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List merossDevices, Provider provider) { List createdMerossDevices = new List(); diff --git a/MyCore/Services/Devices/IoThomas/EnergyService.cs b/MyCore/Services/Devices/IoThomas/EnergyService.cs index 9a2430b..fb8c635 100644 --- a/MyCore/Services/Devices/IoThomas/EnergyService.cs +++ b/MyCore/Services/Devices/IoThomas/EnergyService.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -using MyCore.Models.Energy; namespace MyCore.Services { diff --git a/MyCore/Services/Devices/IoThomas/IoTDeviceService.cs b/MyCore/Services/Devices/IoThomas/IoTDeviceService.cs index 9d953e6..12609da 100644 --- a/MyCore/Services/Devices/IoThomas/IoTDeviceService.cs +++ b/MyCore/Services/Devices/IoThomas/IoTDeviceService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; diff --git a/MyCore/Services/Devices/IoThomas/OddService.cs b/MyCore/Services/Devices/IoThomas/OddService.cs index a6c76ff..0d26d62 100644 --- a/MyCore/Services/Devices/IoThomas/OddService.cs +++ b/MyCore/Services/Devices/IoThomas/OddService.cs @@ -1,4 +1,4 @@ -using MyCore.DTO; +using MyCore.Interfaces; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; diff --git a/MyCore/Services/Devices/MQTTService.cs b/MyCore/Services/Devices/MQTTService.cs index 6f7d4ee..430abc0 100644 --- a/MyCore/Services/Devices/MQTTService.cs +++ b/MyCore/Services/Devices/MQTTService.cs @@ -1,11 +1,7 @@ using MQTTnet; using MQTTnet.Client; using MQTTnet.Client.Options; -using MyCore.Models; -using MyCore.Models.Aqara; -using MyCore.Models.Ikea; -using MyCore.Models.Providers.Zigbee.Aqara; -using MyCore.Models.Providers.Zigbee.Zigbee2Mqtt; +using MyCore.Interfaces.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; diff --git a/MyCore/Services/Devices/SupportedDevices/ArloService.cs b/MyCore/Services/Devices/SupportedDevices/ArloService.cs index 2116350..7cb7e79 100644 --- a/MyCore/Services/Devices/SupportedDevices/ArloService.cs +++ b/MyCore/Services/Devices/SupportedDevices/ArloService.cs @@ -1,5 +1,5 @@ using EvtSource; -using MyCore.Models.Arlo; +using MyCore.Interfaces.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ServiceStack; diff --git a/MyCore/Services/Devices/SupportedDevices/MerossService.cs b/MyCore/Services/Devices/SupportedDevices/MerossService.cs index 7ee7335..7c9e1af 100644 --- a/MyCore/Services/Devices/SupportedDevices/MerossService.cs +++ b/MyCore/Services/Devices/SupportedDevices/MerossService.cs @@ -3,7 +3,7 @@ using MQTTnet.Client; using MQTTnet.Client.Options; using MQTTnet.Formatter; using MQTTnet.Implementations; -using MyCore.Models.Meross; +using MyCore.Interfaces.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; @@ -15,7 +15,7 @@ using System.Security.Authentication; using System.Text; using System.Threading; using System.Threading.Tasks; -using static MyCore.Models.Meross.DeviceAbilities; +using static MyCore.Interfaces.Models.DeviceAbilities; namespace MyCore.Services { diff --git a/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs index 44ae513..0c56cf5 100644 --- a/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -using MyCore.Models.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; namespace MyCore.Services.MyControlPanel { diff --git a/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs index 6320f9c..e24da37 100644 --- a/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -using MyCore.Models.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; namespace MyCore.Services.MyControlPanel { diff --git a/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs index 06d7c35..3728131 100644 --- a/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -using MyCore.Models.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; namespace MyCore.Services.MyControlPanel { diff --git a/MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs index 5ed70f6..bb059cf 100644 --- a/MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -using MyCore.Models.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; namespace MyCore.Services.MyControlPanel { diff --git a/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs index 85ff5ea..badcad1 100644 --- a/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -using MyCore.Models.MyControlPanel.Database; namespace MyCore.Services.MyControlPanel { diff --git a/MyCore/Services/MyControlPanel/Database/ScreenDeviceDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/ScreenDeviceDatabaseService.cs index eabdb18..f3d6b3a 100644 --- a/MyCore/Services/MyControlPanel/Database/ScreenDeviceDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/ScreenDeviceDatabaseService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; diff --git a/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs index 9b7c366..9bda89e 100644 --- a/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using MyCore.Models; +using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -using MyCore.Models.MyControlPanel.Database; namespace MyCore.Services { diff --git a/MyCore/Services/MyControlPanel/ProviderService.cs b/MyCore/Services/MyControlPanel/ProviderService.cs index fde7906..ac39a9d 100644 --- a/MyCore/Services/MyControlPanel/ProviderService.cs +++ b/MyCore/Services/MyControlPanel/ProviderService.cs @@ -1,6 +1,6 @@ using Microsoft.Extensions.Configuration; -using MyCore.DTO.MyControlPanel; -using MyCore.Models.MyControlPanel.Database; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; using System; using System.Collections.Generic; using System.Linq; diff --git a/MyCore/Services/MyControlPanel/TokenService.cs b/MyCore/Services/MyControlPanel/TokenService.cs deleted file mode 100644 index ace3288..0000000 --- a/MyCore/Services/MyControlPanel/TokenService.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Microsoft.IdentityModel.Tokens; -using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Security.Claims; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; - -namespace MyCore.Services -{ - public class TokenService - { - public object GenerateToken(string username) - { - var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("%G2YZ=\tgN7fC9M$FXDt#q*a&]Z")); // Put the secret in a file or something - - var claims = new Claim[] { - new Claim(ClaimTypes.Name, username), - new Claim(JwtRegisteredClaimNames.Email, "john.doe@blinkingcaret.com"), - new Claim(ClaimTypes.Role, "Admin") - }; - - var token = new JwtSecurityToken( - issuer: "MyCore App", - audience: "Miotecher", - claims: claims, - notBefore: DateTime.Now, - expires: DateTime.Now.AddDays(28), - signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256) - ); - - string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); - - return jwtToken; - } - - public static string GenerateSHA256String(string inputString) - { - SHA256 sha256 = SHA256Managed.Create(); - byte[] bytes = Encoding.UTF8.GetBytes(inputString); - byte[] hash = sha256.ComputeHash(bytes); - return GetStringFromHash(hash); - } - - public static string GetStringFromHash(byte[] hash) - { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < hash.Length; i++) - { - result.Append(hash[i].ToString("X2")); - } - return result.ToString(); - } - } -} diff --git a/MyCore/Services/TokensService.cs b/MyCore/Services/TokensService.cs new file mode 100644 index 0000000..e7cb3ac --- /dev/null +++ b/MyCore/Services/TokensService.cs @@ -0,0 +1,141 @@ +using MyCore.Framework.Business; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using System.Security.Cryptography; + +namespace MyCore.Service.Services +{ + /// + /// Tokens service + /// + public class TokensService + { + private readonly ILogger _logger; + private readonly TokensSettings _tokenSettings; + private readonly ProfileLogic _profileLogic; + + private readonly SigningCredentials _signingCredentials; + + /// + /// Constructor + /// + /// Logger + /// Tokens settings + /// Database context + /// Profile logic + /// Email client + public TokensService(ILogger logger, IOptions tokenSettings, ProfileLogic profileLogic) + { + _logger = logger; + _tokenSettings = tokenSettings.Value; + _profileLogic = profileLogic; + + var key = Encoding.UTF8.GetBytes(_tokenSettings.Secret); + _signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature); + } + + /// + /// Authenticate + /// + /// Email + /// Password + /// Token DTO in case of success + public TokenDTO Authenticate(string email, string password) + { + try + { + var claims = new List(); + var expiration = DateTime.UtcNow.AddMinutes(_tokenSettings.AccessTokenExpiration); + + // Todo nothing good here.. + var profile = _profileLogic.Authenticate(email, password); + + claims.Add(new Claim(ClaimTypes.Email, email)); + + // TODO: add refresh token support + + var tokenHandler = new JwtSecurityTokenHandler(); + var tokenDescriptor = new SecurityTokenDescriptor() + { + Subject = new ClaimsIdentity(claims), + Expires = expiration, + SigningCredentials = _signingCredentials + }; + var token = tokenHandler.CreateToken(tokenDescriptor); + + return new TokenDTO() + { + access_token = tokenHandler.WriteToken(token), + expires_in = _tokenSettings.AccessTokenExpiration * 60, + expiration = new DateTimeOffset(token.ValidTo), + token_type = "Bearer", + scope = Security.Scope + }; + } + /*catch (UnauthorizedAccessException ex) + { + _logger?.LogError(ex, $"Authenticate error for user '{email}': unauthorized access"); + throw; + }*/ + catch (Exception ex) + { + _logger?.LogError(ex, $"Authenticate error for user '{email}': {ex.Message}"); + throw; + } + } + + public object GenerateToken(string username) + { + var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("%G2YZ=\tgN7fC9M$FXDt#q*a&]Z")); // Put the secret in a file or something + + var claims = new Claim[] { + new Claim(ClaimTypes.Name, username), + new Claim(JwtRegisteredClaimNames.Email, "john.doe@blinkingcaret.com"), + new Claim(ClaimTypes.Role, "Admin") + }; + + var token = new JwtSecurityToken( + issuer: "MyCore App", + audience: "Miotecher", + claims: claims, + notBefore: DateTime.Now, + expires: DateTime.Now.AddDays(28), + signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256) + ); + + string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); + + return jwtToken; + } + + public static string GenerateSHA256String(string inputString) + { + SHA256 sha256 = SHA256Managed.Create(); + byte[] bytes = Encoding.UTF8.GetBytes(inputString); + byte[] hash = sha256.ComputeHash(bytes); + return GetStringFromHash(hash); + } + + public static string GetStringFromHash(byte[] hash) + { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < hash.Length; i++) + { + result.Append(hash[i].ToString("X2")); + } + return result.ToString(); + } + } +} diff --git a/MyCore/Startup.cs b/MyCore/Startup.cs index b2bc2eb..2b49175 100644 --- a/MyCore/Startup.cs +++ b/MyCore/Startup.cs @@ -4,21 +4,32 @@ using System.IO; using System.Linq; using System.Reflection; using System.Text; +using System.Text.Json.Serialization; using System.Threading.Tasks; -using AspNetCore.Security.Jwt; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; -using MyCore.Models; +using MyCore.Framework.Models; +using MyCore.Interfaces.Models; +using MyCore.Service; using MyCore.Services; using MyCore.Services.MyControlPanel; -using Swashbuckle.AspNetCore.Swagger; +using NSwag; +using NSwag.Generation.AspNetCore; +using NSwag.Generation.Processors.Security; +using MyCore.Framework.Business; +using MyCore.Service.Services; + namespace MyCore { public class Startup @@ -36,10 +47,6 @@ namespace MyCore /*YeelightService yeelighService = new YeelightService(); yeelighService.GetDevices();*/ - MQTTService mQTTService = new MQTTService("192.168.31.140", "mqtt", "mqtt"); - - mQTTService.GetDevices(); - } public IConfiguration Configuration { get; } @@ -47,20 +54,10 @@ namespace MyCore // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - // Add the service (test purpose) - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - - services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); + //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Register the Swagger generator, defining 1 or more Swagger documents - services.AddSwaggerGen(c => + /*services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "MyCoreApi", Version = "v1" }); @@ -98,40 +95,167 @@ namespace MyCore ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date }; + });*/ + + + // Swagger + + services.AddControllers() + .AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); + + services.AddOpenApiDocument(config => + { + ConfigureSwagger(config); + }); + + services.AddCors(o => o.AddPolicy("AllowAll", builder => + { + builder.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + })); + + // Authentication + + var tokensConfiguration = Configuration.GetSection("Tokens"); + var tokenSettings = tokensConfiguration.Get(); + + services.Configure(tokensConfiguration); + + foreach (var policy in Security.PoliciesConfiguration) + services.AddAuthorization(options => + { + options.AddPolicy(policy.Name, policyAdmin => + { + foreach (var claim in policy.Claims) + policyAdmin.RequireClaim(Security.ClaimTypes.Permission, claim); + }); + }); + + services + .AddAuthentication(x => + { + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.RequireHttpsMetadata = false; + x.SaveToken = true; + x.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Secret)), + ValidateIssuer = false, + ValidateAudience = false, + RequireExpirationTime = false, + ValidateLifetime = true + }; + }); + + services.AddScoped(); + services.AddScoped(typeof(ProfileLogic)); + + // Add the service (test purpose) + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + services.AddScoped(); + + + services.AddScoped(c => { + MQTTService mQTTService = new MQTTService("192.168.31.140", "mqtt", "mqtt"); + + mQTTService.GetDevices(); + return mQTTService; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - app.UseCors( + /*app.UseCors( options => options.WithOrigins("http://localhost:4200").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials() - ); - - // Enable middleware to serve generated Swagger as a JSON endpoint. - app.UseSwagger(); + );*/ if (env.IsDevelopment()) { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseHsts(); + //app.UseDeveloperExceptionPage(); + app.UseExceptionHandler(HandleError); } + app.UseHttpsRedirection(); + + app.UseRouting(); app.UseAuthentication(); + app.UseAuthorization(); - // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), - // specifying the Swagger JSON endpoint. - app.UseSwaggerUI(c => + app.UseEndpoints(endpoints => { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyCoreApi V1"); + endpoints.MapControllers(); }); - //app.UseHttpsRedirection(); - app.UseMvc(); + app.UseOpenApi(); + app.UseSwaggerUi3(); + } + + private void ConfigureSwagger(AspNetCoreOpenApiDocumentGeneratorSettings config) + { + config.AddSecurity("bearer", Enumerable.Empty(), new OpenApiSecurityScheme + { + Type = OpenApiSecuritySchemeType.OAuth2, + Description = "MyCore Authentication", + Flow = OpenApiOAuth2Flow.Password, + Flows = new OpenApiOAuthFlows() + { + + Password = new OpenApiOAuthFlow() + { + Scopes = new Dictionary + { + {Security.Scope, "MyCore WebAPI"} + }, + TokenUrl = "/api/authentication/Token", + AuthorizationUrl = "/authentication/Token", + } + } + }); + config.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer")); + + config.PostProcess = document => + { + document.Info.Title = "MyCore Service"; + document.Info.Description = "API description"; + document.Info.Version = "Version Pre-Alpha"; + }; + + config.GenerateEnumMappingDescription = true; + } + + private void HandleError(IApplicationBuilder error) + { + error.Run(async context => + { + var exceptionHandlerPathFeature = context.Features.Get(); + var exception = exceptionHandlerPathFeature?.Error as RequestException; + + if (exception != null) + { + var json = exception.GetJson(); + context.Response.ContentType = "application/json"; + context.Response.StatusCode = exception.StatusCode; + await context.Response.WriteAsync(json); + } + }); } } } diff --git a/MyCore/appsettings.json b/MyCore/appsettings.json index 1403b95..d151b6b 100644 --- a/MyCore/appsettings.json +++ b/MyCore/appsettings.json @@ -5,10 +5,17 @@ }, "Logging": { "LogLevel": { - "Default": "Warning" + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", + "Tokens": { + "Secret": "%G2YZ=\tgN7fC9M$FXDt#q*a&]Z", + "AccessTokenExpiration": 86400, + "RefreshTokenExpiration": 518400 + }, "SecuritySettings": { "Secret": "azertyuiopqsdfgh", "Issuer": "MyCore",