From dee2e37a4a8759108390c664e06bf147b8385cbf Mon Sep 17 00:00:00 2001 From: transtrike Date: Mon, 14 Dec 2020 23:29:14 +0200 Subject: Stabalized project for compilation. Next step after init architecture --- src/DevHive.Web/Startup.cs | 99 +++++++++++++++++++++++----------------------- 1 file changed, 50 insertions(+), 49 deletions(-) (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 303c080..62d9d2c 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -1,59 +1,60 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.OpenApi.Models; +using DevHive.Web.Configurations.Extensions; +using AutoMapper; namespace DevHive.Web { - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - - services.AddControllers(); - services.AddSwaggerGen(c => - { - c.SwaggerDoc("v1", new OpenApiInfo { Title = "DevHive.Web", Version = "v1" }); - }); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - app.UseSwagger(); - app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DevHive.Web v1")); - } - - app.UseHttpsRedirection(); - - app.UseRouting(); - - app.UseAuthorization(); - - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddControllers(); + + services.DatabaseConfiguration(Configuration); + services.SwaggerConfiguration(); + services.JWTConfiguration(Configuration); + //services.AutoMapperConfiguration(); + + services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + //app.UseExceptionHandler("/api/HttpError"); + app.UseSwaggerConfiguration(); + } + else + { + app.UseExceptionHandler("/api/HttpError"); + app.UseHsts(); + } + + app.UseDatabaseConfiguration(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "api/{controller}/{action}" + ); + }); + } + } } -- cgit v1.2.3 From 5c1fdfa47526030d2185eef864b551e9643a3957 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 15 Dec 2020 09:33:18 +0200 Subject: Adjusted & Extracted Configuration --- .../Configurations/Extensions/ConfigureAutoMapper.cs | 15 +++++++++++++++ .../Configurations/Extensions/ConfigureDatabase.cs | 13 ++++++++++++- src/DevHive.Web/Startup.cs | 4 +--- 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs new file mode 100644 index 0000000..afba39c --- /dev/null +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs @@ -0,0 +1,15 @@ +using System; +using AutoMapper; +using AutoMapper.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureAutoMapper + { + public static void AutoMapperConfiguration(this IServiceCollection services) + { + services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 178d345..f877e6c 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Configuration; using DevHive.Data.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Builder; +using System; namespace DevHive.Web.Configurations.Extensions { @@ -20,10 +21,20 @@ namespace DevHive.Web.Configurations.Extensions services.Configure(options => { - //TODO: Add more validations options.User.RequireUniqueEmail = true; + options.Password.RequireDigit = true; options.Password.RequiredLength = 5; + options.Password.RequiredUniqueChars = 0; + options.Password.RequireLowercase = false; + options.Password.RequireNonAlphanumeric = false; + options.Password.RequireUppercase = false; + + options.Lockout.AllowedForNewUsers = true; + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); + options.Lockout.MaxFailedAccessAttempts = 5; + + options.Stores.MaxLengthForKeys = 20; }); } diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 62d9d2c..c7e2bb3 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -26,9 +26,7 @@ namespace DevHive.Web services.DatabaseConfiguration(Configuration); services.SwaggerConfiguration(); services.JWTConfiguration(Configuration); - //services.AutoMapperConfiguration(); - - services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + services.AutoMapperConfiguration(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. -- cgit v1.2.3 From a25be34029e27577d51c5cf1b41010f55fc70ba3 Mon Sep 17 00:00:00 2001 From: Danail Dimitrov Date: Tue, 15 Dec 2020 20:02:59 +0200 Subject: Created ErrorController --- src/DevHive.Web/Controllers/ErrorController.cs | 8 +++----- src/DevHive.Web/Startup.cs | 3 ++- 2 files changed, 5 insertions(+), 6 deletions(-) (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Controllers/ErrorController.cs b/src/DevHive.Web/Controllers/ErrorController.cs index 560b0da..e84c19a 100644 --- a/src/DevHive.Web/Controllers/ErrorController.cs +++ b/src/DevHive.Web/Controllers/ErrorController.cs @@ -10,11 +10,9 @@ namespace DevHive.Web.Controllers public class ErrorController { [HttpGet] - public HttpStatusCode HttpError(HttpRequestException exception) - { - Console.WriteLine("WE HERE, BOIIIIIII"); - - return HttpStatusCode.OK; + public HttpStatusCode Error(HttpRequestException exception) + { + return BadRequest(exception) } } } diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index c7e2bb3..104ba4a 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -34,7 +34,8 @@ namespace DevHive.Web { if (env.IsDevelopment()) { - app.UseDeveloperExceptionPage(); + //app.UseDeveloperExceptionPage(); + app.UseExceptionHandler("/api/Error"); //app.UseExceptionHandler("/api/HttpError"); app.UseSwaggerConfiguration(); } -- cgit v1.2.3 From fb2803789e012cda1aca4c5f8bef779923f5db61 Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 16 Dec 2020 19:00:00 +0200 Subject: Authorization fixed --- src/DevHive.Services/Services/UserService.cs | 15 +++++++++------ .../Configurations/Extensions/ConfigureDatabase.cs | 9 +++++++-- src/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs | 2 +- src/DevHive.Web/Controllers/RoleController.cs | 2 ++ src/DevHive.Web/Controllers/UserController.cs | 5 +++-- src/DevHive.Web/Startup.cs | 1 + 6 files changed, 23 insertions(+), 11 deletions(-) (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 05a48b3..24f74f5 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -11,6 +11,7 @@ using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using System.Security.Cryptography; using System.Text; +using System.Collections.Generic; namespace DevHive.Services.Services { @@ -97,14 +98,16 @@ namespace DevHive.Services.Services private string WriteJWTSecurityToken(string role) { //TODO: Try generating the key - byte[] signingKey = Convert.FromBase64String(_jwtOptions.Secret); - + byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret); + + List claims = new List() + { + new Claim(ClaimTypes.Role, role) + }; + SecurityTokenDescriptor tokenDescriptor = new() { - Subject = new ClaimsIdentity(new Claim[] - { - new Claim(ClaimTypes.Role, role) - }), + Subject = new ClaimsIdentity(claims), Expires = DateTime.Today.AddDays(7), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(signingKey), diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 0fe32de..e656137 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -6,6 +6,7 @@ using DevHive.Data.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Builder; using System; +using Microsoft.AspNetCore.Authentication.JwtBearer; namespace DevHive.Web.Configurations.Extensions { @@ -40,8 +41,12 @@ namespace DevHive.Web.Configurations.Extensions services.AddAuthorization(options => { - options.AddPolicy($"{Role.DefaultRole}", - policy => policy.RequireRole($"{Role.DefaultRole}")); + options.AddPolicy("User", options => + { + options.RequireAuthenticatedUser(); + options.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); + options.RequireRole("User"); + }); }); } diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs index bc5ac15..d422bc8 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs @@ -43,7 +43,7 @@ namespace DevHive.Web.Configurations.Extensions x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { - ValidateIssuerSigningKey = true, + //ValidateIssuerSigningKey = false, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index 1e11ee1..610d370 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -6,11 +6,13 @@ using DevHive.Web.Models.Identity.Role; using AutoMapper; using DevHive.Services.Models.Identity.Role; using System; +using Microsoft.AspNetCore.Authorization; namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] + //[Authorize(Roles = "Admin")] public class RoleController { private readonly RoleService _roleService; diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index f952355..80e1bde 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -14,6 +14,7 @@ namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] + [Authorize(Roles = "User")] public class UserController: ControllerBase { private readonly UserService _userService; @@ -27,6 +28,7 @@ namespace DevHive.Web.Controllers [HttpPost] [Route("Login")] + [AllowAnonymous] public async Task Login([FromBody] LoginWebModel loginModel) { LoginServiceModel loginServiceModel = this._userMapper.Map(loginModel); @@ -39,6 +41,7 @@ namespace DevHive.Web.Controllers [HttpPost] [Route("Register")] + [AllowAnonymous] public async Task Register([FromBody] RegisterWebModel registerModel) { RegisterServiceModel registerServiceModel = this._userMapper.Map(registerModel); @@ -61,7 +64,6 @@ namespace DevHive.Web.Controllers //Update [HttpPut] - [Authorize(Roles = Role.DefaultRole)] public async Task Update(Guid id, [FromBody] UpdateUserWebModel updateModel) { UpdateUserServiceModel updateUserServiceModel = this._userMapper.Map(updateModel); @@ -76,7 +78,6 @@ namespace DevHive.Web.Controllers //Delete [HttpDelete] - [Authorize(Roles = Role.DefaultRole)] public async Task Delete(Guid id) { await this._userService.DeleteUser(id); diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 104ba4a..35dd5c3 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -46,6 +46,7 @@ namespace DevHive.Web } app.UseDatabaseConfiguration(); + app.UseEndpoints(endpoints => { -- cgit v1.2.3 From 26cd8dafb3867d47d20daf8b6723dc40b4bdcd6c Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 17 Dec 2020 11:54:11 +0200 Subject: Cleanup in User and preparation for Friends implementation --- src/DevHive.Web/Startup.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 35dd5c3..e81d307 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -26,7 +26,7 @@ namespace DevHive.Web services.DatabaseConfiguration(Configuration); services.SwaggerConfiguration(); services.JWTConfiguration(Configuration); - services.AutoMapperConfiguration(); + services.AutoMapperConfiguration(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -36,7 +36,6 @@ namespace DevHive.Web { //app.UseDeveloperExceptionPage(); app.UseExceptionHandler("/api/Error"); - //app.UseExceptionHandler("/api/HttpError"); app.UseSwaggerConfiguration(); } else -- cgit v1.2.3 From f4515fc3ff5fc222a3bdd40c5d4113f9bd79106f Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 17 Dec 2020 19:12:17 +0200 Subject: Newtonsoft.Json added --- src/DevHive.Web/Startup.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index e81d307..fac1b4a 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using DevHive.Web.Configurations.Extensions; using AutoMapper; +using Newtonsoft.Json; namespace DevHive.Web { @@ -21,7 +22,11 @@ namespace DevHive.Web // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddControllers(); + services.AddControllers() + .AddNewtonsoftJson(x => + { + x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + }); services.DatabaseConfiguration(Configuration); services.SwaggerConfiguration(); -- cgit v1.2.3 From 33a1a5899a16378691cd62d9ee4644db2a02e2b7 Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 17 Dec 2020 19:37:38 +0200 Subject: RoleModel moved to DevHive.Common --- src/DevHive.Common/Models/Identity/RoleModel.cs | 10 ++++++++++ src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs | 10 ---------- src/DevHive.Services/Models/Identity/User/UserServiceModel.cs | 3 ++- .../Configurations/Extensions/ConfigureAutoMapper.cs | 9 +++++++++ src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs | 10 ---------- src/DevHive.Web/Models/Identity/User/UserWebModel.cs | 3 ++- src/DevHive.Web/Startup.cs | 2 +- 7 files changed, 24 insertions(+), 23 deletions(-) create mode 100644 src/DevHive.Common/Models/Identity/RoleModel.cs delete mode 100644 src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs delete mode 100644 src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Common/Models/Identity/RoleModel.cs b/src/DevHive.Common/Models/Identity/RoleModel.cs new file mode 100644 index 0000000..5db8df9 --- /dev/null +++ b/src/DevHive.Common/Models/Identity/RoleModel.cs @@ -0,0 +1,10 @@ +using System; + +namespace DevHive.Common.Models.Identity +{ + public class RoleModel + { + public Guid Id { get; set; } + public string Name { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs deleted file mode 100644 index 3f834ef..0000000 --- a/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace DevHive.Services.Models.Identity.Role -{ - public class RoleServiceModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } -} diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 868e7ba..8ac71b1 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using DevHive.Common.Models.Identity; using DevHive.Data.Models; using DevHive.Services.Models.Identity.Role; @@ -6,7 +7,7 @@ namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { - public IList Role { get; set; } = new List(); + public IList Role { get; set; } = new List(); public List Friends { get; set; } = new List(); } } diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs index afba39c..b6ebc63 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs @@ -1,6 +1,7 @@ using System; using AutoMapper; using AutoMapper.Configuration; +using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace DevHive.Web.Configurations.Extensions @@ -11,5 +12,13 @@ namespace DevHive.Web.Configurations.Extensions { services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); } + + public static void UseAutoMapperConfiguration(this IApplicationBuilder app) + { + var config = new MapperConfiguration(cfg => + { + cfg.AllowNullCollections = true; + }); + } } } \ No newline at end of file diff --git a/src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs deleted file mode 100644 index d8ae465..0000000 --- a/src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace DevHive.Web.Models.Identity.Role -{ - public class RoleWebModel - { - public Guid Id { get; set; } - public string Name { get; set; } - } -} diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index e7bdb2a..83430ce 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -1,11 +1,12 @@ using System.Collections.Generic; +using DevHive.Common.Models.Identity; using DevHive.Web.Models.Identity.Role; namespace DevHive.Web.Models.Identity.User { public class UserWebModel : BaseUserWebModel { - public IList Role { get; set; } = new List(); + public IList Role { get; set; } = new List(); public IList Friends { get; set; } = new List(); } } diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index fac1b4a..66fde9e 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -50,8 +50,8 @@ namespace DevHive.Web } app.UseDatabaseConfiguration(); + app.UseAutoMapperConfiguration(); - app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( -- cgit v1.2.3 From fa09c0cc6cf99034dcc1301692ccb4d019087213 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 19 Dec 2020 15:47:01 +0200 Subject: Moved Friends to User(you no longer have friends) --- src/DevHive.Data/DevHiveContext.cs | 6 +- src/DevHive.Data/Repositories/FriendsRepository.cs | 38 ----------- .../Repositories/LanguageRepository.cs | 4 +- src/DevHive.Data/Repositories/RoleRepository.cs | 4 +- .../Repositories/TechnologyRepository.cs | 4 +- src/DevHive.Data/Repositories/UserRepository.cs | 20 +++++- src/DevHive.Services/Services/FriendsService.cs | 76 ---------------------- src/DevHive.Services/Services/UserService.cs | 73 +++++++++++++++++---- .../Configurations/Extensions/ConfigureDatabase.cs | 3 +- src/DevHive.Web/Controllers/FriendsController.cs | 59 ----------------- src/DevHive.Web/Controllers/UserController.cs | 28 ++++++++ src/DevHive.Web/Startup.cs | 2 +- 12 files changed, 117 insertions(+), 200 deletions(-) delete mode 100644 src/DevHive.Data/Repositories/FriendsRepository.cs delete mode 100644 src/DevHive.Services/Services/FriendsService.cs delete mode 100644 src/DevHive.Web/Controllers/FriendsController.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Data/DevHiveContext.cs b/src/DevHive.Data/DevHiveContext.cs index e8eb5fb..39d39d3 100644 --- a/src/DevHive.Data/DevHiveContext.cs +++ b/src/DevHive.Data/DevHiveContext.cs @@ -7,7 +7,7 @@ namespace DevHive.Data { public class DevHiveContext : IdentityDbContext { - public DevHiveContext(DbContextOptions options) + public DevHiveContext(DbContextOptions options) : base(options) { } public DbSet Technologies { get; set; } @@ -25,10 +25,6 @@ namespace DevHive.Data builder.Entity() .HasMany(x => x.Friends); - builder.Entity() - .HasIndex(x => x.Id) - .IsUnique(); - base.OnModelCreating(builder); } } diff --git a/src/DevHive.Data/Repositories/FriendsRepository.cs b/src/DevHive.Data/Repositories/FriendsRepository.cs deleted file mode 100644 index c65ba5e..0000000 --- a/src/DevHive.Data/Repositories/FriendsRepository.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using DevHive.Common.Models.Data; -using DevHive.Data.Models; -using Microsoft.EntityFrameworkCore; - -namespace DevHive.Data.Repositories -{ - public class FriendsRepository : UserRepository - { - private readonly DbContext _context; - - public FriendsRepository(DbContext context) - : base(context) - { - this._context = context; - } - - //Create - public async Task AddFriendAsync(User user, User friend) - { - this._context.Update(user); - user.Friends.Add(friend); - - return await RepositoryMethods.SaveChangesAsync(this._context); - } - - //Delete - public async Task RemoveFriendAsync(User user, User friend) - { - this._context.Update(user); - user.Friends.Remove(friend); - - return await RepositoryMethods.SaveChangesAsync(this._context); - } - } -} \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/LanguageRepository.cs b/src/DevHive.Data/Repositories/LanguageRepository.cs index a33bd5b..6e3a2e3 100644 --- a/src/DevHive.Data/Repositories/LanguageRepository.cs +++ b/src/DevHive.Data/Repositories/LanguageRepository.cs @@ -9,9 +9,9 @@ namespace DevHive.Data.Repositories { public class LanguageRepository : IRepository { - private readonly DbContext _context; + private readonly DevHiveContext _context; - public LanguageRepository(DbContext context) + public LanguageRepository(DevHiveContext context) { this._context = context; } diff --git a/src/DevHive.Data/Repositories/RoleRepository.cs b/src/DevHive.Data/Repositories/RoleRepository.cs index 21c29db..1d6f2da 100644 --- a/src/DevHive.Data/Repositories/RoleRepository.cs +++ b/src/DevHive.Data/Repositories/RoleRepository.cs @@ -9,9 +9,9 @@ namespace DevHive.Data.Repositories { public class RoleRepository : IRepository { - private readonly DbContext _context; + private readonly DevHiveContext _context; - public RoleRepository(DbContext context) + public RoleRepository(DevHiveContext context) { this._context = context; } diff --git a/src/DevHive.Data/Repositories/TechnologyRepository.cs b/src/DevHive.Data/Repositories/TechnologyRepository.cs index debfd3e..e2e4257 100644 --- a/src/DevHive.Data/Repositories/TechnologyRepository.cs +++ b/src/DevHive.Data/Repositories/TechnologyRepository.cs @@ -9,9 +9,9 @@ namespace DevHive.Data.Repositories { public class TechnologyRepository : IRepository { - private readonly DbContext _context; + private readonly DevHiveContext _context; - public TechnologyRepository(DbContext context) + public TechnologyRepository(DevHiveContext context) { this._context = context; } diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 5cd4264..d2a8830 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -11,9 +11,9 @@ namespace DevHive.Data.Repositories { public class UserRepository : IRepository { - private readonly DbContext _context; + private readonly DevHiveContext _context; - public UserRepository(DbContext context) + public UserRepository(DevHiveContext context) { this._context = context; } @@ -27,6 +27,14 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } + + public async Task AddFriendAsync(User user, User friend) + { + this._context.Update(user); + user.Friends.Add(friend); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } //Read public IEnumerable QueryAll() @@ -77,6 +85,14 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } + + public async Task RemoveFriendAsync(User user, User friend) + { + this._context.Update(user); + user.Friends.Remove(friend); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } //Validations public bool DoesUserExist(Guid id) diff --git a/src/DevHive.Services/Services/FriendsService.cs b/src/DevHive.Services/Services/FriendsService.cs deleted file mode 100644 index 119c955..0000000 --- a/src/DevHive.Services/Services/FriendsService.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using DevHive.Data.Models; -using DevHive.Data.Repositories; -using DevHive.Services.Models.Identity.User; -using DevHive.Services.Options; - -namespace DevHive.Services.Services -{ - public class FriendsService - { - private readonly FriendsRepository _friendsRepository; - private readonly IMapper _friendsMapper; - - public FriendsService(FriendsRepository friendsRepository, IMapper mapper) - { - this._friendsRepository = friendsRepository; - this._friendsMapper = mapper; - } - - //Create - public async Task AddFriend(Guid userId, Guid friendId) - { - User user = await this._friendsRepository.GetByIdAsync(userId); - User friend = await this._friendsRepository.GetByIdAsync(friendId); - - if (DoesUserHaveThisFriend(user, friend)) - throw new ArgumentException("Friend already exists in your friends list."); - - return user != default(User) && friend != default(User) ? - await this._friendsRepository.AddFriendAsync(user, friend) : - throw new ArgumentException("Invalid user!"); - } - - //Read - public async Task GetFriendById(Guid friendId) - { - if(!_friendsRepository.DoesUserExist(friendId)) - throw new ArgumentException("User does not exist!"); - - User friend = await this._friendsRepository.GetByIdAsync(friendId); - - return this._friendsMapper.Map(friend); - } - - public async Task RemoveFriend(Guid userId, Guid friendId) - { - if(!this._friendsRepository.DoesUserExist(userId) && - !this._friendsRepository.DoesUserExist(friendId)) - throw new ArgumentException("Invalid user!"); - - User user = await this._friendsRepository.GetByIdAsync(userId); - User friend = await this._friendsRepository.GetByIdAsync(friendId); - - if(!this.DoesUserHaveFriends(user)) - throw new ArgumentException("User does not have any friends."); - - if (!DoesUserHaveThisFriend(user, friend)) - throw new ArgumentException("This ain't your friend, amigo."); - - return await this.RemoveFriend(user.Id, friendId); - } - - //Validation - private bool DoesUserHaveThisFriend(User user, User friend) - { - return user.Friends.Contains(friend); - } - - private bool DoesUserHaveFriends(User user) - { - return user.Friends.Count >= 1; - } - } -} \ No newline at end of file diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 99a8d9f..7fd0682 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -67,6 +67,19 @@ namespace DevHive.Services.Services return new TokenModel(WriteJWTSecurityToken(user.UserName, user.Roles)); } + public async Task AddFriend(Guid userId, Guid friendId) + { + User user = await this._userRepository.GetByIdAsync(userId); + User friend = await this._userRepository.GetByIdAsync(friendId); + + if (DoesUserHaveThisFriend(user, friend)) + throw new ArgumentException("Friend already exists in your friends list."); + + return user != default(User) && friend != default(User) ? + await this._userRepository.AddFriendAsync(user, friend) : + throw new ArgumentException("Invalid user!"); + } + public async Task GetUserById(Guid id) { User user = await this._userRepository.GetByIdAsync(id) @@ -75,6 +88,16 @@ namespace DevHive.Services.Services return this._userMapper.Map(user); } + public async Task GetFriendById(Guid friendId) + { + if(!_userRepository.DoesUserExist(friendId)) + throw new ArgumentException("User does not exist!"); + + User friend = await this._userRepository.GetByIdAsync(friendId); + + return this._userMapper.Map(friend); + } + public async Task UpdateUser(UpdateUserServiceModel updateModel) { if (!this._userRepository.DoesUserExist(updateModel.Id)) @@ -105,6 +128,24 @@ namespace DevHive.Services.Services throw new InvalidOperationException("Unable to delete user!"); } + public async Task RemoveFriend(Guid userId, Guid friendId) + { + if(!this._userRepository.DoesUserExist(userId) && + !this._userRepository.DoesUserExist(friendId)) + throw new ArgumentException("Invalid user!"); + + User user = await this._userRepository.GetByIdAsync(userId); + User friend = await this._userRepository.GetByIdAsync(friendId); + + if(!this.DoesUserHaveFriends(user)) + throw new ArgumentException("User does not have any friends."); + + if (!DoesUserHaveThisFriend(user, friend)) + throw new ArgumentException("This ain't your friend, amigo."); + + return await this.RemoveFriend(user.Id, friendId); + } + public async Task ValidJWT(Guid id, string rawTokenData) { // There is authorization name in the beginning, i.e. "Bearer eyJh..." @@ -143,6 +184,27 @@ namespace DevHive.Services.Services return string.Join(string.Empty, SHA512.HashData(Encoding.ASCII.GetBytes(password))); } + private bool DoesUserHaveThisFriend(User user, User friend) + { + return user.Friends.Contains(friend); + } + + private bool DoesUserHaveFriends(User user) + { + return user.Friends.Count >= 1; + } + + private List GetClaimTypeValues(string type, IEnumerable claims) + { + List toReturn = new(); + + foreach(var claim in claims) + if (claim.Type == type) + toReturn.Add(claim.Value); + + return toReturn; + } + private string WriteJWTSecurityToken(string userName, IList roles) { byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret); @@ -170,16 +232,5 @@ namespace DevHive.Services.Services SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } - - private List GetClaimTypeValues(string type, IEnumerable claims) - { - List toReturn = new(); - - foreach(var claim in claims) - if (claim.Type == type) - toReturn.Add(claim.Value); - - return toReturn; - } } } diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 7ef144c..b42ae05 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -16,8 +16,7 @@ namespace DevHive.Web.Configurations.Extensions public static void DatabaseConfiguration(this IServiceCollection services, IConfiguration configuration) { services.AddDbContext(options => - options.UseNpgsql(configuration.GetConnectionString("DEV"), - x => x.MigrationsAssembly("DevHive.Web"))); + options.UseNpgsql(configuration.GetConnectionString("DEV"))); services.AddIdentity() .AddEntityFrameworkStores(); diff --git a/src/DevHive.Web/Controllers/FriendsController.cs b/src/DevHive.Web/Controllers/FriendsController.cs deleted file mode 100644 index 1b9b9c5..0000000 --- a/src/DevHive.Web/Controllers/FriendsController.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using DevHive.Common.Models; -using DevHive.Data.Repositories; -using DevHive.Services.Models.Identity.User; -using DevHive.Services.Options; -using DevHive.Services.Services; -using DevHive.Web.Models.Identity.User; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace DevHive.Web.Controllers -{ - [ApiController] - [Route("/api")] - [Authorize(Roles = "User")] - public class FriendsController - { - private readonly FriendsService _friendsService; - private readonly IMapper _friendsMapper; - - public FriendsController(FriendsService friendsService, IMapper mapper) - { - this._friendsService = friendsService; - this._friendsMapper = mapper; - } - - //Create - [HttpPost] - [Route("AddAFriend")] - public async Task AddAFriend(Guid userId, [FromBody] IdModel friendIdModel) - { - return await this._friendsService.AddFriend(userId, friendIdModel.Id) ? - new OkResult() : - new BadRequestResult(); - } - - //Read - [HttpGet] - [Route("GetAFriend")] - public async Task GetAFriend(Guid friendId) - { - UserServiceModel friendServiceModel = await this._friendsService.GetFriendById(friendId); - UserWebModel friend = this._friendsMapper.Map(friendServiceModel); - - return new OkObjectResult(friend); - } - - //Delete - [HttpDelete] - [Route("RemoveAFriend")] - public async Task RemoveAFriend(Guid userId, Guid friendId) - { - await this._friendsService.RemoveFriend(userId, friendId); - return new OkResult(); - } - } -} \ No newline at end of file diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index b23fdee..ad2656c 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -9,6 +9,7 @@ using DevHive.Web.Models.Identity.User; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using DevHive.Common.Models.Identity; +using DevHive.Common.Models; namespace DevHive.Web.Controllers { @@ -53,6 +54,15 @@ namespace DevHive.Web.Controllers return new CreatedResult("Register", tokenWebModel); } + [HttpPost] + [Route("AddAFriend")] + public async Task AddAFriend(Guid userId, [FromBody] IdModel friendIdModel) + { + return await this._userService.AddFriend(userId, friendIdModel.Id) ? + new OkResult() : + new BadRequestResult(); + } + //Read [HttpGet] public async Task GetById(Guid id, [FromHeader] string authorization) @@ -66,6 +76,16 @@ namespace DevHive.Web.Controllers return new OkObjectResult(userWebModel); } + [HttpGet] + [Route("GetAFriend")] + public async Task GetAFriend(Guid friendId) + { + UserServiceModel friendServiceModel = await this._userService.GetFriendById(friendId); + UserWebModel friend = this._userMapper.Map(friendServiceModel); + + return new OkObjectResult(friend); + } + //Update [HttpPut] public async Task Update(Guid id, [FromBody] UpdateUserWebModel updateModel, [FromHeader] string authorization) @@ -93,5 +113,13 @@ namespace DevHive.Web.Controllers await this._userService.DeleteUser(id); return new OkResult(); } + + [HttpDelete] + [Route("RemoveAFriend")] + public async Task RemoveAFriend(Guid userId, Guid friendId) + { + await this._userService.RemoveFriend(userId, friendId); + return new OkResult(); + } } } diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 66fde9e..12f72f7 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -45,7 +45,7 @@ namespace DevHive.Web } else { - app.UseExceptionHandler("/api/HttpError"); + app.UseExceptionHandler("/api/Error"); app.UseHsts(); } -- cgit v1.2.3 From 1f6962768de80cb2a017d53a1985899063d062dd Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 19 Dec 2020 16:19:29 +0200 Subject: Moved migrations to DevHive.Data --- src/DevHive.Data/ConnectionString.json | 5 + src/DevHive.Data/DevHive.Data.csproj | 2 + src/DevHive.Data/DevHiveContextFactory.cs | 23 ++ .../20201219141035_DbContext_Moved.Designer.cs | 357 +++++++++++++++++++++ .../Migrations/20201219141035_DbContext_Moved.cs | 301 +++++++++++++++++ .../Migrations/DevHiveContextModelSnapshot.cs | 355 ++++++++++++++++++++ src/DevHive.Web/Startup.cs | 12 + src/DevHive.Web/appsettings.json | 6 +- 8 files changed, 1058 insertions(+), 3 deletions(-) create mode 100644 src/DevHive.Data/ConnectionString.json create mode 100644 src/DevHive.Data/DevHiveContextFactory.cs create mode 100644 src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.Designer.cs create mode 100644 src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs create mode 100644 src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Data/ConnectionString.json b/src/DevHive.Data/ConnectionString.json new file mode 100644 index 0000000..00e95c2 --- /dev/null +++ b/src/DevHive.Data/ConnectionString.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "DEV": "Server=localhost;Port=5432;Database=API;User Id=postgres;Password=;" + } +} \ No newline at end of file diff --git a/src/DevHive.Data/DevHive.Data.csproj b/src/DevHive.Data/DevHive.Data.csproj index c1e1592..34a5431 100644 --- a/src/DevHive.Data/DevHive.Data.csproj +++ b/src/DevHive.Data/DevHive.Data.csproj @@ -14,6 +14,8 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all + + diff --git a/src/DevHive.Data/DevHiveContextFactory.cs b/src/DevHive.Data/DevHiveContextFactory.cs new file mode 100644 index 0000000..f4849d7 --- /dev/null +++ b/src/DevHive.Data/DevHiveContextFactory.cs @@ -0,0 +1,23 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Configuration; +using System.IO; + +namespace DevHive.Data +{ + public class DevHiveContextFactory : IDesignTimeDbContextFactory + { + public DevHiveContext CreateDbContext(string[] args) + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("ConnectionString.json") + .Build(); + + var optionsBuilder = new DbContextOptionsBuilder() + .UseNpgsql(configuration.GetConnectionString("DEV")); + + return new DevHiveContext(optionsBuilder.Options); + } + } +} \ No newline at end of file diff --git a/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.Designer.cs b/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.Designer.cs new file mode 100644 index 0000000..dd0e8c7 --- /dev/null +++ b/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.Designer.cs @@ -0,0 +1,357 @@ +// +using System; +using DevHive.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Data.Migrations +{ + [DbContext(typeof(DevHiveContext))] + [Migration("20201219141035_DbContext_Moved")] + partial class DbContext_Moved + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .UseIdentityByDefaultColumns() + .HasAnnotation("Relational:MaxIdentifierLength", 63) + .HasAnnotation("ProductVersion", "5.0.1"); + + modelBuilder.Entity("DevHive.Data.Models.Language", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Languages"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Technologies"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("FirstName") + .HasColumnType("text"); + + b.Property("LastName") + .HasColumnType("text"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("ProfilePicture") + .HasColumnType("text"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.HasIndex("UserId"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("AspNetUsers"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.Property("RolesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("RolesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("RoleUser"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Friends") + .HasForeignKey("UserId"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RolesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Navigation("Friends"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs b/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs new file mode 100644 index 0000000..0c27917 --- /dev/null +++ b/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs @@ -0,0 +1,301 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Data.Migrations +{ + public partial class DbContext_Moved : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AspNetRoles", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetUsers", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + FirstName = table.Column(type: "text", nullable: true), + LastName = table.Column(type: "text", nullable: true), + ProfilePicture = table.Column(type: "text", nullable: true), + UserId = table.Column(type: "uuid", nullable: true), + UserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "boolean", nullable: false), + PasswordHash = table.Column(type: "text", nullable: true), + SecurityStamp = table.Column(type: "text", nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true), + PhoneNumber = table.Column(type: "text", nullable: true), + PhoneNumberConfirmed = table.Column(type: "boolean", nullable: false), + TwoFactorEnabled = table.Column(type: "boolean", nullable: false), + LockoutEnd = table.Column(type: "timestamp with time zone", nullable: true), + LockoutEnabled = table.Column(type: "boolean", nullable: false), + AccessFailedCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUsers_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "Languages", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Languages", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Technologies", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Technologies", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RoleId = table.Column(type: "uuid", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserClaims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + UserId = table.Column(type: "uuid", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserLogins", + columns: table => new + { + LoginProvider = table.Column(type: "text", nullable: false), + ProviderKey = table.Column(type: "text", nullable: false), + ProviderDisplayName = table.Column(type: "text", nullable: true), + UserId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserRoles", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + RoleId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserTokens", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + LoginProvider = table.Column(type: "text", nullable: false), + Name = table.Column(type: "text", nullable: false), + Value = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "RoleUser", + columns: table => new + { + RolesId = table.Column(type: "uuid", nullable: false), + UsersId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RoleUser", x => new { x.RolesId, x.UsersId }); + table.ForeignKey( + name: "FK_RoleUser_AspNetRoles_RolesId", + column: x => x.RolesId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_RoleUser_AspNetUsers_UsersId", + column: x => x.UsersId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "AspNetRoleClaims", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "AspNetRoles", + column: "NormalizedName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserClaims_UserId", + table: "AspNetUserClaims", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserLogins_UserId", + table: "AspNetUserLogins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "AspNetUsers", + column: "NormalizedEmail"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUsers_UserId", + table: "AspNetUsers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUsers_UserName", + table: "AspNetUsers", + column: "UserName", + unique: true); + + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "AspNetUsers", + column: "NormalizedUserName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleUser_UsersId", + table: "RoleUser", + column: "UsersId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AspNetRoleClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserLogins"); + + migrationBuilder.DropTable( + name: "AspNetUserRoles"); + + migrationBuilder.DropTable( + name: "AspNetUserTokens"); + + migrationBuilder.DropTable( + name: "Languages"); + + migrationBuilder.DropTable( + name: "RoleUser"); + + migrationBuilder.DropTable( + name: "Technologies"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + } + } +} diff --git a/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs new file mode 100644 index 0000000..b5300a9 --- /dev/null +++ b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs @@ -0,0 +1,355 @@ +// +using System; +using DevHive.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Data.Migrations +{ + [DbContext(typeof(DevHiveContext))] + partial class DevHiveContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .UseIdentityByDefaultColumns() + .HasAnnotation("Relational:MaxIdentifierLength", 63) + .HasAnnotation("ProductVersion", "5.0.1"); + + modelBuilder.Entity("DevHive.Data.Models.Language", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Languages"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Technologies"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("FirstName") + .HasColumnType("text"); + + b.Property("LastName") + .HasColumnType("text"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("ProfilePicture") + .HasColumnType("text"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.HasIndex("UserId"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("AspNetUsers"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.Property("RolesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("RolesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("RoleUser"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Friends") + .HasForeignKey("UserId"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RolesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Navigation("Friends"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 12f72f7..333735a 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -7,6 +7,8 @@ using Microsoft.Extensions.Hosting; using DevHive.Web.Configurations.Extensions; using AutoMapper; using Newtonsoft.Json; +using DevHive.Data.Repositories; +using DevHive.Services.Services; namespace DevHive.Web { @@ -32,6 +34,16 @@ namespace DevHive.Web services.SwaggerConfiguration(); services.JWTConfiguration(Configuration); services.AutoMapperConfiguration(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/DevHive.Web/appsettings.json b/src/DevHive.Web/appsettings.json index d620c14..a460532 100644 --- a/src/DevHive.Web/appsettings.json +++ b/src/DevHive.Web/appsettings.json @@ -2,9 +2,9 @@ "AppSettings": { "Secret": "gXfQlU6qpDleFWyimscjYcT3tgFsQg3yoFjcvSLxG56n1Vu2yptdIUq254wlJWjm" }, - "ConnectionStrings" : { - "DEV": "Server=localhost;Port=5432;Database=API;User Id=postgres;Password=;" - }, + "ConnectionStrings": { + "DEV": "Server=localhost;Port=5432;Database=API;User Id=postgres;Password=;" + }, "Logging" : { "LogLevel" : { "Default" : "Information", -- cgit v1.2.3 From 05d8be770dd5e728bc93a2322343cda3ddf939b7 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 19 Dec 2020 16:23:45 +0200 Subject: Moved DI config to DevHive.Web/Extensions --- .../Extensions/ConfigureDependencyInjection.cs | 22 ++++++++++++++++++++++ src/DevHive.Web/Startup.cs | 11 +---------- 2 files changed, 23 insertions(+), 10 deletions(-) create mode 100644 src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs new file mode 100644 index 0000000..9b235c7 --- /dev/null +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -0,0 +1,22 @@ +using DevHive.Data.Repositories; +using DevHive.Services.Services; +using Microsoft.Extensions.DependencyInjection; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureDependencyInjection + { + public static void DependencyInjectionConfiguration(this IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 333735a..de1295c 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -34,16 +34,7 @@ namespace DevHive.Web services.SwaggerConfiguration(); services.JWTConfiguration(Configuration); services.AutoMapperConfiguration(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.DependencyInjectionConfiguration(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. -- cgit v1.2.3 From 278130d86378a6b2db6ba443631f303fb7d7e207 Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 30 Dec 2020 21:21:49 +0200 Subject: Implemented Posts and merged Comment to Post --- src/DevHive.Common/Models/Data/IdModel.cs | 9 -- .../Models/Data/RepositoryMethods.cs | 2 +- src/DevHive.Common/Models/Misc/IdModel.cs | 9 ++ src/DevHive.Data/Models/Comment.cs | 4 +- src/DevHive.Data/Models/Post.cs | 21 ++++ src/DevHive.Data/Repositories/CommentRepository.cs | 62 ---------- .../Repositories/LanguageRepository.cs | 2 +- src/DevHive.Data/Repositories/PostRepository.cs | 107 +++++++++++++++++ src/DevHive.Data/Repositories/RoleRepository.cs | 2 +- .../Repositories/TechnologyRepository.cs | 2 +- src/DevHive.Data/Repositories/UserRepository.cs | 2 +- .../Configurations/Mapping/CommentMappings.cs | 7 +- .../Configurations/Mapping/PostMappings.cs | 16 +++ .../Models/Comment/CommentServiceModel.cs | 10 -- .../Models/Comment/GetByIdCommentServiceModel.cs | 9 -- .../Models/Comment/UpdateCommnetServiceModel.cs | 9 -- .../Models/Post/Comment/BaseCommentServiceModel.cs | 11 ++ .../Models/Post/Comment/CommentServiceModel.cs | 9 ++ .../Post/Comment/CreateCommentServiceModel.cs | 9 ++ .../Post/Comment/UpdateCommnetServiceModel.cs | 8 ++ .../Models/Post/Post/BasePostServiceModel.cs | 11 ++ .../Models/Post/Post/CreatePostServiceModel.cs | 9 ++ .../Models/Post/Post/PostServiceModel.cs | 12 ++ .../Models/Post/Post/UpdatePostServiceModel.cs | 7 ++ src/DevHive.Services/Services/CommentService.cs | 62 ---------- src/DevHive.Services/Services/PostService.cs | 98 +++++++++++++++ .../Extensions/ConfigureDependencyInjection.cs | 4 +- .../Configurations/Mapping/CommentMappings.cs | 7 +- src/DevHive.Web/Controllers/CommentController.cs | 72 ----------- src/DevHive.Web/Controllers/PostController.cs | 132 +++++++++++++++++++++ src/DevHive.Web/Controllers/RoleController.cs | 2 +- src/DevHive.Web/Controllers/UserController.cs | 2 +- src/DevHive.Web/Models/Comment/CommentWebModel.cs | 10 -- .../Models/Comment/GetByIdCommentWebModel.cs | 9 -- .../Models/Post/Comment/CommentWebModel.cs | 10 ++ .../Models/Post/Post/BasePostWebModel.cs | 10 ++ .../Models/Post/Post/CreatePostWebModel.cs | 8 ++ src/DevHive.Web/Models/Post/Post/PostWebModel.cs | 21 ++++ .../Models/Post/Post/UpdatePostModel.cs | 7 ++ src/DevHive.Web/Startup.cs | 4 - 40 files changed, 533 insertions(+), 274 deletions(-) delete mode 100644 src/DevHive.Common/Models/Data/IdModel.cs create mode 100644 src/DevHive.Common/Models/Misc/IdModel.cs create mode 100644 src/DevHive.Data/Models/Post.cs delete mode 100644 src/DevHive.Data/Repositories/CommentRepository.cs create mode 100644 src/DevHive.Data/Repositories/PostRepository.cs create mode 100644 src/DevHive.Services/Configurations/Mapping/PostMappings.cs delete mode 100644 src/DevHive.Services/Models/Comment/CommentServiceModel.cs delete mode 100644 src/DevHive.Services/Models/Comment/GetByIdCommentServiceModel.cs delete mode 100644 src/DevHive.Services/Models/Comment/UpdateCommnetServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Comment/BaseCommentServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Comment/CommentServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Comment/CreateCommentServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Comment/UpdateCommnetServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Post/BasePostServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Post/PostServiceModel.cs create mode 100644 src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs delete mode 100644 src/DevHive.Services/Services/CommentService.cs create mode 100644 src/DevHive.Services/Services/PostService.cs delete mode 100644 src/DevHive.Web/Controllers/CommentController.cs create mode 100644 src/DevHive.Web/Controllers/PostController.cs delete mode 100644 src/DevHive.Web/Models/Comment/CommentWebModel.cs delete mode 100644 src/DevHive.Web/Models/Comment/GetByIdCommentWebModel.cs create mode 100644 src/DevHive.Web/Models/Post/Comment/CommentWebModel.cs create mode 100644 src/DevHive.Web/Models/Post/Post/BasePostWebModel.cs create mode 100644 src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs create mode 100644 src/DevHive.Web/Models/Post/Post/PostWebModel.cs create mode 100644 src/DevHive.Web/Models/Post/Post/UpdatePostModel.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Common/Models/Data/IdModel.cs b/src/DevHive.Common/Models/Data/IdModel.cs deleted file mode 100644 index 1f2bf9a..0000000 --- a/src/DevHive.Common/Models/Data/IdModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace DevHive.Common.Models.Data -{ - public class IdModel - { - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/src/DevHive.Common/Models/Data/RepositoryMethods.cs b/src/DevHive.Common/Models/Data/RepositoryMethods.cs index b56aad9..bfd057f 100644 --- a/src/DevHive.Common/Models/Data/RepositoryMethods.cs +++ b/src/DevHive.Common/Models/Data/RepositoryMethods.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; -namespace DevHive.Common.Models.Data +namespace DevHive.Common.Models.Misc { public static class RepositoryMethods { diff --git a/src/DevHive.Common/Models/Misc/IdModel.cs b/src/DevHive.Common/Models/Misc/IdModel.cs new file mode 100644 index 0000000..a5c7b65 --- /dev/null +++ b/src/DevHive.Common/Models/Misc/IdModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Common.Models.Misc +{ + public class IdModel + { + public Guid Id { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Data/Models/Comment.cs b/src/DevHive.Data/Models/Comment.cs index f949a42..8cf848f 100644 --- a/src/DevHive.Data/Models/Comment.cs +++ b/src/DevHive.Data/Models/Comment.cs @@ -4,8 +4,8 @@ namespace DevHive.Data.Models public class Comment : IModel { public Guid Id { get; set; } - public Guid UserId { get; set; } + public Guid IssuerId { get; set; } public string Message { get; set; } - public DateTime Date { get; set; } + public DateTime TimeCreated { get; set; } } } \ No newline at end of file diff --git a/src/DevHive.Data/Models/Post.cs b/src/DevHive.Data/Models/Post.cs new file mode 100644 index 0000000..a5abf12 --- /dev/null +++ b/src/DevHive.Data/Models/Post.cs @@ -0,0 +1,21 @@ +using System; +using System.ComponentModel.DataAnnotations.Schema; + +namespace DevHive.Data.Models +{ + [Table("Posts")] + public class Post + { + public Guid Id { get; set; } + + public Guid IssuerId { get; set; } + + public DateTime TimeCreated { get; set; } + + public string Message { get; set; } + + //public File[] Files { get; set; } + + public Comment[] Comments { get; set; } + } +} diff --git a/src/DevHive.Data/Repositories/CommentRepository.cs b/src/DevHive.Data/Repositories/CommentRepository.cs deleted file mode 100644 index 5a4ef17..0000000 --- a/src/DevHive.Data/Repositories/CommentRepository.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Threading.Tasks; -using Data.Models.Interfaces.Database; -using DevHive.Common.Models.Data; -using DevHive.Data.Models; -using Microsoft.EntityFrameworkCore; - -namespace DevHive.Data.Repositories -{ - public class CommentRepository : IRepository - { - private readonly DevHiveContext _context; - - public CommentRepository(DevHiveContext context) - { - this._context = context; - } - - public async Task AddAsync(Comment entity) - { - await this._context - .Set() - .AddAsync(entity); - - return await RepositoryMethods.SaveChangesAsync(this._context); - } - - public async Task GetByIdAsync(Guid id) - { - return await this._context - .Set() - .FindAsync(id); - } - - - public async Task EditAsync(Comment newEntity) - { - this._context - .Set() - .Update(newEntity); - - return await RepositoryMethods.SaveChangesAsync(this._context); - } - - public async Task DoesCommentExist(Guid id) - { - return await this._context - .Set() - .AsNoTracking() - .AnyAsync(r => r.Id == id); - } - - public async Task DeleteAsync(Comment entity) - { - this._context - .Set() - .Remove(entity); - - return await RepositoryMethods.SaveChangesAsync(this._context); - } - } -} \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/LanguageRepository.cs b/src/DevHive.Data/Repositories/LanguageRepository.cs index 6e3a2e3..1ab870a 100644 --- a/src/DevHive.Data/Repositories/LanguageRepository.cs +++ b/src/DevHive.Data/Repositories/LanguageRepository.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using Data.Models.Interfaces.Database; -using DevHive.Common.Models.Data; +using DevHive.Common.Models.Misc; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/DevHive.Data/Repositories/PostRepository.cs b/src/DevHive.Data/Repositories/PostRepository.cs new file mode 100644 index 0000000..5dfee0b --- /dev/null +++ b/src/DevHive.Data/Repositories/PostRepository.cs @@ -0,0 +1,107 @@ +using System; +using System.Threading.Tasks; +using Data.Models.Interfaces.Database; +using DevHive.Common.Models.Misc; +using DevHive.Data.Models; +using Microsoft.EntityFrameworkCore; + +namespace DevHive.Data.Repositories +{ + public class PostRepository : IRepository + { + private readonly DevHiveContext _context; + + public PostRepository(DevHiveContext context) + { + this._context = context; + } + + //Create + public async Task AddAsync(Post post) + { + await this._context + .Set() + .AddAsync(post); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + public async Task AddCommentAsync(Comment entity) + { + await this._context + .Set() + .AddAsync(entity); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + //Read + public async Task GetByIdAsync(Guid id) + { + return await this._context + .Set() + .FindAsync(id); + } + + public async Task GetCommentByIdAsync(Guid id) + { + return await this._context + .Set() + .FindAsync(id); + } + + //Update + public async Task EditAsync(Post newPost) + { + this._context + .Set() + .Update(newPost); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + public async Task EditCommentAsync(Comment newEntity) + { + this._context + .Set() + .Update(newEntity); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + //Delete + public async Task DeleteAsync(Post post) + { + this._context + .Set() + .Remove(post); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + public async Task DeleteCommentAsync(Comment entity) + { + this._context + .Set() + .Remove(entity); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + public async Task DoesPostExist(Guid postId) + { + return await this._context + .Set() + .AsNoTracking() + .AnyAsync(r => r.Id == postId); + } + + public async Task DoesCommentExist(Guid id) + { + return await this._context + .Set() + .AsNoTracking() + .AnyAsync(r => r.Id == id); + } + } +} \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/RoleRepository.cs b/src/DevHive.Data/Repositories/RoleRepository.cs index 1d6f2da..fd04866 100644 --- a/src/DevHive.Data/Repositories/RoleRepository.cs +++ b/src/DevHive.Data/Repositories/RoleRepository.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using Data.Models.Interfaces.Database; -using DevHive.Common.Models.Data; +using DevHive.Common.Models.Misc; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/DevHive.Data/Repositories/TechnologyRepository.cs b/src/DevHive.Data/Repositories/TechnologyRepository.cs index e2e4257..935582c 100644 --- a/src/DevHive.Data/Repositories/TechnologyRepository.cs +++ b/src/DevHive.Data/Repositories/TechnologyRepository.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using Data.Models.Interfaces.Database; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; -using DevHive.Common.Models.Data; +using DevHive.Common.Models.Misc; namespace DevHive.Data.Repositories { diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index d2a8830..5600451 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Data.Models.Interfaces.Database; -using DevHive.Common.Models.Data; +using DevHive.Common.Models.Misc; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/DevHive.Services/Configurations/Mapping/CommentMappings.cs b/src/DevHive.Services/Configurations/Mapping/CommentMappings.cs index f4197a0..f903128 100644 --- a/src/DevHive.Services/Configurations/Mapping/CommentMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/CommentMappings.cs @@ -1,6 +1,7 @@ using DevHive.Data.Models; using AutoMapper; -using DevHive.Services.Models.Comment; +using DevHive.Services.Models.Post.Comment; +using DevHive.Common.Models.Misc; namespace DevHive.Services.Configurations.Mapping { @@ -11,8 +12,8 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap(); CreateMap(); - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); } } } \ No newline at end of file diff --git a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs new file mode 100644 index 0000000..695ffdb --- /dev/null +++ b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs @@ -0,0 +1,16 @@ +using DevHive.Data.Models; +using AutoMapper; +using DevHive.Services.Models.Post; +using DevHive.Services.Models.Post.Post; + +namespace DevHive.Services.Configurations.Mapping +{ + public class PostMappings : Profile + { + public PostMappings() + { + CreateMap(); + CreateMap(); + } + } +} diff --git a/src/DevHive.Services/Models/Comment/CommentServiceModel.cs b/src/DevHive.Services/Models/Comment/CommentServiceModel.cs deleted file mode 100644 index f3638ac..0000000 --- a/src/DevHive.Services/Models/Comment/CommentServiceModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace DevHive.Services.Models.Comment -{ - public class CommentServiceModel - { - public Guid UserId { get; set; } - public string Message { get; set; } - } -} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Comment/GetByIdCommentServiceModel.cs b/src/DevHive.Services/Models/Comment/GetByIdCommentServiceModel.cs deleted file mode 100644 index c2b84b3..0000000 --- a/src/DevHive.Services/Models/Comment/GetByIdCommentServiceModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace DevHive.Services.Models.Comment -{ - public class GetByIdCommentServiceModel : CommentServiceModel - { - public DateTime Date { get; set; } - } -} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Comment/UpdateCommnetServiceModel.cs b/src/DevHive.Services/Models/Comment/UpdateCommnetServiceModel.cs deleted file mode 100644 index 3a461c5..0000000 --- a/src/DevHive.Services/Models/Comment/UpdateCommnetServiceModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace DevHive.Services.Models.Comment -{ - public class UpdateCommentServiceModel : CommentServiceModel - { - public Guid Id { get; set; } - } -} diff --git a/src/DevHive.Services/Models/Post/Comment/BaseCommentServiceModel.cs b/src/DevHive.Services/Models/Post/Comment/BaseCommentServiceModel.cs new file mode 100644 index 0000000..3aa92ee --- /dev/null +++ b/src/DevHive.Services/Models/Post/Comment/BaseCommentServiceModel.cs @@ -0,0 +1,11 @@ +using System; + +namespace DevHive.Services.Models.Post.Comment +{ + public class BaseCommentServiceModel + { + public Guid Id { get; set; } + public Guid IssuerId { get; set; } + public string Message { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Post/Comment/CommentServiceModel.cs b/src/DevHive.Services/Models/Post/Comment/CommentServiceModel.cs new file mode 100644 index 0000000..a0fa53e --- /dev/null +++ b/src/DevHive.Services/Models/Post/Comment/CommentServiceModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Services.Models.Post.Comment +{ + public class CommentServiceModel : CreateCommentServiceModel + { + + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Post/Comment/CreateCommentServiceModel.cs b/src/DevHive.Services/Models/Post/Comment/CreateCommentServiceModel.cs new file mode 100644 index 0000000..33f3bfe --- /dev/null +++ b/src/DevHive.Services/Models/Post/Comment/CreateCommentServiceModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Services.Models.Post.Comment +{ + public class CreateCommentServiceModel : BaseCommentServiceModel + { + public DateTime TimeCreated { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Post/Comment/UpdateCommnetServiceModel.cs b/src/DevHive.Services/Models/Post/Comment/UpdateCommnetServiceModel.cs new file mode 100644 index 0000000..9516a2b --- /dev/null +++ b/src/DevHive.Services/Models/Post/Comment/UpdateCommnetServiceModel.cs @@ -0,0 +1,8 @@ +using System; + +namespace DevHive.Services.Models.Post.Comment +{ + public class UpdateCommentServiceModel : BaseCommentServiceModel + { + } +} diff --git a/src/DevHive.Services/Models/Post/Post/BasePostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/BasePostServiceModel.cs new file mode 100644 index 0000000..45a677c --- /dev/null +++ b/src/DevHive.Services/Models/Post/Post/BasePostServiceModel.cs @@ -0,0 +1,11 @@ +using System; + +namespace DevHive.Services.Models.Post.Post +{ + public class BasePostServiceModel + { + public Guid Id { get; set; } + public Guid IssuerId { get; set; } + public string Message { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs new file mode 100644 index 0000000..97225c7 --- /dev/null +++ b/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Services.Models.Post.Post +{ + public class CreatePostServiceModel : BasePostServiceModel + { + public DateTime TimeCreated { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Post/Post/PostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/PostServiceModel.cs new file mode 100644 index 0000000..b9c2128 --- /dev/null +++ b/src/DevHive.Services/Models/Post/Post/PostServiceModel.cs @@ -0,0 +1,12 @@ +using System; + +namespace DevHive.Services.Models.Post.Post +{ + public class PostServiceModel : CreatePostServiceModel + { + + //public File[] Files { get; set; } + + //public Comment[] Comments { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs new file mode 100644 index 0000000..de61a72 --- /dev/null +++ b/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Services.Models.Post.Post +{ + public class UpdatePostServiceModel : BasePostServiceModel + { + + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Services/CommentService.cs b/src/DevHive.Services/Services/CommentService.cs deleted file mode 100644 index 69dbcc0..0000000 --- a/src/DevHive.Services/Services/CommentService.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using DevHive.Data.Models; -using DevHive.Data.Repositories; -using DevHive.Services.Models.Comment; - -namespace DevHive.Services.Services -{ - public class CommentService - { - private readonly CommentRepository _commentRepository; - private readonly IMapper _commentMapper; - - public CommentService(CommentRepository commentRepository, IMapper mapper) - { - this._commentRepository = commentRepository; - this._commentMapper = mapper; - } - - public async Task CreateComment(CommentServiceModel commentServiceModel) - { - Comment comment = this._commentMapper.Map(commentServiceModel); - comment.Date = DateTime.Now; - bool result = await this._commentRepository.AddAsync(comment); - - return result; - } - - public async Task GetCommentById(Guid id) - { - Comment comment = await this._commentRepository.GetByIdAsync(id); - - if(comment == null) - throw new ArgumentException("The comment does not exist"); - - return this._commentMapper.Map(comment); - } - - public async Task UpdateComment(UpdateCommentServiceModel commentServiceModel) - { - if (!await this._commentRepository.DoesCommentExist(commentServiceModel.Id)) - throw new ArgumentException("Comment does not exist!"); - - Comment comment = this._commentMapper.Map(commentServiceModel); - bool result = await this._commentRepository.EditAsync(comment); - - return result; - } - - public async Task DeleteComment(Guid id) - { - if (!await this._commentRepository.DoesCommentExist(id)) - throw new ArgumentException("Comment does not exist!"); - - Comment comment = await this._commentRepository.GetByIdAsync(id); - bool result = await this._commentRepository.DeleteAsync(comment); - - return result; - } - } -} \ No newline at end of file diff --git a/src/DevHive.Services/Services/PostService.cs b/src/DevHive.Services/Services/PostService.cs new file mode 100644 index 0000000..0c0fd5c --- /dev/null +++ b/src/DevHive.Services/Services/PostService.cs @@ -0,0 +1,98 @@ +using System; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Data.Models; +using DevHive.Data.Repositories; +using DevHive.Services.Models.Post.Comment; +using DevHive.Services.Models.Post.Post; + +namespace DevHive.Services.Services +{ + public class PostService + { + private readonly PostRepository _postRepository; + private readonly IMapper _postMapper; + + public PostService(PostRepository postRepository, IMapper postMapper) + { + this._postRepository = postRepository; + this._postMapper = postMapper; + } + + //Create + public async Task CreatePost(CreatePostServiceModel postServiceModel) + { + Post post = this._postMapper.Map(postServiceModel); + + return await this._postRepository.AddAsync(post); + } + + public async Task AddComment(CreateCommentServiceModel commentServiceModel) + { + commentServiceModel.TimeCreated = DateTime.Now; + Comment comment = this._postMapper.Map(commentServiceModel); + + bool result = await this._postRepository.AddCommentAsync(comment); + + return result; + } + + //Read + public async Task GetPostById(Guid id) + { + Post post = await this._postRepository.GetByIdAsync(id) + ?? throw new ArgumentException("Post does not exist!"); + + return this._postMapper.Map(post); + } + + public async Task GetCommentById(Guid id) + { + Comment comment = await this._postRepository.GetCommentByIdAsync(id); + + if(comment == null) + throw new ArgumentException("The comment does not exist"); + + return this._postMapper.Map(comment); + } + + //Update + public async Task UpdatePost(UpdatePostServiceModel postServiceModel) + { + if (!await this._postRepository.DoesPostExist(postServiceModel.IssuerId)) + throw new ArgumentException("Comment does not exist!"); + + Post post = this._postMapper.Map(postServiceModel); + return await this._postRepository.EditAsync(post); + } + + public async Task UpdateComment(UpdateCommentServiceModel commentServiceModel) + { + if (!await this._postRepository.DoesCommentExist(commentServiceModel.Id)) + throw new ArgumentException("Comment does not exist!"); + + Comment comment = this._postMapper.Map(commentServiceModel); + bool result = await this._postRepository.EditCommentAsync(comment); + + return result; + } + + //Delete + public async Task DeletePost(Guid id) + { + Post post = await this._postRepository.GetByIdAsync(id); + return await this._postRepository.DeleteAsync(post); + } + + public async Task DeleteComment(Guid id) + { + if (!await this._postRepository.DoesCommentExist(id)) + throw new ArgumentException("Comment does not exist!"); + + Comment comment = await this._postRepository.GetCommentByIdAsync(id); + bool result = await this._postRepository.DeleteCommentAsync(comment); + + return result; + } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs index 76d7c6f..2707d91 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -12,13 +12,13 @@ namespace DevHive.Web.Configurations.Extensions services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs b/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs index dd11420..394490e 100644 --- a/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs @@ -1,10 +1,10 @@ using AutoMapper; -using DevHive.Web.Models.Comment; -using DevHive.Services.Models.Comment; +using DevHive.Services.Models.Post.Comment; +using DevHive.Web.Models.Post.Comment; namespace DevHive.Web.Configurations.Mapping { - public class CommentMappings : Profile + public class CommentMappings : Profile { public CommentMappings() { @@ -12,7 +12,6 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap(); CreateMap(); - CreateMap(); } } } \ No newline at end of file diff --git a/src/DevHive.Web/Controllers/CommentController.cs b/src/DevHive.Web/Controllers/CommentController.cs deleted file mode 100644 index 5b6b0ee..0000000 --- a/src/DevHive.Web/Controllers/CommentController.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using DevHive.Data.Repositories; -using DevHive.Services.Models.Comment; -using DevHive.Services.Services; -using DevHive.Web.Models.Comment; -using Microsoft.AspNetCore.Mvc; - -namespace DevHive.Web.Controllers -{ - [ApiController] - [Route("/api/[controller]")] - public class CommentController - { - private readonly CommentService _commentService; - private readonly IMapper _commentMapper; - - public CommentController(CommentService commentService, IMapper mapper) - { - this._commentService = commentService; - this._commentMapper = mapper; - } - - [HttpPost] - public async Task Create([FromBody] CommentWebModel commentWebModel) - { - CommentServiceModel commentServiceModel = this._commentMapper.Map(commentWebModel); - - bool result = await this._commentService.CreateComment(commentServiceModel); - - if(!result) - return new BadRequestObjectResult("Could not create the Comment"); - - return new OkResult(); - } - - [HttpGet] - public async Task GetById(Guid id) - { - GetByIdCommentServiceModel getByIdCommentServiceModel = await this._commentService.GetCommentById(id); - GetByIdCommentWebModel getByIdCommentWebModel = this._commentMapper.Map(getByIdCommentServiceModel); - - return new OkObjectResult(getByIdCommentWebModel); - } - - [HttpPut] - public async Task Update(Guid id, [FromBody] CommentWebModel commentWebModel) - { - UpdateCommentServiceModel updateCommentServiceModel = this._commentMapper.Map(commentWebModel); - updateCommentServiceModel.Id = id; - - bool result = await this._commentService.UpdateComment(updateCommentServiceModel); - - if (!result) - return new BadRequestObjectResult("Could not update Comment"); - - return new OkResult(); - } - - [HttpDelete] - public async Task Delete(Guid id) - { - bool result = await this._commentService.DeleteComment(id); - - if (!result) - return new BadRequestObjectResult("Could not delete Comment"); - - return new OkResult(); - } - } -} \ No newline at end of file diff --git a/src/DevHive.Web/Controllers/PostController.cs b/src/DevHive.Web/Controllers/PostController.cs new file mode 100644 index 0000000..397ddbc --- /dev/null +++ b/src/DevHive.Web/Controllers/PostController.cs @@ -0,0 +1,132 @@ +using System.Threading.Tasks; +using DevHive.Services.Services; +using Microsoft.AspNetCore.Mvc; +using AutoMapper; +using System; +using DevHive.Web.Models.Post.Post; +using DevHive.Services.Models.Post.Post; +using DevHive.Web.Models.Post.Comment; +using DevHive.Services.Models.Post.Comment; +using DevHive.Common.Models.Misc; + +namespace DevHive.Web.Controllers +{ + [ApiController] + [Route("/api/[controller]")] + //[Authorize(Posts = "Admin")] + public class PostController + { + private readonly PostService _postService; + private readonly IMapper _postMapper; + + public PostController(PostService postService, IMapper mapper) + { + this._postService = postService; + this._postMapper = mapper; + } + + //Create + [HttpPost] + public async Task Create([FromBody] CreatePostWebModel createPostModel) + { + CreatePostServiceModel postServiceModel = + this._postMapper.Map(createPostModel); + + bool result = await this._postService.CreatePost(postServiceModel); + + if (!result) + return new BadRequestObjectResult("Could not create post!"); + + return new OkResult(); + } + + [HttpPost] + [Route("Comment")] + public async Task AddComment([FromBody] CommentWebModel commentWebModel) + { + CommentServiceModel commentServiceModel = this._postMapper.Map(commentWebModel); + + bool result = await this._postService.AddComment(commentServiceModel); + + if(!result) + return new BadRequestObjectResult("Could not create the Comment"); + + return new OkResult(); + } + + //Read + [HttpGet] + public async Task GetById(Guid id) + { + PostServiceModel postServiceModel = await this._postService.GetPostById(id); + PostWebModel postWebModel = this._postMapper.Map(postServiceModel); + + return new OkObjectResult(postWebModel); + } + + [HttpGet] + [Route("Comment")] + public async Task GetCommentById(Guid id) + { + CommentServiceModel commentServiceModel = await this._postService.GetCommentById(id); + IdModel idModel = this._postMapper.Map(commentServiceModel); + + return new OkObjectResult(idModel); + } + + //Update + [HttpPut] + public async Task Update(Guid id, [FromBody] UpdatePostWebModel updatePostModel) + { + UpdatePostServiceModel postServiceModel = + this._postMapper.Map(updatePostModel); + postServiceModel.IssuerId = id; + + bool result = await this._postService.UpdatePost(postServiceModel); + + if (!result) + return new BadRequestObjectResult("Could not update post!"); + + return new OkResult(); + } + + [HttpPut] + [Route("Comment")] + public async Task UpdateComment(Guid id, [FromBody] CommentWebModel commentWebModel) + { + UpdateCommentServiceModel updateCommentServiceModel = this._postMapper.Map(commentWebModel); + updateCommentServiceModel.Id = id; + + bool result = await this._postService.UpdateComment(updateCommentServiceModel); + + if (!result) + return new BadRequestObjectResult("Could not update Comment"); + + return new OkResult(); + } + + //Delete + [HttpDelete] + public async Task Delete(Guid id) + { + bool result = await this._postService.DeletePost(id); + + if (!result) + return new BadRequestObjectResult("Could not delete post!"); + + return new OkResult(); + } + + [HttpDelete] + [Route("Comment")] + public async Task DeleteComment(Guid id) + { + bool result = await this._postService.DeleteComment(id); + + if (!result) + return new BadRequestObjectResult("Could not delete Comment"); + + return new OkResult(); + } + } +} diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index 6b81ab8..d710f5a 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -67,7 +67,7 @@ namespace DevHive.Web.Controllers bool result = await this._roleService.DeleteRole(id); if (!result) - return new BadRequestObjectResult("Could nor delete role!"); + return new BadRequestObjectResult("Could not delete role!"); return new OkResult(); } diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index 02cae0c..ce972a5 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -9,7 +9,7 @@ using DevHive.Web.Models.Identity.User; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using DevHive.Common.Models.Identity; -using DevHive.Common.Models.Data; +using DevHive.Common.Models.Misc; namespace DevHive.Web.Controllers { diff --git a/src/DevHive.Web/Models/Comment/CommentWebModel.cs b/src/DevHive.Web/Models/Comment/CommentWebModel.cs deleted file mode 100644 index 37806a5..0000000 --- a/src/DevHive.Web/Models/Comment/CommentWebModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace DevHive.Web.Models.Comment -{ - public class CommentWebModel - { - public Guid UserId { get; set; } - public string Message { get; set; } - } -} \ No newline at end of file diff --git a/src/DevHive.Web/Models/Comment/GetByIdCommentWebModel.cs b/src/DevHive.Web/Models/Comment/GetByIdCommentWebModel.cs deleted file mode 100644 index 3d03348..0000000 --- a/src/DevHive.Web/Models/Comment/GetByIdCommentWebModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace DevHive.Web.Models.Comment -{ - public class GetByIdCommentWebModel : CommentWebModel - { - public DateTime Date { get; set; } - } -} \ No newline at end of file diff --git a/src/DevHive.Web/Models/Post/Comment/CommentWebModel.cs b/src/DevHive.Web/Models/Post/Comment/CommentWebModel.cs new file mode 100644 index 0000000..2a8650a --- /dev/null +++ b/src/DevHive.Web/Models/Post/Comment/CommentWebModel.cs @@ -0,0 +1,10 @@ +using System; + +namespace DevHive.Web.Models.Post.Comment +{ + public class CommentWebModel + { + public Guid IssuerId { get; set; } + public string Message { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Models/Post/Post/BasePostWebModel.cs b/src/DevHive.Web/Models/Post/Post/BasePostWebModel.cs new file mode 100644 index 0000000..caa9925 --- /dev/null +++ b/src/DevHive.Web/Models/Post/Post/BasePostWebModel.cs @@ -0,0 +1,10 @@ +using System; + +namespace DevHive.Web.Models.Post.Post +{ + public class BasePostWebModel + { + public Guid IssuerId { get; set; } + public string Message { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs b/src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs new file mode 100644 index 0000000..7558b2c --- /dev/null +++ b/src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs @@ -0,0 +1,8 @@ +using System; + +namespace DevHive.Web.Models.Post.Post +{ + public class CreatePostWebModel : BasePostWebModel + { + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Models/Post/Post/PostWebModel.cs b/src/DevHive.Web/Models/Post/Post/PostWebModel.cs new file mode 100644 index 0000000..fa18c3a --- /dev/null +++ b/src/DevHive.Web/Models/Post/Post/PostWebModel.cs @@ -0,0 +1,21 @@ +using DevHive.Web.Models.Post.Comment; + +namespace DevHive.Web.Models.Post.Post +{ + public class PostWebModel + { + //public string Picture { get; set; } + + public string IssuerFirstName { get; set; } + + public string IssuerLastName { get; set; } + + public string IssuerUsername { get; set; } + + public string Message { get; set; } + + //public Files[] Files { get; set; } + + public CommentWebModel[] Comments { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Models/Post/Post/UpdatePostModel.cs b/src/DevHive.Web/Models/Post/Post/UpdatePostModel.cs new file mode 100644 index 0000000..c774900 --- /dev/null +++ b/src/DevHive.Web/Models/Post/Post/UpdatePostModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Web.Models.Post.Post +{ + public class UpdatePostWebModel : BasePostWebModel + { + //public Files[] Files { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index de1295c..42fc88a 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -1,14 +1,10 @@ -using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using DevHive.Web.Configurations.Extensions; -using AutoMapper; using Newtonsoft.Json; -using DevHive.Data.Repositories; -using DevHive.Services.Services; namespace DevHive.Web { -- cgit v1.2.3 From 4919ce8002a4f8660ec306f73c041c4ad273ddc0 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Fri, 8 Jan 2021 14:09:56 +0200 Subject: Implemented CORS in API (so Angular could accept requests from the API) --- src/DevHive.Web/Startup.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 42fc88a..96ab318 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -20,6 +20,8 @@ namespace DevHive.Web // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { + services.AddCors(); + services.AddControllers() .AddNewtonsoftJson(x => { @@ -36,6 +38,12 @@ namespace DevHive.Web // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { + app.UseCors(x => x + .AllowAnyMethod() + .AllowAnyHeader() + .SetIsOriginAllowed(origin => true) // allow any origin + .AllowCredentials()); // allow credentials + if (env.IsDevelopment()) { //app.UseDeveloperExceptionPage(); -- cgit v1.2.3 From 61c51944844ed404cd4f174440d6e81b2a8591ba Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 13 Jan 2021 23:06:18 +0200 Subject: Fixed sln-wide code formatting --- .../Configurations/Extensions/ConfigureDatabase.cs | 4 +- .../Configurations/Mapping/CommentMappings.cs | 4 +- .../Configurations/Mapping/LanguageMappings.cs | 6 +- .../Configurations/Mapping/RoleMappings.cs | 6 +- .../Configurations/Mapping/TechnologyMappings.cs | 6 +- .../Configurations/Mapping/UserMappings.cs | 2 +- src/DevHive.Web/Controllers/ErrorController.cs | 2 +- src/DevHive.Web/Controllers/LanguageController.cs | 12 +- src/DevHive.Web/Controllers/PostController.cs | 12 +- src/DevHive.Web/Controllers/RoleController.cs | 8 +- .../Controllers/TechnologyController.cs | 12 +- src/DevHive.Web/Controllers/UserController.cs | 6 +- .../Models/Identity/User/BaseUserWebModel.cs | 4 +- .../Models/Identity/User/LoginWebModel.cs | 4 +- .../Models/Identity/User/RegisterWebModel.cs | 4 +- .../Models/Identity/User/UpdateUserWebModel.cs | 2 +- .../Models/Identity/User/UserWebModel.cs | 2 +- .../Validation/GoodPasswordModelValidation.cs | 2 +- .../Models/Language/UpdateLanguageWebModel.cs | 4 +- src/DevHive.Web/Startup.cs | 142 ++++++++++----------- 20 files changed, 122 insertions(+), 122 deletions(-) (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index b42ae05..4831435 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -20,7 +20,7 @@ namespace DevHive.Web.Configurations.Extensions services.AddIdentity() .AddEntityFrameworkStores(); - + services.Configure(options => { options.User.RequireUniqueEmail = true; @@ -41,7 +41,7 @@ namespace DevHive.Web.Configurations.Extensions services.AddAuthorization(options => { - options.AddPolicy("User", options => + options.AddPolicy("User", options => { options.RequireAuthenticatedUser(); options.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); diff --git a/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs b/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs index 394490e..5998e7a 100644 --- a/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/CommentMappings.cs @@ -13,5 +13,5 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap(); } - } -} \ No newline at end of file + } +} diff --git a/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs b/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs index bae8562..3c2a4d0 100644 --- a/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs @@ -4,7 +4,7 @@ using DevHive.Services.Models.Language; namespace DevHive.Web.Configurations.Mapping { - public class LanguageMappings : Profile + public class LanguageMappings : Profile { public LanguageMappings() { @@ -16,5 +16,5 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap(); } - } -} \ No newline at end of file + } +} diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs index 5d33c56..afa3a94 100644 --- a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -4,15 +4,15 @@ using DevHive.Common.Models.Identity; namespace DevHive.Web.Configurations.Mapping { - public class RoleMappings : Profile + public class RoleMappings : Profile { public RoleMappings() { CreateMap(); CreateMap(); - + CreateMap(); CreateMap(); } - } + } } diff --git a/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs b/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs index 849e47f..8523897 100644 --- a/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs @@ -4,7 +4,7 @@ using DevHive.Services.Models.Technology; namespace DevHive.Web.Configurations.Mapping { - public class TechnologyMappings : Profile + public class TechnologyMappings : Profile { public TechnologyMappings() { @@ -13,5 +13,5 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap(); } - } -} \ No newline at end of file + } +} diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index 4420368..59003ea 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -18,5 +18,5 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); } - } + } } diff --git a/src/DevHive.Web/Controllers/ErrorController.cs b/src/DevHive.Web/Controllers/ErrorController.cs index c3f1e55..b187501 100644 --- a/src/DevHive.Web/Controllers/ErrorController.cs +++ b/src/DevHive.Web/Controllers/ErrorController.cs @@ -19,7 +19,7 @@ namespace DevHive.Web.Controllers IExceptionHandlerFeature exception = HttpContext.Features.Get(); - + object result = ProcessException(requestId, exception); return new BadRequestObjectResult(JsonConvert.SerializeObject(result)); } diff --git a/src/DevHive.Web/Controllers/LanguageController.cs b/src/DevHive.Web/Controllers/LanguageController.cs index 29c1e99..486e16e 100644 --- a/src/DevHive.Web/Controllers/LanguageController.cs +++ b/src/DevHive.Web/Controllers/LanguageController.cs @@ -29,7 +29,7 @@ namespace DevHive.Web.Controllers bool result = await this._languageService.CreateLanguage(languageServiceModel); - if(!result) + if (!result) return new BadRequestObjectResult("Could not create Language"); return new OkResult(); @@ -52,21 +52,21 @@ namespace DevHive.Web.Controllers bool result = await this._languageService.UpdateLanguage(updatelanguageServiceModel); - if(!result) + if (!result) return new BadRequestObjectResult("Could not update Language"); return new OkResult(); } - + [HttpDelete] public async Task Delete(Guid id) { bool result = await this._languageService.DeleteLanguage(id); - - if(!result) + + if (!result) return new BadRequestObjectResult("Could not delete Language"); return new OkResult(); } } -} \ No newline at end of file +} diff --git a/src/DevHive.Web/Controllers/PostController.cs b/src/DevHive.Web/Controllers/PostController.cs index 753897c..a906e47 100644 --- a/src/DevHive.Web/Controllers/PostController.cs +++ b/src/DevHive.Web/Controllers/PostController.cs @@ -30,9 +30,9 @@ namespace DevHive.Web.Controllers [HttpPost] public async Task Create([FromBody] CreatePostWebModel createPostModel) { - CreatePostServiceModel postServiceModel = - this._postMapper.Map(createPostModel); - + CreatePostServiceModel postServiceModel = + this._postMapper.Map(createPostModel); + bool result = await this._postService.CreatePost(postServiceModel); if (!result) @@ -49,7 +49,7 @@ namespace DevHive.Web.Controllers bool result = await this._postService.AddComment(createCommentServiceModel); - if(!result) + if (!result) return new BadRequestObjectResult("Could not create the Comment"); return new OkResult(); @@ -81,7 +81,7 @@ namespace DevHive.Web.Controllers [HttpPut] public async Task Update(Guid id, [FromBody] UpdatePostWebModel updatePostModel) { - UpdatePostServiceModel postServiceModel = + UpdatePostServiceModel postServiceModel = this._postMapper.Map(updatePostModel); postServiceModel.IssuerId = id; @@ -129,7 +129,7 @@ namespace DevHive.Web.Controllers { if (!await this._postService.ValidateJwtForComment(id, authorization)) return new UnauthorizedResult(); - + bool result = await this._postService.DeleteComment(id); if (!result) diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index d710f5a..0a8f7a1 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -26,9 +26,9 @@ namespace DevHive.Web.Controllers [HttpPost] public async Task Create([FromBody] CreateRoleModel createRoleModel) { - RoleModel roleServiceModel = - this._roleMapper.Map(createRoleModel); - + RoleModel roleServiceModel = + this._roleMapper.Map(createRoleModel); + bool result = await this._roleService.CreateRole(roleServiceModel); if (!result) @@ -49,7 +49,7 @@ namespace DevHive.Web.Controllers [HttpPut] public async Task Update(Guid id, [FromBody] UpdateRoleModel updateRoleModel) { - RoleModel roleServiceModel = + RoleModel roleServiceModel = this._roleMapper.Map(updateRoleModel); roleServiceModel.Id = id; diff --git a/src/DevHive.Web/Controllers/TechnologyController.cs b/src/DevHive.Web/Controllers/TechnologyController.cs index e02ca3d..905a71d 100644 --- a/src/DevHive.Web/Controllers/TechnologyController.cs +++ b/src/DevHive.Web/Controllers/TechnologyController.cs @@ -29,7 +29,7 @@ namespace DevHive.Web.Controllers bool result = await this._technologyService.Create(technologyServiceModel); - if(!result) + if (!result) return new BadRequestObjectResult("Could not create the Technology"); return new OkResult(); @@ -51,21 +51,21 @@ namespace DevHive.Web.Controllers bool result = await this._technologyService.UpdateTechnology(updateTechnologyWebModel); - if(!result) + if (!result) return new BadRequestObjectResult("Could not update Technology"); return new OkResult(); } - + [HttpDelete] public async Task Delete(Guid id) { bool result = await this._technologyService.DeleteTechnology(id); - - if(!result) + + if (!result) return new BadRequestObjectResult("Could not delete Technology"); return new OkResult(); } } -} \ No newline at end of file +} diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index 0960915..26271b2 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -20,7 +20,7 @@ namespace DevHive.Web.Controllers [ApiController] [Route("/api/[controller]")] [Authorize(Roles = "User")] - public class UserController: ControllerBase + public class UserController : ControllerBase { private readonly UserService _userService; private readonly IMapper _userMapper; @@ -154,7 +154,7 @@ namespace DevHive.Web.Controllers await this._userService.RemoveFriend(userId, friendId); return new OkResult(); } - + [HttpDelete] [Route("RemoveLanguageFromUser")] public async Task RemoveLanguageFromUser(Guid userId, [FromBody] LanguageWebModel languageWebModel) @@ -176,7 +176,7 @@ namespace DevHive.Web.Controllers new OkResult() : new BadRequestResult(); } - + #endregion } } diff --git a/src/DevHive.Web/Models/Identity/User/BaseUserWebModel.cs b/src/DevHive.Web/Models/Identity/User/BaseUserWebModel.cs index ff9fac5..2d99786 100644 --- a/src/DevHive.Web/Models/Identity/User/BaseUserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/BaseUserWebModel.cs @@ -1,9 +1,9 @@ using System.ComponentModel.DataAnnotations; using DevHive.Web.Models.Identity.Validation; -namespace DevHive.Web.Models.Identity.User +namespace DevHive.Web.Models.Identity.User { - public class BaseUserWebModel + public class BaseUserWebModel { [Required] [MinLength(3)] diff --git a/src/DevHive.Web/Models/Identity/User/LoginWebModel.cs b/src/DevHive.Web/Models/Identity/User/LoginWebModel.cs index 3bd7428..87c7416 100644 --- a/src/DevHive.Web/Models/Identity/User/LoginWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/LoginWebModel.cs @@ -1,6 +1,6 @@ -namespace DevHive.Web.Models.Identity.User +namespace DevHive.Web.Models.Identity.User { - public class LoginWebModel + public class LoginWebModel { public string UserName { get; set; } public string Password { get; set; } diff --git a/src/DevHive.Web/Models/Identity/User/RegisterWebModel.cs b/src/DevHive.Web/Models/Identity/User/RegisterWebModel.cs index 22b178b..273c2d3 100644 --- a/src/DevHive.Web/Models/Identity/User/RegisterWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/RegisterWebModel.cs @@ -1,9 +1,9 @@ using System.ComponentModel.DataAnnotations; using DevHive.Web.Models.Identity.Validation; -namespace DevHive.Web.Models.Identity.User +namespace DevHive.Web.Models.Identity.User { - public class RegisterWebModel : BaseUserWebModel + public class RegisterWebModel : BaseUserWebModel { [Required] [GoodPassword] diff --git a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs index fbe02a5..91fbc64 100644 --- a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs @@ -1,7 +1,7 @@ using System.ComponentModel.DataAnnotations; using DevHive.Web.Models.Identity.Validation; -namespace DevHive.Web.Models.Identity.User +namespace DevHive.Web.Models.Identity.User { public class UpdateUserWebModel : BaseUserWebModel { diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 260d34c..8f7995c 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -4,7 +4,7 @@ using DevHive.Web.Models.Identity.Role; using DevHive.Web.Models.Language; using DevHive.Web.Models.Technology; -namespace DevHive.Web.Models.Identity.User +namespace DevHive.Web.Models.Identity.User { public class UserWebModel : BaseUserWebModel { diff --git a/src/DevHive.Web/Models/Identity/Validation/GoodPasswordModelValidation.cs b/src/DevHive.Web/Models/Identity/Validation/GoodPasswordModelValidation.cs index f69121a..f920c35 100644 --- a/src/DevHive.Web/Models/Identity/Validation/GoodPasswordModelValidation.cs +++ b/src/DevHive.Web/Models/Identity/Validation/GoodPasswordModelValidation.cs @@ -3,7 +3,7 @@ using System.ComponentModel.DataAnnotations; namespace DevHive.Web.Models.Identity.Validation { - public class GoodPassword : ValidationAttribute + public class GoodPassword : ValidationAttribute { public override bool IsValid(object value) { diff --git a/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs b/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs index 2da8217..deca0fc 100644 --- a/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs +++ b/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs @@ -2,5 +2,5 @@ using System; namespace DevHive.Web.Models.Language { - public class UpdateLanguageWebModel : CreateLanguageWebModel {} -} \ No newline at end of file + public class UpdateLanguageWebModel : CreateLanguageWebModel { } +} diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 96ab318..94aabe8 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -1,71 +1,71 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using DevHive.Web.Configurations.Extensions; -using Newtonsoft.Json; - -namespace DevHive.Web -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddCors(); - - services.AddControllers() - .AddNewtonsoftJson(x => - { - x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - }); - - services.DatabaseConfiguration(Configuration); - services.SwaggerConfiguration(); - services.JWTConfiguration(Configuration); - services.AutoMapperConfiguration(); - services.DependencyInjectionConfiguration(); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.UseCors(x => x - .AllowAnyMethod() - .AllowAnyHeader() - .SetIsOriginAllowed(origin => true) // allow any origin - .AllowCredentials()); // allow credentials - - if (env.IsDevelopment()) - { - //app.UseDeveloperExceptionPage(); - app.UseExceptionHandler("/api/Error"); - app.UseSwaggerConfiguration(); - } - else - { - app.UseExceptionHandler("/api/Error"); - app.UseHsts(); - } - - app.UseDatabaseConfiguration(); - app.UseAutoMapperConfiguration(); - - app.UseEndpoints(endpoints => - { - endpoints.MapControllerRoute( - name: "default", - pattern: "api/{controller}/{action}" - ); - }); - } - } -} +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using DevHive.Web.Configurations.Extensions; +using Newtonsoft.Json; + +namespace DevHive.Web +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddCors(); + + services.AddControllers() + .AddNewtonsoftJson(x => + { + x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + }); + + services.DatabaseConfiguration(Configuration); + services.SwaggerConfiguration(); + services.JWTConfiguration(Configuration); + services.AutoMapperConfiguration(); + services.DependencyInjectionConfiguration(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.UseCors(x => x + .AllowAnyMethod() + .AllowAnyHeader() + .SetIsOriginAllowed(origin => true) // allow any origin + .AllowCredentials()); // allow credentials + + if (env.IsDevelopment()) + { + //app.UseDeveloperExceptionPage(); + app.UseExceptionHandler("/api/Error"); + app.UseSwaggerConfiguration(); + } + else + { + app.UseExceptionHandler("/api/Error"); + app.UseHsts(); + } + + app.UseDatabaseConfiguration(); + app.UseAutoMapperConfiguration(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "api/{controller}/{action}" + ); + }); + } + } +} -- cgit v1.2.3 From 90e0126d4078b5fef44b085b34caf7a35161ff50 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 19 Jan 2021 21:12:49 +0200 Subject: Added Custom Middleware for Exception Handling --- .../Extensions/ConfigureCustomMiddleware.cs | 16 +++++++ .../Models/Middleware/ExceptionMiddleware.cs | 50 ++++++++++++++++++++++ src/DevHive.Web/Startup.cs | 3 +- 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs create mode 100644 src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs new file mode 100644 index 0000000..24c2adf --- /dev/null +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs @@ -0,0 +1,16 @@ +using DevHive.Web.Models.Middleware; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureCustomMiddleware + { + public static void CustomMiddlewareConfiguration(this IServiceCollection services) { } + + public static void UseCustomMiddlewareConfiguration(this IApplicationBuilder app) + { + app.UseMiddleware(); + } + } +} diff --git a/src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs b/src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs new file mode 100644 index 0000000..d952ff4 --- /dev/null +++ b/src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs @@ -0,0 +1,50 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace DevHive.Web.Models.Middleware +{ + public class ExceptionMiddleware + { + private readonly RequestDelegate _next; + // private readonly ILogger _logger; + + public ExceptionMiddleware(RequestDelegate next) + { + this._next = next; + // this._logger = logger; + } + // public ExceptionMiddleware(RequestDelegate next, ILogger logger) + // { + // this._logger = logger; + // this._next = next; + // } + + public async Task InvokeAsync(HttpContext httpContext) + { + try + { + await this._next(httpContext); + } + catch (Exception ex) + { + // this._logger.LogError($"Something went wrong: {ex}"); + await HandleExceptionAsync(httpContext, ex); + } + } + + private Task HandleExceptionAsync(HttpContext context, Exception exception) + { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)HttpStatusCode.BadRequest; + + return context.Response.WriteAsync(new + { + StatusCode = context.Response.StatusCode, + Message = "Internal Server Error from the custom middleware." + }.ToString()); + } + } +} diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 94aabe8..4e55873 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -33,6 +33,7 @@ namespace DevHive.Web services.JWTConfiguration(Configuration); services.AutoMapperConfiguration(); services.DependencyInjectionConfiguration(); + services.CustomMiddlewareConfiguration(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -47,7 +48,6 @@ namespace DevHive.Web if (env.IsDevelopment()) { //app.UseDeveloperExceptionPage(); - app.UseExceptionHandler("/api/Error"); app.UseSwaggerConfiguration(); } else @@ -58,6 +58,7 @@ namespace DevHive.Web app.UseDatabaseConfiguration(); app.UseAutoMapperConfiguration(); + app.UseCustomMiddlewareConfiguration(); app.UseEndpoints(endpoints => { -- cgit v1.2.3 From 661c3194b750e42146e9e28a33da08419b2b2cea Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 19 Jan 2021 21:21:13 +0200 Subject: Adjusted custom exception middleware; Removed old Global Exception Handler --- src/DevHive.Web/Controllers/ErrorController.cs | 50 ---------------------- .../Models/Middleware/ExceptionMiddleware.cs | 2 +- src/DevHive.Web/Startup.cs | 3 +- 3 files changed, 2 insertions(+), 53 deletions(-) delete mode 100644 src/DevHive.Web/Controllers/ErrorController.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Web/Controllers/ErrorController.cs b/src/DevHive.Web/Controllers/ErrorController.cs deleted file mode 100644 index b187501..0000000 --- a/src/DevHive.Web/Controllers/ErrorController.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Diagnostics; -using AutoMapper; -using Microsoft.AspNetCore.Diagnostics; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; - -namespace DevHive.Web.Controllers -{ - public class ErrorController : ControllerBase - { - [HttpPost] - [Route("/api/Error")] - public IActionResult Error() - { - //Later for logging - string requestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - - IExceptionHandlerFeature exception = - HttpContext.Features.Get(); - - object result = ProcessException(requestId, exception); - return new BadRequestObjectResult(JsonConvert.SerializeObject(result)); - } - - private object ProcessException(string requestId, IExceptionHandlerFeature exception) - { - switch (exception.Error) - { - case ArgumentException _: - case InvalidOperationException _: - case AutoMapperMappingException _: - case AutoMapperConfigurationException _: - return MessageToObject(exception.Error.Message); - default: - return MessageToObject(null); - } - } - - private object MessageToObject(string message) - { - return new - { - Error = message - }; - } - } -} - diff --git a/src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs b/src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs index d952ff4..c57452e 100644 --- a/src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs +++ b/src/DevHive.Web/Models/Middleware/ExceptionMiddleware.cs @@ -43,7 +43,7 @@ namespace DevHive.Web.Models.Middleware return context.Response.WriteAsync(new { StatusCode = context.Response.StatusCode, - Message = "Internal Server Error from the custom middleware." + Message = exception.Message }.ToString()); } } diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 4e55873..8fa346a 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -47,12 +47,11 @@ namespace DevHive.Web if (env.IsDevelopment()) { - //app.UseDeveloperExceptionPage(); + app.UseDeveloperExceptionPage(); app.UseSwaggerConfiguration(); } else { - app.UseExceptionHandler("/api/Error"); app.UseHsts(); } -- cgit v1.2.3 From aa4f7bdd9a2df09fc47e82c2b85fb7647203ba8d Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 19 Jan 2021 23:01:33 +0200 Subject: Config ExceptionMiddleware; Config Mapper; Fixed User editing; Implmeneted Friend add trough HttpPatch --- src/DevHive.Data/Models/User.cs | 1 + src/DevHive.Data/Repositories/UserRepository.cs | 12 +++++----- .../Configurations/Mapping/UserMappings.cs | 2 ++ .../Models/Identity/User/FriendServiceModel.cs | 7 ++++++ .../Models/Identity/User/UserServiceModel.cs | 2 +- src/DevHive.Services/Services/UserService.cs | 26 +++++++++++++++++++--- .../Extensions/ConfigureCustomMiddleware.cs | 16 ------------- .../ConfigureExceptionHandlerMiddleware.cs | 16 +++++++++++++ .../Configurations/Mapping/UserMappings.cs | 3 +++ .../Models/Identity/User/UserWebModel.cs | 2 +- src/DevHive.Web/Startup.cs | 4 ++-- 11 files changed, 63 insertions(+), 28 deletions(-) create mode 100644 src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs delete mode 100644 src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs create mode 100644 src/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Data/Models/User.cs b/src/DevHive.Data/Models/User.cs index 31e36ac..cf779f5 100644 --- a/src/DevHive.Data/Models/User.cs +++ b/src/DevHive.Data/Models/User.cs @@ -18,6 +18,7 @@ namespace DevHive.Data.Models /// /// Languages that the user uses or is familiar with /// + // [Unique] public IList Languages { get; set; } /// diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 81c974c..2ca8099 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -109,12 +109,14 @@ namespace DevHive.Data.Repositories public async Task EditAsync(User newEntity) { - User user = await this.GetByIdAsync(newEntity.Id); + // User user = await this.GetByIdAsync(newEntity.Id); - this._context - .Entry(user) - .CurrentValues - .SetValues(newEntity); + // this._context + // .Entry(user) + // .CurrentValues + // .SetValues(newEntity); + + this._context.Update(newEntity); return await this.SaveChangesAsync(this._context); } diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index d57c6ba..541e16e 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -11,8 +11,10 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap(); CreateMap(); + CreateMap(); CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs b/src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs new file mode 100644 index 0000000..63d57f7 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class FriendServiceModel + { + public string UserName { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index aa77a0c..913b5c0 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -9,7 +9,7 @@ namespace DevHive.Services.Models.Identity.User { public IList Roles { get; set; } = new List(); - public IList Friends { get; set; } = new List(); + public IList Friends { get; set; } = new List(); public IList Languages { get; set; } = new List(); diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index a8b9ef9..ee4b24d 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -15,6 +15,7 @@ using DevHive.Services.Interfaces; using DevHive.Data.Interfaces.Repositories; using Microsoft.AspNetCore.JsonPatch; using System.Linq; +using Newtonsoft.Json; namespace DevHive.Services.Services { @@ -171,18 +172,37 @@ namespace DevHive.Services.Services User user = await this._userRepository.GetByIdAsync(id) ?? throw new ArgumentException("User does not exist!"); - var password = jsonPatch.Operations + object password = jsonPatch.Operations .Where(x => x.path == "/password") .Select(x => x.value) .FirstOrDefault(); + IEnumerable friends = jsonPatch.Operations + .Where(x => x.path == "/friends") + .Select(x => x.value); + if(password != null) { string passwordHash = this.GeneratePasswordHash(password.ToString()); user.PasswordHash = passwordHash; } - else - jsonPatch.ApplyTo(user); + + if (friends != null) + { + foreach (object friendObj in friends) + { + FriendServiceModel friendServiceModel = + JsonConvert.DeserializeObject(friendObj.ToString()); + + User amigo = await this._userRepository.GetByUsernameAsync(friendServiceModel.UserName) + ?? throw new ArgumentException($"User {friendServiceModel.UserName} does not exist!"); + + user.Friends.Add(amigo); + } + } + + //Remove password and friends peace from the request patch before applying the rest + // jsonPatch.ApplyTo(user); bool success = await this._userRepository.EditAsync(user); if (success) diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs deleted file mode 100644 index efcb8e1..0000000 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureCustomMiddleware.cs +++ /dev/null @@ -1,16 +0,0 @@ -using DevHive.Web.Middleware; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace DevHive.Web.Configurations.Extensions -{ - public static class ConfigureCustomMiddleware - { - public static void CustomMiddlewareConfiguration(this IServiceCollection services) { } - - public static void UseCustomMiddlewareConfiguration(this IApplicationBuilder app) - { - app.UseMiddleware(); - } - } -} diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs new file mode 100644 index 0000000..286727f --- /dev/null +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs @@ -0,0 +1,16 @@ +using DevHive.Web.Middleware; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureExceptionHandlerMiddleware + { + public static void ExceptionHandlerMiddlewareConfiguration(this IServiceCollection services) { } + + public static void UseExceptionHandlerMiddlewareConfiguration(this IApplicationBuilder app) + { + app.UseMiddleware(); + } + } +} diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index beb9607..5faf4b5 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -20,6 +20,9 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); + CreateMap(); + CreateMap(); + CreateMap() .ForMember(f => f.Name, u => u.MapFrom(src => src.UserName)); CreateMap(); diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 88f199d..1d2d17b 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -15,7 +15,7 @@ namespace DevHive.Web.Models.Identity.User [NotNull] [Required] - public IList Friends { get; set; } = new List(); + public IList Friends { get; set; } = new List(); [NotNull] [Required] diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 8fa346a..92d4359 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -33,7 +33,7 @@ namespace DevHive.Web services.JWTConfiguration(Configuration); services.AutoMapperConfiguration(); services.DependencyInjectionConfiguration(); - services.CustomMiddlewareConfiguration(); + services.ExceptionHandlerMiddlewareConfiguration(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -53,11 +53,11 @@ namespace DevHive.Web else { app.UseHsts(); + app.UseExceptionHandlerMiddlewareConfiguration(); } app.UseDatabaseConfiguration(); app.UseAutoMapperConfiguration(); - app.UseCustomMiddlewareConfiguration(); app.UseEndpoints(endpoints => { -- cgit v1.2.3 From b38d6693476917972345397298b534af2b8b8f78 Mon Sep 17 00:00:00 2001 From: transtrike Date: Fri, 29 Jan 2021 20:39:07 +0200 Subject: File Upload implemented; Post Layers adapted to File Uploading --- src/DevHive.Data/Interfaces/Models/IPost.cs | 2 +- .../Interfaces/Repositories/IPostRepository.cs | 4 ++ src/DevHive.Data/Models/Post.cs | 2 +- src/DevHive.Data/Repositories/BaseRepository.cs | 6 +-- src/DevHive.Data/Repositories/PostRepository.cs | 16 +++++++ .../Configurations/Mapping/PostMappings.cs | 4 +- src/DevHive.Services/DevHive.Services.csproj | 56 +++++++++++----------- src/DevHive.Services/Interfaces/ICloudService.cs | 13 +++++ .../Models/Cloud/CloudinaryService.cs | 55 +++++++++++++++++++++ .../Models/Post/Post/CreatePostServiceModel.cs | 4 +- .../Models/Post/Post/ReadPostServiceModel.cs | 3 +- .../Models/Post/Post/UpdatePostServiceModel.cs | 4 +- src/DevHive.Services/Services/PostService.cs | 34 +++++++++++-- .../Extensions/ConfigureDependencyInjection.cs | 8 +++- .../Models/Post/Post/CreatePostWebModel.cs | 4 +- .../Models/Post/Post/ReadPostWebModel.cs | 3 +- .../Models/Post/Post/UpdatePostWebModel.cs | 4 ++ src/DevHive.Web/Startup.cs | 2 +- src/DevHive.Web/appsettings.json | 7 ++- 19 files changed, 186 insertions(+), 45 deletions(-) create mode 100644 src/DevHive.Services/Interfaces/ICloudService.cs create mode 100644 src/DevHive.Services/Models/Cloud/CloudinaryService.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Data/Interfaces/Models/IPost.cs b/src/DevHive.Data/Interfaces/Models/IPost.cs index 0902465..86469a7 100644 --- a/src/DevHive.Data/Interfaces/Models/IPost.cs +++ b/src/DevHive.Data/Interfaces/Models/IPost.cs @@ -14,6 +14,6 @@ namespace DevHive.Data.Interfaces.Models List Comments { get; set; } - //List Files + List FileUrls { get; set; } } } diff --git a/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs b/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs index aa0afc7..5022df5 100644 --- a/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs +++ b/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using DevHive.Data.Models; using DevHive.Data.Repositories.Interfaces; @@ -8,6 +9,9 @@ namespace DevHive.Data.Interfaces.Repositories public interface IPostRepository : IRepository { Task GetPostByCreatorAndTimeCreatedAsync(Guid issuerId, DateTime timeCreated); + Task> GetFileUrls(Guid postId); + Task DoesPostExist(Guid postId); + Task DoesPostHaveFiles(Guid postId); } } diff --git a/src/DevHive.Data/Models/Post.cs b/src/DevHive.Data/Models/Post.cs index 0ea7142..c513eb4 100644 --- a/src/DevHive.Data/Models/Post.cs +++ b/src/DevHive.Data/Models/Post.cs @@ -18,6 +18,6 @@ namespace DevHive.Data.Models public List Comments { get; set; } = new(); - // public List Files { get; set; } = new(); + public List FileUrls { get; set; } = new(); } } diff --git a/src/DevHive.Data/Repositories/BaseRepository.cs b/src/DevHive.Data/Repositories/BaseRepository.cs index f1e6673..cac802e 100644 --- a/src/DevHive.Data/Repositories/BaseRepository.cs +++ b/src/DevHive.Data/Repositories/BaseRepository.cs @@ -34,10 +34,10 @@ namespace DevHive.Data.Repositories public virtual async Task EditAsync(Guid id, TEntity newEntity) { var entry = this._context.Entry(newEntity); - if (entry.State == EntityState.Detached) - this._context.Attach(newEntity); + if (entry.State == EntityState.Detached) + this._context.Attach(newEntity); - entry.State = EntityState.Modified; + entry.State = EntityState.Modified; return await this.SaveChangesAsync(_context); } diff --git a/src/DevHive.Data/Repositories/PostRepository.cs b/src/DevHive.Data/Repositories/PostRepository.cs index 67988f2..78b40cd 100644 --- a/src/DevHive.Data/Repositories/PostRepository.cs +++ b/src/DevHive.Data/Repositories/PostRepository.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using DevHive.Data.Interfaces.Repositories; using DevHive.Data.Models; @@ -30,6 +32,11 @@ namespace DevHive.Data.Repositories .FirstOrDefaultAsync(p => p.Creator.Id == creatorId && p.TimeCreated == timeCreated); } + + public async Task> GetFileUrls(Guid postId) + { + return (await this.GetByIdAsync(postId)).FileUrls; + } #endregion #region Validations @@ -39,6 +46,15 @@ namespace DevHive.Data.Repositories .AsNoTracking() .AnyAsync(r => r.Id == postId); } + + public async Task DoesPostHaveFiles(Guid postId) + { + return await this._context.Posts + .AsNoTracking() + .Where(x => x.Id == postId) + .Select(x => x.FileUrls) + .AnyAsync(); + } #endregion } } diff --git a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs index d8dcc84..c7466d9 100644 --- a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs @@ -9,7 +9,7 @@ namespace DevHive.Services.Configurations.Mapping public PostMappings() { CreateMap(); - // .ForMember(dest => dest.Files, src => src.Ignore()); + // .ForMember(dest => dest.Files, src => src.Ignore()); CreateMap() .ForMember(dest => dest.Id, src => src.MapFrom(p => p.PostId)) // .ForMember(dest => dest.Files, src => src.Ignore()) @@ -20,7 +20,7 @@ namespace DevHive.Services.Configurations.Mapping .ForMember(dest => dest.CreatorFirstName, src => src.Ignore()) .ForMember(dest => dest.CreatorLastName, src => src.Ignore()) .ForMember(dest => dest.CreatorUsername, src => src.Ignore()); - //TODO: Map those here /\ + //TODO: Map those here /\ } } } diff --git a/src/DevHive.Services/DevHive.Services.csproj b/src/DevHive.Services/DevHive.Services.csproj index 52f0323..66df209 100644 --- a/src/DevHive.Services/DevHive.Services.csproj +++ b/src/DevHive.Services/DevHive.Services.csproj @@ -1,27 +1,29 @@ - - - net5.0 - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - - - - - - - - true - latest - - + + + net5.0 + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + + + + true + latest + + diff --git a/src/DevHive.Services/Interfaces/ICloudService.cs b/src/DevHive.Services/Interfaces/ICloudService.cs new file mode 100644 index 0000000..6616444 --- /dev/null +++ b/src/DevHive.Services/Interfaces/ICloudService.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + +namespace DevHive.Services.Interfaces +{ + public interface ICloudService + { + Task> UploadFilesToCloud(List formFiles); + + Task RemoveFilesFromCloud(List fileUrls); + } +} diff --git a/src/DevHive.Services/Models/Cloud/CloudinaryService.cs b/src/DevHive.Services/Models/Cloud/CloudinaryService.cs new file mode 100644 index 0000000..a9bc9bd --- /dev/null +++ b/src/DevHive.Services/Models/Cloud/CloudinaryService.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using CloudinaryDotNet; +using CloudinaryDotNet.Actions; +using DevHive.Services.Interfaces; +using Microsoft.AspNetCore.Http; + +namespace DevHive.Services.Services +{ + public class CloudinaryService : ICloudService + { + private readonly Cloudinary _cloudinary; + + public CloudinaryService(string cloudName, string apiKey, string apiSecret) + { + this._cloudinary = new Cloudinary(new Account(cloudName, apiKey, apiSecret)); + } + + public async Task> UploadFilesToCloud(List formFiles) + { + List fileUrls = new(); + foreach (var formFile in formFiles) + { + string formFileId = Guid.NewGuid().ToString(); + + if (formFile.Length > 0) + { + using (var ms = new MemoryStream()) + { + formFile.CopyTo(ms); + byte[] formBytes = ms.ToArray(); + + ImageUploadParams imageUploadParams = new() + { + File = new FileDescription(formFileId, new MemoryStream(formBytes)), + PublicId = formFileId + }; + + ImageUploadResult uploadResult = await this._cloudinary.UploadAsync(imageUploadParams); + fileUrls.Add(uploadResult.Url.AbsoluteUri); + } + } + } + + return fileUrls; + } + + public async Task RemoveFilesFromCloud(List fileUrls) + { + return true; + } + } +} diff --git a/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs index 36f6351..8676f6c 100644 --- a/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs +++ b/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using Microsoft.AspNetCore.Http; namespace DevHive.Services.Models.Post.Post { @@ -8,6 +10,6 @@ namespace DevHive.Services.Models.Post.Post public string Message { get; set; } - // public List Files { get; set; } + public List Files { get; set; } } } diff --git a/src/DevHive.Services/Models/Post/Post/ReadPostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/ReadPostServiceModel.cs index 3e673c1..f0a4fe5 100644 --- a/src/DevHive.Services/Models/Post/Post/ReadPostServiceModel.cs +++ b/src/DevHive.Services/Models/Post/Post/ReadPostServiceModel.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using DevHive.Services.Models.Post.Comment; +using Microsoft.Extensions.FileProviders; namespace DevHive.Services.Models.Post.Post { @@ -20,6 +21,6 @@ namespace DevHive.Services.Models.Post.Post public List Comments { get; set; } = new(); - //public List Files { get; set; } + public List Files { get; set; } } } diff --git a/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs index 8924b07..24b0b74 100644 --- a/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs +++ b/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using Microsoft.AspNetCore.Http; namespace DevHive.Services.Models.Post.Post { @@ -10,6 +12,6 @@ namespace DevHive.Services.Models.Post.Post public string NewMessage { get; set; } - // public List Files { get; set; } + public List Files { get; set; } } } diff --git a/src/DevHive.Services/Services/PostService.cs b/src/DevHive.Services/Services/PostService.cs index d80d815..7ce7b58 100644 --- a/src/DevHive.Services/Services/PostService.cs +++ b/src/DevHive.Services/Services/PostService.cs @@ -15,13 +15,15 @@ namespace DevHive.Services.Services { public class PostService : IPostService { + private readonly ICloudService _cloudService; private readonly IUserRepository _userRepository; private readonly IPostRepository _postRepository; private readonly ICommentRepository _commentRepository; private readonly IMapper _postMapper; - public PostService(IUserRepository userRepository, IPostRepository postRepository, ICommentRepository commentRepository, IMapper postMapper) + public PostService(ICloudService cloudService, IUserRepository userRepository, IPostRepository postRepository, ICommentRepository commentRepository, IMapper postMapper) { + this._cloudService = cloudService; this._userRepository = userRepository; this._postRepository = postRepository; this._commentRepository = commentRepository; @@ -35,9 +37,12 @@ namespace DevHive.Services.Services throw new ArgumentException("User does not exist!"); Post post = this._postMapper.Map(createPostServiceModel); - post.TimeCreated = DateTime.Now; + + if (createPostServiceModel.Files.Count != 0) + post.FileUrls = await _cloudService.UploadFilesToCloud(createPostServiceModel.Files); post.Creator = await this._userRepository.GetByIdAsync(createPostServiceModel.CreatorId); + post.TimeCreated = DateTime.Now; bool success = await this._postRepository.AddAsync(post); if (success) @@ -116,9 +121,23 @@ namespace DevHive.Services.Services throw new ArgumentException("Post does not exist!"); Post post = this._postMapper.Map(updatePostServiceModel); - post.TimeCreated = DateTime.Now; + + if (updatePostServiceModel.Files.Count != 0) + { + if (await this._postRepository.DoesPostHaveFiles(updatePostServiceModel.PostId)) + { + List fileUrls = await this._postRepository.GetFileUrls(updatePostServiceModel.PostId); + bool success = await _cloudService.RemoveFilesFromCloud(fileUrls); + if (!success) + throw new InvalidCastException("Could not delete files from the post!"); + } + + post.FileUrls = await _cloudService.UploadFilesToCloud(updatePostServiceModel.Files) ?? + throw new ArgumentNullException("Unable to upload images to cloud"); + } post.Creator = await this._userRepository.GetByIdAsync(updatePostServiceModel.CreatorId); + post.TimeCreated = DateTime.Now; bool result = await this._postRepository.EditAsync(updatePostServiceModel.PostId, post); @@ -155,6 +174,15 @@ namespace DevHive.Services.Services throw new ArgumentException("Post does not exist!"); Post post = await this._postRepository.GetByIdAsync(id); + + if (await this._postRepository.DoesPostHaveFiles(id)) + { + List fileUrls = await this._postRepository.GetFileUrls(id); + bool success = await _cloudService.RemoveFilesFromCloud(fileUrls); + if (!success) + throw new InvalidCastException("Could not delete files from the post. Please try again"); + } + return await this._postRepository.DeleteAsync(post); } diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs index d7c859e..fe2c788 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -3,13 +3,14 @@ using DevHive.Data.Models; using DevHive.Data.Repositories; using DevHive.Services.Interfaces; using DevHive.Services.Services; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace DevHive.Web.Configurations.Extensions { public static class ConfigureDependencyInjection { - public static void DependencyInjectionConfiguration(this IServiceCollection services) + public static void DependencyInjectionConfiguration(this IServiceCollection services, IConfiguration configuration) { services.AddTransient(); services.AddTransient(); @@ -25,6 +26,11 @@ namespace DevHive.Web.Configurations.Extensions services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(options => + new CloudinaryService( + cloudName: configuration.GetSection("Cloud").GetSection("cloudName").Value, + apiKey: configuration.GetSection("Cloud").GetSection("apiKey").Value, + apiSecret: configuration.GetSection("Cloud").GetSection("apiSecret").Value)); } } } diff --git a/src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs b/src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs index b7b4cf4..e35a813 100644 --- a/src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs +++ b/src/DevHive.Web/Models/Post/Post/CreatePostWebModel.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Http; namespace DevHive.Web.Models.Post.Post { @@ -10,6 +12,6 @@ namespace DevHive.Web.Models.Post.Post [Required] public string Message { get; set; } - // public List Files { get; set; } + public List Files { get; set; } } } diff --git a/src/DevHive.Web/Models/Post/Post/ReadPostWebModel.cs b/src/DevHive.Web/Models/Post/Post/ReadPostWebModel.cs index 04c6275..5d4da31 100644 --- a/src/DevHive.Web/Models/Post/Post/ReadPostWebModel.cs +++ b/src/DevHive.Web/Models/Post/Post/ReadPostWebModel.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using DevHive.Web.Models.Post.Comment; +using Microsoft.AspNetCore.Http; namespace DevHive.Web.Models.Post.Post { @@ -20,6 +21,6 @@ namespace DevHive.Web.Models.Post.Post public List Comments { get; set; } - //public Files[] Files { get; set; } + public List Files { get; set; } } } diff --git a/src/DevHive.Web/Models/Post/Post/UpdatePostWebModel.cs b/src/DevHive.Web/Models/Post/Post/UpdatePostWebModel.cs index 685f08b..ac84d2c 100644 --- a/src/DevHive.Web/Models/Post/Post/UpdatePostWebModel.cs +++ b/src/DevHive.Web/Models/Post/Post/UpdatePostWebModel.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Http; namespace DevHive.Web.Models.Post.Post { @@ -13,5 +15,7 @@ namespace DevHive.Web.Models.Post.Post [NotNull] [Required] public string NewMessage { get; set; } + + public List Files { get; set; } = new(); } } diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index 92d4359..dd7e852 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -32,7 +32,7 @@ namespace DevHive.Web services.SwaggerConfiguration(); services.JWTConfiguration(Configuration); services.AutoMapperConfiguration(); - services.DependencyInjectionConfiguration(); + services.DependencyInjectionConfiguration(this.Configuration); services.ExceptionHandlerMiddlewareConfiguration(); } diff --git a/src/DevHive.Web/appsettings.json b/src/DevHive.Web/appsettings.json index 83932a7..bcdcae7 100644 --- a/src/DevHive.Web/appsettings.json +++ b/src/DevHive.Web/appsettings.json @@ -4,7 +4,12 @@ }, "ConnectionStrings": { "DEV": "Server=localhost;Port=5432;Database=API;User Id=postgres;Password=;" - }, + }, + "Cloud": { + "cloudName": "devhive", + "apiKey": "488664116365813", + "apiSecret": "" + }, "Logging": { "LogLevel": { "Default": "Information", -- cgit v1.2.3 From 8b62011960ce88d722c64b72af6837c2e2dbcda5 Mon Sep 17 00:00:00 2001 From: transtrike Date: Fri, 5 Feb 2021 19:02:35 +0200 Subject: Friends relation FUCKING FINALLY FIXED, NIGGA --- src/DevHive.Data/DevHiveContext.cs | 15 - .../Interfaces/Repositories/IUserRepository.cs | 5 +- .../20210205150447_Friends_Init_Config.Designer.cs | 643 +++++++++++++++++++++ .../20210205150447_Friends_Init_Config.cs | 45 ++ .../20210205160520_Friends_First_Tweek.Designer.cs | 609 +++++++++++++++++++ .../20210205160520_Friends_First_Tweek.cs | 46 ++ .../Migrations/DevHiveContextModelSnapshot.cs | 43 +- src/DevHive.Data/Models/User.cs | 4 +- src/DevHive.Data/RelationModels/UserFriend.cs | 17 - src/DevHive.Data/Repositories/UserRepository.cs | 73 +-- .../Configurations/Mapping/UserMappings.cs | 17 +- src/DevHive.Services/Services/UserService.cs | 102 ++-- .../Configurations/Extensions/ConfigureDatabase.cs | 3 - src/DevHive.Web/Startup.cs | 1 - 14 files changed, 1415 insertions(+), 208 deletions(-) create mode 100644 src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs create mode 100644 src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs create mode 100644 src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs create mode 100644 src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs delete mode 100644 src/DevHive.Data/RelationModels/UserFriend.cs (limited to 'src/DevHive.Web/Startup.cs') diff --git a/src/DevHive.Data/DevHiveContext.cs b/src/DevHive.Data/DevHiveContext.cs index 0b81f92..9de33c3 100644 --- a/src/DevHive.Data/DevHiveContext.cs +++ b/src/DevHive.Data/DevHiveContext.cs @@ -16,7 +16,6 @@ namespace DevHive.Data public DbSet Posts { get; set; } public DbSet PostAttachments { get; set; } public DbSet Comments { get; set; } - public DbSet UserFriends { get; set; } public DbSet Rating { get; set; } public DbSet RatedPost { get; set; } public DbSet UserRate { get; set; } @@ -38,20 +37,6 @@ namespace DevHive.Data .HasMany(x => x.Roles) .WithMany(x => x.Users); - /* Friends */ - builder.Entity() - .HasKey(x => new { x.UserId, x.FriendId }); - - builder.Entity() - .HasOne(x => x.User) - .WithMany(x => x.MyFriends) - .HasForeignKey(x => x.UserId); - - builder.Entity() - .HasOne(x => x.Friend) - .WithMany(x => x.FriendsOf) - .HasForeignKey(x => x.FriendId); - /* Languages */ builder.Entity() .HasMany(x => x.Languages) diff --git a/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs b/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs index 5b6ab9e..5ebe3d3 100644 --- a/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs +++ b/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs @@ -10,14 +10,13 @@ namespace DevHive.Data.Interfaces.Repositories { //Read Task GetByUsernameAsync(string username); - IEnumerable QueryAll(); Task UpdateProfilePicture(Guid userId, string pictureUrl); //Validations + Task ValidateFriendsCollectionAsync(List usernames); Task DoesEmailExistAsync(string email); Task DoesUserExistAsync(Guid id); - Task DoesUserHaveThisFriendAsync(Guid userId, Guid friendId); - bool DoesUserHaveThisUsername(Guid id, string username); Task DoesUsernameExistAsync(string username); + bool DoesUserHaveThisUsername(Guid id, string username); } } diff --git a/src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs b/src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs new file mode 100644 index 0000000..c11374a --- /dev/null +++ b/src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs @@ -0,0 +1,643 @@ +// +using System; +using System.Collections.Generic; +using DevHive.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Data.Migrations +{ + [DbContext(typeof(DevHiveContext))] + [Migration("20210205150447_Friends_Init_Config")] + partial class Friends_Init_Config + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .UseIdentityByDefaultColumns() + .HasAnnotation("Relational:MaxIdentifierLength", 63) + .HasAnnotation("ProductVersion", "5.0.1"); + + modelBuilder.Entity("DevHive.Data.Models.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatorId") + .HasColumnType("uuid"); + + b.Property("Message") + .HasColumnType("text"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.Property("TimeCreated") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatorId"); + + b.HasIndex("PostId"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Language", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Languages"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatorId") + .HasColumnType("uuid"); + + b.Property>("FileUrls") + .HasColumnType("text[]"); + + b.Property("Message") + .HasColumnType("text"); + + b.Property("TimeCreated") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatorId"); + + b.ToTable("Posts"); + }); + + modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PictureURL") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("ProfilePicture"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Rating", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Rating"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Technologies"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("FirstName") + .HasColumnType("text"); + + b.Property("LastName") + .HasColumnType("text"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.HasIndex("UserId"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("AspNetUsers"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "PostId"); + + b.HasIndex("PostId"); + + b.ToTable("RatedPosts"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.UserFriend", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("FriendId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "FriendId"); + + b.HasIndex("FriendId"); + + b.ToTable("UserFriends"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Rate") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserRates"); + }); + + modelBuilder.Entity("LanguageUser", b => + { + b.Property("LanguagesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("LanguagesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("LanguageUser"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.Property("RolesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("RolesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("RoleUser"); + }); + + modelBuilder.Entity("TechnologyUser", b => + { + b.Property("TechnologiesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("TechnologiesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("TechnologyUser"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Comment", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Comments") + .HasForeignKey("CreatorId"); + + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany("Comments") + .HasForeignKey("PostId"); + + b.Navigation("Creator"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Posts") + .HasForeignKey("CreatorId"); + + b.Navigation("Creator"); + }); + + modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => + { + b.HasOne("DevHive.Data.Models.User", "User") + .WithOne("ProfilePicture") + .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Friends") + .HasForeignKey("UserId"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.UserFriend", b => + { + b.HasOne("DevHive.Data.Models.User", "Friend") + .WithMany() + .HasForeignKey("FriendId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Friend"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => + { + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany() + .HasForeignKey("UserId"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("LanguageUser", b => + { + b.HasOne("DevHive.Data.Models.Language", null) + .WithMany() + .HasForeignKey("LanguagesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RolesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TechnologyUser", b => + { + b.HasOne("DevHive.Data.Models.Technology", null) + .WithMany() + .HasForeignKey("TechnologiesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.Navigation("Comments"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Navigation("Comments"); + + b.Navigation("Friends"); + + b.Navigation("Posts"); + + b.Navigation("ProfilePicture"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs b/src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs new file mode 100644 index 0000000..1fc970d --- /dev/null +++ b/src/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs @@ -0,0 +1,45 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DevHive.Data.Migrations +{ + public partial class Friends_Init_Config : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "UserId", + table: "AspNetUsers", + type: "uuid", + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUsers_UserId", + table: "AspNetUsers", + column: "UserId"); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUsers_AspNetUsers_UserId", + table: "AspNetUsers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_AspNetUsers_AspNetUsers_UserId", + table: "AspNetUsers"); + + migrationBuilder.DropIndex( + name: "IX_AspNetUsers_UserId", + table: "AspNetUsers"); + + migrationBuilder.DropColumn( + name: "UserId", + table: "AspNetUsers"); + } + } +} diff --git a/src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs b/src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs new file mode 100644 index 0000000..3ad3ec8 --- /dev/null +++ b/src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs @@ -0,0 +1,609 @@ +// +using System; +using System.Collections.Generic; +using DevHive.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Data.Migrations +{ + [DbContext(typeof(DevHiveContext))] + [Migration("20210205160520_Friends_First_Tweek")] + partial class Friends_First_Tweek + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .UseIdentityByDefaultColumns() + .HasAnnotation("Relational:MaxIdentifierLength", 63) + .HasAnnotation("ProductVersion", "5.0.1"); + + modelBuilder.Entity("DevHive.Data.Models.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatorId") + .HasColumnType("uuid"); + + b.Property("Message") + .HasColumnType("text"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.Property("TimeCreated") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatorId"); + + b.HasIndex("PostId"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Language", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Languages"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatorId") + .HasColumnType("uuid"); + + b.Property>("FileUrls") + .HasColumnType("text[]"); + + b.Property("Message") + .HasColumnType("text"); + + b.Property("TimeCreated") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatorId"); + + b.ToTable("Posts"); + }); + + modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PictureURL") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("ProfilePicture"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Rating", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Rating"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Technologies"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("FirstName") + .HasColumnType("text"); + + b.Property("LastName") + .HasColumnType("text"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.HasIndex("UserId"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("AspNetUsers"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "PostId"); + + b.HasIndex("PostId"); + + b.ToTable("RatedPosts"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Rate") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserRates"); + }); + + modelBuilder.Entity("LanguageUser", b => + { + b.Property("LanguagesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("LanguagesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("LanguageUser"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .UseIdentityByDefaultColumn(); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.Property("RolesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("RolesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("RoleUser"); + }); + + modelBuilder.Entity("TechnologyUser", b => + { + b.Property("TechnologiesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("TechnologiesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("TechnologyUser"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Comment", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Comments") + .HasForeignKey("CreatorId"); + + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany("Comments") + .HasForeignKey("PostId"); + + b.Navigation("Creator"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Posts") + .HasForeignKey("CreatorId"); + + b.Navigation("Creator"); + }); + + modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => + { + b.HasOne("DevHive.Data.Models.User", "User") + .WithOne("ProfilePicture") + .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Friends") + .HasForeignKey("UserId"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => + { + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany() + .HasForeignKey("UserId"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("LanguageUser", b => + { + b.HasOne("DevHive.Data.Models.Language", null) + .WithMany() + .HasForeignKey("LanguagesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.HasOne("DevHive.Data.Models.Role", null) + .WithMany() + .HasForeignKey("RolesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TechnologyUser", b => + { + b.HasOne("DevHive.Data.Models.Technology", null) + .WithMany() + .HasForeignKey("TechnologiesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.Navigation("Comments"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Navigation("Comments"); + + b.Navigation("Friends"); + + b.Navigation("Posts"); + + b.Navigation("ProfilePicture"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs b/src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs new file mode 100644 index 0000000..565f863 --- /dev/null +++ b/src/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DevHive.Data.Migrations +{ + public partial class Friends_First_Tweek : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserFriends"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "UserFriends", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + FriendId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_UserFriends", x => new { x.UserId, x.FriendId }); + table.ForeignKey( + name: "FK_UserFriends_AspNetUsers_FriendId", + column: x => x.FriendId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserFriends_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserFriends_FriendId", + table: "UserFriends", + column: "FriendId"); + } + } +} diff --git a/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs index 6e0a03a..dc5739c 100644 --- a/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs +++ b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs @@ -218,6 +218,9 @@ namespace DevHive.Data.Migrations b.Property("TwoFactorEnabled") .HasColumnType("boolean"); + b.Property("UserId") + .HasColumnType("uuid"); + b.Property("UserName") .HasMaxLength(256) .HasColumnType("character varying(256)"); @@ -231,6 +234,8 @@ namespace DevHive.Data.Migrations .IsUnique() .HasDatabaseName("UserNameIndex"); + b.HasIndex("UserId"); + b.HasIndex("UserName") .IsUnique(); @@ -271,21 +276,6 @@ namespace DevHive.Data.Migrations b.ToTable("RatedPosts"); }); - modelBuilder.Entity("DevHive.Data.RelationModels.UserFriend", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("FriendId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "FriendId"); - - b.HasIndex("FriendId"); - - b.ToTable("UserFriends"); - }); - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => { b.Property("Id") @@ -530,25 +520,6 @@ namespace DevHive.Data.Migrations b.Navigation("User"); }); - modelBuilder.Entity("DevHive.Data.RelationModels.UserFriend", b => - { - b.HasOne("DevHive.Data.Models.User", "Friend") - .WithMany("FriendsOf") - .HasForeignKey("FriendId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany("MyFriends") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Friend"); - - b.Navigation("User"); - }); - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => { b.HasOne("DevHive.Data.Models.Post", "Post") @@ -673,9 +644,7 @@ namespace DevHive.Data.Migrations { b.Navigation("Comments"); - b.Navigation("FriendsOf"); - - b.Navigation("MyFriends"); + b.Navigation("Friends"); b.Navigation("Posts"); diff --git a/src/DevHive.Data/Models/User.cs b/src/DevHive.Data/Models/User.cs index f666677..983d073 100644 --- a/src/DevHive.Data/Models/User.cs +++ b/src/DevHive.Data/Models/User.cs @@ -24,9 +24,7 @@ namespace DevHive.Data.Models public HashSet Posts { get; set; } = new(); - public HashSet MyFriends { get; set; } = new(); - - public HashSet FriendsOf { get; set; } = new(); + public HashSet Friends { get; set; } = new(); public HashSet Comments { get; set; } = new(); diff --git a/src/DevHive.Data/RelationModels/UserFriend.cs b/src/DevHive.Data/RelationModels/UserFriend.cs deleted file mode 100644 index 32a00d4..0000000 --- a/src/DevHive.Data/RelationModels/UserFriend.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using DevHive.Data.Models; - -namespace DevHive.Data.RelationModels -{ - [Table("UserFriends")] - public class UserFriend - { - public Guid UserId { get; set; } - public User User { get; set; } - - public Guid FriendId { get; set; } - public User Friend { get; set; } - } -} diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index ed8db49..6e97e60 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -23,14 +23,6 @@ namespace DevHive.Data.Repositories } #region Read - public IEnumerable QueryAll() - { - return this._context.Users - .Include(x => x.Roles) - .AsNoTracking() - .AsEnumerable(); - } - public override async Task GetByIdAsync(Guid id) { return await this._context.Users @@ -38,8 +30,7 @@ namespace DevHive.Data.Repositories .Include(x => x.Languages) .Include(x => x.Technologies) .Include(x => x.Posts) - .Include(x => x.MyFriends) - .Include(x => x.FriendsOf) + .Include(x => x.Friends) .Include(x => x.ProfilePicture) .FirstOrDefaultAsync(x => x.Id == id); } @@ -51,56 +42,15 @@ namespace DevHive.Data.Repositories .Include(x => x.Languages) .Include(x => x.Technologies) .Include(x => x.Posts) - .Include(x => x.MyFriends) - .Include(x => x.FriendsOf) + .Include(x => x.Friends) .Include(x => x.ProfilePicture) .FirstOrDefaultAsync(x => x.UserName == username); } #endregion #region Update - public override async Task EditAsync(Guid id, User newEntity) + public async Task UpdateProfilePicture(Guid userId, string pictureUrl) { - User user = await this.GetByIdAsync(id); - - this._context - .Entry(user) - .CurrentValues - .SetValues(newEntity); - - HashSet languages = new(); - foreach (var lang in newEntity.Languages) - languages.Add(lang); - user.Languages = languages; - - HashSet roles = new(); - foreach (var role in newEntity.Roles) - roles.Add(role); - user.Roles = roles; - - foreach (var friend in newEntity.MyFriends) - { - user.MyFriends.Add(friend); - this._context.Entry(friend).State = EntityState.Modified; - } - - foreach (var friend in newEntity.FriendsOf) - { - user.FriendsOf.Add(friend); - this._context.Entry(friend).State = EntityState.Modified; - } - - HashSet technologies = new(); - foreach (var tech in newEntity.Technologies) - technologies.Add(tech); - user.Technologies = technologies; - - this._context.Entry(user).State = EntityState.Modified; - - return await this.SaveChangesAsync(); - } - - public async Task UpdateProfilePicture(Guid userId, string pictureUrl) { User user = await this.GetByIdAsync(userId); user.ProfilePicture.PictureURL = pictureUrl; @@ -131,14 +81,19 @@ namespace DevHive.Data.Repositories .AnyAsync(u => u.Email == email); } - public async Task DoesUserHaveThisFriendAsync(Guid userId, Guid friendId) + public async Task ValidateFriendsCollectionAsync(List usernames) { - return true; - // User user = await this.GetByIdAsync(userId); + bool valid = true; - // User friend = await this.GetByIdAsync(friendId); - - // return user.Friends.Any(x => x.Friend.Id == friendId); + foreach (var username in usernames) + { + if (!await this._context.Users.AnyAsync(x => x.UserName == username)) + { + valid = false; + break; + } + } + return valid; } public bool DoesUserHaveThisUsername(Guid id, string username) diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index 6922cd7..2b0f4ed 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -12,27 +12,20 @@ namespace DevHive.Services.Configurations.Mapping { CreateMap(); CreateMap(); - CreateMap(); - // .ForMember(dest => dest.Friends, src => src.Ignore()); - CreateMap() - .ForMember(dest => dest.UserName, src => src.MapFrom(p => p.Friend.UserName)); + CreateMap() + .ForMember(dest => dest.Friends, src => src.Ignore()); CreateMap() - // .ForMember(dest => dest.Friends, src => src.Ignore()) + .ForMember(dest => dest.Friends, src => src.Ignore()) .AfterMap((src, dest) => dest.PasswordHash = PasswordModifications.GeneratePasswordHash(src.Password)); CreateMap(); CreateMap() - .ForMember(dest => dest.Friends, src => src.MapFrom(p => p.MyFriends)) - .ForMember(dest => dest.ProfilePictureURL, src => src.MapFrom(p => p.ProfilePicture.PictureURL)); - // .ForMember(dest => dest.Friends, src => src.MapFrom(p => p.Friends)); + .ForMember(dest => dest.ProfilePictureURL, src => src.MapFrom(p => p.ProfilePicture.PictureURL)) + .ForMember(dest => dest.Friends, src => src.MapFrom(p => p.Friends)); CreateMap() .ForMember(x => x.Password, opt => opt.Ignore()) .ForMember(dest => dest.ProfilePictureURL, src => src.MapFrom(p => p.ProfilePicture.PictureURL)); CreateMap(); - - CreateMap() - .ForMember(dest => dest.UserName, src => src.MapFrom(p => p.Friend.UserName)) - .ForMember(dest => dest.Id, src => src.MapFrom(p => p.FriendId)); } } } diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 9cc4a8e..8f9ebc4 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -14,8 +14,8 @@ using DevHive.Services.Interfaces; using DevHive.Data.Interfaces.Repositories; using System.Linq; using DevHive.Common.Models.Misc; -using DevHive.Data.RelationModels; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; namespace DevHive.Services.Services { @@ -25,6 +25,8 @@ namespace DevHive.Services.Services private readonly IRoleRepository _roleRepository; private readonly ILanguageRepository _languageRepository; private readonly ITechnologyRepository _technologyRepository; + private readonly UserManager _userManager; + private readonly RoleManager _roleManager; private readonly IMapper _userMapper; private readonly JWTOptions _jwtOptions; private readonly ICloudService _cloudService; @@ -33,6 +35,8 @@ namespace DevHive.Services.Services ILanguageRepository languageRepository, IRoleRepository roleRepository, ITechnologyRepository technologyRepository, + UserManager userManager, + RoleManager roleManager, IMapper mapper, JWTOptions jwtOptions, ICloudService cloudService) @@ -43,6 +47,8 @@ namespace DevHive.Services.Services this._jwtOptions = jwtOptions; this._languageRepository = languageRepository; this._technologyRepository = technologyRepository; + this._userManager = userManager; + this._roleManager = roleManager; this._cloudService = cloudService; } @@ -77,20 +83,22 @@ namespace DevHive.Services.Services User user = this._userMapper.Map(registerModel); user.PasswordHash = PasswordModifications.GeneratePasswordHash(registerModel.Password); - user.ProfilePicture = new ProfilePicture() { PictureURL = "/assets/images/feed/profile-pic.png" }; + user.ProfilePicture = new ProfilePicture() { PictureURL = string.Empty }; // Make sure the default role exists //TODO: Move when project starts if (!await this._roleRepository.DoesNameExist(Role.DefaultRole)) await this._roleRepository.AddAsync(new Role { Name = Role.DefaultRole }); - // Set the default role to the user - Role defaultRole = await this._roleRepository.GetByNameAsync(Role.DefaultRole); - user.Roles.Add(defaultRole); + user.Roles.Add(await this._roleRepository.GetByNameAsync(Role.DefaultRole)); - await this._userRepository.AddAsync(user); + IdentityResult userResult = await this._userManager.CreateAsync(user); + User createdUser = await this._userRepository.GetByUsernameAsync(registerModel.UserName); - return new TokenModel(WriteJWTSecurityToken(user.Id, user.UserName, user.Roles)); + if (!userResult.Succeeded) + throw new ArgumentException("Unable to create a user"); + + return new TokenModel(WriteJWTSecurityToken(createdUser.Id, createdUser.UserName, createdUser.Roles)); } #endregion @@ -105,9 +113,7 @@ namespace DevHive.Services.Services public async Task GetUserByUsername(string username) { - User user = await this._userRepository.GetByUsernameAsync(username); - - if (user == null) + User user = await this._userRepository.GetByUsernameAsync(username) ?? throw new ArgumentException("User does not exist!"); return this._userMapper.Map(user); @@ -119,16 +125,17 @@ namespace DevHive.Services.Services { await this.ValidateUserOnUpdate(updateUserServiceModel); - User user = await this.PopulateModel(updateUserServiceModel); + User currentUser = await this._userRepository.GetByIdAsync(updateUserServiceModel.Id); + await this.PopulateUserModel(currentUser, updateUserServiceModel); - await this.CreateRelationToFriends(user, updateUserServiceModel.Friends.ToList()); + await this.CreateRelationToFriends(currentUser, updateUserServiceModel.Friends.ToList()); - bool successful = await this._userRepository.EditAsync(updateUserServiceModel.Id, user); + IdentityResult result = await this._userManager.UpdateAsync(currentUser); - if (!successful) + if (!result.Succeeded) throw new InvalidOperationException("Unable to edit user!"); - User newUser = await this._userRepository.GetByIdAsync(user.Id); + User newUser = await this._userRepository.GetByIdAsync(currentUser.Id); return this._userMapper.Map(newUser); } @@ -139,7 +146,7 @@ namespace DevHive.Services.Services { User user = await this._userRepository.GetByIdAsync(updateProfilePictureServiceModel.UserId); - if (!String.IsNullOrEmpty(user.ProfilePicture.PictureURL)) + if (!string.IsNullOrEmpty(user.ProfilePicture.PictureURL)) { bool success = await _cloudService.RemoveFilesFromCloud(new List { user.ProfilePicture.PictureURL }); if (!success) @@ -165,9 +172,9 @@ namespace DevHive.Services.Services throw new ArgumentException("User does not exist!"); User user = await this._userRepository.GetByIdAsync(id); - bool result = await this._userRepository.DeleteAsync(user); + IdentityResult result = await this._userManager.DeleteAsync(user); - return result; + return result.Succeeded; } #endregion @@ -233,9 +240,19 @@ namespace DevHive.Services.Services if (!await this._userRepository.DoesUserExistAsync(updateUserServiceModel.Id)) throw new ArgumentException("User does not exist!"); + if (updateUserServiceModel.Friends.Any(x => x.UserName == updateUserServiceModel.UserName)) + throw new ArgumentException("You cant add yourself as a friend(sry, bro)!"); + if (!this._userRepository.DoesUserHaveThisUsername(updateUserServiceModel.Id, updateUserServiceModel.UserName) && await this._userRepository.DoesUsernameExistAsync(updateUserServiceModel.UserName)) throw new ArgumentException("Username already exists!"); + + List usernames = new(); + foreach (var friend in updateUserServiceModel.Friends) + usernames.Add(friend.UserName); + + if (!await this._userRepository.ValidateFriendsCollectionAsync(usernames)) + throw new ArgumentException("One or more friends do not exist!"); } /// @@ -288,29 +305,20 @@ namespace DevHive.Services.Services await this._roleRepository.AddAsync(adminRole); } - Role admin = await this._roleRepository.GetByNameAsync(Role.AdminRole); + Role admin = await this._roleManager.FindByNameAsync(Role.AdminRole); user.Roles.Add(admin); - await this._userRepository.EditAsync(user.Id, user); + await this._userManager.UpdateAsync(user); User newUser = await this._userRepository.GetByIdAsync(userId); return new TokenModel(WriteJWTSecurityToken(newUser.Id, newUser.UserName, newUser.Roles)); } - /// - /// Returns the user with the Id in the model, adding to him the roles, languages and technologies, specified by the parameter model. - /// This practically maps HashSet to HashSet (and the equvalent HashSets for Languages and Technologies) - /// and assigns the latter to the returned user. - /// - private async Task PopulateModel(UpdateUserServiceModel updateUserServiceModel) + private async Task PopulateUserModel(User user, UpdateUserServiceModel updateUserServiceModel) { - User user = this._userMapper.Map(updateUserServiceModel); - - /* Fetch Roles and replace model's*/ //Do NOT allow a user to change his roles, unless he is an Admin - bool isAdmin = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id)) - .Roles.Any(r => r.Name == Role.AdminRole); + bool isAdmin = await this._userManager.IsInRoleAsync(user, Role.AdminRole); if (isAdmin) { @@ -324,11 +332,7 @@ namespace DevHive.Services.Services } user.Roles = roles; } - //Preserve original user roles - else - user.Roles = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id)).Roles; - /* Fetch Languages and replace model's*/ HashSet languages = new(); int languagesCount = updateUserServiceModel.Languages.Count; for (int i = 0; i < languagesCount; i++) @@ -351,37 +355,19 @@ namespace DevHive.Services.Services technologies.Add(technology); } user.Technologies = technologies; - - return user; } - private async Task CreateRelationToFriends(User user, List friends) + private async Task CreateRelationToFriends(User user, List friends) { foreach (var friend in friends) { - User amigo = await this._userRepository.GetByUsernameAsync(friend.UserName) ?? - throw new ArgumentException("No amigo, bro!"); - - UserFriend relation = new() - { - UserId = user.Id, - User = user, - FriendId = amigo.Id, - Friend = amigo - }; + User amigo = await this._userRepository.GetByUsernameAsync(friend.UserName); - UserFriend theOtherRelation = new() - { - UserId = amigo.Id, - User = amigo, - FriendId = user.Id, - Friend = user - }; + user.Friends.Add(amigo); + amigo.Friends.Add(user); - user.MyFriends.Add(relation); - user.FriendsOf.Add(theOtherRelation); + await this._userManager.UpdateAsync(amigo); } - return true; } #endregion } diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 3748edf..9f02dd7 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using DevHive.Data.Repositories; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using DevHive.Data.Models; @@ -8,8 +7,6 @@ using Microsoft.AspNetCore.Builder; using System; using Microsoft.AspNetCore.Authentication.JwtBearer; using DevHive.Data; -using Microsoft.AspNetCore.Authorization; -using System.Collections.Generic; namespace DevHive.Web.Configurations.Extensions { diff --git a/src/DevHive.Web/Startup.cs b/src/DevHive.Web/Startup.cs index dd7e852..46521cf 100644 --- a/src/DevHive.Web/Startup.cs +++ b/src/DevHive.Web/Startup.cs @@ -33,7 +33,6 @@ namespace DevHive.Web services.JWTConfiguration(Configuration); services.AutoMapperConfiguration(); services.DependencyInjectionConfiguration(this.Configuration); - services.ExceptionHandlerMiddlewareConfiguration(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. -- cgit v1.2.3