diff --git a/Application/ApplicationServiceRegister.cs b/Application/ApplicationServiceRegister.cs new file mode 100644 index 0000000..d3e4d1d --- /dev/null +++ b/Application/ApplicationServiceRegister.cs @@ -0,0 +1,33 @@ +using Microsoft.Extensions.DependencyInjection; +using MTWireGuard; +using MTWireGuard.Application.Mapper; +using MTWireGuard.Application.Repositories; +using MTWireGuard.Application.Services; +using System.Reflection; + +namespace MTWireGuard.Application +{ + public static class ApplicationServiceRegister + { + public static void AddApplicationServices(this IServiceCollection services) + { + // Add DBContext + services.AddDbContext(ServiceLifetime.Singleton); + + // Auto Mapper Configurations + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddAutoMapper( + (provider, expression) => { + expression.AddProfile(provider.GetService()); + expression.AddProfile(provider.GetService()); + expression.AddProfile(provider.GetService()); + }, + new List()); + + // Add Mikrotik API Service + services.AddSingleton(); + } + } +} diff --git a/DBContext.cs b/Application/DBContext.cs similarity index 83% rename from DBContext.cs rename to Application/DBContext.cs index 7779e08..66ef3f9 100644 --- a/DBContext.cs +++ b/Application/DBContext.cs @@ -1,8 +1,7 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Hosting; -using MTWireGuard.Models.Mikrotik; +using MTWireGuard.Application.Models.Mikrotik; -namespace MTWireGuard +namespace MTWireGuard.Application { public class DBContext : DbContext { diff --git a/Helper.cs b/Application/Helper.cs similarity index 95% rename from Helper.cs rename to Application/Helper.cs index e8475c7..e120bd8 100644 --- a/Helper.cs +++ b/Application/Helper.cs @@ -1,11 +1,8 @@ -using MTWireGuard.Models.Mikrotik; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO.Compression; +using System.IO.Compression; using System.Text; using System.Text.RegularExpressions; -namespace MTWireGuard +namespace MTWireGuard.Application { public class Helper { diff --git a/Application/MTWireGuard.Application.csproj b/Application/MTWireGuard.Application.csproj new file mode 100644 index 0000000..880ef54 --- /dev/null +++ b/Application/MTWireGuard.Application.csproj @@ -0,0 +1,28 @@ + + + + net6.0 + enable + enable + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/Mapper/MappingProfile.cs b/Application/Mapper/MappingProfile.cs similarity index 87% rename from Mapper/MappingProfile.cs rename to Application/Mapper/MappingProfile.cs index 2497574..cf8f6a9 100644 --- a/Mapper/MappingProfile.cs +++ b/Application/Mapper/MappingProfile.cs @@ -1,24 +1,22 @@ using AutoMapper; -using Microsoft.EntityFrameworkCore; -using MTWireGuard.Models; -using MTWireGuard.Models.Mikrotik; +using MTWireGuard.Application.Models.Mikrotik; using System.Text.RegularExpressions; -namespace MTWireGuard.Mapper +namespace MTWireGuard.Application.Mapper { public class MappingProfile : Profile { public MappingProfile() { // Logs - CreateMap() + CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => Convert.ToUInt64(src.Id.Substring(1), 16))) .ForMember(dest =>dest.Topics, opt => opt.MapFrom(src => FormatTopics(src.Topics))); // Server Traffic - CreateMap() + CreateMap() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)) .ForMember(dest => dest.Type, @@ -33,7 +31,7 @@ namespace MTWireGuard.Mapper opt => opt.MapFrom(src => Convert.ToInt64(src.RX))); // Mikrotik HWInfo - CreateMap() + CreateMap() .ForMember(dest => dest.Architecture, opt => opt.MapFrom(src => src.ArchitectureName)) .ForMember(dest => dest.CPUCount, @@ -74,32 +72,23 @@ namespace MTWireGuard.Mapper opt => opt.MapFrom(src => FormatUptime(src.Uptime))); // Router Identity - CreateMap(); + CreateMap(); // Active Users - CreateMap() + CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => Convert.ToInt16(src.Id.Substring(1), 16))) .ForMember(dest => dest.LoggedIn, opt => opt.MapFrom(src => src.When)); // Active Jobs - CreateMap() + CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => Convert.ToInt16(src.Id.Substring(1), 16))) .ForMember(dest => dest.NextId, opt => opt.MapFrom(src => Convert.ToInt16(src.NextId.Substring(1), 16))) .ForMember(dest => dest.Policies, opt => opt.MapFrom(src => src.Policy.Split(',', StringSplitOptions.None).ToList())); - - // Item Creation - CreateMap() - .ForMember(dest => dest.Code, - opt => opt.MapFrom(src => (src.Success) ? "200" : src.Code.ToString())) - .ForMember(dest => dest.Title, - opt => opt.MapFrom(src => (src.Success) ? "Done" : src.Message)) - .ForMember(dest => dest.Description, - opt => opt.MapFrom(src => (src.Success) ? "Item created/updated successfully." : src.Detail)); } private static List FormatTopics(string topics) diff --git a/Mapper/PeerMapping.cs b/Application/Mapper/PeerMapping.cs similarity index 76% rename from Mapper/PeerMapping.cs rename to Application/Mapper/PeerMapping.cs index ae99700..334eacc 100644 --- a/Mapper/PeerMapping.cs +++ b/Application/Mapper/PeerMapping.cs @@ -1,16 +1,18 @@ using AutoMapper; -using MTWireGuard.Models.Mikrotik; -using MTWireGuard.Models.Requests; +using Microsoft.Extensions.DependencyInjection; +using MikrotikAPI.Models; +using MTWireGuard.Application.Models.Mikrotik; -namespace MTWireGuard.Mapper +namespace MTWireGuard.Application.Mapper { public class PeerMapping : Profile { - DBContext db; - public PeerMapping(DBContext context) - { - db = context; + private readonly IServiceProvider _provider; + private IServiceProvider Provider => _provider.CreateScope().ServiceProvider; + public PeerMapping(IServiceProvider provider) + { + _provider = provider; /* * Mikrotik Peer to ViewModel */ @@ -44,19 +46,6 @@ namespace MTWireGuard.Mapper CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => $"*{src.Id:X}")); - CreateMap() - .ForMember(dest => dest.Disabled, - opt => opt.MapFrom(src => !src.Enabled)) - .ForMember(dest => dest.EndpointAddress, - opt => opt.MapFrom(src => src.Endpoint)) - .ForMember(dest => dest.PersistentKeepalive, - opt => opt.MapFrom(src => src.KeepAlive.ToString())); - CreateMap(); - CreateMap() - .ForMember(dest => dest.EndpointAddress, - opt => opt.MapFrom(src => src.Endpoint)) - .ForMember(dest => dest.PersistentKeepalive, - opt => opt.MapFrom(src => src.KeepAlive)); // DBUser CreateMap(); @@ -69,16 +58,19 @@ namespace MTWireGuard.Mapper private string? GetPeerName(WGPeer source) { + var db = Provider.GetService(); return (db.Users.ToList().Find(u => u.Id == Convert.ToInt32(source.Id[1..], 16)) != null) ? db.Users.ToList().Find(u => u.Id == Convert.ToInt32(source.Id[1..], 16)).Name : ""; } private string? GetPeerPrivateKey(WGPeer source) { + var db = Provider.GetService(); return (db.Users.ToList().Find(u => u.Id == Convert.ToInt32(source.Id[1..], 16)) != null) ? db.Users.ToList().Find(u => u.Id == Convert.ToInt32(source.Id[1..], 16)).PrivateKey : ""; } private bool HasDifferences(WGPeer source) { + var db = Provider.GetService(); var id = Convert.ToInt32(source.Id[1..], 16); var dbUser = db.Users.ToList().Find(x => x.Id == id); if (dbUser is null) return true; diff --git a/Mapper/ServerMapping.cs b/Application/Mapper/ServerMapping.cs similarity index 58% rename from Mapper/ServerMapping.cs rename to Application/Mapper/ServerMapping.cs index 776c877..a85a02b 100644 --- a/Mapper/ServerMapping.cs +++ b/Application/Mapper/ServerMapping.cs @@ -1,8 +1,7 @@ using AutoMapper; -using MTWireGuard.Models.Mikrotik; -using MTWireGuard.Models.Requests; +using MTWireGuard.Application.Models.Mikrotik; -namespace MTWireGuard.Mapper +namespace MTWireGuard.Application.Mapper { public class ServerMapping : Profile { @@ -11,7 +10,7 @@ namespace MTWireGuard.Mapper /* * Convert Mikrotik Server Model to ViewModel */ - CreateMap() + CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => Convert.ToInt32(src.Id.Substring(1), 16))) .ForMember(dest => dest.IsEnabled, @@ -20,23 +19,14 @@ namespace MTWireGuard.Mapper /* * Convert Wrapper CreateModel to Rest-API CreateModel */ - CreateMap() - .ForMember(dest => dest.ListenPort, - opt => opt.MapFrom(src => src.Port)); - - CreateMap() + CreateMap() .ForMember(dest => dest.Disabled, opt => opt.MapFrom(src => !src.Enabled)); /* * Convert Wrapper UpdateModel to Rest-API UpdateModel */ - CreateMap() - .ForMember(dest => dest.ListenPort, - opt => opt.MapFrom(src => src.Port)); - - - CreateMap() + CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => $"*{src.Id:X}")); } diff --git a/Migrations/20230108171012_Initialize.Designer.cs b/Application/Migrations/20230108171012_Initialize.Designer.cs similarity index 97% rename from Migrations/20230108171012_Initialize.Designer.cs rename to Application/Migrations/20230108171012_Initialize.Designer.cs index e67bdf3..86847ff 100644 --- a/Migrations/20230108171012_Initialize.Designer.cs +++ b/Application/Migrations/20230108171012_Initialize.Designer.cs @@ -7,7 +7,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; #nullable disable -namespace MTWireGuard.Migrations +namespace MTWireGuard.Application.Migrations { [DbContext(typeof(DBContext))] [Migration("20230108171012_Initialize")] diff --git a/Migrations/20230108171012_Initialize.cs b/Application/Migrations/20230108171012_Initialize.cs similarity index 97% rename from Migrations/20230108171012_Initialize.cs rename to Application/Migrations/20230108171012_Initialize.cs index 366dda5..ea3d7f2 100644 --- a/Migrations/20230108171012_Initialize.cs +++ b/Application/Migrations/20230108171012_Initialize.cs @@ -2,7 +2,7 @@ #nullable disable -namespace MTWireGuard.Migrations +namespace MTWireGuard.Application.Migrations { /// public partial class Initialize : Migration diff --git a/Migrations/DBContextModelSnapshot.cs b/Application/Migrations/DBContextModelSnapshot.cs similarity index 97% rename from Migrations/DBContextModelSnapshot.cs rename to Application/Migrations/DBContextModelSnapshot.cs index d7bb835..dd99923 100644 --- a/Migrations/DBContextModelSnapshot.cs +++ b/Application/Migrations/DBContextModelSnapshot.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; #nullable disable -namespace MTWireGuard.Migrations +namespace MTWireGuard.Application.Migrations { [DbContext(typeof(DBContext))] partial class DBContextModelSnapshot : ModelSnapshot diff --git a/Application/Models/CreationResult.cs b/Application/Models/CreationResult.cs new file mode 100644 index 0000000..9178e8b --- /dev/null +++ b/Application/Models/CreationResult.cs @@ -0,0 +1,10 @@ +namespace MTWireGuard.Application.Models +{ + + public class CreationResult + { + public string Code { get; set; } + public string Title { get; set; } + public string Description { get; set; } + } +} diff --git a/Application/Models/Mikrotik/ActiveUser.cs b/Application/Models/Mikrotik/ActiveUser.cs new file mode 100644 index 0000000..46a6291 --- /dev/null +++ b/Application/Models/Mikrotik/ActiveUser.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace MTWireGuard.Application.Models.Mikrotik +{ + public class ActiveUserViewModel + { + public short Id { get; set; } + public string Group { get; set; } + public string Name { get; set; } + public bool Radius { get; set; } + public string Via { get; set; } + public string LoggedIn { get; set; } + } +} diff --git a/Application/Models/Mikrotik/Identity.cs b/Application/Models/Mikrotik/Identity.cs new file mode 100644 index 0000000..1a9f31b --- /dev/null +++ b/Application/Models/Mikrotik/Identity.cs @@ -0,0 +1,7 @@ +namespace MTWireGuard.Application.Models.Mikrotik +{ + public class MTIdentityViewModel + { + public string Name { get; set; } + } +} diff --git a/Application/Models/Mikrotik/Job.cs b/Application/Models/Mikrotik/Job.cs new file mode 100644 index 0000000..7785861 --- /dev/null +++ b/Application/Models/Mikrotik/Job.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace MTWireGuard.Application.Models.Mikrotik +{ + public class JobViewModel + { + public short Id { get; set; } + public short NextId { get; set; } + public string Owner { get; set; } + public List Policies { get; set; } + public string Started { get; set; } + public string Type { get; set; } + } +} diff --git a/Application/Models/Mikrotik/Log.cs b/Application/Models/Mikrotik/Log.cs new file mode 100644 index 0000000..714cd30 --- /dev/null +++ b/Application/Models/Mikrotik/Log.cs @@ -0,0 +1,10 @@ +namespace MTWireGuard.Application.Models.Mikrotik +{ + public class LogViewModel + { + public ulong Id { get; set; } + public string Message { get; set; } + public string Time { get; set; } + public List Topics { get; set; } + } +} diff --git a/Application/Models/Mikrotik/MTInfo.cs b/Application/Models/Mikrotik/MTInfo.cs new file mode 100644 index 0000000..d02ce39 --- /dev/null +++ b/Application/Models/Mikrotik/MTInfo.cs @@ -0,0 +1,29 @@ +namespace MTWireGuard.Application.Models.Mikrotik +{ + public class MTInfoViewModel + { + public string Architecture { get; set; } + public string BoardName { get; set; } + public string Platform { get; set; } + public string CPU { get; set; } + public byte CPUCount { get; set; } + public short CPUFrequency { get; set; } + public byte CPULoad { get; set; } + public string TotalHDD { get; set; } + public string UsedHDD { get; set; } + public string FreeHDD { get; set; } + public long TotalHDDBytes { get; set; } + public long UsedHDDBytes { get; set; } + public long FreeHDDBytes { get; set; } + public byte FreeHDDPercentage { get; set; } + public string TotalRAM { get; set; } + public string UsedRAM { get; set; } + public string FreeRAM { get; set; } + public long TotalRAMBytes { get; set; } + public long UsedRAMBytes { get; set; } + public long FreeRAMBytes { get; set; } + public byte FreeRAMPercentage { get; set; } + public string UPTime { get; set; } + public string Version { get; set; } + } +} diff --git a/Application/Models/Mikrotik/ServerTraffic.cs b/Application/Models/Mikrotik/ServerTraffic.cs new file mode 100644 index 0000000..43e0ead --- /dev/null +++ b/Application/Models/Mikrotik/ServerTraffic.cs @@ -0,0 +1,12 @@ +namespace MTWireGuard.Application.Models.Mikrotik +{ + public class ServerTrafficViewModel + { + public string Name { get; set; } + public string Type { get; set; } + public string Upload { get; set; } + public string Download { get; set; } + public long UploadBytes { get; set; } + public long DownloadBytes { get; set; } + } +} diff --git a/Application/Models/Mikrotik/WGPeer.cs b/Application/Models/Mikrotik/WGPeer.cs new file mode 100644 index 0000000..ec1bd4c --- /dev/null +++ b/Application/Models/Mikrotik/WGPeer.cs @@ -0,0 +1,68 @@ +using Microsoft.EntityFrameworkCore; + +namespace MTWireGuard.Application.Models.Mikrotik +{ + [PrimaryKey("Id")] + [Index("PrivateKey", IsUnique = true)] + [Index("PublicKey", IsUnique = true)] + public class WGPeerDBModel + { + public int Id { get; set; } + public string? Name { get; set; } + public string PrivateKey { get; set; } + public string PublicKey { get; set; } + } + + public class WGPeerViewModel + { + public int Id { get; set; } + public string Name { get; set; } + public string Address { get; set; } + public string CurrentAddress { get; set; } + public bool IsEnabled { get; set; } + public string Interface { get; set; } + public string PrivateKey { get; set; } + public string PublicKey { get; set; } + public string Download { get; set; } + public string Upload { get; set; } + public long DownloadBytes { get; set; } + public long UploadBytes { get; set; } + public bool IsDifferent { get; set; } + } + + public class UserCreateModel + { + public string Name { get; set; } + public string PrivateKey { get; set; } + public string AllowedAddress { get; set; } + public bool Disabled { get; set; } + public string Interface { get; set; } + public string EndpointAddress { get; set; } + public string EndpointPort { get; set; } + public string PublicKey { get; set; } + public string PresharedKey { get; set; } + public string PersistentKeepalive { get; set; } + } + + public class UserSyncModel + { + public int Id { get; set; } + public string Name { get; set; } + public string PrivateKey { get; set; } + public string PublicKey { get; set; } + } + + public class UserUpdateModel + { + public int Id { get; set; } + public string Name { get; set; } + public string AllowedAddress { get; set; } + public string Interface { get; set; } + public string EndpointAddress { get; set; } + public ushort EndpointPort { get; set; } + public string PublicKey { get; set; } + public string PrivateKey { get; set; } + public string PresharedKey { get; set; } + public int PersistentKeepalive { get; set; } + } +} diff --git a/Application/Models/Mikrotik/WGServer.cs b/Application/Models/Mikrotik/WGServer.cs new file mode 100644 index 0000000..58f23a7 --- /dev/null +++ b/Application/Models/Mikrotik/WGServer.cs @@ -0,0 +1,32 @@ +namespace MTWireGuard.Application.Models.Mikrotik +{ + public class WGServerViewModel + { + public int Id { get; set; } + public string Name { get; set; } + public bool IsEnabled { get; set; } + public ushort ListenPort { get; set; } + public ushort MTU { get; set; } + public string PrivateKey { get; set; } + public string PublicKey { get; set; } + public bool Running { get; set; } + } + + public class ServerCreateModel + { + public string Name { get; set; } + public bool Enabled { get; set; } + public string ListenPort { get; set; } + public string MTU { get; set; } + public string PrivateKey { get; set; } + } + + public class ServerUpdateModel + { + public int Id { get; set; } + public string Name { get; set; } + public ushort ListenPort { get; set; } + public ushort MTU { get; set; } + public string PrivateKey { get; set; } + } +} diff --git a/Application/Models/SidebarInfo.cs b/Application/Models/SidebarInfo.cs new file mode 100644 index 0000000..cb5e6ac --- /dev/null +++ b/Application/Models/SidebarInfo.cs @@ -0,0 +1,16 @@ +namespace MTWireGuard.Application.Models +{ + public class SidebarInfo + { + public int RAMUsedPercentage { get; set; } + public int CPUUsedPercentage { get; set; } + public int HDDUsedPercentage { get; set; } + public string RAMUsed { get; set; } + public string HDDUsed { get; set; } + public string TotalRAM { get; set; } + public string TotalHDD { get; set; } + public string RAMBgColor { get; set; } + public string CPUBgColor { get; set; } + public string HDDBgColor { get; set; } + } +} diff --git a/Repositories/IMikrotikRepository.cs b/Application/Repositories/IMikrotikRepository.cs similarity index 89% rename from Repositories/IMikrotikRepository.cs rename to Application/Repositories/IMikrotikRepository.cs index 2ace03b..2a051da 100644 --- a/Repositories/IMikrotikRepository.cs +++ b/Application/Repositories/IMikrotikRepository.cs @@ -1,7 +1,8 @@ -using MTWireGuard.Models; -using MTWireGuard.Models.Mikrotik; +using MTWireGuard.Application.Models; +using MTWireGuard.Application.Models.Mikrotik; +using MikrotikAPI.Models; -namespace MTWireGuard.Repositories +namespace MTWireGuard.Application.Repositories { public interface IMikrotikRepository : IDisposable { diff --git a/Services/MTAPI.cs b/Application/Services/MTAPI.cs similarity index 80% rename from Services/MTAPI.cs rename to Application/Services/MTAPI.cs index 319599b..ae8c0b1 100644 --- a/Services/MTAPI.cs +++ b/Application/Services/MTAPI.cs @@ -1,55 +1,58 @@ using AutoMapper; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.EntityFrameworkCore; -using MTWireGuard.Models; -using MTWireGuard.Models.Mikrotik; -using MTWireGuard.Repositories; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +using MikrotikAPI; +using MTWireGuard.Application.Models; +using MTWireGuard.Application.Models.Mikrotik; +using MTWireGuard.Application.Repositories; using QRCoder; -namespace MTWireGuard.Services +namespace MTWireGuard.Application.Services { public class MTAPI : IMikrotikRepository { private readonly IMapper mapper; private readonly DBContext dbContext; + private readonly APIWrapper wrapper; private bool disposed = false; public MTAPI(IMapper mapper, DBContext dbContext) { this.mapper = mapper; this.dbContext = dbContext; + + string MT_IP = Environment.GetEnvironmentVariable("MT_IP"); + string MT_USER = Environment.GetEnvironmentVariable("MT_USER"); + string MT_PASS = Environment.GetEnvironmentVariable("MT_PASS"); + this.wrapper = new(MT_IP, MT_USER, MT_PASS); } public async Task> GetLogsAsync() { - var model = await APIHandler.GetLogsAsync(); + var model = await wrapper.GetLogsAsync(); var result = mapper.Map>(model); return result.OrderBy(list => list.Id).ToList(); } public async Task> GetServersAsync() { - var model = await APIHandler.GetServersAsync(); + var model = await wrapper.GetServersAsync(); var result = mapper.Map>(model); return result.OrderBy(list => list.Id).ToList(); } public async Task GetServer(string Name) { - var model = await APIHandler.GetServer(Name); + var model = await wrapper.GetServer(Name); return mapper.Map(model); } public async Task> GetServersTraffic() { - var model = await APIHandler.GetServersTraffic(); + var model = await wrapper.GetServersTraffic(); return mapper.Map>(model); } public async Task> GetUsersAsync() { - var model = await APIHandler.GetUsersAsync(); + var model = await wrapper.GetUsersAsync(); var result = mapper.Map>(model); return result.OrderBy(list => list.Id).ToList(); } public async Task GetUser(int id) { - var model = await APIHandler.GetUser($"*{id:X}"); + var model = await wrapper.GetUser($"*{id:X}"); return mapper.Map(model); } public async Task GetUserTunnelConfig(int id) @@ -79,19 +82,19 @@ namespace MTWireGuard.Services } public async Task GetInfo() { - var model = await APIHandler.GetInfo(); + var model = await wrapper.GetInfo(); return mapper.Map(model); } public async Task GetName() { - var model = await APIHandler.GetName(); + var model = await wrapper.GetName(); return mapper.Map(model); } public async Task TryConnectAsync() { try { - var model = await APIHandler.TryConnectAsync(); + var model = await wrapper.TryConnectAsync(); if ((model.Error == 400 && model.Message == "Bad Request") || (model.Error == 401 && model.Message == "Unauthorized")) { return true; @@ -105,42 +108,42 @@ namespace MTWireGuard.Services } public async Task> GetActiveSessions() { - var model = await APIHandler.GetActiveSessions(); + var model = await wrapper.GetActiveSessions(); return mapper.Map>(model); } public async Task> GetJobs() { - var model = await APIHandler.GetJobs(); + var model = await wrapper.GetJobs(); return mapper.Map>(model); } public async Task GetCurrentSessionID() { - var activeSessions = await APIHandler.GetActiveSessions(); + var activeSessions = await wrapper.GetActiveSessions(); var apiSession = activeSessions.Find(x => x.Via == "api"); - var jobs = await APIHandler.GetJobs(); + var jobs = await wrapper.GetJobs(); var currentJob = jobs.Find(x => x.Started == apiSession.When); return currentJob.Id; } public async Task KillJob(string JobID) { - return await APIHandler.KillJob(JobID); + return await wrapper.KillJob(JobID); } public async Task CreateServer(ServerCreateModel server) { - var srv = mapper.Map(server); - var model = await APIHandler.CreateServer(srv); + var srv = mapper.Map(server); + var model = await wrapper.CreateServer(srv); return mapper.Map(model); } public async Task CreateUser(UserCreateModel peer) { - var user = mapper.Map(peer); - var model = await APIHandler.CreateUser(user); + var user = mapper.Map(peer); + var model = await wrapper.CreateUser(user); if (model.Success) { - var item = model.Item as WGPeer; + var item = model.Item as MikrotikAPI.Models.WGPeer; await dbContext.Users.AddAsync(new() { Id = Convert.ToInt32(item.Id[1..], 16), @@ -193,8 +196,8 @@ namespace MTWireGuard.Services } if (mtUser.PublicKey != user.PublicKey) { - var fxUser = mapper.Map(user); - var update = await APIHandler.UpdateUser(fxUser); + var fxUser = mapper.Map(user); + var update = await wrapper.UpdateUser(fxUser); result = mapper.Map(update); } return result; @@ -202,8 +205,8 @@ namespace MTWireGuard.Services public async Task UpdateUser(UserUpdateModel user) { - var mtPeer = mapper.Map(user); - var mtUpdate = await APIHandler.UpdateUser(mtPeer); + var mtPeer = mapper.Map(user); + var mtUpdate = await wrapper.UpdateUser(mtPeer); if (mtUpdate.Success) { var exists = await dbContext.Users.FindAsync(user.Id); @@ -233,14 +236,14 @@ namespace MTWireGuard.Services public async Task UpdateServer(ServerUpdateModel server) { - var srv = mapper.Map(server); - var mtUpdate = await APIHandler.UpdateServer(srv); + var srv = mapper.Map(server); + var mtUpdate = await wrapper.UpdateServer(srv); return mapper.Map(mtUpdate); } public async Task EnableServer(int id) { - var enable = await APIHandler.SetServerEnabled(new() + var enable = await wrapper.SetServerEnabled(new() { ID = $"*{id:X}", Disabled = false @@ -250,7 +253,7 @@ namespace MTWireGuard.Services public async Task DisableServer(int id) { - var enable = await APIHandler.SetServerEnabled(new() + var enable = await wrapper.SetServerEnabled(new() { ID = $"*{id:X}", Disabled = true @@ -260,7 +263,7 @@ namespace MTWireGuard.Services public async Task EnableUser(int id) { - var enable = await APIHandler.SetUserEnabled(new() + var enable = await wrapper.SetUserEnabled(new() { ID = $"*{id:X}", Disabled = false @@ -270,7 +273,7 @@ namespace MTWireGuard.Services public async Task DisableUser(int id) { - var enable = await APIHandler.SetUserEnabled(new() + var enable = await wrapper.SetUserEnabled(new() { ID = $"*{id:X}", Disabled = true @@ -280,12 +283,12 @@ namespace MTWireGuard.Services public async Task DeleteServer(int id) { - var delete = await APIHandler.DeleteServer($"*{id:X}"); + var delete = await wrapper.DeleteServer($"*{id:X}"); return mapper.Map(delete); } public async Task DeleteUser(int id) { - var delete = await APIHandler.DeleteUser($"*{id:X}"); + var delete = await wrapper.DeleteUser($"*{id:X}"); return mapper.Map(delete); } diff --git a/MTWireGuard.sln b/MTWireGuard.sln index 864ffa9..a0ffe51 100644 --- a/MTWireGuard.sln +++ b/MTWireGuard.sln @@ -3,13 +3,17 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.3.32819.101 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MTWireGuard", "MTWireGuard.csproj", "{F4826D62-8AB3-4565-A3F1-8FD5998DFA43}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MTWireGuard", "UI\MTWireGuard.csproj", "{F4826D62-8AB3-4565-A3F1-8FD5998DFA43}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{810BE84C-BB0A-4280-BBE9-E0A1B859BDED}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig EndProjectSection EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MTWireGuard.Application", "Application\MTWireGuard.Application.csproj", "{D287FE39-390B-44B2-A62E-CE6030CA945B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MikrotikAPI", "MikrotikAPI\MikrotikAPI.csproj", "{357EE40B-AA30-482C-94CF-34854BE24D61}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -20,6 +24,14 @@ Global {F4826D62-8AB3-4565-A3F1-8FD5998DFA43}.Debug|Any CPU.Build.0 = Debug|Any CPU {F4826D62-8AB3-4565-A3F1-8FD5998DFA43}.Release|Any CPU.ActiveCfg = Release|Any CPU {F4826D62-8AB3-4565-A3F1-8FD5998DFA43}.Release|Any CPU.Build.0 = Release|Any CPU + {D287FE39-390B-44B2-A62E-CE6030CA945B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D287FE39-390B-44B2-A62E-CE6030CA945B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D287FE39-390B-44B2-A62E-CE6030CA945B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D287FE39-390B-44B2-A62E-CE6030CA945B}.Release|Any CPU.Build.0 = Release|Any CPU + {357EE40B-AA30-482C-94CF-34854BE24D61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {357EE40B-AA30-482C-94CF-34854BE24D61}.Debug|Any CPU.Build.0 = Debug|Any CPU + {357EE40B-AA30-482C-94CF-34854BE24D61}.Release|Any CPU.ActiveCfg = Release|Any CPU + {357EE40B-AA30-482C-94CF-34854BE24D61}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/APIHandler.cs b/MikrotikAPI/APIWrapper.cs similarity index 53% rename from APIHandler.cs rename to MikrotikAPI/APIWrapper.cs index 3338dbd..6ae755a 100644 --- a/APIHandler.cs +++ b/MikrotikAPI/APIWrapper.cs @@ -1,94 +1,98 @@ -using Microsoft.AspNetCore.Hosting.Server; -using MTWireGuard.Models; -using MTWireGuard.Models.Mikrotik; +using MikrotikAPI.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Net.Http.Headers; using System.Text; -namespace MTWireGuard +namespace MikrotikAPI { - public static class APIHandler + public class APIWrapper { - private static readonly string MT_IP = Environment.GetEnvironmentVariable("MT_IP"); - private static readonly string MT_USER = Environment.GetEnvironmentVariable("MT_USER"); - private static readonly string MT_PASS = Environment.GetEnvironmentVariable("MT_PASS"); + private string MT_IP { get; set; } + private string MT_USER { get; set; } + private string MT_PASS { get; set; } - public static async Task> GetLogsAsync() + public APIWrapper(string IP, string User, string Password) { - string json = await SendGetRequestAsync("log"); - return JsonConvert.DeserializeObject>(json); + MT_IP = IP; + MT_USER = User; + MT_PASS = Password; } - public static async Task> GetServersAsync() + public async Task> GetLogsAsync() { - string json = await SendGetRequestAsync("interface/wireguard"); - return JsonConvert.DeserializeObject>(json); + string json = await SendGetRequestAsync(Endpoints.Log); + return json.ToModel>(); } - public static async Task GetServer(string Name) + public async Task> GetServersAsync() + { + string json = await SendGetRequestAsync(Endpoints.Wireguard); + return json.ToModel>(); + } + + public async Task GetServer(string Name) { var servers = await GetServersAsync(); return servers.Find(s => s.Name == Name); } - public static async Task> GetServersTraffic() + public async Task> GetServersTraffic() { - var json = await SendPostRequestAsync("interface", "{\"stats\", {\".proplist\":\"name, type, rx-byte, tx-byte\"}}"); - return JsonConvert.DeserializeObject>(json); + var json = await SendRequestBase(RequestMethod.GET, Endpoints.Interface, "{\"stats\", {\".proplist\":\"name, type, rx-byte, tx-byte\"}}"); + return json.ToModel>(); } - public static async Task> GetUsersAsync() + public async Task> GetUsersAsync() { - using var db = new DBContext(); - string json = await SendGetRequestAsync("interface/wireguard/peers"); - return JsonConvert.DeserializeObject>(json); + string json = await SendGetRequestAsync(Endpoints.WireguardPeers); + return json.ToModel>(); } - public static async Task GetUser(string id) + public async Task GetUser(string id) { var users = await GetUsersAsync(); return users.Find(u => u.Id == id); } - public static async Task GetInfo() + public async Task GetInfo() { - var json = await SendGetRequestAsync("system/resource"); - return JsonConvert.DeserializeObject(json); + var json = await SendGetRequestAsync(Endpoints.SystemResource); + return json.ToModel(); } - public static async Task GetName() + public async Task GetName() { - var json = await SendGetRequestAsync("system/identity"); - return JsonConvert.DeserializeObject(json); + var json = await SendGetRequestAsync(Endpoints.SystemIdentity); + return json.ToModel(); } - public static async Task TryConnectAsync() + public async Task TryConnectAsync() { - var connection = await SendGetRequestAsync("", true); - return JsonConvert.DeserializeObject(connection); + var connection = await SendGetRequestAsync(Endpoints.Empty, true); + return connection.ToModel(); } - public static async Task> GetActiveSessions() + public async Task> GetActiveSessions() { - var json = await SendGetRequestAsync("user/active?name=" + MT_USER); - return JsonConvert.DeserializeObject>(json); + var json = await SendGetRequestAsync($"{Endpoints.ActiveUsers}?name=" + MT_USER); + return json.ToModel>(); } - public static async Task> GetJobs() + public async Task> GetJobs() { - var json = await SendGetRequestAsync("system/script/job"); - return JsonConvert.DeserializeObject>(json); + var json = await SendGetRequestAsync(Endpoints.Jobs); + return json.ToModel>(); } - public static async Task KillJob(string JobID) + public async Task KillJob(string JobID) { - return await SendDeleteRequestAsync("system/script/job/" + JobID); + return await SendDeleteRequestAsync($"{Endpoints.Jobs}/" + JobID); } - public static async Task CreateServer(WGServerCreateModel server) + public async Task CreateServer(WGServerCreateModel server) { - var json = await SendPutRequestAsync("interface/wireguard", server); + var json = await SendPutRequestAsync(Endpoints.Wireguard, server); var obj = JObject.Parse(json); bool success = false; string code = string.Empty, message = string.Empty, detail = string.Empty; @@ -119,7 +123,7 @@ namespace MTWireGuard }; } - public static async Task CreateUser(WGPeerCreateModel user) + public async Task CreateUser(WGPeerCreateModel user) { var jsonData = JObject.Parse(JsonConvert.SerializeObject(user, new JsonSerializerSettings { @@ -127,7 +131,7 @@ namespace MTWireGuard DefaultValueHandling = DefaultValueHandling.Ignore })); - var json = await SendPutRequestAsync("interface/wireguard/peers", jsonData); + var json = await SendPutRequestAsync(Endpoints.WireguardPeers, jsonData); var obj = JObject.Parse(json); bool success = false; string code = string.Empty, message = string.Empty, detail = string.Empty; @@ -161,14 +165,14 @@ namespace MTWireGuard }; } - public static async Task UpdateServer(WGServerUpdateModel server) + public async Task UpdateServer(WGServerUpdateModel server) { var serverJson = JObject.Parse(JsonConvert.SerializeObject(server, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore })); - var json = await SendPatchRequestAsync($"interface/wireguard/{server.Id}", serverJson); + var json = await SendPatchRequestAsync($"{Endpoints.Wireguard}/{server.Id}", serverJson); var obj = JObject.Parse(json); bool success = false; string code = string.Empty, message = string.Empty, detail = string.Empty; @@ -202,14 +206,14 @@ namespace MTWireGuard }; } - public static async Task UpdateUser(WGPeerUpdateModel user) + public async Task UpdateUser(WGPeerUpdateModel user) { var userJson = JObject.Parse(JsonConvert.SerializeObject(user, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore })); - var json = await SendPatchRequestAsync($"interface/wireguard/peers/{user.Id}", userJson); + var json = await SendPatchRequestAsync($"{Endpoints.WireguardPeers}/{user.Id}", userJson); var obj = JObject.Parse(json); bool success = false; string code = string.Empty, message = string.Empty, detail = string.Empty; @@ -243,9 +247,9 @@ namespace MTWireGuard }; } - public static async Task SetServerEnabled(WGEnability enability) + public async Task SetServerEnabled(WGEnability enability) { - var json = await SendPatchRequestAsync($"interface/wireguard/{enability.ID}", new { disabled = enability.Disabled }); + var json = await SendPatchRequestAsync($"{Endpoints.Wireguard}/{enability.ID}", new { disabled = enability.Disabled }); var obj = JObject.Parse(json); bool success = false; string code = string.Empty, message = string.Empty, detail = string.Empty; @@ -279,9 +283,9 @@ namespace MTWireGuard }; } - public static async Task SetUserEnabled(WGEnability enability) + public async Task SetUserEnabled(WGEnability enability) { - var json = await SendPatchRequestAsync($"interface/wireguard/peers/{enability.ID}", new { disabled = enability.Disabled }); + var json = await SendPatchRequestAsync($"{Endpoints.WireguardPeers}/{enability.ID}", new { disabled = enability.Disabled }); var obj = JObject.Parse(json); bool success = false; string code = string.Empty, message = string.Empty, detail = string.Empty; @@ -315,9 +319,9 @@ namespace MTWireGuard }; } - public static async Task DeleteServer(string id) + public async Task DeleteServer(string id) { - var json = await SendDeleteRequestAsync("interface/wireguard/" + id); + var json = await SendDeleteRequestAsync($"{Endpoints.Wireguard}/" + id); if (string.IsNullOrWhiteSpace(json)) { return new() @@ -335,9 +339,9 @@ namespace MTWireGuard } } - public static async Task DeleteUser(string id) + public async Task DeleteUser(string id) { - var json = await SendDeleteRequestAsync("interface/wireguard/peers/" + id); + var json = await SendDeleteRequestAsync($"{Endpoints.WireguardPeers}/" + id); if (string.IsNullOrWhiteSpace(json)) { return new() @@ -355,93 +359,55 @@ namespace MTWireGuard } } - public static async Task GetTrafficSpeed() + public async Task GetTrafficSpeed() { - return await SendPostRequestAsync("interface/monitor-traffic", "{\"interface\":\"ether1\",\"duration\":\"3s\"}"); + return await SendPostRequestAsync(Endpoints.MonitorTraffic, "{\"interface\":\"ether1\",\"duration\":\"3s\"}"); } - private static async Task SendGetRequestAsync(string URL, bool IsTest = false) + private async Task SendRequestBase(RequestMethod Method, string Endpoint, object Data = null, bool IsTest = false) { HttpClientHandler handler = new() { - ServerCertificateCustomValidationCallback = delegate { return true; } + ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true }; using HttpClient httpClient = new(handler); - using var request = new HttpRequestMessage(new HttpMethod("GET"), $"https://{MT_IP}/rest/{URL}"); + using var request = new HttpRequestMessage(new HttpMethod(Method.ToString()), $"https://{MT_IP}/rest/{Endpoint}"); string base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{MT_USER}:{MT_PASS}")); if (!IsTest) request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); + if (Data != null) + { + string content = (Data is string @string) ? @string : JsonConvert.SerializeObject(Data); + request.Content = new StringContent(content); + request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + } HttpResponseMessage response = await httpClient.SendAsync(request); return await response.Content.ReadAsStringAsync(); } - private static async Task SendPostRequestAsync(string URL, string Data) + private async Task SendGetRequestAsync(string URL, bool IsTest = false) { - HttpClientHandler handler = new() - { - ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true - }; - using HttpClient httpClient = new(handler); - using var request = new HttpRequestMessage(new HttpMethod("GET"), $"https://{MT_IP}/rest/{URL}"); - string base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{MT_USER}:{MT_PASS}")); - request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); - - request.Content = new StringContent(Data); - request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); - - HttpResponseMessage response = await httpClient.SendAsync(request); - return await response.Content.ReadAsStringAsync(); + return await SendRequestBase(RequestMethod.GET, URL, IsTest: IsTest); } - private static async Task SendDeleteRequestAsync(string URL) + private async Task SendPostRequestAsync(string URL, string Data) { - HttpClientHandler handler = new() - { - ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true - }; - using HttpClient httpClient = new(handler); - using var request = new HttpRequestMessage(new HttpMethod("DELETE"), $"https://{MT_IP}/rest/{URL}"); - string base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{MT_USER}:{MT_PASS}")); - request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); - - HttpResponseMessage response = await httpClient.SendAsync(request); - return await response.Content.ReadAsStringAsync(); + return await SendRequestBase(RequestMethod.POST, URL, Data); } - private static async Task SendPutRequestAsync(string URL, object Data) + private async Task SendDeleteRequestAsync(string URL) { - HttpClientHandler handler = new() - { - ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true - }; - using HttpClient httpClient = new(handler); - using var request = new HttpRequestMessage(new HttpMethod("PUT"), $"https://{MT_IP}/rest/{URL}"); - string base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{MT_USER}:{MT_PASS}")); - request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); - - request.Content = new StringContent(JsonConvert.SerializeObject(Data)); - request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); - - HttpResponseMessage response = await httpClient.SendAsync(request); - return await response.Content.ReadAsStringAsync(); + return await SendRequestBase(RequestMethod.DELETE, URL); } - private static async Task SendPatchRequestAsync(string URL, object Data) + private async Task SendPutRequestAsync(string URL, object Data) { - HttpClientHandler handler = new() - { - ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true - }; - using HttpClient httpClient = new(handler); - using var request = new HttpRequestMessage(new HttpMethod("PATCH"), $"https://{MT_IP}/rest/{URL}"); - string base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{MT_USER}:{MT_PASS}")); - request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); + return await SendRequestBase(RequestMethod.PUT, URL, Data); + } - request.Content = new StringContent(JsonConvert.SerializeObject(Data)); - request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); - - HttpResponseMessage response = await httpClient.SendAsync(request); - return await response.Content.ReadAsStringAsync(); + private async Task SendPatchRequestAsync(string URL, object Data) + { + return await SendRequestBase(RequestMethod.PATCH, URL, Data); } } } diff --git a/MikrotikAPI/Endpoints.cs b/MikrotikAPI/Endpoints.cs new file mode 100644 index 0000000..78b2279 --- /dev/null +++ b/MikrotikAPI/Endpoints.cs @@ -0,0 +1,25 @@ +namespace MikrotikAPI +{ + public static class Endpoints + { + public const string Log = "log"; + public const string Wireguard = "interface/wireguard"; + public const string Interface = "interface"; + public const string WireguardPeers = "interface/wireguard/peers"; + public const string SystemResource = "system/resource"; + public const string SystemIdentity = "system/identity"; + public const string ActiveUsers = "user/active"; + public const string Jobs = "system/script/job"; + public const string MonitorTraffic = "interface/monitor-traffic"; + public static string Empty => string.Empty; + } + + public enum RequestMethod + { + GET, + POST, + PUT, + DELETE, + PATCH + } +} diff --git a/MikrotikAPI/Extensions.cs b/MikrotikAPI/Extensions.cs new file mode 100644 index 0000000..87ae78b --- /dev/null +++ b/MikrotikAPI/Extensions.cs @@ -0,0 +1,13 @@ +using Newtonsoft.Json; + +namespace MikrotikAPI +{ + public static class Extensions + { + public static T ToModel(this string str) + { + if (string.IsNullOrWhiteSpace(str)) return default; + return JsonConvert.DeserializeObject(str); + } + } +} diff --git a/MikrotikAPI/MikrotikAPI.csproj b/MikrotikAPI/MikrotikAPI.csproj new file mode 100644 index 0000000..96e8a44 --- /dev/null +++ b/MikrotikAPI/MikrotikAPI.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/Models/Mikrotik/ActiveUser.cs b/MikrotikAPI/Models/ActiveUser.cs similarity index 50% rename from Models/Mikrotik/ActiveUser.cs rename to MikrotikAPI/Models/ActiveUser.cs index c5aeeb1..0ff6ed5 100644 --- a/Models/Mikrotik/ActiveUser.cs +++ b/MikrotikAPI/Models/ActiveUser.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; -namespace MTWireGuard.Models.Mikrotik +namespace MikrotikAPI.Models { public class ActiveUser { @@ -12,14 +12,4 @@ namespace MTWireGuard.Models.Mikrotik public string Via { get; set; } public string When { get; set; } } - - public class ActiveUserViewModel - { - public short Id { get; set; } - public string Group { get; set; } - public string Name { get; set; } - public bool Radius { get; set; } - public string Via { get; set; } - public string LoggedIn { get; set; } - } } diff --git a/Models/CreationStatus.cs b/MikrotikAPI/Models/CreationStatus.cs similarity index 55% rename from Models/CreationStatus.cs rename to MikrotikAPI/Models/CreationStatus.cs index 0755286..b67ea44 100644 --- a/Models/CreationStatus.cs +++ b/MikrotikAPI/Models/CreationStatus.cs @@ -1,4 +1,4 @@ -namespace MTWireGuard.Models +namespace MikrotikAPI.Models { public class CreationStatus { @@ -8,11 +8,4 @@ public string Message { get; set; } public object Item { get; set; } } - - public class CreationResult - { - public string Code { get; set; } - public string Title { get; set; } - public string Description { get; set; } - } } diff --git a/MikrotikAPI/Models/Identity.cs b/MikrotikAPI/Models/Identity.cs new file mode 100644 index 0000000..b177a68 --- /dev/null +++ b/MikrotikAPI/Models/Identity.cs @@ -0,0 +1,7 @@ +namespace MikrotikAPI.Models +{ + public class MTIdentity + { + public string Name { get; set; } + } +} diff --git a/Models/Mikrotik/Job.cs b/MikrotikAPI/Models/Job.cs similarity index 52% rename from Models/Mikrotik/Job.cs rename to MikrotikAPI/Models/Job.cs index 1cf590e..1f0508b 100644 --- a/Models/Mikrotik/Job.cs +++ b/MikrotikAPI/Models/Job.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; -namespace MTWireGuard.Models.Mikrotik +namespace MikrotikAPI.Models { public class Job { @@ -13,14 +13,4 @@ namespace MTWireGuard.Models.Mikrotik public string Started { get; set; } public string Type { get; set; } } - - public class JobViewModel - { - public short Id { get; set; } - public short NextId { get; set; } - public string Owner { get; set; } - public List Policies { get; set; } - public string Started { get; set; } - public string Type { get; set; } - } } diff --git a/Models/Mikrotik/Log.cs b/MikrotikAPI/Models/Log.cs similarity index 50% rename from Models/Mikrotik/Log.cs rename to MikrotikAPI/Models/Log.cs index e36a3f7..54e2c76 100644 --- a/Models/Mikrotik/Log.cs +++ b/MikrotikAPI/Models/Log.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; -namespace MTWireGuard.Models.Mikrotik +namespace MikrotikAPI.Models { public class Log { @@ -10,12 +10,4 @@ namespace MTWireGuard.Models.Mikrotik public string Time { get; set; } public string Topics { get; set; } } - - public class LogViewModel - { - public ulong Id { get; set; } - public string Message { get; set; } - public string Time { get; set; } - public List Topics { get; set; } - } } diff --git a/Models/LoginFailed.cs b/MikrotikAPI/Models/LoginStatus.cs similarity index 80% rename from Models/LoginFailed.cs rename to MikrotikAPI/Models/LoginStatus.cs index 9f949c1..0ada74b 100644 --- a/Models/LoginFailed.cs +++ b/MikrotikAPI/Models/LoginStatus.cs @@ -1,4 +1,4 @@ -namespace MTWireGuard.Models +namespace MikrotikAPI.Models { public class LoginStatus { diff --git a/MikrotikAPI/Models/MTInfo.cs b/MikrotikAPI/Models/MTInfo.cs new file mode 100644 index 0000000..05beb35 --- /dev/null +++ b/MikrotikAPI/Models/MTInfo.cs @@ -0,0 +1,47 @@ +using Newtonsoft.Json; + +namespace MikrotikAPI.Models +{ + public class MTInfo + { + [JsonProperty("architecture-name")] + public string ArchitectureName { get; set; } + + [JsonProperty("board-name")] + public string BoardName { get; set; } + + [JsonProperty("build-time")] + public string BuildTime { get; set; } + public string CPU { get; set; } + + [JsonProperty("cpu-count")] + public string CPUCount { get; set; } + + [JsonProperty("cpu-frequency")] + public string CPUFrequency { get; set; } + + [JsonProperty("cpu-load")] + public string CPULoad { get; set; } + + [JsonProperty("free-hdd-space")] + public string FreeHDDSpace { get; set; } + + [JsonProperty("free-memory")] + public string FreeMemory { get; set; } + public string Platform { get; set; } + + [JsonProperty("total-hdd-space")] + public string TotalHDDSpace { get; set; } + + [JsonProperty("total-memory")] + public string TotalMemory { get; set; } + public string Uptime { get; set; } + public string Version { get; set; } + + [JsonProperty("write-sect-since-reboot")] + public string WriteSectSinceReboot { get; set; } + + [JsonProperty("write-sect-total")] + public string WriteSectTotal { get; set; } + } +} diff --git a/MikrotikAPI/Models/ServerTraffic.cs b/MikrotikAPI/Models/ServerTraffic.cs new file mode 100644 index 0000000..0b4015a --- /dev/null +++ b/MikrotikAPI/Models/ServerTraffic.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace MikrotikAPI.Models +{ + public class ServerTraffic + { + public string Name { get; set; } + public string Type { get; set; } + [JsonProperty("tx-byte")] + public string TX { get; set; } + [JsonProperty("rx-byte")] + public string RX { get; set; } + } +} diff --git a/Models/WGEnability.cs b/MikrotikAPI/Models/WGEnability.cs similarity index 88% rename from Models/WGEnability.cs rename to MikrotikAPI/Models/WGEnability.cs index a6f744f..4a9e7b5 100644 --- a/Models/WGEnability.cs +++ b/MikrotikAPI/Models/WGEnability.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; -namespace MTWireGuard.Models +namespace MikrotikAPI.Models { public class WGEnability { diff --git a/Models/Mikrotik/WGPeer.cs b/MikrotikAPI/Models/WGPeer.cs similarity index 55% rename from Models/Mikrotik/WGPeer.cs rename to MikrotikAPI/Models/WGPeer.cs index 6b5512b..9274c06 100644 --- a/Models/Mikrotik/WGPeer.cs +++ b/MikrotikAPI/Models/WGPeer.cs @@ -1,8 +1,13 @@ using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; +using System; +using System.Collections.Generic; using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; -namespace MTWireGuard.Models.Mikrotik +namespace MikrotikAPI.Models { public class WGPeer { @@ -30,34 +35,6 @@ namespace MTWireGuard.Models.Mikrotik public string TX { get; set; } } - [PrimaryKey("Id")] - [Index("PrivateKey", IsUnique = true)] - [Index("PublicKey", IsUnique = true)] - public class WGPeerDBModel - { - public int Id { get; set; } - public string? Name { get; set; } - public string PrivateKey { get; set; } - public string PublicKey { get; set; } - } - - public class WGPeerViewModel - { - public int Id { get; set; } - public string Name { get; set; } - public string Address { get; set; } - public string CurrentAddress { get; set; } - public bool IsEnabled { get; set; } - public string Interface { get; set; } - public string PrivateKey { get; set; } - public string PublicKey { get; set; } - public string Download { get; set; } - public string Upload { get; set; } - public long DownloadBytes { get; set; } - public long UploadBytes { get; set; } - public bool IsDifferent { get; set; } - } - public class WGPeerCreateModel { [JsonProperty("allowed-address")] @@ -97,40 +74,4 @@ namespace MTWireGuard.Models.Mikrotik [JsonProperty("persistent-keepalive"), DefaultValue(0)] public int PersistentKeepalive { get; set; } } - - public class UserCreateModel - { - public string Name { get; set; } - public string PrivateKey { get; set; } - public string AllowedAddress { get; set; } - public bool Disabled { get; set; } - public string Interface { get; set; } - public string EndpointAddress { get; set; } - public string EndpointPort { get; set; } - public string PublicKey { get; set; } - public string PresharedKey { get; set; } - public string PersistentKeepalive { get; set; } - } - - public class UserSyncModel - { - public int Id { get; set; } - public string Name { get; set; } - public string PrivateKey { get; set; } - public string PublicKey { get; set; } - } - - public class UserUpdateModel - { - public int Id { get; set; } - public string Name { get; set; } - public string AllowedAddress { get; set; } - public string Interface { get; set; } - public string EndpointAddress { get; set; } - public ushort EndpointPort { get; set; } - public string PublicKey { get; set; } - public string PrivateKey { get; set; } - public string PresharedKey { get; set; } - public int PersistentKeepalive { get; set; } - } } diff --git a/Models/Mikrotik/WGServer.cs b/MikrotikAPI/Models/WGServer.cs similarity index 63% rename from Models/Mikrotik/WGServer.cs rename to MikrotikAPI/Models/WGServer.cs index 9094eef..e0a39e0 100644 --- a/Models/Mikrotik/WGServer.cs +++ b/MikrotikAPI/Models/WGServer.cs @@ -1,7 +1,12 @@ using Newtonsoft.Json; +using System; +using System.Collections.Generic; using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; -namespace MTWireGuard.Models.Mikrotik +namespace MikrotikAPI.Models { public class WGServer { @@ -23,36 +28,6 @@ namespace MTWireGuard.Models.Mikrotik public bool Running { get; set; } } - public class WGServerViewModel - { - public int Id { get; set; } - public string Name { get; set; } - public bool IsEnabled { get; set; } - public ushort ListenPort { get; set; } - public ushort MTU { get; set; } - public string PrivateKey { get; set; } - public string PublicKey { get; set; } - public bool Running { get; set; } - } - - public class ServerCreateModel - { - public string Name { get; set; } - public bool Enabled { get; set; } - public string ListenPort { get; set; } - public string MTU { get; set; } - public string PrivateKey { get; set; } - } - - public class ServerUpdateModel - { - public int Id { get; set; } - public string Name { get; set; } - public ushort ListenPort { get; set; } - public ushort MTU { get; set; } - public string PrivateKey { get; set; } - } - public class WGServerCreateModel { [JsonProperty("name")] diff --git a/Models/Mikrotik/EtherIP.cs b/Models/Mikrotik/EtherIP.cs deleted file mode 100644 index d15b852..0000000 --- a/Models/Mikrotik/EtherIP.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Newtonsoft.Json; -using System.Text.Json.Serialization; - -namespace MTWireGuard.Models.Mikrotik -{ - public class EtherIP - { - [JsonProperty(".id")] - public string Id { get; set; } - public string Address { get; set; } - } -} diff --git a/Models/Mikrotik/Identity.cs b/Models/Mikrotik/Identity.cs deleted file mode 100644 index 36af405..0000000 --- a/Models/Mikrotik/Identity.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace MTWireGuard.Models.Mikrotik -{ - public class MTIdentity - { - public string Name { get; set; } - } - - public class MTIdentityViewModel - { - public string Name { get; set; } - } -} diff --git a/Models/Mikrotik/MTInfo.cs b/Models/Mikrotik/MTInfo.cs deleted file mode 100644 index 024128a..0000000 --- a/Models/Mikrotik/MTInfo.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Newtonsoft.Json; - -namespace MTWireGuard.Models.Mikrotik -{ - public class MTInfo - { - [JsonProperty("architecture-name")] - public string ArchitectureName { get; set; } - - [JsonProperty("board-name")] - public string BoardName { get; set; } - - [JsonProperty("build-time")] - public string BuildTime { get; set; } - public string CPU { get; set; } - - [JsonProperty("cpu-count")] - public string CPUCount { get; set; } - - [JsonProperty("cpu-frequency")] - public string CPUFrequency { get; set; } - - [JsonProperty("cpu-load")] - public string CPULoad { get; set; } - - [JsonProperty("free-hdd-space")] - public string FreeHDDSpace { get; set; } - - [JsonProperty("free-memory")] - public string FreeMemory { get; set; } - public string Platform { get; set; } - - [JsonProperty("total-hdd-space")] - public string TotalHDDSpace { get; set; } - - [JsonProperty("total-memory")] - public string TotalMemory { get; set; } - public string Uptime { get; set; } - public string Version { get; set; } - - [JsonProperty("write-sect-since-reboot")] - public string WriteSectSinceReboot { get; set; } - - [JsonProperty("write-sect-total")] - public string WriteSectTotal { get; set; } - } - - public class MTInfoViewModel - { - public string Architecture { get; set; } - public string BoardName { get; set; } - public string Platform { get; set; } - public string CPU { get; set; } - public byte CPUCount { get; set; } - public short CPUFrequency { get; set; } - public byte CPULoad { get; set; } - public string TotalHDD { get; set; } - public string UsedHDD { get; set; } - public string FreeHDD { get; set; } - public long TotalHDDBytes { get; set; } - public long UsedHDDBytes { get; set; } - public long FreeHDDBytes { get; set; } - public byte FreeHDDPercentage { get; set; } - public string TotalRAM { get; set; } - public string UsedRAM { get; set; } - public string FreeRAM { get; set; } - public long TotalRAMBytes { get; set; } - public long UsedRAMBytes { get; set; } - public long FreeRAMBytes { get; set; } - public byte FreeRAMPercentage { get; set; } - public string UPTime { get; set; } - public string Version { get; set; } - } - - public class SidebarInfo - { - public int RAMUsedPercentage { get; set; } - public int CPUUsedPercentage { get; set; } - public int HDDUsedPercentage { get; set; } - public string RAMUsed { get; set; } - public string HDDUsed { get; set; } - public string TotalRAM { get; set; } - public string TotalHDD { get; set; } - public string RAMBgColor { get; set; } - public string CPUBgColor { get; set; } - public string HDDBgColor { get; set; } - } -} diff --git a/Models/Mikrotik/ServerTraffic.cs b/Models/Mikrotik/ServerTraffic.cs deleted file mode 100644 index 80bd74b..0000000 --- a/Models/Mikrotik/ServerTraffic.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Newtonsoft.Json; - -namespace MTWireGuard.Models.Mikrotik -{ - public class ServerTraffic - { - public string Name { get; set; } - public string Type { get; set; } - [JsonProperty("tx-byte")] - public string TX { get; set; } - [JsonProperty("rx-byte")] - public string RX { get; set; } - } - - public class ServerTrafficViewModel - { - public string Name { get; set; } - public string Type { get; set; } - public string Upload { get; set; } - public string Download { get; set; } - public long UploadBytes { get; set; } - public long DownloadBytes { get; set; } - } -} diff --git a/Models/Responses/ToastResult.cs b/Models/Responses/ToastResult.cs deleted file mode 100644 index 3eda25a..0000000 --- a/Models/Responses/ToastResult.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; - -namespace MTWireGuard.Models.Responses -{ - public class ToastResult : IActionResult - { - private class Toast - { - public string Title { get; set; } - public string Body { get; set; } - public string Background { get; set; } - } - - private readonly Toast _result; - - public ToastResult(string title, string body, string background) - { - _result = new() - { - Title = title, - Body = body, - Background = background - }; - } - - public async Task ExecuteResultAsync(ActionContext context) - { - var objectResult = new ObjectResult(_result); - - await objectResult.ExecuteResultAsync(context); - } - } -} diff --git a/MTWireGuard.csproj b/UI/MTWireGuard.csproj similarity index 60% rename from MTWireGuard.csproj rename to UI/MTWireGuard.csproj index d5c94cb..86c20d9 100644 --- a/MTWireGuard.csproj +++ b/UI/MTWireGuard.csproj @@ -11,18 +11,16 @@ - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + - - + + + + + diff --git a/UI/Mapper/RequestProfile.cs b/UI/Mapper/RequestProfile.cs new file mode 100644 index 0000000..2af4687 --- /dev/null +++ b/UI/Mapper/RequestProfile.cs @@ -0,0 +1,58 @@ +using AutoMapper; +using MTWireGuard.Application.Models; +using MTWireGuard.Application.Models.Mikrotik; +using MTWireGuard.Models.Requests; +using MTWireGuard.Models.Responses; + +namespace MTWireGuard.Mapper +{ + public class RequestProfile : Profile + { + public RequestProfile() + { + // Peer Request + CreateMap() + .ForMember(dest => dest.Disabled, + opt => opt.MapFrom(src => !src.Enabled)) + .ForMember(dest => dest.EndpointAddress, + opt => opt.MapFrom(src => src.Endpoint)) + .ForMember(dest => dest.PersistentKeepalive, + opt => opt.MapFrom(src => src.KeepAlive.ToString())); + + CreateMap(); + + CreateMap() + .ForMember(dest => dest.EndpointAddress, + opt => opt.MapFrom(src => src.Endpoint)) + .ForMember(dest => dest.PersistentKeepalive, + opt => opt.MapFrom(src => src.KeepAlive)); + + // Server Request + CreateMap() + .ForMember(dest => dest.ListenPort, + opt => opt.MapFrom(src => src.Port)); + + CreateMap() + .ForMember(dest => dest.ListenPort, + opt => opt.MapFrom(src => src.Port)); + + // Item Creation + CreateMap() + .ForMember(dest => dest.Code, + opt => opt.MapFrom(src => (src.Success) ? "200" : src.Code.ToString())) + .ForMember(dest => dest.Title, + opt => opt.MapFrom(src => (src.Success) ? "Done" : src.Message)) + .ForMember(dest => dest.Description, + opt => opt.MapFrom(src => (src.Success) ? "Item created/updated successfully." : src.Detail)); + + // Toast Result + CreateMap() + .ForMember(dest => dest.Title, + opt => opt.MapFrom(src => src.Code == "200" ? src.Title : $"[{src.Code}] {src.Title}")) + .ForMember(dest => dest.Body, + opt => opt.MapFrom(src => src.Description)) + .ForMember(dest => dest.Background, + opt => opt.MapFrom(src => src.Code == "200" ? "success" : "danger")); + } + } +} diff --git a/Middlewares/AntiForgeryMiddleware.cs b/UI/Middlewares/AntiForgeryMiddleware.cs similarity index 97% rename from Middlewares/AntiForgeryMiddleware.cs rename to UI/Middlewares/AntiForgeryMiddleware.cs index a5e5f70..d3ca90e 100644 --- a/Middlewares/AntiForgeryMiddleware.cs +++ b/UI/Middlewares/AntiForgeryMiddleware.cs @@ -1,9 +1,7 @@ using Microsoft.AspNetCore.Antiforgery; using MTWireGuard.Pages; -using MTWireGuard.Repositories; using Newtonsoft.Json; using Razor.Templating.Core; -using System.Globalization; namespace MTWireGuard.Middlewares { diff --git a/Middlewares/DependencyCheckMiddleware.cs b/UI/Middlewares/DependencyCheckMiddleware.cs similarity index 98% rename from Middlewares/DependencyCheckMiddleware.cs rename to UI/Middlewares/DependencyCheckMiddleware.cs index 5db6c1e..a0cb4c4 100644 --- a/Middlewares/DependencyCheckMiddleware.cs +++ b/UI/Middlewares/DependencyCheckMiddleware.cs @@ -1,5 +1,5 @@ using MTWireGuard.Pages; -using MTWireGuard.Repositories; +using MTWireGuard.Application.Repositories; using Razor.Templating.Core; using System.Globalization; diff --git a/Middlewares/ExceptionHandlerMiddleware.cs b/UI/Middlewares/ExceptionHandlerMiddleware.cs similarity index 94% rename from Middlewares/ExceptionHandlerMiddleware.cs rename to UI/Middlewares/ExceptionHandlerMiddleware.cs index 03e72d9..19f35ae 100644 --- a/Middlewares/ExceptionHandlerMiddleware.cs +++ b/UI/Middlewares/ExceptionHandlerMiddleware.cs @@ -1,6 +1,4 @@ -using MTWireGuard.Models.Mikrotik; -using System.Net; -using System.Reflection; +using System.Net; namespace MTWireGuard.Middlewares { diff --git a/Models/Requests/ChangeStateRequest.cs b/UI/Models/Requests/ChangeStateRequest.cs similarity index 86% rename from Models/Requests/ChangeStateRequest.cs rename to UI/Models/Requests/ChangeStateRequest.cs index 721b5cb..8a7aec7 100644 --- a/Models/Requests/ChangeStateRequest.cs +++ b/UI/Models/Requests/ChangeStateRequest.cs @@ -1,5 +1,5 @@ using Microsoft.AspNetCore.Mvc; -using Microsoft.Build.Framework; +using System.ComponentModel.DataAnnotations; namespace MTWireGuard.Models.Requests { diff --git a/Models/Requests/CreateClientRequest.cs b/UI/Models/Requests/CreateClientRequest.cs similarity index 89% rename from Models/Requests/CreateClientRequest.cs rename to UI/Models/Requests/CreateClientRequest.cs index 198b615..1a51c48 100644 --- a/Models/Requests/CreateClientRequest.cs +++ b/UI/Models/Requests/CreateClientRequest.cs @@ -1,6 +1,4 @@ -using System.Net; - -namespace MTWireGuard.Models.Requests +namespace MTWireGuard.Models.Requests { public class CreateClientRequest { diff --git a/Models/Requests/CreateServerRequest.cs b/UI/Models/Requests/CreateServerRequest.cs similarity index 80% rename from Models/Requests/CreateServerRequest.cs rename to UI/Models/Requests/CreateServerRequest.cs index e993f94..aecd41e 100644 --- a/Models/Requests/CreateServerRequest.cs +++ b/UI/Models/Requests/CreateServerRequest.cs @@ -1,6 +1,4 @@ -using System.ComponentModel; - -namespace MTWireGuard.Models.Requests +namespace MTWireGuard.Models.Requests { public class CreateServerRequest { diff --git a/Models/Requests/DeleteRequest.cs b/UI/Models/Requests/DeleteRequest.cs similarity index 100% rename from Models/Requests/DeleteRequest.cs rename to UI/Models/Requests/DeleteRequest.cs diff --git a/Models/Requests/SyncUserRequest.cs b/UI/Models/Requests/SyncUserRequest.cs similarity index 100% rename from Models/Requests/SyncUserRequest.cs rename to UI/Models/Requests/SyncUserRequest.cs diff --git a/Models/Requests/UpdateClientRequest.cs b/UI/Models/Requests/UpdateClientRequest.cs similarity index 100% rename from Models/Requests/UpdateClientRequest.cs rename to UI/Models/Requests/UpdateClientRequest.cs diff --git a/Models/Requests/UpdateServerRequest.cs b/UI/Models/Requests/UpdateServerRequest.cs similarity index 100% rename from Models/Requests/UpdateServerRequest.cs rename to UI/Models/Requests/UpdateServerRequest.cs diff --git a/UI/Models/Responses/ToastMessage.cs b/UI/Models/Responses/ToastMessage.cs new file mode 100644 index 0000000..61e4df3 --- /dev/null +++ b/UI/Models/Responses/ToastMessage.cs @@ -0,0 +1,9 @@ +namespace MTWireGuard.Models.Responses +{ + public class ToastMessage + { + public string Title { get; set; } + public string Body { get; set; } + public string Background { get; set; } + } +} diff --git a/UI/Models/Responses/ToastResult.cs b/UI/Models/Responses/ToastResult.cs new file mode 100644 index 0000000..7a28f53 --- /dev/null +++ b/UI/Models/Responses/ToastResult.cs @@ -0,0 +1,22 @@ +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; + +namespace MTWireGuard.Models.Responses +{ + public class ToastResult : IActionResult + { + private readonly ToastMessage _result; + + public ToastResult(ToastMessage message) + { + _result = message; + } + + public async Task ExecuteResultAsync(ActionContext context) + { + var objectResult = new ObjectResult(_result); + + await objectResult.ExecuteResultAsync(context); + } + } +} diff --git a/Pages/Clients.cshtml b/UI/Pages/Clients.cshtml similarity index 97% rename from Pages/Clients.cshtml rename to UI/Pages/Clients.cshtml index 7041e99..452e4e4 100644 --- a/Pages/Clients.cshtml +++ b/UI/Pages/Clients.cshtml @@ -1,5 +1,5 @@ @page "{handler?}" -@using MTWireGuard.Models.Mikrotik +@using MTWireGuard.Application.Models.Mikrotik @model MTWireGuard.Pages.ClientsModel @{ ViewData["Title"] = "Clients"; diff --git a/Pages/Clients.cshtml.cs b/UI/Pages/Clients.cshtml.cs similarity index 83% rename from Pages/Clients.cshtml.cs rename to UI/Pages/Clients.cshtml.cs index e463a00..1e03853 100644 --- a/Pages/Clients.cshtml.cs +++ b/UI/Pages/Clients.cshtml.cs @@ -1,15 +1,11 @@ using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -using MTWireGuard.Models; -using MTWireGuard.Models.Mikrotik; +using MTWireGuard.Application.Models; +using MTWireGuard.Application.Models.Mikrotik; +using MTWireGuard.Application.Repositories; using MTWireGuard.Models.Requests; using MTWireGuard.Models.Responses; -using MTWireGuard.Repositories; -using Newtonsoft.Json; -using QRCoder; -using System.Drawing; -using System.Security.Cryptography.X509Certificates; namespace MTWireGuard.Pages { @@ -59,35 +55,47 @@ namespace MTWireGuard.Pages { var model = mapper.Map(request); var make = await API.CreateUser(model); + var message = mapper.Map(make); + return new ToastResult(message); + /* string status = make.Code == "200" ? "success" : "danger"; string title = make.Code == "200" ? make.Title : $"[{make.Code}] {make.Title}"; - return new ToastResult(title, make.Description, status); + return new ToastResult(title, make.Description, status);*/ } public async Task OnPostDelete(DeleteRequest request) { var delete = await API.DeleteUser(request.Id); + var message = mapper.Map(delete); + return new ToastResult(message); + /* string status = delete.Code == "200" ? "success" : "danger"; string title = delete.Code == "200" ? delete.Title : $"[{delete.Code}] {delete.Title}"; - return new ToastResult(title, delete.Description, status); + return new ToastResult(title, delete.Description, status);*/ } public async Task OnPostUpdate(UpdateClientRequest request) { var model = mapper.Map(request); var update = await API.UpdateUser(model); + var message = mapper.Map(update); + return new ToastResult(message); + /* string status = update.Code == "200" ? "success" : "danger"; string title = update.Code == "200" ? update.Title : $"[{update.Code}] {update.Title}"; - return new ToastResult(title, update.Description, status); + return new ToastResult(title, update.Description, status);*/ } public async Task OnPostSyncAsync(SyncUserRequest request) { var model = mapper.Map(request); var update = await API.SyncUser(model); + var message = mapper.Map(update); + return new ToastResult(message); + /* string status = update.Code == "200" ? "success" : "danger"; string title = update.Code == "200" ? update.Title : $"[{update.Code}] {update.Title}"; - return new ToastResult(title, update.Description, status); + return new ToastResult(title, update.Description, status);*/ } public async Task OnGetEnableAsync(ChangeStateRequest request) @@ -97,9 +105,12 @@ namespace MTWireGuard.Pages result = await API.EnableUser(request.Id); else result = await API.DisableUser(request.Id); + var message = mapper.Map(result); + return new ToastResult(message); + /* string status = result.Code == "200" ? "success" : "danger"; string title = result.Code == "200" ? result.Title : $"[{result.Code}] {result.Title}"; - return new ToastResult(title, result.Description, status); + return new ToastResult(title, result.Description, status);*/ } } } diff --git a/Pages/Components/CreateClientForm/CreateClientForm.cshtml b/UI/Pages/Components/CreateClientForm/CreateClientForm.cshtml similarity index 96% rename from Pages/Components/CreateClientForm/CreateClientForm.cshtml rename to UI/Pages/Components/CreateClientForm/CreateClientForm.cshtml index 25fc683..86123f2 100644 --- a/Pages/Components/CreateClientForm/CreateClientForm.cshtml +++ b/UI/Pages/Components/CreateClientForm/CreateClientForm.cshtml @@ -1,7 +1,8 @@ -@using MTWireGuard.Models.Requests +@using MTWireGuard.Application.Models.Mikrotik +@using MTWireGuard.Models.Requests @model CreateClientRequest @{ - List Servers = ViewData["Servers"] as List; + List Servers = ViewData["Servers"] as List; }
Quick add peer
diff --git a/Pages/Components/CreateClientForm/CreateClientForm.cshtml.cs b/UI/Pages/Components/CreateClientForm/CreateClientForm.cshtml.cs similarity index 100% rename from Pages/Components/CreateClientForm/CreateClientForm.cshtml.cs rename to UI/Pages/Components/CreateClientForm/CreateClientForm.cshtml.cs diff --git a/Pages/Components/CreateServerForm/CreateServerForm.cshtml b/UI/Pages/Components/CreateServerForm/CreateServerForm.cshtml similarity index 100% rename from Pages/Components/CreateServerForm/CreateServerForm.cshtml rename to UI/Pages/Components/CreateServerForm/CreateServerForm.cshtml diff --git a/Pages/Components/CreateServerForm/CreateServerForm.cshtml.cs b/UI/Pages/Components/CreateServerForm/CreateServerForm.cshtml.cs similarity index 100% rename from Pages/Components/CreateServerForm/CreateServerForm.cshtml.cs rename to UI/Pages/Components/CreateServerForm/CreateServerForm.cshtml.cs diff --git a/Pages/Components/DeleteModal/DeleteModal.cshtml b/UI/Pages/Components/DeleteModal/DeleteModal.cshtml similarity index 100% rename from Pages/Components/DeleteModal/DeleteModal.cshtml rename to UI/Pages/Components/DeleteModal/DeleteModal.cshtml diff --git a/Pages/Components/DeleteModal/DeleteModal.cshtml.cs b/UI/Pages/Components/DeleteModal/DeleteModal.cshtml.cs similarity index 100% rename from Pages/Components/DeleteModal/DeleteModal.cshtml.cs rename to UI/Pages/Components/DeleteModal/DeleteModal.cshtml.cs diff --git a/Pages/Components/LogsView.razor b/UI/Pages/Components/LogsView.razor similarity index 95% rename from Pages/Components/LogsView.razor rename to UI/Pages/Components/LogsView.razor index ec956be..10ee86f 100644 --- a/Pages/Components/LogsView.razor +++ b/UI/Pages/Components/LogsView.razor @@ -1,4 +1,5 @@ -@{ +@using MTWireGuard.Application.Models.Mikrotik +@{ int LogCount = Logs.Count <= 20 ? Logs.Count : 20; var LastLogs = Logs.TakeLast(LogCount).ToList(); } @@ -50,5 +51,5 @@ @code { [Parameter] - public List Logs { get; set; } + public List Logs { get; set; } } diff --git a/Pages/Components/SyncUserModal/SyncUserModal.cshtml b/UI/Pages/Components/SyncUserModal/SyncUserModal.cshtml similarity index 100% rename from Pages/Components/SyncUserModal/SyncUserModal.cshtml rename to UI/Pages/Components/SyncUserModal/SyncUserModal.cshtml diff --git a/Pages/Components/SyncUserModal/SyncUserModal.cshtml.cs b/UI/Pages/Components/SyncUserModal/SyncUserModal.cshtml.cs similarity index 100% rename from Pages/Components/SyncUserModal/SyncUserModal.cshtml.cs rename to UI/Pages/Components/SyncUserModal/SyncUserModal.cshtml.cs diff --git a/Pages/Components/ToastContainer.razor b/UI/Pages/Components/ToastContainer.razor similarity index 100% rename from Pages/Components/ToastContainer.razor rename to UI/Pages/Components/ToastContainer.razor diff --git a/Pages/Components/UpdateClientModal/UpdateClientModal.cshtml b/UI/Pages/Components/UpdateClientModal/UpdateClientModal.cshtml similarity index 96% rename from Pages/Components/UpdateClientModal/UpdateClientModal.cshtml rename to UI/Pages/Components/UpdateClientModal/UpdateClientModal.cshtml index 98bb169..f871993 100644 --- a/Pages/Components/UpdateClientModal/UpdateClientModal.cshtml +++ b/UI/Pages/Components/UpdateClientModal/UpdateClientModal.cshtml @@ -1,7 +1,8 @@ -@using MTWireGuard.Models.Requests +@using MTWireGuard.Application.Models.Mikrotik +@using MTWireGuard.Models.Requests @model UpdateClientRequest @{ - List Servers = ViewData["Servers"] as List; + List Servers = ViewData["Servers"] as List; }