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.Services/Models/Identity/LoginServiceModel.cs | 8 ++++++++ src/DevHive.Services/Models/Identity/RegisterServiceModel.cs | 11 +++++++++++ .../Models/Identity/UpdateUserServiceModel.cs | 9 +++++++++ src/DevHive.Services/Models/Identity/UserServiceModel.cs | 11 +++++++++++ 4 files changed, 39 insertions(+) create mode 100644 src/DevHive.Services/Models/Identity/LoginServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/RegisterServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/UserServiceModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Models/Identity/LoginServiceModel.cs b/src/DevHive.Services/Models/Identity/LoginServiceModel.cs new file mode 100644 index 0000000..d056f9a --- /dev/null +++ b/src/DevHive.Services/Models/Identity/LoginServiceModel.cs @@ -0,0 +1,8 @@ +namespace DevHive.Services.Models.Identity +{ + public class LoginServiceModel + { + public string UserName { get; set; } + public string Password { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/RegisterServiceModel.cs b/src/DevHive.Services/Models/Identity/RegisterServiceModel.cs new file mode 100644 index 0000000..45f42d2 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/RegisterServiceModel.cs @@ -0,0 +1,11 @@ +namespace DevHive.Services.Models.Identity +{ + public class RegisterServiceModel + { + public string UserName { get; set; } + public string Email { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Password { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs new file mode 100644 index 0000000..94600ae --- /dev/null +++ b/src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Services.Models.Identity +{ + public class UpdateUserServiceModel : UserServiceModel + { + public Guid Id { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Identity/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/UserServiceModel.cs new file mode 100644 index 0000000..387afdd --- /dev/null +++ b/src/DevHive.Services/Models/Identity/UserServiceModel.cs @@ -0,0 +1,11 @@ +namespace DevHive.Services.Models.Identity +{ + public class UserServiceModel + { + public string UserName { get; set; } + public string Email { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Role { get; set;} + } +} -- cgit v1.2.3 From 89734a6561532e8ab9a657fc6417747d837cea99 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 15 Dec 2020 10:27:55 +0200 Subject: Moved user service models into their own folder and updated their namespaces --- src/DevHive.Services/Models/Identity/LoginServiceModel.cs | 8 -------- src/DevHive.Services/Models/Identity/RegisterServiceModel.cs | 11 ----------- .../Models/Identity/UpdateUserServiceModel.cs | 9 --------- .../Models/Identity/User/LoginServiceModel.cs | 8 ++++++++ .../Models/Identity/User/RegisterServiceModel.cs | 11 +++++++++++ .../Models/Identity/User/UpdateUserServiceModel.cs | 9 +++++++++ src/DevHive.Services/Models/Identity/User/UserServiceModel.cs | 11 +++++++++++ src/DevHive.Services/Models/Identity/UserServiceModel.cs | 11 ----------- 8 files changed, 39 insertions(+), 39 deletions(-) delete mode 100644 src/DevHive.Services/Models/Identity/LoginServiceModel.cs delete mode 100644 src/DevHive.Services/Models/Identity/RegisterServiceModel.cs delete mode 100644 src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/User/LoginServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/User/UserServiceModel.cs delete mode 100644 src/DevHive.Services/Models/Identity/UserServiceModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Models/Identity/LoginServiceModel.cs b/src/DevHive.Services/Models/Identity/LoginServiceModel.cs deleted file mode 100644 index d056f9a..0000000 --- a/src/DevHive.Services/Models/Identity/LoginServiceModel.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace DevHive.Services.Models.Identity -{ - public class LoginServiceModel - { - public string UserName { get; set; } - public string Password { get; set; } - } -} diff --git a/src/DevHive.Services/Models/Identity/RegisterServiceModel.cs b/src/DevHive.Services/Models/Identity/RegisterServiceModel.cs deleted file mode 100644 index 45f42d2..0000000 --- a/src/DevHive.Services/Models/Identity/RegisterServiceModel.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace DevHive.Services.Models.Identity -{ - public class RegisterServiceModel - { - public string UserName { get; set; } - public string Email { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string Password { get; set; } - } -} diff --git a/src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs deleted file mode 100644 index 94600ae..0000000 --- a/src/DevHive.Services/Models/Identity/UpdateUserServiceModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace DevHive.Services.Models.Identity -{ - public class UpdateUserServiceModel : UserServiceModel - { - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/src/DevHive.Services/Models/Identity/User/LoginServiceModel.cs b/src/DevHive.Services/Models/Identity/User/LoginServiceModel.cs new file mode 100644 index 0000000..4d53283 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/LoginServiceModel.cs @@ -0,0 +1,8 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class LoginServiceModel + { + public string UserName { get; set; } + public string Password { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs new file mode 100644 index 0000000..f0b343a --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs @@ -0,0 +1,11 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class RegisterServiceModel + { + public string UserName { get; set; } + public string Email { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Password { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs new file mode 100644 index 0000000..96d1ff0 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Services.Models.Identity.User +{ + public class UpdateUserServiceModel : UserServiceModel + { + public Guid Id { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs new file mode 100644 index 0000000..f01d13c --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -0,0 +1,11 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class UserServiceModel + { + public string UserName { get; set; } + public string Email { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Role { get; set;} + } +} diff --git a/src/DevHive.Services/Models/Identity/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/UserServiceModel.cs deleted file mode 100644 index 387afdd..0000000 --- a/src/DevHive.Services/Models/Identity/UserServiceModel.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace DevHive.Services.Models.Identity -{ - public class UserServiceModel - { - public string UserName { get; set; } - public string Email { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string Role { get; set;} - } -} -- cgit v1.2.3 From 1f84b7d7da1464fab8178188f97164e4718527ed Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 15 Dec 2020 11:02:54 +0200 Subject: Updated role controller and role service to use custom models and implemented role mapping --- .../Models/Identity/Role/RoleServiceModel.cs | 10 +++++++ src/DevHive.Services/Services/RoleService.cs | 20 ++++++++++--- .../Configurations/Mapping/RoleMappings.cs | 15 ++++++++++ src/DevHive.Web/Controllers/RoleController.cs | 34 ++++++++++++++++------ .../Models/Identity/Role/UpdateRoleWebModel.cs | 4 ++- 5 files changed, 69 insertions(+), 14 deletions(-) create mode 100644 src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs create mode 100644 src/DevHive.Web/Configurations/Mapping/RoleMappings.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs new file mode 100644 index 0000000..3f834ef --- /dev/null +++ b/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs @@ -0,0 +1,10 @@ +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/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index 202c611..9077a47 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -1,26 +1,38 @@ using System; using System.Threading.Tasks; using DevHive.Data.Repositories; +using DevHive.Services.Models.Identity.Role; +using Microsoft.AspNetCore.Mvc; namespace DevHive.Services.Services { public class RoleService { - /* private readonly DevHiveContext _context; + private readonly DevHiveContext _context; public RoleService(DevHiveContext context) { this._context = context; } - public Task CreatePost(string name) + public Task CreateRole(RoleServiceModel roleServiceModel) { throw new NotImplementedException(); } - public Task GetPostById(uint postId) + public Task GetRoleById(Guid id) { throw new NotImplementedException(); - }*/ + } + + public Task UpdateRole(RoleServiceModel roleServiceModel) + { + throw new NotImplementedException(); + } + + public Task DeleteRole(Guid id) + { + throw new NotImplementedException(); + } } } diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs new file mode 100644 index 0000000..9ccb7d7 --- /dev/null +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -0,0 +1,15 @@ +using AutoMapper; +using DevHive.Web.Models.Identity.Role; +using DevHive.Services.Models.Identity.Role; + +namespace DevHive.Web.Configurations.Mapping +{ + public class RoleMappings : Profile + { + public RoleMappings() + { + CreateMap(); + CreateMap(); + } + } +} diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index fda8bb2..e39d858 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -1,34 +1,50 @@ -using System; using System.Threading.Tasks; using DevHive.Data.Repositories; using DevHive.Services.Services; using Microsoft.AspNetCore.Mvc; +using DevHive.Web.Models.Identity.Role; +using AutoMapper; +using DevHive.Services.Models.Identity.Role; +using System; namespace DevHive.Web.Controllers { - [ApiController] + [ApiController] [Route("/api/[controller]")] public class RoleController { private readonly RoleService _service; + private readonly IMapper _roleMapper; public RoleController(DevHiveContext context) { - //this._service = new RoleService(context); + this._service = new RoleService(context); } [HttpPost] - public Task Create(string name) + public Task Create(CreateRoleWebModel createRoleWebModel) { - //return this._service.CreatePost(name); - throw new NotImplementedException(); + RoleServiceModel roleServiceModel = this._roleMapper.Map(createRoleWebModel); + return this._service.CreateRole(roleServiceModel); } [HttpGet] - public Task ShowPost(uint postId) + public Task Get(Guid id) + { + return this._service.GetRoleById(id); + } + + [HttpPut] + public Task Update(UpdateRoleWebModel updateRoleWebModel) + { + RoleServiceModel roleServiceModel = this._roleMapper.Map(updateRoleWebModel); + return this._service.UpdateRole(roleServiceModel); + } + + [HttpDelete] + public Task Delete(Guid id) { - //return this._service.GetPostById(postId); - throw new NotImplementedException(); + return this._service.DeleteRole(id); } } } diff --git a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs index 58eef1f..b970dd5 100644 --- a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs +++ b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs @@ -1,8 +1,10 @@ +using System; + namespace DevHive.Web.Models.Identity.Role { public class UpdateRoleWebModel { - public string OldName { get; set; } + public Guid Id { get; set; } public string NewName { get; set; } } } -- cgit v1.2.3 From c50beb167dabe08d6407b54630bfe2b47eab23e6 Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 16 Dec 2020 12:14:57 +0200 Subject: Changed models in the Service to have inheritance --- .../Models/Identity/User/BaseUserServiceModel.cs | 10 + .../Models/Identity/User/RegisterServiceModel.cs | 8 +- .../Models/Identity/User/UserServiceModel.cs | 6 +- ...91145_Testing_Attributes_Validation.Designer.cs | 319 +++++++++++++++++++++ ...20201216091145_Testing_Attributes_Validation.cs | 49 ++++ 5 files changed, 381 insertions(+), 11 deletions(-) create mode 100644 src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs create mode 100644 src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.Designer.cs create mode 100644 src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs new file mode 100644 index 0000000..2e75848 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs @@ -0,0 +1,10 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class BaseUserServiceModel + { + public string UserName { get; set; } + public string Email { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs index f0b343a..77f2733 100644 --- a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs @@ -1,11 +1,7 @@ namespace DevHive.Services.Models.Identity.User { - public class RegisterServiceModel - { - public string UserName { get; set; } - public string Email { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public class RegisterServiceModel : BaseUserServiceModel + { public string Password { get; set; } } } diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index f01d13c..576e502 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -1,11 +1,7 @@ namespace DevHive.Services.Models.Identity.User { - public class UserServiceModel + public class UserServiceModel : BaseUserServiceModel { - public string UserName { get; set; } - public string Email { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } public string Role { get; set;} } } diff --git a/src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.Designer.cs b/src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.Designer.cs new file mode 100644 index 0000000..db042a9 --- /dev/null +++ b/src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.Designer.cs @@ -0,0 +1,319 @@ +// +using System; +using DevHive.Data.Repositories; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Web.Migrations +{ + [DbContext(typeof(DevHiveContext))] + [Migration("20201216091145_Testing_Attributes_Validation")] + partial class Testing_Attributes_Validation + { + 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.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") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + 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("Role") + .HasColumnType("text"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + 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") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ProviderKey") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + 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") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Name") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + 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(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.cs b/src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.cs new file mode 100644 index 0000000..9892aa5 --- /dev/null +++ b/src/DevHive.Web/Migrations/20201216091145_Testing_Attributes_Validation.cs @@ -0,0 +1,49 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DevHive.Web.Migrations +{ + public partial class Testing_Attributes_Validation : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "LastName", + table: "AspNetUsers", + type: "character varying(50)", + maxLength: 50, + nullable: false, + oldClrType: typeof(string), + oldType: "text"); + + migrationBuilder.AlterColumn( + name: "FirstName", + table: "AspNetUsers", + type: "character varying(50)", + maxLength: 50, + nullable: false, + oldClrType: typeof(string), + oldType: "text"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "LastName", + table: "AspNetUsers", + type: "text", + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(50)", + oldMaxLength: 50); + + migrationBuilder.AlterColumn( + name: "FirstName", + table: "AspNetUsers", + type: "text", + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(50)", + oldMaxLength: 50); + } + } +} -- cgit v1.2.3 From 534f3012d19b8a8a114153c11e7f8109577ac6e9 Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 16 Dec 2020 17:48:55 +0200 Subject: Fixed User Service and User Controller return types --- .../Models/Identity/User/TokenServiceModel.cs | 12 ++++++++ src/DevHive.Services/Services/UserService.cs | 36 +++++++++------------- .../Configurations/Mapping/UserMappings.cs | 2 ++ src/DevHive.Web/Controllers/UserController.cs | 26 +++++++++++----- .../Models/Identity/User/TokenWebModel.cs | 12 ++++++++ 5 files changed, 60 insertions(+), 28 deletions(-) create mode 100644 src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs create mode 100644 src/DevHive.Web/Models/Identity/User/TokenWebModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs b/src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs new file mode 100644 index 0000000..631808e --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs @@ -0,0 +1,12 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class TokenServiceModel + { + public TokenServiceModel(string token) + { + this.Token = token; + } + + public string Token { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 06f8b1b..1e81837 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -27,30 +27,26 @@ namespace DevHive.Services.Services this._jwtOptions = jwtOptions; } - public async Task LoginUser(LoginServiceModel loginModel) + public async Task LoginUser(LoginServiceModel loginModel) { if (!await this._userRepository.IsUsernameValid(loginModel.UserName)) - return new BadRequestObjectResult("Invalid username!"); + throw new ArgumentException("Invalid username!"); - User user = await this._userRepository - .GetByUsername(loginModel.UserName); + User user = await this._userRepository.GetByUsername(loginModel.UserName); if (user.PasswordHash != GeneratePasswordHash(loginModel.Password)) - return new BadRequestObjectResult("Incorrect password!"); + throw new ArgumentException("Incorrect password!"); - return new OkObjectResult(new - { - Token = WriteJWTSecurityToken(user.Role) - }); + return new TokenServiceModel(WriteJWTSecurityToken(user.Role)); } - public async Task RegisterUser(RegisterServiceModel registerModel) + public async Task RegisterUser(RegisterServiceModel registerModel) { if (await this._userRepository.DoesUsernameExist(registerModel.UserName)) - return new BadRequestObjectResult("Username already exists!"); + throw new ArgumentException("Username already exists!"); if (await this._userRepository.DoesEmailExist(registerModel.Email)) - return new BadRequestObjectResult("Email already exists!"); + throw new ArgumentException("Email already exists!"); User user = this._userMapper.Map(registerModel); user.Role = Role.DefaultRole; @@ -58,7 +54,7 @@ namespace DevHive.Services.Services await this._userRepository.AddAsync(user); - return new CreatedResult("CreateUser", user); + return this._userMapper.Map(user); } public async Task GetUserById(Guid id) @@ -69,30 +65,28 @@ namespace DevHive.Services.Services return this._userMapper.Map(user); } - public async Task UpdateUser(UpdateUserServiceModel updateModel) + public async Task UpdateUser(UpdateUserServiceModel updateModel) { if (!this._userRepository.DoesUserExist(updateModel.Id)) - return new NotFoundObjectResult("User does not exist!"); + throw new ArgumentException("User does not exist!"); if (!this._userRepository.DoesUserHaveThisUsername(updateModel.Id, updateModel.UserName) && await this._userRepository.IsUsernameValid(updateModel.UserName)) - return new BadRequestObjectResult("Username already exists!"); + throw new ArgumentException("Username already exists!"); User user = this._userMapper.Map(updateModel); await this._userRepository.EditAsync(user); - return new AcceptedResult("UpdateUser", user); + return this._userMapper.Map(user);; } - public async Task DeleteUser(Guid id) + public async Task DeleteUser(Guid id) { if (!this._userRepository.DoesUserExist(id)) - return new NotFoundObjectResult("User does not exist!"); + throw new ArgumentException("User does not exist!"); User user = await this._userRepository.GetByIdAsync(id); await this._userRepository.DeleteAsync(user); - - return new OkResult(); } private string GeneratePasswordHash(string password) diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index 06083de..1fdfc6a 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -15,6 +15,8 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap(); + + CreateMap(); } } } diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index 74eccd4..44828e0 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -31,7 +31,10 @@ namespace DevHive.Web.Controllers { LoginServiceModel loginServiceModel = this._userMapper.Map(loginModel); - return await this._userService.LoginUser(loginServiceModel); + TokenServiceModel tokenServiceModel = await this._userService.LoginUser(loginServiceModel); + TokenWebModel tokenWebModel = this._userMapper.Map(tokenServiceModel); + + return new OkObjectResult(tokenWebModel); } [HttpPost] @@ -40,27 +43,35 @@ namespace DevHive.Web.Controllers { RegisterServiceModel registerServiceModel = this._userMapper.Map(registerModel); - return await this._userService.RegisterUser(registerServiceModel); + UserServiceModel userServiceModel = await this._userService.RegisterUser(registerServiceModel); + UserWebModel userWebModel = this._userMapper.Map(userServiceModel); + + return new CreatedResult("Register", userWebModel); } //Read [HttpGet] public async Task GetById(Guid id) { - UserServiceModel serviceModel = await this._userService.GetUserById(id); + UserServiceModel userServiceModel = await this._userService.GetUserById(id); + UserWebModel userWebModel = this._userMapper.Map(userServiceModel); - return new OkObjectResult(this._userMapper.Map(serviceModel)); + return new OkObjectResult(userWebModel); } //Update [HttpPut] - [Authorize] + [Authorize(Roles = Role.DefaultRole)] public async Task Update(Guid id, [FromBody] UpdateUserWebModel updateModel) { UpdateUserServiceModel updateUserServiceModel = this._userMapper.Map(updateModel); updateUserServiceModel.Id = id; - return await this._userService.UpdateUser(updateUserServiceModel); + UserServiceModel userServiceModel = await this._userService.UpdateUser(updateUserServiceModel); + UserWebModel userWebModel = this._userMapper.Map(userServiceModel); + + return new AcceptedResult("UpdateUser", userWebModel); + } //Delete @@ -68,7 +79,8 @@ namespace DevHive.Web.Controllers [Authorize(Roles = Role.DefaultRole)] public async Task Delete(Guid id) { - return await this._userService.DeleteUser(id); + await this._userService.DeleteUser(id); + return new OkResult(); } } } diff --git a/src/DevHive.Web/Models/Identity/User/TokenWebModel.cs b/src/DevHive.Web/Models/Identity/User/TokenWebModel.cs new file mode 100644 index 0000000..154b64b --- /dev/null +++ b/src/DevHive.Web/Models/Identity/User/TokenWebModel.cs @@ -0,0 +1,12 @@ +namespace DevHive.Web.Models.Identity.User +{ + public class TokenWebModel + { + public TokenWebModel(string token) + { + this.Token = token; + } + + public string Token { get; set; } + } +} \ No newline at end of file -- cgit v1.2.3 From cd02428e748e691a0005b2687edf69a99766aac6 Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 16 Dec 2020 22:38:25 +0200 Subject: Added DevHive.Common; Changed repositories behavior; Abstracted some common logic --- src/DevHive.Common/DevHive.Common.csproj | 12 ++++++++++++ src/DevHive.Common/Models/Data/RepositoryMethods.cs | 15 +++++++++++++++ src/DevHive.Common/Models/Identity/TokenModel.cs | 12 ++++++++++++ src/DevHive.Data/DevHive.Data.csproj | 4 ++++ src/DevHive.Data/Repositories/LanguageRepository.cs | 14 ++++---------- src/DevHive.Data/Repositories/RoleRepository.cs | 20 ++++++++++++-------- src/DevHive.Data/Repositories/UserRepository.cs | 13 +++++++------ src/DevHive.Services/DevHive.Services.csproj | 4 ++++ .../Models/Identity/User/TokenServiceModel.cs | 12 ------------ src/DevHive.Services/Services/UserService.cs | 20 +++++++++++++------- .../Configurations/Mapping/UserMappings.cs | 4 ++-- src/DevHive.Web/Controllers/UserController.cs | 10 +++++----- src/DevHive.Web/DevHive.Web.csproj | 1 + src/DevHive.code-workspace | 4 ++++ 14 files changed, 95 insertions(+), 50 deletions(-) create mode 100644 src/DevHive.Common/DevHive.Common.csproj create mode 100644 src/DevHive.Common/Models/Data/RepositoryMethods.cs create mode 100644 src/DevHive.Common/Models/Identity/TokenModel.cs delete mode 100644 src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Common/DevHive.Common.csproj b/src/DevHive.Common/DevHive.Common.csproj new file mode 100644 index 0000000..1aca8a6 --- /dev/null +++ b/src/DevHive.Common/DevHive.Common.csproj @@ -0,0 +1,12 @@ + + + + net5.0 + + + + + + + + diff --git a/src/DevHive.Common/Models/Data/RepositoryMethods.cs b/src/DevHive.Common/Models/Data/RepositoryMethods.cs new file mode 100644 index 0000000..b56aad9 --- /dev/null +++ b/src/DevHive.Common/Models/Data/RepositoryMethods.cs @@ -0,0 +1,15 @@ +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace DevHive.Common.Models.Data +{ + public static class RepositoryMethods + { + public static async Task SaveChangesAsync(DbContext context) + { + int result = await context.SaveChangesAsync(); + + return result >= 1; + } + } +} \ No newline at end of file diff --git a/src/DevHive.Common/Models/Identity/TokenModel.cs b/src/DevHive.Common/Models/Identity/TokenModel.cs new file mode 100644 index 0000000..0fb6c82 --- /dev/null +++ b/src/DevHive.Common/Models/Identity/TokenModel.cs @@ -0,0 +1,12 @@ +namespace DevHive.Common.Models.Identity +{ + public class TokenModel + { + public TokenModel(string token) + { + this.Token = token; + } + + public string Token { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Data/DevHive.Data.csproj b/src/DevHive.Data/DevHive.Data.csproj index d472d1c..c1e1592 100644 --- a/src/DevHive.Data/DevHive.Data.csproj +++ b/src/DevHive.Data/DevHive.Data.csproj @@ -16,4 +16,8 @@ + + + + diff --git a/src/DevHive.Data/Repositories/LanguageRepository.cs b/src/DevHive.Data/Repositories/LanguageRepository.cs index 08efd18..a33bd5b 100644 --- a/src/DevHive.Data/Repositories/LanguageRepository.cs +++ b/src/DevHive.Data/Repositories/LanguageRepository.cs @@ -1,6 +1,7 @@ using System; using System.Threading.Tasks; using Data.Models.Interfaces.Database; +using DevHive.Common.Models.Data; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; @@ -22,7 +23,7 @@ namespace DevHive.Data.Repositories .Set() .AddAsync(entity); - return await this.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } //Read @@ -56,7 +57,7 @@ namespace DevHive.Data.Repositories .Set() .Update(newEntity); - return await this.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } //Delete @@ -66,14 +67,7 @@ namespace DevHive.Data.Repositories .Set() .Remove(entity); - return await this.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } - - private async Task SaveChangesAsync() - { - int result = await this._context.SaveChangesAsync(); - - return result >= 0; - } } } \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/RoleRepository.cs b/src/DevHive.Data/Repositories/RoleRepository.cs index 9b6cf14..ad9bda0 100644 --- a/src/DevHive.Data/Repositories/RoleRepository.cs +++ b/src/DevHive.Data/Repositories/RoleRepository.cs @@ -1,6 +1,7 @@ using System; using System.Threading.Tasks; using Data.Models.Interfaces.Database; +using DevHive.Common.Models.Data; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; @@ -16,13 +17,13 @@ namespace DevHive.Data.Repositories } //Create - public async Task AddAsync(Role entity) + public async Task AddAsync(Role entity) { await this._context .Set() .AddAsync(entity); - await this._context.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } //Read @@ -35,23 +36,26 @@ namespace DevHive.Data.Repositories } //Update - public async Task EditAsync(Role newEntity) + public async Task EditAsync(Role newEntity) { + Role role = await this.GetByIdAsync(newEntity.Id); + this._context - .Set() - .Update(newEntity); + .Entry(role) + .CurrentValues + .SetValues(newEntity); - await this._context.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } //Delete - public async Task DeleteAsync(Role entity) + public async Task DeleteAsync(Role entity) { this._context .Set() .Remove(entity); - await this._context.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } public async Task DoesNameExist(string name) diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 714218d..f5a074b 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -3,6 +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.Data.Models; using Microsoft.EntityFrameworkCore; @@ -18,13 +19,13 @@ namespace DevHive.Data.Repositories } //Create - public async Task AddAsync(User entity) + public async Task AddAsync(User entity) { await this._context .Set() .AddAsync(entity); - await this._context.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } //Read @@ -51,7 +52,7 @@ namespace DevHive.Data.Repositories } //Update - public async Task EditAsync(User newEntity) + public async Task EditAsync(User newEntity) { User user = await this.GetByIdAsync(newEntity.Id); @@ -60,17 +61,17 @@ namespace DevHive.Data.Repositories .CurrentValues .SetValues(newEntity); - await this._context.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } //Delete - public async Task DeleteAsync(User entity) + public async Task DeleteAsync(User entity) { this._context .Set() .Remove(entity); - await this._context.SaveChangesAsync(); + return await RepositoryMethods.SaveChangesAsync(this._context); } //Validations diff --git a/src/DevHive.Services/DevHive.Services.csproj b/src/DevHive.Services/DevHive.Services.csproj index 280610d..19f67d8 100644 --- a/src/DevHive.Services/DevHive.Services.csproj +++ b/src/DevHive.Services/DevHive.Services.csproj @@ -16,5 +16,9 @@ + + + + diff --git a/src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs b/src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs deleted file mode 100644 index 631808e..0000000 --- a/src/DevHive.Services/Models/Identity/User/TokenServiceModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace DevHive.Services.Models.Identity.User -{ - public class TokenServiceModel - { - public TokenServiceModel(string token) - { - this.Token = token; - } - - public string Token { get; set; } - } -} \ No newline at end of file diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 24f74f5..63b8389 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -3,7 +3,6 @@ using DevHive.Data.Repositories; using DevHive.Services.Options; using DevHive.Services.Models.Identity.User; using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; using DevHive.Data.Models; using System; using System.IdentityModel.Tokens.Jwt; @@ -12,6 +11,7 @@ using Microsoft.IdentityModel.Tokens; using System.Security.Cryptography; using System.Text; using System.Collections.Generic; +using DevHive.Common.Models.Identity; namespace DevHive.Services.Services { @@ -28,7 +28,7 @@ namespace DevHive.Services.Services this._jwtOptions = jwtOptions; } - public async Task LoginUser(LoginServiceModel loginModel) + public async Task LoginUser(LoginServiceModel loginModel) { if (!await this._userRepository.IsUsernameValid(loginModel.UserName)) throw new ArgumentException("Invalid username!"); @@ -38,10 +38,10 @@ namespace DevHive.Services.Services if (user.PasswordHash != GeneratePasswordHash(loginModel.Password)) throw new ArgumentException("Incorrect password!"); - return new TokenServiceModel(WriteJWTSecurityToken(user.Role)); + return new TokenModel(WriteJWTSecurityToken(user.Role)); } - public async Task RegisterUser(RegisterServiceModel registerModel) + public async Task RegisterUser(RegisterServiceModel registerModel) { if (await this._userRepository.DoesUsernameExist(registerModel.UserName)) throw new ArgumentException("Username already exists!"); @@ -55,7 +55,7 @@ namespace DevHive.Services.Services await this._userRepository.AddAsync(user); - return new TokenServiceModel(WriteJWTSecurityToken(user.Role)); + return new TokenModel(WriteJWTSecurityToken(user.Role)); } public async Task GetUserById(Guid id) @@ -76,7 +76,10 @@ namespace DevHive.Services.Services throw new ArgumentException("Username already exists!"); User user = this._userMapper.Map(updateModel); - await this._userRepository.EditAsync(user); + bool result = await this._userRepository.EditAsync(user); + + if (!result) + throw new InvalidOperationException("Unable to edit user!"); return this._userMapper.Map(user);; } @@ -87,7 +90,10 @@ namespace DevHive.Services.Services throw new ArgumentException("User does not exist!"); User user = await this._userRepository.GetByIdAsync(id); - await this._userRepository.DeleteAsync(user); + bool result = await this._userRepository.DeleteAsync(user); + + if (!result) + throw new InvalidOperationException("Unable to delete user!"); } private string GeneratePasswordHash(string password) diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index 1fdfc6a..4420368 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -1,7 +1,7 @@ -using DevHive.Data.Models; using AutoMapper; using DevHive.Services.Models.Identity.User; using DevHive.Web.Models.Identity.User; +using DevHive.Common.Models.Identity; namespace DevHive.Web.Configurations.Mapping { @@ -16,7 +16,7 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); - CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index 80e1bde..1360bfe 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -1,7 +1,6 @@ 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; @@ -9,6 +8,7 @@ using DevHive.Services.Services; using DevHive.Web.Models.Identity.User; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using DevHive.Common.Models.Identity; namespace DevHive.Web.Controllers { @@ -33,8 +33,8 @@ namespace DevHive.Web.Controllers { LoginServiceModel loginServiceModel = this._userMapper.Map(loginModel); - TokenServiceModel tokenServiceModel = await this._userService.LoginUser(loginServiceModel); - TokenWebModel tokenWebModel = this._userMapper.Map(tokenServiceModel); + TokenModel TokenModel = await this._userService.LoginUser(loginServiceModel); + TokenWebModel tokenWebModel = this._userMapper.Map(TokenModel); return new OkObjectResult(tokenWebModel); } @@ -46,8 +46,8 @@ namespace DevHive.Web.Controllers { RegisterServiceModel registerServiceModel = this._userMapper.Map(registerModel); - TokenServiceModel tokenServiceModel = await this._userService.RegisterUser(registerServiceModel); - TokenWebModel tokenWebModel = this._userMapper.Map(tokenServiceModel); + TokenModel TokenModel = await this._userService.RegisterUser(registerServiceModel); + TokenWebModel tokenWebModel = this._userMapper.Map(TokenModel); return new CreatedResult("Register", tokenWebModel); } diff --git a/src/DevHive.Web/DevHive.Web.csproj b/src/DevHive.Web/DevHive.Web.csproj index 2a1faf1..0be5bdc 100644 --- a/src/DevHive.Web/DevHive.Web.csproj +++ b/src/DevHive.Web/DevHive.Web.csproj @@ -20,5 +20,6 @@ + \ No newline at end of file diff --git a/src/DevHive.code-workspace b/src/DevHive.code-workspace index 730aab1..7e952c7 100644 --- a/src/DevHive.code-workspace +++ b/src/DevHive.code-workspace @@ -12,6 +12,10 @@ "name": "DevHive.Data", "path": "./DevHive.Data" }, + { + "name": "DevHive.Common", + "path": "./DevHive.Common" + }, ], "settings": { "files.exclude": { -- cgit v1.2.3 From 94a3b0661106e91ab3a1a523af3c60df131a4f63 Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 17 Dec 2020 19:13:01 +0200 Subject: Friends implementation added. UserController/AddAFriend added --- src/DevHive.Common/Models/IdModel.cs | 9 + src/DevHive.Data/Models/User.cs | 4 +- src/DevHive.Data/Repositories/DevHiveContext.cs | 8 +- src/DevHive.Data/Repositories/UserRepository.cs | 9 + .../Models/Identity/User/UserServiceModel.cs | 7 +- src/DevHive.Services/Services/UserService.cs | 22 +- .../Configurations/Mapping/RoleMappings.cs | 1 + src/DevHive.Web/Controllers/UserController.cs | 11 + src/DevHive.Web/DevHive.Web.csproj | 22 +- .../20201217163729_Friends_Implemented.Designer.cs | 364 +++++++++++++++++++++ .../20201217163729_Friends_Implemented.cs | 45 +++ .../Migrations/DevHiveContextModelSnapshot.cs | 17 + .../Models/Identity/User/UserWebModel.cs | 6 +- 13 files changed, 505 insertions(+), 20 deletions(-) create mode 100644 src/DevHive.Common/Models/IdModel.cs create mode 100644 src/DevHive.Web/Migrations/20201217163729_Friends_Implemented.Designer.cs create mode 100644 src/DevHive.Web/Migrations/20201217163729_Friends_Implemented.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Common/Models/IdModel.cs b/src/DevHive.Common/Models/IdModel.cs new file mode 100644 index 0000000..a342e6d --- /dev/null +++ b/src/DevHive.Common/Models/IdModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Common.Models +{ + public class IdModel + { + public Guid Id { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Data/Models/User.cs b/src/DevHive.Data/Models/User.cs index fd0ee7b..eef0af2 100644 --- a/src/DevHive.Data/Models/User.cs +++ b/src/DevHive.Data/Models/User.cs @@ -14,8 +14,8 @@ namespace DevHive.Data.Models public string ProfilePicture { get; set; } - public virtual IList Roles { get; set; } + public virtual IList Roles { get; set; } = new List(); - //public List Friends { get; set; } + public IList Friends { get; set; } = new List(); } } diff --git a/src/DevHive.Data/Repositories/DevHiveContext.cs b/src/DevHive.Data/Repositories/DevHiveContext.cs index 373eb5e..7fa8130 100644 --- a/src/DevHive.Data/Repositories/DevHiveContext.cs +++ b/src/DevHive.Data/Repositories/DevHiveContext.cs @@ -18,7 +18,13 @@ namespace DevHive.Data.Repositories builder.Entity() .HasIndex(x => x.UserName) .IsUnique(); - + + builder.Entity() + .HasMany(x => x.Roles); + + builder.Entity() + .HasMany(x => x.Friends); + builder.Entity() .HasIndex(x => x.Id) .IsUnique(); diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 130f96e..577f02f 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -43,6 +43,7 @@ namespace DevHive.Data.Repositories return await this._context .Set() .Include(x => x.Roles) + .Include(x => x.Friends) .FirstOrDefaultAsync(x => x.Id == id); } @@ -115,5 +116,13 @@ namespace DevHive.Data.Repositories .AsNoTracking() .AnyAsync(u => u.Email == email); } + + public async Task AddFriend(User user, User friend) + { + this._context.Update(user); + user.Friends.Add(friend); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } } } diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 576e502..868e7ba 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -1,7 +1,12 @@ +using System.Collections.Generic; +using DevHive.Data.Models; +using DevHive.Services.Models.Identity.Role; + namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { - public string Role { get; set;} + public IList Role { get; set; } = new List(); + public List Friends { get; set; } = new List(); } } diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index bd9eaa6..3e65dab 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -72,7 +72,13 @@ namespace DevHive.Services.Services User user = await this._userRepository.GetByIdAsync(id) ?? throw new ArgumentException("User does not exist!"); - return this._userMapper.Map(user); + //Here User has 1 role + + UserServiceModel model = this._userMapper.Map(user); + + //here model has 0 roles + + return model; } public async Task UpdateUser(UpdateUserServiceModel updateModel) @@ -105,6 +111,16 @@ namespace DevHive.Services.Services throw new InvalidOperationException("Unable to delete user!"); } + public async Task AddFriend(Guid userId, Guid friendId) + { + User user = await this._userRepository.GetByIdAsync(userId); + User friend = await this._userRepository.GetByIdAsync(friendId); + + return user != default(User) && friend != default(User) ? + await this._userRepository.AddFriend(user, friend) : + throw new ArgumentException("Invalid user!"); + } + private string GeneratePasswordHash(string password) { return string.Join(string.Empty, SHA512.HashData(Encoding.ASCII.GetBytes(password))); @@ -114,9 +130,9 @@ namespace DevHive.Services.Services { byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret); - List claims = new List() + List claims = new() { - new Claim(ClaimTypes.Role, roles[0].Name) // TODO: add support for mulitple roles + new Claim(ClaimTypes.Role, roles[0].Name) // TODO: add support for multiple roles }; SecurityTokenDescriptor tokenDescriptor = new() diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs index 2743df3..4bc25c4 100644 --- a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -10,6 +10,7 @@ namespace DevHive.Web.Configurations.Mapping { CreateMap(); CreateMap(); + CreateMap(); CreateMap(); } diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index 1360bfe..cdb8dc1 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 { @@ -39,6 +40,7 @@ namespace DevHive.Web.Controllers return new OkObjectResult(tokenWebModel); } + //Create [HttpPost] [Route("Register")] [AllowAnonymous] @@ -52,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) diff --git a/src/DevHive.Web/DevHive.Web.csproj b/src/DevHive.Web/DevHive.Web.csproj index 0be5bdc..ad23ce9 100644 --- a/src/DevHive.Web/DevHive.Web.csproj +++ b/src/DevHive.Web/DevHive.Web.csproj @@ -3,23 +3,21 @@ net5.0 - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - - - - + + + + + + - - + + \ No newline at end of file diff --git a/src/DevHive.Web/Migrations/20201217163729_Friends_Implemented.Designer.cs b/src/DevHive.Web/Migrations/20201217163729_Friends_Implemented.Designer.cs new file mode 100644 index 0000000..d066f18 --- /dev/null +++ b/src/DevHive.Web/Migrations/20201217163729_Friends_Implemented.Designer.cs @@ -0,0 +1,364 @@ +// +using System; +using DevHive.Data.Repositories; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Web.Migrations +{ + [DbContext(typeof(DevHiveContext))] + [Migration("20201217163729_Friends_Implemented")] + partial class Friends_Implemented + { + 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("Id") + .IsUnique(); + + 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") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ProviderKey") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + 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") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Name") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + 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/Migrations/20201217163729_Friends_Implemented.cs b/src/DevHive.Web/Migrations/20201217163729_Friends_Implemented.cs new file mode 100644 index 0000000..e20bfc1 --- /dev/null +++ b/src/DevHive.Web/Migrations/20201217163729_Friends_Implemented.cs @@ -0,0 +1,45 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DevHive.Web.Migrations +{ + public partial class Friends_Implemented : 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.Web/Migrations/DevHiveContextModelSnapshot.cs b/src/DevHive.Web/Migrations/DevHiveContextModelSnapshot.cs index c1464d4..328eb9c 100644 --- a/src/DevHive.Web/Migrations/DevHiveContextModelSnapshot.cs +++ b/src/DevHive.Web/Migrations/DevHiveContextModelSnapshot.cs @@ -135,6 +135,9 @@ namespace DevHive.Web.Migrations b.Property("TwoFactorEnabled") .HasColumnType("boolean"); + b.Property("UserId") + .HasColumnType("uuid"); + b.Property("UserName") .HasMaxLength(256) .HasColumnType("character varying(256)"); @@ -148,6 +151,8 @@ namespace DevHive.Web.Migrations .IsUnique() .HasDatabaseName("UserNameIndex"); + b.HasIndex("UserId"); + b.HasIndex("UserName") .IsUnique(); @@ -274,6 +279,13 @@ namespace DevHive.Web.Migrations 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) @@ -339,6 +351,11 @@ namespace DevHive.Web.Migrations .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/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 88ee1b7..e7bdb2a 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -1,7 +1,11 @@ +using System.Collections.Generic; +using DevHive.Web.Models.Identity.Role; + namespace DevHive.Web.Models.Identity.User { public class UserWebModel : BaseUserWebModel { - public string Role { get; set; } + public IList Role { get; set; } = new List(); + public IList Friends { get; set; } = new List(); } } -- 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.Services/Models/Identity') 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 875857f118d0364a94eb88bf03673e1d0165c23c Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 17 Dec 2020 19:42:45 +0200 Subject: Fixed namespaces --- .../Configurations/Mapping/RoleMapings.cs | 6 +++--- .../Models/Identity/User/UserServiceModel.cs | 2 -- src/DevHive.Services/Services/RoleService.cs | 10 +++++----- .../Configurations/Mapping/RoleMappings.cs | 10 +++++----- src/DevHive.Web/Controllers/RoleController.cs | 21 ++++++++++----------- .../Models/Identity/Role/CreateRoleWebModel.cs | 2 +- .../Models/Identity/Role/UpdateRoleWebModel.cs | 2 +- 7 files changed, 25 insertions(+), 28 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index 25b314a..db4473e 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -1,6 +1,6 @@ using DevHive.Data.Models; using AutoMapper; -using DevHive.Services.Models.Identity.Role; +using DevHive.Common.Models.Identity; namespace DevHive.Services.Configurations.Mapping { @@ -8,8 +8,8 @@ namespace DevHive.Services.Configurations.Mapping { public RoleMappings() { - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 8ac71b1..de57faf 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using DevHive.Common.Models.Identity; -using DevHive.Data.Models; -using DevHive.Services.Models.Identity.Role; namespace DevHive.Services.Models.Identity.User { diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index d5c1848..c0b9062 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -1,9 +1,9 @@ using System; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Models.Identity; using DevHive.Data.Models; using DevHive.Data.Repositories; -using DevHive.Services.Models.Identity.Role; namespace DevHive.Services.Services { @@ -18,7 +18,7 @@ namespace DevHive.Services.Services this._roleMapper = mapper; } - public async Task CreateRole(RoleServiceModel roleServiceModel) + public async Task CreateRole(RoleModel roleServiceModel) { if (await this._roleRepository.DoesNameExist(roleServiceModel.Name)) throw new ArgumentException("Role already exists!"); @@ -28,15 +28,15 @@ namespace DevHive.Services.Services return await this._roleRepository.AddAsync(role); } - public async Task GetRoleById(Guid id) + public async Task GetRoleById(Guid id) { Role role = await this._roleRepository.GetByIdAsync(id) ?? throw new ArgumentException("Role does not exist!"); - return this._roleMapper.Map(role); + return this._roleMapper.Map(role); } - public async Task UpdateRole(RoleServiceModel roleServiceModel) + public async Task UpdateRole(RoleModel roleServiceModel) { if (!await this._roleRepository.DoesRoleExist(roleServiceModel.Id)) throw new ArgumentException("Role does not exist!"); diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs index 4bc25c4..8c5cd85 100644 --- a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -1,6 +1,6 @@ using AutoMapper; using DevHive.Web.Models.Identity.Role; -using DevHive.Services.Models.Identity.Role; +using DevHive.Common.Models.Identity; namespace DevHive.Web.Configurations.Mapping { @@ -8,11 +8,11 @@ namespace DevHive.Web.Configurations.Mapping { public RoleMappings() { - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index 1664f4f..fc05481 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -4,13 +4,12 @@ using DevHive.Services.Services; using Microsoft.AspNetCore.Mvc; using DevHive.Web.Models.Identity.Role; using AutoMapper; -using DevHive.Services.Models.Identity.Role; using System; -using Microsoft.AspNetCore.Authorization; +using DevHive.Common.Models.Identity; namespace DevHive.Web.Controllers { - [ApiController] + [ApiController] [Route("/api/[controller]")] //[Authorize(Roles = "Admin")] public class RoleController @@ -25,10 +24,10 @@ namespace DevHive.Web.Controllers } [HttpPost] - public async Task Create([FromBody] CreateRoleWebModel createRoleWebModel) + public async Task Create([FromBody] CreateRoleModel createRoleModel) { - RoleServiceModel roleServiceModel = - this._roleMapper.Map(createRoleWebModel); + RoleModel roleServiceModel = + this._roleMapper.Map(createRoleModel); bool result = await this._roleService.CreateRole(roleServiceModel); @@ -41,17 +40,17 @@ namespace DevHive.Web.Controllers [HttpGet] public async Task GetById(Guid id) { - RoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); - RoleWebModel roleWebModel = this._roleMapper.Map(roleServiceModel); + RoleModel roleServiceModel = await this._roleService.GetRoleById(id); + RoleModel roleWebModel = this._roleMapper.Map(roleServiceModel); return new OkObjectResult(roleWebModel); } [HttpPut] - public async Task Update(Guid id, [FromBody] UpdateRoleWebModel updateRoleWebModel) + public async Task Update(Guid id, [FromBody] UpdateRoleModel updateRoleModel) { - RoleServiceModel roleServiceModel = - this._roleMapper.Map(updateRoleWebModel); + RoleModel roleServiceModel = + this._roleMapper.Map(updateRoleModel); roleServiceModel.Id = id; bool result = await this._roleService.UpdateRole(roleServiceModel); diff --git a/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs index e872428..becb3c9 100644 --- a/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs +++ b/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs @@ -1,6 +1,6 @@ namespace DevHive.Web.Models.Identity.Role { - public class CreateRoleWebModel + public class CreateRoleModel { public string Name { get; set; } } diff --git a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs index 213ec55..1eaad57 100644 --- a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs +++ b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs @@ -1,6 +1,6 @@ namespace DevHive.Web.Models.Identity.Role { - public class UpdateRoleWebModel : CreateRoleWebModel + public class UpdateRoleModel : CreateRoleModel { } } -- cgit v1.2.3 From b24b9b1ffa528f29aa87f0e48097a35386fbb8b1 Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 17 Dec 2020 20:15:31 +0200 Subject: Fixed roles not mapping properly --- src/DevHive.Services/Models/Identity/User/UserServiceModel.cs | 2 +- src/DevHive.Web/Models/Identity/User/UserWebModel.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index de57faf..953b038 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -5,7 +5,7 @@ namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { - public IList Role { get; set; } = new List(); + public IList Roles { get; set; } = new List(); public List Friends { get; set; } = new List(); } } diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 83430ce..4b523b5 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -6,7 +6,7 @@ namespace DevHive.Web.Models.Identity.User { public class UserWebModel : BaseUserWebModel { - public IList Role { get; set; } = new List(); + public IList Roles { get; set; } = new List(); public IList Friends { get; set; } = new List(); } } -- cgit v1.2.3 From 11bd1d9a9760c7bc6a601d78b3d89ec9028647a2 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 12 Jan 2021 13:16:39 +0200 Subject: Language layers refactored; User implements adding & removing Languages; Migrations added --- ...112111416_User_Implements_Languages.Designer.cs | 405 +++++++++++++++++++++ .../20210112111416_User_Implements_Languages.cs | 106 ++++++ .../Migrations/DevHiveContextModelSnapshot.cs | 38 +- src/DevHive.Data/Models/Technology.cs | 1 - src/DevHive.Data/Models/User.cs | 12 +- .../Repositories/Contracts/ILanguageRepository.cs | 13 - .../Repositories/Contracts/IPostRepository.cs | 21 -- .../Repositories/Contracts/IRepository.cs | 21 -- .../Repositories/Contracts/IRoleRepository.cs | 15 - .../Contracts/ITechnologyRepository.cs | 13 - .../Repositories/Contracts/IUserRepository.cs | 26 -- src/DevHive.Data/Repositories/IRepository.cs | 21 ++ .../Repositories/LanguageRepository.cs | 55 +-- src/DevHive.Data/Repositories/PostRepository.cs | 6 +- src/DevHive.Data/Repositories/RoleRepository.cs | 3 +- .../Repositories/TechnologyRepository.cs | 5 +- src/DevHive.Data/Repositories/UserRepository.cs | 162 +++++++-- .../Configurations/Mapping/LanguageMappings.cs | 1 - .../Models/Identity/User/RegisterServiceModel.cs | 8 +- .../Models/Language/CreateLanguageServiceModel.cs | 9 + .../Models/Language/LanguageServiceModel.cs | 4 +- .../Models/Language/UpdateLanguageServiceModel.cs | 7 +- src/DevHive.Services/Services/LanguageService.cs | 38 +- src/DevHive.Services/Services/PostService.cs | 8 +- src/DevHive.Services/Services/RoleService.cs | 6 +- src/DevHive.Services/Services/TechnologyService.cs | 6 +- src/DevHive.Services/Services/UserService.cs | 146 +++++--- .../TechnologyRepository.Tests.cs | 4 +- .../Configurations/Mapping/LanguageMappings.cs | 7 +- src/DevHive.Web/Controllers/LanguageController.cs | 4 +- .../Models/Language/CreateLanguageWebModel.cs | 9 + .../Models/Language/LanguageWebModel.cs | 4 +- .../Models/Language/UpdateLanguageWebModel.cs | 5 +- 33 files changed, 912 insertions(+), 277 deletions(-) create mode 100644 src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.Designer.cs create mode 100644 src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs delete mode 100644 src/DevHive.Data/Repositories/Contracts/ILanguageRepository.cs delete mode 100644 src/DevHive.Data/Repositories/Contracts/IPostRepository.cs delete mode 100644 src/DevHive.Data/Repositories/Contracts/IRepository.cs delete mode 100644 src/DevHive.Data/Repositories/Contracts/IRoleRepository.cs delete mode 100644 src/DevHive.Data/Repositories/Contracts/ITechnologyRepository.cs delete mode 100644 src/DevHive.Data/Repositories/Contracts/IUserRepository.cs create mode 100644 src/DevHive.Data/Repositories/IRepository.cs create mode 100644 src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs create mode 100644 src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.Designer.cs b/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.Designer.cs new file mode 100644 index 0000000..0f1aa80 --- /dev/null +++ b/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.Designer.cs @@ -0,0 +1,405 @@ +// +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("20210112111416_User_Implements_Languages")] + partial class User_Implements_Languages + { + 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("IssuerId") + .HasColumnType("uuid"); + + b.Property("Message") + .HasColumnType("text"); + + b.Property("TimeCreated") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Language", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + 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.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + 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("ProfilePictureUrl") + .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.Language", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Langauges") + .HasForeignKey("UserId"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Technologies") + .HasForeignKey("UserId"); + }); + + 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"); + + b.Navigation("Langauges"); + + b.Navigation("Technologies"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs b/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs new file mode 100644 index 0000000..a51ad09 --- /dev/null +++ b/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs @@ -0,0 +1,106 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DevHive.Data.Migrations +{ + public partial class User_Implements_Languages : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "UserId", + table: "Comments", + newName: "IssuerId"); + + migrationBuilder.RenameColumn( + name: "Date", + table: "Comments", + newName: "TimeCreated"); + + migrationBuilder.RenameColumn( + name: "ProfilePicture", + table: "AspNetUsers", + newName: "ProfilePictureUrl"); + + migrationBuilder.AddColumn( + name: "UserId", + table: "Technologies", + type: "uuid", + nullable: true); + + migrationBuilder.AddColumn( + name: "UserId", + table: "Languages", + type: "uuid", + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_Technologies_UserId", + table: "Technologies", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Languages_UserId", + table: "Languages", + column: "UserId"); + + migrationBuilder.AddForeignKey( + name: "FK_Languages_AspNetUsers_UserId", + table: "Languages", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Technologies_AspNetUsers_UserId", + table: "Technologies", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Languages_AspNetUsers_UserId", + table: "Languages"); + + migrationBuilder.DropForeignKey( + name: "FK_Technologies_AspNetUsers_UserId", + table: "Technologies"); + + migrationBuilder.DropIndex( + name: "IX_Technologies_UserId", + table: "Technologies"); + + migrationBuilder.DropIndex( + name: "IX_Languages_UserId", + table: "Languages"); + + migrationBuilder.DropColumn( + name: "UserId", + table: "Technologies"); + + migrationBuilder.DropColumn( + name: "UserId", + table: "Languages"); + + migrationBuilder.RenameColumn( + name: "TimeCreated", + table: "Comments", + newName: "Date"); + + migrationBuilder.RenameColumn( + name: "IssuerId", + table: "Comments", + newName: "UserId"); + + migrationBuilder.RenameColumn( + name: "ProfilePictureUrl", + table: "AspNetUsers", + newName: "ProfilePicture"); + } + } +} diff --git a/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs index c7ff6c6..cc6d24d 100644 --- a/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs +++ b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs @@ -25,14 +25,14 @@ namespace DevHive.Data.Migrations .ValueGeneratedOnAdd() .HasColumnType("uuid"); - b.Property("Date") - .HasColumnType("timestamp without time zone"); + b.Property("IssuerId") + .HasColumnType("uuid"); b.Property("Message") .HasColumnType("text"); - b.Property("UserId") - .HasColumnType("uuid"); + b.Property("TimeCreated") + .HasColumnType("timestamp without time zone"); b.HasKey("Id"); @@ -48,8 +48,13 @@ namespace DevHive.Data.Migrations b.Property("Name") .HasColumnType("text"); + b.Property("UserId") + .HasColumnType("uuid"); + b.HasKey("Id"); + b.HasIndex("UserId"); + b.ToTable("Languages"); }); @@ -89,8 +94,13 @@ namespace DevHive.Data.Migrations b.Property("Name") .HasColumnType("text"); + b.Property("UserId") + .HasColumnType("uuid"); + b.HasKey("Id"); + b.HasIndex("UserId"); + b.ToTable("Technologies"); }); @@ -143,7 +153,7 @@ namespace DevHive.Data.Migrations b.Property("PhoneNumberConfirmed") .HasColumnType("boolean"); - b.Property("ProfilePicture") + b.Property("ProfilePictureUrl") .HasColumnType("text"); b.Property("SecurityStamp") @@ -292,6 +302,20 @@ namespace DevHive.Data.Migrations b.ToTable("RoleUser"); }); + modelBuilder.Entity("DevHive.Data.Models.Language", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Langauges") + .HasForeignKey("UserId"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Technologies") + .HasForeignKey("UserId"); + }); + modelBuilder.Entity("DevHive.Data.Models.User", b => { b.HasOne("DevHive.Data.Models.User", null) @@ -368,6 +392,10 @@ namespace DevHive.Data.Migrations modelBuilder.Entity("DevHive.Data.Models.User", b => { b.Navigation("Friends"); + + b.Navigation("Langauges"); + + b.Navigation("Technologies"); }); #pragma warning restore 612, 618 } diff --git a/src/DevHive.Data/Models/Technology.cs b/src/DevHive.Data/Models/Technology.cs index 2e0aeed..a462d20 100644 --- a/src/DevHive.Data/Models/Technology.cs +++ b/src/DevHive.Data/Models/Technology.cs @@ -5,7 +5,6 @@ namespace DevHive.Data.Models public class Technology : IModel { public Guid Id { get; set; } - public string Name { get; set; } } } diff --git a/src/DevHive.Data/Models/User.cs b/src/DevHive.Data/Models/User.cs index eef0af2..fda4651 100644 --- a/src/DevHive.Data/Models/User.cs +++ b/src/DevHive.Data/Models/User.cs @@ -12,7 +12,17 @@ namespace DevHive.Data.Models public string LastName { get; set; } - public string ProfilePicture { get; set; } + public string ProfilePictureUrl { get; set; } + + /// + /// Languages that the user uses or is familiar with + /// + public IList Langauges { get; set; } + + /// + /// Technologies that the user uses or is familiar with + /// + public IList Technologies { get; set; } public virtual IList Roles { get; set; } = new List(); diff --git a/src/DevHive.Data/Repositories/Contracts/ILanguageRepository.cs b/src/DevHive.Data/Repositories/Contracts/ILanguageRepository.cs deleted file mode 100644 index e44d27b..0000000 --- a/src/DevHive.Data/Repositories/Contracts/ILanguageRepository.cs +++ /dev/null @@ -1,13 +0,0 @@ -using DevHive.Data.Models; -using System; -using System.Threading.Tasks; - -namespace DevHive.Data.Repositories.Contracts -{ - public interface ILanguageRepository : IRepository - { - public Task DoesLanguageNameExist(string languageName); - - public Task DoesLanguageExist(Guid id); - } -} diff --git a/src/DevHive.Data/Repositories/Contracts/IPostRepository.cs b/src/DevHive.Data/Repositories/Contracts/IPostRepository.cs deleted file mode 100644 index 930138a..0000000 --- a/src/DevHive.Data/Repositories/Contracts/IPostRepository.cs +++ /dev/null @@ -1,21 +0,0 @@ -using DevHive.Data.Models; -using System; -using System.Threading.Tasks; - -namespace DevHive.Data.Repositories.Contracts -{ - public interface IPostRepository : IRepository - { - public Task AddCommentAsync(Comment entity); - - public Task GetCommentByIdAsync(Guid id); - - public Task EditCommentAsync(Comment newEntity); - - public Task DeleteCommentAsync(Comment entity); - - public Task DoesPostExist(Guid postId); - - public Task DoesCommentExist(Guid id); - } -} diff --git a/src/DevHive.Data/Repositories/Contracts/IRepository.cs b/src/DevHive.Data/Repositories/Contracts/IRepository.cs deleted file mode 100644 index 37c5170..0000000 --- a/src/DevHive.Data/Repositories/Contracts/IRepository.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace DevHive.Data.Repositories.Contracts -{ - public interface IRepository - where TEntity : class - { - //Add Entity to database - Task AddAsync(TEntity entity); - - //Find entity by id - Task GetByIdAsync(Guid id); - - //Modify Entity from database - Task EditAsync(TEntity newEntity); - - //Delete Entity from database - Task DeleteAsync(TEntity entity); - } -} \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/Contracts/IRoleRepository.cs b/src/DevHive.Data/Repositories/Contracts/IRoleRepository.cs deleted file mode 100644 index 6cb8a4e..0000000 --- a/src/DevHive.Data/Repositories/Contracts/IRoleRepository.cs +++ /dev/null @@ -1,15 +0,0 @@ -using DevHive.Data.Models; -using System; -using System.Threading.Tasks; - -namespace DevHive.Data.Repositories.Contracts -{ - public interface IRoleRepository : IRepository - { - public Task GetByNameAsync(string name); - - public Task DoesNameExist(string name); - - public Task DoesRoleExist(Guid id); - } -} diff --git a/src/DevHive.Data/Repositories/Contracts/ITechnologyRepository.cs b/src/DevHive.Data/Repositories/Contracts/ITechnologyRepository.cs deleted file mode 100644 index 3c4a6b6..0000000 --- a/src/DevHive.Data/Repositories/Contracts/ITechnologyRepository.cs +++ /dev/null @@ -1,13 +0,0 @@ -using DevHive.Data.Models; -using System; -using System.Threading.Tasks; - -namespace DevHive.Data.Repositories.Contracts -{ - public interface ITechnologyRepository : IRepository - { - public Task DoesTechnologyNameExist(string technologyName); - - public Task DoesTechnologyExist(Guid id); - } -} diff --git a/src/DevHive.Data/Repositories/Contracts/IUserRepository.cs b/src/DevHive.Data/Repositories/Contracts/IUserRepository.cs deleted file mode 100644 index 74c4486..0000000 --- a/src/DevHive.Data/Repositories/Contracts/IUserRepository.cs +++ /dev/null @@ -1,26 +0,0 @@ -using DevHive.Data.Models; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace DevHive.Data.Repositories.Contracts -{ - public interface IUserRepository : IRepository - { - public Task AddFriendAsync(User user, User friend); - - public IEnumerable QueryAll(); - - public Task GetByUsername(string username); - - public Task RemoveFriendAsync(User user, User friend); - - public bool DoesUserExist(Guid id); - - public bool DoesUserHaveThisUsername(Guid id, string username); - - public Task DoesUsernameExist(string username); - - public Task DoesEmailExist(string email); - } -} diff --git a/src/DevHive.Data/Repositories/IRepository.cs b/src/DevHive.Data/Repositories/IRepository.cs new file mode 100644 index 0000000..920ba13 --- /dev/null +++ b/src/DevHive.Data/Repositories/IRepository.cs @@ -0,0 +1,21 @@ +using System; +using System.Threading.Tasks; + +namespace DevHive.Data.Repositories +{ + public interface IRepository + where TEntity : class + { + //Add Entity to database + Task AddAsync(TEntity entity); + + //Find entity by id + Task GetByIdAsync(Guid id); + + //Modify Entity from database + Task EditAsync(TEntity newEntity); + + //Delete Entity from database + Task DeleteAsync(TEntity entity); + } +} \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/LanguageRepository.cs b/src/DevHive.Data/Repositories/LanguageRepository.cs index 243192a..5d8217a 100644 --- a/src/DevHive.Data/Repositories/LanguageRepository.cs +++ b/src/DevHive.Data/Repositories/LanguageRepository.cs @@ -1,13 +1,13 @@ using System; +using System.Linq; using System.Threading.Tasks; using DevHive.Common.Models.Misc; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; using Microsoft.EntityFrameworkCore; namespace DevHive.Data.Repositories { - public class LanguageRepository : ILanguageRepository + public class LanguageRepository : IRepository { private readonly DevHiveContext _context; @@ -16,7 +16,8 @@ namespace DevHive.Data.Repositories this._context = context; } - //Create + #region Create + public async Task AddAsync(Language entity) { await this._context @@ -25,42 +26,32 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } + #endregion + + #region Read - //Read public async Task GetByIdAsync(Guid id) { return await this._context .Set() .FindAsync(id); } + #endregion - public async Task DoesLanguageNameExist(string languageName) - { - return await this._context - .Set() - .AsNoTracking() - .AnyAsync(r => r.Name == languageName); - } - - public async Task DoesLanguageExist(Guid id) - { - return await this._context - .Set() - .AsNoTracking() - .AnyAsync(r => r.Id == id); - } + #region Update - //Update public async Task EditAsync(Language newEntity) { - this._context - .Set() - .Update(newEntity); + this._context + .Set() + .Update(newEntity); return await RepositoryMethods.SaveChangesAsync(this._context); } + #endregion + + #region Delete - //Delete public async Task DeleteAsync(Language entity) { this._context @@ -69,5 +60,21 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } + #endregion + + #region Validations + + public async Task DoesLanguageNameExistAsync(string languageName) + { + return await this._context.Languages + .AnyAsync(r => r.Name == languageName); + } + + public async Task DoesLanguageExistAsync(Guid id) + { + return await this._context.Languages + .AnyAsync(r => r.Id == id); + } + #endregion } } \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/PostRepository.cs b/src/DevHive.Data/Repositories/PostRepository.cs index 0acfc23..002fb17 100644 --- a/src/DevHive.Data/Repositories/PostRepository.cs +++ b/src/DevHive.Data/Repositories/PostRepository.cs @@ -2,12 +2,11 @@ using System; using System.Threading.Tasks; using DevHive.Common.Models.Misc; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; using Microsoft.EntityFrameworkCore; namespace DevHive.Data.Repositories { - public class PostRepository : IPostRepository + public class PostRepository : IRepository { private readonly DevHiveContext _context; @@ -88,6 +87,8 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } + #region Validations + public async Task DoesPostExist(Guid postId) { return await this._context @@ -103,5 +104,6 @@ namespace DevHive.Data.Repositories .AsNoTracking() .AnyAsync(r => r.Id == id); } + #endregion } } \ No newline at end of file diff --git a/src/DevHive.Data/Repositories/RoleRepository.cs b/src/DevHive.Data/Repositories/RoleRepository.cs index d6f83a8..0ca1646 100644 --- a/src/DevHive.Data/Repositories/RoleRepository.cs +++ b/src/DevHive.Data/Repositories/RoleRepository.cs @@ -2,12 +2,11 @@ using System; using System.Threading.Tasks; using DevHive.Common.Models.Misc; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; using Microsoft.EntityFrameworkCore; namespace DevHive.Data.Repositories { - public class RoleRepository : IRoleRepository + public class RoleRepository : IRepository { private readonly DevHiveContext _context; diff --git a/src/DevHive.Data/Repositories/TechnologyRepository.cs b/src/DevHive.Data/Repositories/TechnologyRepository.cs index 27918ca..2ed3a23 100644 --- a/src/DevHive.Data/Repositories/TechnologyRepository.cs +++ b/src/DevHive.Data/Repositories/TechnologyRepository.cs @@ -2,13 +2,12 @@ using System; using System.Threading.Tasks; using DevHive.Common.Models.Misc; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; using Microsoft.EntityFrameworkCore; namespace DevHive.Data.Repositories { - public abstract class TechnologyRepository : ITechnologyRepository + public abstract class TechnologyRepository : IRepository { private DevHiveContext _context; @@ -27,7 +26,7 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } - //Read + //Read public async Task GetByIdAsync(Guid id) { return await this._context diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 5142b82..e3c1304 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -4,12 +4,11 @@ using System.Linq; using System.Threading.Tasks; using DevHive.Common.Models.Misc; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; using Microsoft.EntityFrameworkCore; namespace DevHive.Data.Repositories { - public class UserRepository : IUserRepository + public class UserRepository : IRepository { private readonly DevHiveContext _context; @@ -18,11 +17,11 @@ namespace DevHive.Data.Repositories this._context = context; } - //Create + #region Create + public async Task AddAsync(User entity) { - await this._context - .Set() + await this._context.Users .AddAsync(entity); return await RepositoryMethods.SaveChangesAsync(this._context); @@ -35,12 +34,31 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } - - //Read + + public async Task AddLanguageToUserAsync(User user, Language language) + { + this._context.Update(user); + + user.Langauges.Add(language); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + public async Task AddTechnologyToUserAsync(User user, Technology technology) + { + this._context.Update(user); + + user.Technologies.Add(technology); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + #endregion + + #region Read + public IEnumerable QueryAll() { - return this._context - .Set() + return this._context.Users .Include(x => x.Roles) .AsNoTracking() .AsEnumerable(); @@ -48,8 +66,7 @@ namespace DevHive.Data.Repositories public async Task GetByIdAsync(Guid id) { - return await this._context - .Set() + return await this._context.Users .Include(x => x.Roles) .Include(x => x.Friends) .FirstOrDefaultAsync(x => x.Id == id); @@ -57,13 +74,36 @@ namespace DevHive.Data.Repositories public async Task GetByUsername(string username) { - return await this._context - .Set() + return await this._context.Users .Include(u => u.Roles) .FirstOrDefaultAsync(x => x.UserName == username); } - //Update + public IList GetUserLanguages(User user) + { + return user.Langauges; + } + + public Language GetUserLanguage(User user, Language language) + { + return user.Langauges + .FirstOrDefault(x => x.Id == language.Id); + } + + public IList GetUserTechnologies(User user) + { + return user.Technologies; + } + + public Technology GetUserTechnology(User user, Technology technology) + { + return user.Technologies + .FirstOrDefault(x => x.Id == technology.Id); + } + #endregion + + #region Update + public async Task EditAsync(User newEntity) { User user = await this.GetByIdAsync(newEntity.Id); @@ -76,11 +116,32 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } - //Delete + public async Task EditUserLanguage(User user, Language oldLang, Language newLang) + { + this._context.Update(user); + + user.Langauges.Remove(oldLang); + user.Langauges.Add(newLang); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + + public async Task EditUserTechnologies(User user, Technology oldTech, Technology newTech) + { + this._context.Update(user); + + user.Technologies.Remove(oldTech); + user.Technologies.Add(newTech); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + #endregion + + #region Delete + public async Task DeleteAsync(User entity) { - this._context - .Set() + this._context.Users .Remove(entity); return await RepositoryMethods.SaveChangesAsync(this._context); @@ -93,37 +154,70 @@ namespace DevHive.Data.Repositories return await RepositoryMethods.SaveChangesAsync(this._context); } - - //Validations - public bool DoesUserExist(Guid id) + + public async Task RemoveLanguageFromUserAsync(User user, Language language) { - return this._context - .Set() - .Any(x => x.Id == id); + this._context.Update(user); + + user.Langauges.Remove(language); + + return await RepositoryMethods.SaveChangesAsync(this._context); } - public bool DoesUserHaveThisUsername(Guid id, string username) + public async Task RemoveTechnologyFromUserAsync(User user, Technology technology) { - return this._context - .Set() - .Any(x => x.Id == id && - x.UserName == username); + this._context.Update(user); + + user.Technologies.Remove(technology); + + return await RepositoryMethods.SaveChangesAsync(this._context); + } + #endregion + + #region Validations + + public async Task DoesUserExistAsync(Guid id) + { + return await this._context.Users + .AnyAsync(x => x.Id == id); } - public async Task DoesUsernameExist(string username) + public async Task DoesUsernameExistAsync(string username) { - return await this._context - .Set() + return await this._context.Users .AsNoTracking() .AnyAsync(u => u.UserName == username); } - public async Task DoesEmailExist(string email) + public async Task DoesEmailExistAsync(string email) { - return await this._context - .Set() + return await this._context.Users .AsNoTracking() .AnyAsync(u => u.Email == email); } + + public async Task DoesUserHaveThisFriendAsync(Guid userId, Guid friendId) + { + User user = await this._context.Users + .FirstOrDefaultAsync(x => x.Id == userId); + + User friend = await this._context.Users + .FirstOrDefaultAsync(x => x.Id == friendId); + + return user.Friends.Contains(friend); + } + + public bool DoesUserHaveThisUsername(Guid id, string username) + { + return this._context.Users + .Any(x => x.Id == id && + x.UserName == username); + } + + public bool DoesUserHaveFriends(User user) + { + return user.Friends.Count >= 1; + } + #endregion } } diff --git a/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs b/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs index 27f392d..0be9ca2 100644 --- a/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs @@ -10,7 +10,6 @@ namespace DevHive.Services.Configurations.Mapping { CreateMap(); CreateMap(); - CreateMap(); } } } \ No newline at end of file diff --git a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs index 77f2733..74f66b4 100644 --- a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs @@ -1,7 +1,13 @@ +using System.Collections.Generic; +using DevHive.Services.Models.Language; +using DevHive.Services.Models.Technology; + namespace DevHive.Services.Models.Identity.User { public class RegisterServiceModel : BaseUserServiceModel - { + { + public IList Languages { get; set; } + public IList Technologies { get; set; } public string Password { get; set; } } } diff --git a/src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs b/src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs new file mode 100644 index 0000000..75e7714 --- /dev/null +++ b/src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Services.Models.Language +{ + public class CreateLanguageServiceModel : LanguageServiceModel + { + public string Name { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Language/LanguageServiceModel.cs b/src/DevHive.Services/Models/Language/LanguageServiceModel.cs index f06ebb6..a07aa16 100644 --- a/src/DevHive.Services/Models/Language/LanguageServiceModel.cs +++ b/src/DevHive.Services/Models/Language/LanguageServiceModel.cs @@ -1,7 +1,9 @@ +using System; + namespace DevHive.Services.Models.Language { public class LanguageServiceModel { - public string Name { get; set; } + public Guid Id { get; set; } } } diff --git a/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs b/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs index 30194dd..fdc309e 100644 --- a/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs +++ b/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs @@ -1,9 +1,4 @@ -using System; - namespace DevHive.Services.Models.Language { - public class UpdateLanguageServiceModel : LanguageServiceModel - { - public Guid Id { get; set; } - } + public class UpdateLanguageServiceModel : CreateLanguageServiceModel { } } diff --git a/src/DevHive.Services/Services/LanguageService.cs b/src/DevHive.Services/Services/LanguageService.cs index 3c011c6..127bde4 100644 --- a/src/DevHive.Services/Services/LanguageService.cs +++ b/src/DevHive.Services/Services/LanguageService.cs @@ -2,25 +2,25 @@ using System; using System.Threading.Tasks; using AutoMapper; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; +using DevHive.Data.Repositories; using DevHive.Services.Models.Language; namespace DevHive.Services.Services { public class LanguageService { - private readonly ILanguageRepository _languageRepository; + private readonly LanguageRepository _languageRepository; private readonly IMapper _languageMapper; - public LanguageService(ILanguageRepository languageRepository, IMapper mapper) + public LanguageService(LanguageRepository languageRepository, IMapper mapper) { this._languageRepository = languageRepository; this._languageMapper = mapper; } - public async Task CreateLanguage(LanguageServiceModel languageServiceModel) + public async Task CreateLanguage(CreateLanguageServiceModel languageServiceModel) { - if (await this._languageRepository.DoesLanguageNameExist(languageServiceModel.Name)) + if (await this._languageRepository.DoesLanguageNameExistAsync(languageServiceModel.Name)) throw new ArgumentException("Language already exists!"); Language language = this._languageMapper.Map(languageServiceModel); @@ -33,7 +33,7 @@ namespace DevHive.Services.Services { Language language = await this._languageRepository.GetByIdAsync(id); - if(language == null) + if (language == null) throw new ArgumentException("The language does not exist"); return this._languageMapper.Map(language); @@ -41,28 +41,28 @@ namespace DevHive.Services.Services public async Task UpdateLanguage(UpdateLanguageServiceModel languageServiceModel) { - if (!await this._languageRepository.DoesLanguageExist(languageServiceModel.Id)) - throw new ArgumentException("Language does not exist!"); + Task langExist = this._languageRepository.DoesLanguageExistAsync(languageServiceModel.Id); + Task newLangNameExists = this._languageRepository.DoesLanguageNameExistAsync(languageServiceModel.Name); - if (await this._languageRepository.DoesLanguageNameExist(languageServiceModel.Name)) - throw new ArgumentException("Language name already exists!"); + await Task.WhenAny(langExist, newLangNameExists); - Language language = this._languageMapper.Map(languageServiceModel); - //language.Id = languageServiceModel.Id; - bool result = await this._languageRepository.EditAsync(language); + if (!langExist.Result) + throw new ArgumentException("Language already exists!"); - return result; + if (newLangNameExists.Result) + throw new ArgumentException("This name is already in our datbase!"); + + Language lang = this._languageMapper.Map(languageServiceModel); + return await this._languageRepository.EditAsync(lang); } - + public async Task DeleteLanguage(Guid id) { - if (!await this._languageRepository.DoesLanguageExist(id)) + if (!await this._languageRepository.DoesLanguageExistAsync(id)) throw new ArgumentException("Language does not exist!"); Language language = await this._languageRepository.GetByIdAsync(id); - bool result = await this._languageRepository.DeleteAsync(language); - - return result; + return await this._languageRepository.DeleteAsync(language); } } } \ No newline at end of file diff --git a/src/DevHive.Services/Services/PostService.cs b/src/DevHive.Services/Services/PostService.cs index e0a2be9..321c694 100644 --- a/src/DevHive.Services/Services/PostService.cs +++ b/src/DevHive.Services/Services/PostService.cs @@ -7,17 +7,17 @@ using DevHive.Services.Models.Post.Comment; using DevHive.Services.Models.Post.Post; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; -using DevHive.Data.Repositories.Contracts; +using DevHive.Data.Repositories; namespace DevHive.Services.Services { public class PostService { - private readonly IPostRepository _postRepository; - private readonly IUserRepository _userRepository; + private readonly PostRepository _postRepository; + private readonly UserRepository _userRepository; private readonly IMapper _postMapper; - public PostService(IPostRepository postRepository, IUserRepository userRepository , IMapper postMapper) + public PostService(PostRepository postRepository, UserRepository userRepository , IMapper postMapper) { this._postRepository = postRepository; this._userRepository = userRepository; diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index 372984d..7ba0a98 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -3,16 +3,16 @@ using System.Threading.Tasks; using AutoMapper; using DevHive.Common.Models.Identity; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; +using DevHive.Data.Repositories; namespace DevHive.Services.Services { public class RoleService { - private readonly IRoleRepository _roleRepository; + private readonly RoleRepository _roleRepository; private readonly IMapper _roleMapper; - public RoleService(IRoleRepository roleRepository, IMapper mapper) + public RoleService(RoleRepository roleRepository, IMapper mapper) { this._roleRepository = roleRepository; this._roleMapper = mapper; diff --git a/src/DevHive.Services/Services/TechnologyService.cs b/src/DevHive.Services/Services/TechnologyService.cs index e03d4d1..2913a55 100644 --- a/src/DevHive.Services/Services/TechnologyService.cs +++ b/src/DevHive.Services/Services/TechnologyService.cs @@ -2,17 +2,17 @@ using System; using System.Threading.Tasks; using AutoMapper; using DevHive.Data.Models; -using DevHive.Data.Repositories.Contracts; +using DevHive.Data.Repositories; using DevHive.Services.Models.Technology; namespace DevHive.Services.Services { public class TechnologyService { - private readonly ITechnologyRepository _technologyRepository; + private readonly TechnologyRepository _technologyRepository; private readonly IMapper _technologyMapper; - public TechnologyService(ITechnologyRepository technologyRepository, IMapper technologyMapper) + public TechnologyService(TechnologyRepository technologyRepository, IMapper technologyMapper) { this._technologyRepository = technologyRepository; this._technologyMapper = technologyMapper; diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index c8bcab9..e1f925d 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -11,28 +11,40 @@ using System.Security.Cryptography; using System.Text; using System.Collections.Generic; using DevHive.Common.Models.Identity; -using DevHive.Data.Repositories.Contracts; +using DevHive.Services.Models.Language; +using DevHive.Data.Repositories; namespace DevHive.Services.Services { public class UserService { - private readonly IUserRepository _userRepository; - private readonly IRoleRepository _roleRepository; + private readonly UserRepository _userRepository; + private readonly RoleRepository _roleRepository; + private readonly LanguageRepository _languageRepository; + private readonly TechnologyRepository _technologyRepository; private readonly IMapper _userMapper; private readonly JWTOptions _jwtOptions; - public UserService(IUserRepository userRepository, IRoleRepository roleRepository, IMapper mapper, JWTOptions jwtOptions) + public UserService(UserRepository userRepository, + LanguageRepository languageRepository, + RoleRepository roleRepository, + TechnologyRepository technologyRepository, + IMapper mapper, + JWTOptions jwtOptions) { this._userRepository = userRepository; this._roleRepository = roleRepository; this._userMapper = mapper; this._jwtOptions = jwtOptions; + this._languageRepository = languageRepository; + this._technologyRepository = technologyRepository; } + #region Authentication + public async Task LoginUser(LoginServiceModel loginModel) { - if (!await this._userRepository.DoesUsernameExist(loginModel.UserName)) + if (!await this._userRepository.DoesUsernameExistAsync(loginModel.UserName)) throw new ArgumentException("Invalid username!"); User user = await this._userRepository.GetByUsername(loginModel.UserName); @@ -45,10 +57,10 @@ namespace DevHive.Services.Services public async Task RegisterUser(RegisterServiceModel registerModel) { - if (await this._userRepository.DoesUsernameExist(registerModel.UserName)) + if (await this._userRepository.DoesUsernameExistAsync(registerModel.UserName)) throw new ArgumentException("Username already exists!"); - if (await this._userRepository.DoesEmailExist(registerModel.Email)) + if (await this._userRepository.DoesEmailExistAsync(registerModel.Email)) throw new ArgumentException("Email already exists!"); User user = this._userMapper.Map(registerModel); @@ -66,20 +78,58 @@ namespace DevHive.Services.Services return new TokenModel(WriteJWTSecurityToken(user.UserName, user.Roles)); } + #endregion + + #region Create public async Task AddFriend(Guid userId, Guid friendId) { - User user = await this._userRepository.GetByIdAsync(userId); - User friend = await this._userRepository.GetByIdAsync(friendId); + Task userExists = this._userRepository.DoesUserExistAsync(userId); + Task friendExists = this._userRepository.DoesUserExistAsync(friendId); + + await Task.WhenAll(userExists, friendExists); + + if (!userExists.Result) + throw new ArgumentException("User doesn't exist!"); - if (DoesUserHaveThisFriend(user, friend)) + if (!friendExists.Result) + throw new ArgumentException("Friend doesn't exist!"); + + if (await this._userRepository.DoesUserHaveThisFriendAsync(userId, friendId)) throw new ArgumentException("Friend already exists in your friends list."); - return user != default(User) && friend != default(User) ? - await this._userRepository.AddFriendAsync(user, friend) : + User user = await this._userRepository.GetByIdAsync(userId); + User friend = await this._userRepository.GetByIdAsync(friendId); + + return user != default(User) && friend != default(User) ? + await this._userRepository.AddFriendAsync(user, friend) : throw new ArgumentException("Invalid user!"); } + public async Task AddLanguageToUser(Guid userId, LanguageServiceModel languageServiceModel) + { + Task userExists = this._userRepository.DoesUserExistAsync(userId); + Task languageExists = this._languageRepository.DoesLanguageExistAsync(languageServiceModel.Id); + + await Task.WhenAll(userExists, languageExists); + + if (!userExists.Result) + throw new ArgumentException("User does not exist!"); + + if (!languageExists.Result) + throw new ArgumentException("Language does not exist!"); + + Task user = this._userRepository.GetByIdAsync(userId); + Task language = this._languageRepository.GetByIdAsync(languageServiceModel.Id); + + await Task.WhenAll(user, language); + + return await this._userRepository.AddLanguageToUserAsync(user.Result, language.Result); + } + #endregion + + #region Read + public async Task GetUserById(Guid id) { User user = await this._userRepository.GetByIdAsync(id) @@ -90,21 +140,24 @@ namespace DevHive.Services.Services public async Task GetFriendById(Guid friendId) { - if(!_userRepository.DoesUserExist(friendId)) + if (!await _userRepository.DoesUserExistAsync(friendId)) throw new ArgumentException("User does not exist!"); User friend = await this._userRepository.GetByIdAsync(friendId); return this._userMapper.Map(friend); } + #endregion + + #region Update public async Task UpdateUser(UpdateUserServiceModel updateModel) { - if (!this._userRepository.DoesUserExist(updateModel.Id)) + if (!await this._userRepository.DoesUserExistAsync(updateModel.Id)) throw new ArgumentException("User does not exist!"); if (!this._userRepository.DoesUserHaveThisUsername(updateModel.Id, updateModel.UserName) - && await this._userRepository.DoesUsernameExist(updateModel.UserName)) + && await this._userRepository.DoesUsernameExistAsync(updateModel.UserName)) throw new ArgumentException("Username already exists!"); User user = this._userMapper.Map(updateModel); @@ -113,12 +166,15 @@ namespace DevHive.Services.Services if (!result) throw new InvalidOperationException("Unable to edit user!"); - return this._userMapper.Map(user);; + return this._userMapper.Map(user); ; } + #endregion + + #region Delete public async Task DeleteUser(Guid id) { - if (!this._userRepository.DoesUserExist(id)) + if (!await this._userRepository.DoesUserExistAsync(id)) throw new ArgumentException("User does not exist!"); User user = await this._userRepository.GetByIdAsync(id); @@ -130,21 +186,25 @@ namespace DevHive.Services.Services public async Task RemoveFriend(Guid userId, Guid friendId) { - if(!this._userRepository.DoesUserExist(userId) && - !this._userRepository.DoesUserExist(friendId)) - throw new ArgumentException("Invalid user!"); + Task userExists = this._userRepository.DoesUserExistAsync(userId); + Task friendExists = this._userRepository.DoesUserExistAsync(friendId); - User user = await this._userRepository.GetByIdAsync(userId); - User friend = await this._userRepository.GetByIdAsync(friendId); + await Task.WhenAll(userExists, friendExists); + + if (!userExists.Result) + throw new ArgumentException("User doesn't exist!"); - if(!this.DoesUserHaveFriends(user)) - throw new ArgumentException("User does not have any friends."); + if (!friendExists.Result) + throw new ArgumentException("Friend doesn't exist!"); - if (!DoesUserHaveThisFriend(user, friend)) + if (!await this._userRepository.DoesUserHaveThisFriendAsync(userId, friendId)) throw new ArgumentException("This ain't your friend, amigo."); - return await this.RemoveFriend(user.Id, friendId); + return await this.RemoveFriend(userId, friendId); } + #endregion + + #region Validations public async Task ValidJWT(Guid id, string rawTokenData) { @@ -153,7 +213,7 @@ namespace DevHive.Services.Services string jwtUserName = this.GetClaimTypeValues("unique_name", jwt.Claims)[0]; List jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims); - + User user = await this._userRepository.GetByUsername(jwtUserName) ?? throw new ArgumentException("User does not exist!"); @@ -164,9 +224,9 @@ namespace DevHive.Services.Services return false; /* Check roles */ - + // Check if jwt contains all user roles (if it doesn't, jwt is either old or tampered with) - foreach(var role in user.Roles) + foreach (var role in user.Roles) { if (!jwtRoleNames.Contains(role.Name)) return false; @@ -179,26 +239,11 @@ namespace DevHive.Services.Services return true; } - private string GeneratePasswordHash(string password) - { - 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) + + foreach (var claim in claims) if (claim.Type == type) toReturn.Add(claim.Value); @@ -214,7 +259,7 @@ namespace DevHive.Services.Services new Claim(ClaimTypes.Name, userName), }; - foreach(var role in roles) + foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role.Name)); } @@ -232,5 +277,12 @@ namespace DevHive.Services.Services SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } + + private string GeneratePasswordHash(string password) + { + return string.Join(string.Empty, SHA512.HashData(Encoding.ASCII.GetBytes(password))); + } + + #endregion } } diff --git a/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs b/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs index ee0ca4b..beac798 100644 --- a/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs +++ b/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs @@ -34,7 +34,7 @@ namespace DevHive.Data.Tests this.Context.Database.EnsureDeleted(); } - #region AddAync + #region AddAsync [Test] public void AddAsync_AddsTheGivenTechnologyToTheDatabase() { @@ -127,7 +127,7 @@ namespace DevHive.Data.Tests { bool result = await this.TechnologyRepository.DoesTechnologyNameExist(TECHNOLOGY_NAME); - Assert.False(result, "DoesTechnologyNameExist returns true when tehcnology name does not exist"); + Assert.False(result, "DoesTechnologyNameExist returns true when technology name does not exist"); }).GetAwaiter().GetResult(); } #endregion diff --git a/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs b/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs index 5715b13..bae8562 100644 --- a/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs @@ -9,9 +9,12 @@ namespace DevHive.Web.Configurations.Mapping public LanguageMappings() { CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); } } } \ No newline at end of file diff --git a/src/DevHive.Web/Controllers/LanguageController.cs b/src/DevHive.Web/Controllers/LanguageController.cs index d71d622..29c1e99 100644 --- a/src/DevHive.Web/Controllers/LanguageController.cs +++ b/src/DevHive.Web/Controllers/LanguageController.cs @@ -23,9 +23,9 @@ namespace DevHive.Web.Controllers } [HttpPost] - public async Task Create([FromBody] LanguageWebModel languageWebModel) + public async Task Create([FromBody] CreateLanguageWebModel createLanguageWebModel) { - LanguageServiceModel languageServiceModel = this._languageMapper.Map(languageWebModel); + CreateLanguageServiceModel languageServiceModel = this._languageMapper.Map(createLanguageWebModel); bool result = await this._languageService.CreateLanguage(languageServiceModel); diff --git a/src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs b/src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs new file mode 100644 index 0000000..111beed --- /dev/null +++ b/src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Web.Models.Language +{ + public class CreateLanguageWebModel : LanguageWebModel + { + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/src/DevHive.Web/Models/Language/LanguageWebModel.cs b/src/DevHive.Web/Models/Language/LanguageWebModel.cs index 1ec38f3..455b559 100644 --- a/src/DevHive.Web/Models/Language/LanguageWebModel.cs +++ b/src/DevHive.Web/Models/Language/LanguageWebModel.cs @@ -1,7 +1,9 @@ +using System; + namespace DevHive.Web.Models.Language { public class LanguageWebModel { - public string Name { get; set; } + public Guid Id { get; set; } } } \ No newline at end of file diff --git a/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs b/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs index 26eb6c2..2da8217 100644 --- a/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs +++ b/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs @@ -2,8 +2,5 @@ using System; namespace DevHive.Web.Models.Language { - public class UpdateLanguageWebModel : LanguageWebModel - { - public Guid Id { get; set; } - } + public class UpdateLanguageWebModel : CreateLanguageWebModel {} } \ No newline at end of file -- cgit v1.2.3 From 8e11fbaa79ad6fba234e8162c5b291174ed31fbb Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 12 Jan 2021 23:07:13 +0200 Subject: Fixed bugs with Lang features, User's GetById, Lang & User mappings; Added more UserService validations --- src/DevHive.Data/Repositories/UserRepository.cs | 9 ++++- .../Configurations/Mapping/LanguageMappings.cs | 5 +++ .../Models/Identity/User/UserServiceModel.cs | 6 +++- .../Models/Language/CreateLanguageServiceModel.cs | 2 +- .../Models/Language/UpdateLanguageServiceModel.cs | 7 +++- src/DevHive.Services/Services/LanguageService.cs | 7 ++-- src/DevHive.Services/Services/UserService.cs | 42 +++++++++++----------- .../Extensions/ConfigureDependencyInjection.cs | 2 -- src/DevHive.Web/Controllers/ErrorController.cs | 3 ++ src/DevHive.Web/Controllers/UserController.cs | 2 ++ .../Models/Identity/User/UserWebModel.cs | 4 +++ .../Models/Language/CreateLanguageWebModel.cs | 2 +- src/DevHive.code-workspace | 3 ++ 13 files changed, 62 insertions(+), 32 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index e3c1304..64a81ae 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -67,8 +67,10 @@ namespace DevHive.Data.Repositories public async Task GetByIdAsync(Guid id) { return await this._context.Users - .Include(x => x.Roles) .Include(x => x.Friends) + .Include(x => x.Roles) + .Include(x => x.Langauges) + .Include(x => x.Technologies) .FirstOrDefaultAsync(x => x.Id == id); } @@ -218,6 +220,11 @@ namespace DevHive.Data.Repositories { return user.Friends.Count >= 1; } + + public bool DoesUserHaveThisLanguage(User user, Language language) + { + return user.Langauges.Contains(language); + } #endregion } } diff --git a/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs b/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs index 0be9ca2..e483fff 100644 --- a/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/LanguageMappings.cs @@ -9,7 +9,12 @@ namespace DevHive.Services.Configurations.Mapping public LanguageMappings() { CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); } } } \ No newline at end of file diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 953b038..8825f50 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -1,11 +1,15 @@ using System.Collections.Generic; using DevHive.Common.Models.Identity; +using DevHive.Services.Models.Language; +using DevHive.Services.Models.Technology; namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { public IList Roles { get; set; } = new List(); - public List Friends { get; set; } = new List(); + public IList Friends { get; set; } = new List(); + public IList Languages { get; set; } = new List(); + public IList TechnologyServiceModels { get; set; } = new List(); } } diff --git a/src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs b/src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs index 75e7714..9d66d3e 100644 --- a/src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs +++ b/src/DevHive.Services/Models/Language/CreateLanguageServiceModel.cs @@ -2,7 +2,7 @@ using System; namespace DevHive.Services.Models.Language { - public class CreateLanguageServiceModel : LanguageServiceModel + public class CreateLanguageServiceModel { public string Name { get; set; } } diff --git a/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs b/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs index fdc309e..8536693 100644 --- a/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs +++ b/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs @@ -1,4 +1,9 @@ +using System; + namespace DevHive.Services.Models.Language { - public class UpdateLanguageServiceModel : CreateLanguageServiceModel { } + public class UpdateLanguageServiceModel : LanguageServiceModel + { + public string Name { get; set; } + } } diff --git a/src/DevHive.Services/Services/LanguageService.cs b/src/DevHive.Services/Services/LanguageService.cs index 127bde4..ccc64fd 100644 --- a/src/DevHive.Services/Services/LanguageService.cs +++ b/src/DevHive.Services/Services/LanguageService.cs @@ -18,12 +18,13 @@ namespace DevHive.Services.Services this._languageMapper = mapper; } - public async Task CreateLanguage(CreateLanguageServiceModel languageServiceModel) + public async Task CreateLanguage(CreateLanguageServiceModel createLanguageServiceModel) { - if (await this._languageRepository.DoesLanguageNameExistAsync(languageServiceModel.Name)) + if (await this._languageRepository.DoesLanguageNameExistAsync(createLanguageServiceModel.Name)) throw new ArgumentException("Language already exists!"); - Language language = this._languageMapper.Map(languageServiceModel); + //TODO: Fix, cuz it breaks + Language language = this._languageMapper.Map(createLanguageServiceModel); bool result = await this._languageRepository.AddAsync(language); return result; diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 4fb18a0..c1de741 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -111,6 +111,9 @@ namespace DevHive.Services.Services { Tuple tuple = await ValidateUserAndLanguage(userId, languageServiceModel); + if (this._userRepository.DoesUserHaveThisLanguage(tuple.Item1, tuple.Item2)) + throw new ArgumentException("User already has this language!"); + return await this._userRepository.AddLanguageToUserAsync(tuple.Item1, tuple.Item2); } @@ -201,6 +204,9 @@ namespace DevHive.Services.Services { Tuple tuple = await ValidateUserAndLanguage(userId, languageServiceModel); + if (!this._userRepository.DoesUserHaveThisLanguage(tuple.Item1, tuple.Item2)) + throw new ArgumentException("User does not have this language!"); + return await this._userRepository.RemoveLanguageFromUserAsync(tuple.Item1, tuple.Item2); } @@ -293,44 +299,36 @@ namespace DevHive.Services.Services private async Task> ValidateUserAndLanguage(Guid userId, LanguageServiceModel languageServiceModel) { - Task userExists = this._userRepository.DoesUserExistAsync(userId); - Task languageExists = this._languageRepository.DoesLanguageExistAsync(languageServiceModel.Id); + bool userExists = await this._userRepository.DoesUserExistAsync(userId); + bool languageExists = await this._languageRepository.DoesLanguageExistAsync(languageServiceModel.Id); - await Task.WhenAll(userExists, languageExists); - - if (!userExists.Result) + if (!userExists) throw new ArgumentException("User does not exist!"); - if (!languageExists.Result) + if (!languageExists) throw new ArgumentException("Language does not exist!"); - Task user = this._userRepository.GetByIdAsync(userId); - Task language = this._languageRepository.GetByIdAsync(languageServiceModel.Id); - - await Task.WhenAll(user, language); + User user = await this._userRepository.GetByIdAsync(userId); + Language language = await this._languageRepository.GetByIdAsync(languageServiceModel.Id); - return new Tuple(user.Result, language.Result); + return new Tuple(user, language); } private async Task> ValidateUserAndTechnology(Guid userId, TechnologyServiceModel technologyServiceModel) { - Task userExists = this._userRepository.DoesUserExistAsync(userId); - Task technologyExists = this._technologyRepository.DoesTechnologyExistAsync(technologyServiceModel.Id); - - await Task.WhenAll(userExists, technologyExists); + bool userExists = await this._userRepository.DoesUserExistAsync(userId); + bool technologyExists = await this._technologyRepository.DoesTechnologyExistAsync(technologyServiceModel.Id); - if (!userExists.Result) + if (!userExists) throw new ArgumentException("User does not exist!"); - if (!technologyExists.Result) + if (!technologyExists) throw new ArgumentException("Language does not exist!"); - Task user = this._userRepository.GetByIdAsync(userId); - Task technology = this._technologyRepository.GetByIdAsync(technologyServiceModel.Id); - - await Task.WhenAll(user, technology); + User user = await this._userRepository.GetByIdAsync(userId); + Technology technology = await this._technologyRepository.GetByIdAsync(technologyServiceModel.Id); - return new Tuple(user.Result, technology.Result); + return new Tuple(user, technology); } #endregion } diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs index cce5174..46b2591 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -20,8 +20,6 @@ namespace DevHive.Web.Configurations.Extensions services.AddTransient(); services.AddTransient(); services.AddTransient(); - - System.Console.WriteLine(services.Count); } } } \ No newline at end of file diff --git a/src/DevHive.Web/Controllers/ErrorController.cs b/src/DevHive.Web/Controllers/ErrorController.cs index 67a83fe..c3f1e55 100644 --- a/src/DevHive.Web/Controllers/ErrorController.cs +++ b/src/DevHive.Web/Controllers/ErrorController.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using AutoMapper; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -29,6 +30,8 @@ namespace DevHive.Web.Controllers { case ArgumentException _: case InvalidOperationException _: + case AutoMapperMappingException _: + case AutoMapperConfigurationException _: return MessageToObject(exception.Error.Message); default: return MessageToObject(null); diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index c222ba6..0960915 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -94,6 +94,7 @@ namespace DevHive.Web.Controllers #endregion #region Read + [HttpGet] public async Task GetById(Guid id, [FromHeader] string authorization) { @@ -135,6 +136,7 @@ namespace DevHive.Web.Controllers #endregion #region Delete + [HttpDelete] public async Task Delete(Guid id, [FromHeader] string authorization) { diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 37d6553..260d34c 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; using DevHive.Common.Models.Identity; using DevHive.Web.Models.Identity.Role; +using DevHive.Web.Models.Language; +using DevHive.Web.Models.Technology; namespace DevHive.Web.Models.Identity.User { @@ -8,5 +10,7 @@ namespace DevHive.Web.Models.Identity.User { public IList Roles { get; set; } = new List(); public IList Friends { get; set; } = new List(); + public IList Languages { get; set; } = new List(); + public IList Technologies { get; set; } = new List(); } } diff --git a/src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs b/src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs index 111beed..d261500 100644 --- a/src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs +++ b/src/DevHive.Web/Models/Language/CreateLanguageWebModel.cs @@ -2,7 +2,7 @@ using System; namespace DevHive.Web.Models.Language { - public class CreateLanguageWebModel : LanguageWebModel + public class CreateLanguageWebModel { public string Name { get; set; } } diff --git a/src/DevHive.code-workspace b/src/DevHive.code-workspace index 8899918..04a9a2f 100644 --- a/src/DevHive.code-workspace +++ b/src/DevHive.code-workspace @@ -57,6 +57,9 @@ "env": { "ASPNETCORE_ENVIRONMENT": "Development" }, + "launchBrowser": { + "enabled": true + } }, ], "compounds": [] -- cgit v1.2.3 From e20e89e83c73864d5dc3615733836a1f1d1565c6 Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 14 Jan 2021 11:09:39 +0200 Subject: More formatting fixes --- src/DevHive.Data/DevHiveContext.cs | 2 +- src/DevHive.Data/Interfaces/IPostRepository.cs | 4 +- src/DevHive.Data/Interfaces/IRoleRepository.cs | 4 +- .../Migrations/20201219141035_DbContext_Moved.cs | 530 ++++++++++----------- .../Migrations/20201230154737_CommentMigration.cs | 48 +- .../20210112111416_User_Implements_Languages.cs | 200 ++++---- src/DevHive.Data/Models/Language.cs | 2 +- .../Configurations/Mapping/PostMappings.cs | 2 +- .../Configurations/Mapping/RoleMapings.cs | 2 +- .../Configurations/Mapping/UserMappings.cs | 2 +- src/DevHive.Services/Interfaces/IPostService.cs | 6 +- src/DevHive.Services/Interfaces/IRoleService.cs | 4 +- .../Models/Identity/User/BaseUserServiceModel.cs | 2 +- .../Models/Post/Post/CreatePostServiceModel.cs | 4 +- .../Models/Post/Post/UpdatePostServiceModel.cs | 6 +- .../TechnologyRepository.Tests.cs | 378 +++++++-------- src/DevHive.Tests/DevHive.Web.Tests/UnitTest1.cs | 18 - 17 files changed, 598 insertions(+), 616 deletions(-) delete mode 100644 src/DevHive.Tests/DevHive.Web.Tests/UnitTest1.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/DevHiveContext.cs b/src/DevHive.Data/DevHiveContext.cs index c9959dc..10fd004 100644 --- a/src/DevHive.Data/DevHiveContext.cs +++ b/src/DevHive.Data/DevHiveContext.cs @@ -22,7 +22,7 @@ namespace DevHive.Data builder.Entity() .HasMany(x => x.Roles); - + builder.Entity() .HasMany(x => x.Friends); diff --git a/src/DevHive.Data/Interfaces/IPostRepository.cs b/src/DevHive.Data/Interfaces/IPostRepository.cs index 9c75ecc..a02fd08 100644 --- a/src/DevHive.Data/Interfaces/IPostRepository.cs +++ b/src/DevHive.Data/Interfaces/IPostRepository.cs @@ -10,11 +10,11 @@ namespace DevHive.Data.Interfaces Task AddCommentAsync(Comment entity); Task GetCommentByIdAsync(Guid id); - + Task EditCommentAsync(Comment newEntity); Task DeleteCommentAsync(Comment entity); Task DoesCommentExist(Guid id); Task DoesPostExist(Guid postId); } -} \ No newline at end of file +} diff --git a/src/DevHive.Data/Interfaces/IRoleRepository.cs b/src/DevHive.Data/Interfaces/IRoleRepository.cs index 48761db..a1080bb 100644 --- a/src/DevHive.Data/Interfaces/IRoleRepository.cs +++ b/src/DevHive.Data/Interfaces/IRoleRepository.cs @@ -8,8 +8,8 @@ namespace DevHive.Data.Interfaces public interface IRoleRepository : IRepository { Task GetByNameAsync(string name); - + Task DoesNameExist(string name); Task DoesRoleExist(Guid id); } -} \ No newline at end of file +} diff --git a/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs b/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs index 0c27917..ccc5e91 100644 --- a/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs +++ b/src/DevHive.Data/Migrations/20201219141035_DbContext_Moved.cs @@ -4,298 +4,298 @@ 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); - }); + 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: "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: "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: "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: "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: "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: "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: "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: "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.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: "IX_AspNetRoleClaims_RoleId", + table: "AspNetRoleClaims", + column: "RoleId"); - migrationBuilder.CreateIndex( - name: "RoleNameIndex", - table: "AspNetRoles", - column: "NormalizedName", - unique: true); + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "AspNetRoles", + column: "NormalizedName", + unique: true); - migrationBuilder.CreateIndex( - name: "IX_AspNetUserClaims_UserId", - table: "AspNetUserClaims", - column: "UserId"); + migrationBuilder.CreateIndex( + name: "IX_AspNetUserClaims_UserId", + table: "AspNetUserClaims", + column: "UserId"); - migrationBuilder.CreateIndex( - name: "IX_AspNetUserLogins_UserId", - table: "AspNetUserLogins", - 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: "IX_AspNetUserRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId"); - migrationBuilder.CreateIndex( - name: "EmailIndex", - table: "AspNetUsers", - column: "NormalizedEmail"); + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "AspNetUsers", + column: "NormalizedEmail"); - migrationBuilder.CreateIndex( - name: "IX_AspNetUsers_UserId", - table: "AspNetUsers", - column: "UserId"); + 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: "IX_AspNetUsers_UserName", + table: "AspNetUsers", + column: "UserName", + unique: true); - migrationBuilder.CreateIndex( - name: "UserNameIndex", - table: "AspNetUsers", - column: "NormalizedUserName", - unique: true); + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "AspNetUsers", + column: "NormalizedUserName", + unique: true); - migrationBuilder.CreateIndex( - name: "IX_RoleUser_UsersId", - table: "RoleUser", - column: "UsersId"); - } + migrationBuilder.CreateIndex( + name: "IX_RoleUser_UsersId", + table: "RoleUser", + column: "UsersId"); + } - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "AspNetRoleClaims"); + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AspNetRoleClaims"); - migrationBuilder.DropTable( - name: "AspNetUserClaims"); + migrationBuilder.DropTable( + name: "AspNetUserClaims"); - migrationBuilder.DropTable( - name: "AspNetUserLogins"); + migrationBuilder.DropTable( + name: "AspNetUserLogins"); - migrationBuilder.DropTable( - name: "AspNetUserRoles"); + migrationBuilder.DropTable( + name: "AspNetUserRoles"); - migrationBuilder.DropTable( - name: "AspNetUserTokens"); + migrationBuilder.DropTable( + name: "AspNetUserTokens"); - migrationBuilder.DropTable( - name: "Languages"); + migrationBuilder.DropTable( + name: "Languages"); - migrationBuilder.DropTable( - name: "RoleUser"); + migrationBuilder.DropTable( + name: "RoleUser"); - migrationBuilder.DropTable( - name: "Technologies"); + migrationBuilder.DropTable( + name: "Technologies"); - migrationBuilder.DropTable( - name: "AspNetRoles"); + migrationBuilder.DropTable( + name: "AspNetRoles"); - migrationBuilder.DropTable( - name: "AspNetUsers"); - } - } + migrationBuilder.DropTable( + name: "AspNetUsers"); + } + } } diff --git a/src/DevHive.Data/Migrations/20201230154737_CommentMigration.cs b/src/DevHive.Data/Migrations/20201230154737_CommentMigration.cs index b952be5..a442bfa 100644 --- a/src/DevHive.Data/Migrations/20201230154737_CommentMigration.cs +++ b/src/DevHive.Data/Migrations/20201230154737_CommentMigration.cs @@ -3,29 +3,29 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace DevHive.Data.Migrations { - public partial class CommentMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Comments", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - UserId = table.Column(type: "uuid", nullable: false), - Message = table.Column(type: "text", nullable: true), - Date = table.Column(type: "timestamp without time zone", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Comments", x => x.Id); - }); - } + public partial class CommentMigration : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Comments", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + Message = table.Column(type: "text", nullable: true), + Date = table.Column(type: "timestamp without time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Comments", x => x.Id); + }); + } - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Comments"); - } - } + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Comments"); + } + } } diff --git a/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs b/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs index a51ad09..d698f10 100644 --- a/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs +++ b/src/DevHive.Data/Migrations/20210112111416_User_Implements_Languages.cs @@ -3,104 +3,104 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace DevHive.Data.Migrations { - public partial class User_Implements_Languages : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.RenameColumn( - name: "UserId", - table: "Comments", - newName: "IssuerId"); - - migrationBuilder.RenameColumn( - name: "Date", - table: "Comments", - newName: "TimeCreated"); - - migrationBuilder.RenameColumn( - name: "ProfilePicture", - table: "AspNetUsers", - newName: "ProfilePictureUrl"); - - migrationBuilder.AddColumn( - name: "UserId", - table: "Technologies", - type: "uuid", - nullable: true); - - migrationBuilder.AddColumn( - name: "UserId", - table: "Languages", - type: "uuid", - nullable: true); - - migrationBuilder.CreateIndex( - name: "IX_Technologies_UserId", - table: "Technologies", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_Languages_UserId", - table: "Languages", - column: "UserId"); - - migrationBuilder.AddForeignKey( - name: "FK_Languages_AspNetUsers_UserId", - table: "Languages", - column: "UserId", - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - - migrationBuilder.AddForeignKey( - name: "FK_Technologies_AspNetUsers_UserId", - table: "Technologies", - column: "UserId", - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropForeignKey( - name: "FK_Languages_AspNetUsers_UserId", - table: "Languages"); - - migrationBuilder.DropForeignKey( - name: "FK_Technologies_AspNetUsers_UserId", - table: "Technologies"); - - migrationBuilder.DropIndex( - name: "IX_Technologies_UserId", - table: "Technologies"); - - migrationBuilder.DropIndex( - name: "IX_Languages_UserId", - table: "Languages"); - - migrationBuilder.DropColumn( - name: "UserId", - table: "Technologies"); - - migrationBuilder.DropColumn( - name: "UserId", - table: "Languages"); - - migrationBuilder.RenameColumn( - name: "TimeCreated", - table: "Comments", - newName: "Date"); - - migrationBuilder.RenameColumn( - name: "IssuerId", - table: "Comments", - newName: "UserId"); - - migrationBuilder.RenameColumn( - name: "ProfilePictureUrl", - table: "AspNetUsers", - newName: "ProfilePicture"); - } - } + public partial class User_Implements_Languages : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "UserId", + table: "Comments", + newName: "IssuerId"); + + migrationBuilder.RenameColumn( + name: "Date", + table: "Comments", + newName: "TimeCreated"); + + migrationBuilder.RenameColumn( + name: "ProfilePicture", + table: "AspNetUsers", + newName: "ProfilePictureUrl"); + + migrationBuilder.AddColumn( + name: "UserId", + table: "Technologies", + type: "uuid", + nullable: true); + + migrationBuilder.AddColumn( + name: "UserId", + table: "Languages", + type: "uuid", + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_Technologies_UserId", + table: "Technologies", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Languages_UserId", + table: "Languages", + column: "UserId"); + + migrationBuilder.AddForeignKey( + name: "FK_Languages_AspNetUsers_UserId", + table: "Languages", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Technologies_AspNetUsers_UserId", + table: "Technologies", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Languages_AspNetUsers_UserId", + table: "Languages"); + + migrationBuilder.DropForeignKey( + name: "FK_Technologies_AspNetUsers_UserId", + table: "Technologies"); + + migrationBuilder.DropIndex( + name: "IX_Technologies_UserId", + table: "Technologies"); + + migrationBuilder.DropIndex( + name: "IX_Languages_UserId", + table: "Languages"); + + migrationBuilder.DropColumn( + name: "UserId", + table: "Technologies"); + + migrationBuilder.DropColumn( + name: "UserId", + table: "Languages"); + + migrationBuilder.RenameColumn( + name: "TimeCreated", + table: "Comments", + newName: "Date"); + + migrationBuilder.RenameColumn( + name: "IssuerId", + table: "Comments", + newName: "UserId"); + + migrationBuilder.RenameColumn( + name: "ProfilePictureUrl", + table: "AspNetUsers", + newName: "ProfilePicture"); + } + } } diff --git a/src/DevHive.Data/Models/Language.cs b/src/DevHive.Data/Models/Language.cs index fb3a042..556d019 100644 --- a/src/DevHive.Data/Models/Language.cs +++ b/src/DevHive.Data/Models/Language.cs @@ -4,6 +4,6 @@ namespace DevHive.Data.Models public class Language : IModel { public Guid Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } } } diff --git a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs index 695ffdb..7f99c66 100644 --- a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs @@ -12,5 +12,5 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap(); } - } + } } diff --git a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index db4473e..65b0b5a 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -11,5 +11,5 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap(); } - } + } } diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index ca8fa20..d57c6ba 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -14,5 +14,5 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); } - } + } } diff --git a/src/DevHive.Services/Interfaces/IPostService.cs b/src/DevHive.Services/Interfaces/IPostService.cs index 9cb21ed..dd886b4 100644 --- a/src/DevHive.Services/Interfaces/IPostService.cs +++ b/src/DevHive.Services/Interfaces/IPostService.cs @@ -15,10 +15,10 @@ namespace DevHive.Services.Interfaces Task UpdateComment(UpdateCommentServiceModel commentServiceModel); Task UpdatePost(UpdatePostServiceModel postServiceModel); - + Task DeleteComment(Guid id); Task DeletePost(Guid id); - + Task ValidateJwtForComment(Guid commentId, string rawTokenData); } -} \ No newline at end of file +} diff --git a/src/DevHive.Services/Interfaces/IRoleService.cs b/src/DevHive.Services/Interfaces/IRoleService.cs index 3bf236c..2c7195c 100644 --- a/src/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/DevHive.Services/Interfaces/IRoleService.cs @@ -11,7 +11,7 @@ namespace DevHive.Services.Interfaces Task GetRoleById(Guid id); Task UpdateRole(RoleModel roleServiceModel); - + Task DeleteRole(Guid id); } -} \ No newline at end of file +} diff --git a/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs index 2e75848..514f82a 100644 --- a/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs @@ -1,6 +1,6 @@ namespace DevHive.Services.Models.Identity.User { - public class BaseUserServiceModel + public class BaseUserServiceModel { public string UserName { get; set; } public string Email { get; set; } diff --git a/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs index 97225c7..1bf60ae 100644 --- a/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs +++ b/src/DevHive.Services/Models/Post/Post/CreatePostServiceModel.cs @@ -5,5 +5,5 @@ 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/UpdatePostServiceModel.cs b/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs index de61a72..5a4f621 100644 --- a/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs +++ b/src/DevHive.Services/Models/Post/Post/UpdatePostServiceModel.cs @@ -1,7 +1,5 @@ namespace DevHive.Services.Models.Post.Post { public class UpdatePostServiceModel : BasePostServiceModel - { - - } -} \ No newline at end of file + { } +} diff --git a/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs b/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs index 6ff5fa2..18d72b9 100644 --- a/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs +++ b/src/DevHive.Tests/DevHive.Data.Tests/TechnologyRepository.Tests.cs @@ -8,192 +8,194 @@ using System.Threading.Tasks; namespace DevHive.Data.Tests { - [TestFixture] - public class TechnologyRepositoryTests - { - private const string TECHNOLOGY_NAME = "Technology test name"; - - protected DevHiveContext Context { get; set; } - - protected TechnologyRepository TechnologyRepository { get; set; } - - [SetUp] - public void Setup() - { - var optionsBuilder = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: "DevHive_Test_Database"); - - this.Context = new DevHiveContext(optionsBuilder.Options); - - TechnologyRepository = new TechnologyRepository(Context); - } - - [TearDown] - public void TearDown() - { - this.Context.Database.EnsureDeleted(); - } - - #region AddAsync - [Test] - public void AddAsync_AddsTheGivenTechnologyToTheDatabase() - { - AddEntity(); - - int numberOfTechnologies = Context.Technologies.Count(); - - Assert.True(numberOfTechnologies > 0, "Technologies repo does not store Technologies correctly"); - } - #endregion - - #region GetByIdAsync - [Test] - public void GetByIdAsync_ReturnsTheCorrectTechnology_IfIdExists() - { - Task.Run(async () => - { - AddEntity(); - Technology technology = this.Context.Technologies.Where(x => x.Name == TECHNOLOGY_NAME).ToList().FirstOrDefault(); - Guid id = technology.Id; - - Technology technologyReturned = await this.TechnologyRepository.GetByIdAsync(id); - - Assert.AreEqual(TECHNOLOGY_NAME, technologyReturned.Name, "GetByIdAsync does not return the correct Technology when id is valid"); - }).GetAwaiter().GetResult(); - } - - [Test] - public void GetByIdAsync_ReturnsNull_IfIdDoesNotExists() - { - Task.Run(async () => - { - Guid id = new Guid(); - - Technology technologyReturned = await this.TechnologyRepository.GetByIdAsync(id); - - Assert.IsNull(technologyReturned, "GetByIdAsync returns Technology when it should be null"); - }).GetAwaiter().GetResult(); - } - #endregion - - #region DoesTechnologyExistAsync - [Test] - public void DoesTechnologyExist_ReturnsTrue_IfIdExists() - { - Task.Run(async () => - { - AddEntity(); - Technology technology = this.Context.Technologies.Where(x => x.Name == TECHNOLOGY_NAME).ToList().FirstOrDefault(); - Guid id = technology.Id; - - bool result = await this.TechnologyRepository.DoesTechnologyExistAsync(id); - - Assert.IsTrue(result, "DoesTechnologyExistAsync returns flase hwen technology exists"); - }).GetAwaiter().GetResult(); - } - - [Test] - public void DoesTechnologyExist_ReturnsFalse_IfIdDoesNotExists() - { - Task.Run(async () => - { - Guid id = new Guid(); - - bool result = await this.TechnologyRepository.DoesTechnologyExistAsync(id); - - Assert.IsFalse(result, "DoesTechnologyExistAsync returns true when technology does not exist"); - }).GetAwaiter().GetResult(); - } - #endregion - - #region DoesTechnologyNameExistAsync - [Test] - public void DoesTechnologyNameExist_ReturnsTrue_IfTechnologyExists() - { - Task.Run(async () => - { - AddEntity(); - - bool result = await this.TechnologyRepository.DoesTechnologyNameExistAsync(TECHNOLOGY_NAME); - - Assert.IsTrue(result, "DoesTechnologyNameExists returns true when technology name does not exist"); - }).GetAwaiter().GetResult(); - } - - [Test] - public void DoesTechnologyNameExist_ReturnsFalse_IfTechnologyDoesNotExists() - { - Task.Run(async () => - { - bool result = await this.TechnologyRepository.DoesTechnologyNameExistAsync(TECHNOLOGY_NAME); - - Assert.False(result, "DoesTechnologyNameExistAsync returns true when technology name does not exist"); - }).GetAwaiter().GetResult(); - } - #endregion - - #region EditAsync - [Test] - public void EditAsync_UpdatesEntity() - { - Task.Run(async () => - { - string newName = "New name"; - Guid id = new Guid(); - Technology technology = new Technology - { - Name = TECHNOLOGY_NAME, - Id = id - }; - Technology newTechnology = new Technology - { - Name = newName, - Id = id - }; - await this.TechnologyRepository.AddAsync(technology); - - bool result = await this.TechnologyRepository.EditAsync(newTechnology); - - Assert.IsTrue(result); - }).GetAwaiter().GetResult(); - } - #endregion - - #region DeleteAsync - [Test] - public void DeleteAsync_ReturnsTrue_IfDeletionIsSuccesfull() - { - Task.Run(async () => - { - AddEntity(); - Technology technology = this.Context.Technologies.Where(x => x.Name == TECHNOLOGY_NAME).ToList().FirstOrDefault(); - - bool result = await this.TechnologyRepository.DeleteAsync(technology); - - Assert.IsTrue(result, "DeleteAsync returns false when deletion is successfull"); - - }).GetAwaiter().GetResult(); - } - #endregion - - #region HelperMethods - private void AddEntity(string name = TECHNOLOGY_NAME) - { - Task.Run(async () => - { - Technology technology = new Technology - { - Name = name - }; - - await this.TechnologyRepository.AddAsync(technology); - }).GetAwaiter().GetResult(); - } - #endregion - - //Task.Run(async () => - //{ - // - //}).GetAwaiter().GetResult(); - } + [TestFixture] + public class TechnologyRepositoryTests + { + private const string TECHNOLOGY_NAME = "Technology test name"; + + protected DevHiveContext Context { get; set; } + + protected TechnologyRepository TechnologyRepository { get; set; } + + [SetUp] + public void Setup() + { + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "DevHive_Test_Database"); + + this.Context = new DevHiveContext(optionsBuilder.Options); + + TechnologyRepository = new TechnologyRepository(Context); + } + + [TearDown] + public void TearDown() + { + this.Context.Database.EnsureDeleted(); + } + + #region AddAsync + + [Test] + public void AddAsync_AddsTheGivenTechnologyToTheDatabase() + { + AddEntity(); + + int numberOfTechnologies = Context.Technologies.Count(); + + Assert.True(numberOfTechnologies > 0, "Technologies repo does not store Technologies correctly"); + } + #endregion + + #region GetByIdAsync + + [Test] + public void GetByIdAsync_ReturnsTheCorrectTechnology_IfIdExists() + { + Task.Run(async () => + { + AddEntity(); + Technology technology = this.Context.Technologies.Where(x => x.Name == TECHNOLOGY_NAME).ToList().FirstOrDefault(); + Guid id = technology.Id; + + Technology technologyReturned = await this.TechnologyRepository.GetByIdAsync(id); + + Assert.AreEqual(TECHNOLOGY_NAME, technologyReturned.Name, "GetByIdAsync does not return the correct Technology when id is valid"); + }).GetAwaiter().GetResult(); + } + + [Test] + public void GetByIdAsync_ReturnsNull_IfIdDoesNotExists() + { + Task.Run(async () => + { + Guid id = new Guid(); + + Technology technologyReturned = await this.TechnologyRepository.GetByIdAsync(id); + + Assert.IsNull(technologyReturned, "GetByIdAsync returns Technology when it should be null"); + }).GetAwaiter().GetResult(); + } + #endregion + + #region DoesTechnologyExistAsync + [Test] + public void DoesTechnologyExist_ReturnsTrue_IfIdExists() + { + Task.Run(async () => + { + AddEntity(); + Technology technology = this.Context.Technologies.Where(x => x.Name == TECHNOLOGY_NAME).ToList().FirstOrDefault(); + Guid id = technology.Id; + + bool result = await this.TechnologyRepository.DoesTechnologyExistAsync(id); + + Assert.IsTrue(result, "DoesTechnologyExistAsync returns flase hwen technology exists"); + }).GetAwaiter().GetResult(); + } + + [Test] + public void DoesTechnologyExist_ReturnsFalse_IfIdDoesNotExists() + { + Task.Run(async () => + { + Guid id = new Guid(); + + bool result = await this.TechnologyRepository.DoesTechnologyExistAsync(id); + + Assert.IsFalse(result, "DoesTechnologyExistAsync returns true when technology does not exist"); + }).GetAwaiter().GetResult(); + } + #endregion + + #region DoesTechnologyNameExistAsync + [Test] + public void DoesTechnologyNameExist_ReturnsTrue_IfTechnologyExists() + { + Task.Run(async () => + { + AddEntity(); + + bool result = await this.TechnologyRepository.DoesTechnologyNameExistAsync(TECHNOLOGY_NAME); + + Assert.IsTrue(result, "DoesTechnologyNameExists returns true when technology name does not exist"); + }).GetAwaiter().GetResult(); + } + + [Test] + public void DoesTechnologyNameExist_ReturnsFalse_IfTechnologyDoesNotExists() + { + Task.Run(async () => + { + bool result = await this.TechnologyRepository.DoesTechnologyNameExistAsync(TECHNOLOGY_NAME); + + Assert.False(result, "DoesTechnologyNameExistAsync returns true when technology name does not exist"); + }).GetAwaiter().GetResult(); + } + #endregion + + #region EditAsync + [Test] + public void EditAsync_UpdatesEntity() + { + Task.Run(async () => + { + string newName = "New name"; + Guid id = new Guid(); + Technology technology = new Technology + { + Name = TECHNOLOGY_NAME, + Id = id + }; + Technology newTechnology = new Technology + { + Name = newName, + Id = id + }; + await this.TechnologyRepository.AddAsync(technology); + + bool result = await this.TechnologyRepository.EditAsync(newTechnology); + + Assert.IsTrue(result); + }).GetAwaiter().GetResult(); + } + #endregion + + #region DeleteAsync + [Test] + public void DeleteAsync_ReturnsTrue_IfDeletionIsSuccesfull() + { + Task.Run(async () => + { + AddEntity(); + Technology technology = this.Context.Technologies.Where(x => x.Name == TECHNOLOGY_NAME).ToList().FirstOrDefault(); + + bool result = await this.TechnologyRepository.DeleteAsync(technology); + + Assert.IsTrue(result, "DeleteAsync returns false when deletion is successfull"); + + }).GetAwaiter().GetResult(); + } + #endregion + + #region HelperMethods + private void AddEntity(string name = TECHNOLOGY_NAME) + { + Task.Run(async () => + { + Technology technology = new Technology + { + Name = name + }; + + await this.TechnologyRepository.AddAsync(technology); + }).GetAwaiter().GetResult(); + } + #endregion + + //Task.Run(async () => + //{ + // + //}).GetAwaiter().GetResult(); + } } diff --git a/src/DevHive.Tests/DevHive.Web.Tests/UnitTest1.cs b/src/DevHive.Tests/DevHive.Web.Tests/UnitTest1.cs deleted file mode 100644 index e6f54b0..0000000 --- a/src/DevHive.Tests/DevHive.Web.Tests/UnitTest1.cs +++ /dev/null @@ -1,18 +0,0 @@ -using NUnit.Framework; - -namespace DevHive.Web.Tests -{ - public class Tests - { - [SetUp] - public void Setup() - { - } - - [Test] - public void Test1() - { - Assert.Pass(); - } - } -} \ No newline at end of file -- cgit v1.2.3 From c43a7665b9febe890eb6dac143b62c36464cc94d Mon Sep 17 00:00:00 2001 From: transtrike Date: Sun, 17 Jan 2021 12:24:17 +0200 Subject: Moved Lang&Tech CRUD to Update in User Layer --- .../Interfaces/ILanguageService.cs | 2 +- .../Interfaces/ITechnologyService.cs | 2 +- src/DevHive.Services/Interfaces/IUserService.cs | 2 +- .../Models/Identity/User/UserServiceModel.cs | 5 +- src/DevHive.Services/Services/LanguageService.cs | 5 +- src/DevHive.Services/Services/TechnologyService.cs | 5 +- src/DevHive.Services/Services/UserService.cs | 8 +-- src/DevHive.Web/Controllers/LanguageController.cs | 3 +- .../Controllers/TechnologyController.cs | 5 +- src/DevHive.Web/Controllers/UserController.cs | 70 +--------------------- .../Models/Identity/User/FriendWebModel.cs | 7 +++ .../Models/Identity/User/UpdateUserWebModel.cs | 9 +++ .../Models/Identity/User/UserWebModel.cs | 4 +- .../Models/Language/UpdateLanguageWebModel.cs | 2 +- .../Models/Technology/UpdateTechnologyWebModel.cs | 2 +- 15 files changed, 44 insertions(+), 87 deletions(-) create mode 100644 src/DevHive.Web/Models/Identity/User/FriendWebModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Interfaces/ILanguageService.cs b/src/DevHive.Services/Interfaces/ILanguageService.cs index eb45a8d..08b3812 100644 --- a/src/DevHive.Services/Interfaces/ILanguageService.cs +++ b/src/DevHive.Services/Interfaces/ILanguageService.cs @@ -10,7 +10,7 @@ namespace DevHive.Services.Interfaces Task GetLanguageById(Guid languageId); - Task UpdateLanguage(Guid languageId, UpdateLanguageServiceModel languageServiceModel); + Task UpdateLanguage(UpdateLanguageServiceModel languageServiceModel); Task DeleteLanguage(Guid languageId); } diff --git a/src/DevHive.Services/Interfaces/ITechnologyService.cs b/src/DevHive.Services/Interfaces/ITechnologyService.cs index 0797078..9e1e955 100644 --- a/src/DevHive.Services/Interfaces/ITechnologyService.cs +++ b/src/DevHive.Services/Interfaces/ITechnologyService.cs @@ -10,7 +10,7 @@ namespace DevHive.Services.Interfaces Task GetTechnologyById(Guid id); - Task UpdateTechnology(Guid technologyId, UpdateTechnologyServiceModel updateTechnologyServiceModel); + Task UpdateTechnology(UpdateTechnologyServiceModel updateTechnologyServiceModel); Task DeleteTechnology(Guid id); } diff --git a/src/DevHive.Services/Interfaces/IUserService.cs b/src/DevHive.Services/Interfaces/IUserService.cs index 5ef141f..0f834e9 100644 --- a/src/DevHive.Services/Interfaces/IUserService.cs +++ b/src/DevHive.Services/Interfaces/IUserService.cs @@ -16,7 +16,7 @@ namespace DevHive.Services.Interfaces Task AddLanguageToUser(Guid userId, LanguageServiceModel languageServiceModel); Task AddTechnologyToUser(Guid userId, TechnologyServiceModel technologyServiceModel); - Task GetFriendById(Guid friendId); + Task GetFriend(string username); Task GetUserById(Guid id); Task UpdateUser(UpdateUserServiceModel updateModel); diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 8825f50..ecf8c42 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -8,8 +8,11 @@ namespace DevHive.Services.Models.Identity.User public class UserServiceModel : BaseUserServiceModel { public IList Roles { get; set; } = new List(); + public IList Friends { get; set; } = new List(); + public IList Languages { get; set; } = new List(); - public IList TechnologyServiceModels { get; set; } = new List(); + + public IList Technologies { get; set; } = new List(); } } diff --git a/src/DevHive.Services/Services/LanguageService.cs b/src/DevHive.Services/Services/LanguageService.cs index be035c2..5b697cd 100644 --- a/src/DevHive.Services/Services/LanguageService.cs +++ b/src/DevHive.Services/Services/LanguageService.cs @@ -48,9 +48,9 @@ namespace DevHive.Services.Services #region Update - public async Task UpdateLanguage(Guid languageId, UpdateLanguageServiceModel languageServiceModel) + public async Task UpdateLanguage(UpdateLanguageServiceModel languageServiceModel) { - bool langExists = await this._languageRepository.DoesLanguageExistAsync(languageId); + bool langExists = await this._languageRepository.DoesLanguageExistAsync(languageServiceModel.Id); bool newLangNameExists = await this._languageRepository.DoesLanguageNameExistAsync(languageServiceModel.Name); if (!langExists) @@ -59,7 +59,6 @@ namespace DevHive.Services.Services if (newLangNameExists) throw new ArgumentException("This name is already in our datbase!"); - languageServiceModel.Id = languageId; Language lang = this._languageMapper.Map(languageServiceModel); return await this._languageRepository.EditAsync(lang); } diff --git a/src/DevHive.Services/Services/TechnologyService.cs b/src/DevHive.Services/Services/TechnologyService.cs index d8b7262..c088281 100644 --- a/src/DevHive.Services/Services/TechnologyService.cs +++ b/src/DevHive.Services/Services/TechnologyService.cs @@ -48,15 +48,14 @@ namespace DevHive.Services.Services #region Update - public async Task UpdateTechnology(Guid technologyId, UpdateTechnologyServiceModel updateTechnologyServiceModel) + public async Task UpdateTechnology(UpdateTechnologyServiceModel updateTechnologyServiceModel) { - if (!await this._technologyRepository.DoesTechnologyExistAsync(technologyId)) + if (!await this._technologyRepository.DoesTechnologyExistAsync(updateTechnologyServiceModel.Id)) throw new ArgumentException("Technology does not exist!"); if (await this._technologyRepository.DoesTechnologyNameExistAsync(updateTechnologyServiceModel.Name)) throw new ArgumentException("Technology name already exists!"); - updateTechnologyServiceModel.Id = technologyId; Technology technology = this._technologyMapper.Map(updateTechnologyServiceModel); bool result = await this._technologyRepository.EditAsync(technology); diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 37dbc7b..d9e87e0 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -160,12 +160,12 @@ namespace DevHive.Services.Services return this._userMapper.Map(user); } - public async Task GetFriendById(Guid friendId) + public async Task GetFriend(string username) { - if (!await _userRepository.DoesUserExistAsync(friendId)) - throw new ArgumentException("User does not exist!"); + User friend = await this._userRepository.GetByUsernameAsync(username); - User friend = await this._userRepository.GetByIdAsync(friendId); + if (default(User) == friend) + throw new ArgumentException("User does not exist!"); return this._userMapper.Map(friend); } diff --git a/src/DevHive.Web/Controllers/LanguageController.cs b/src/DevHive.Web/Controllers/LanguageController.cs index 5202f16..c503a47 100644 --- a/src/DevHive.Web/Controllers/LanguageController.cs +++ b/src/DevHive.Web/Controllers/LanguageController.cs @@ -47,8 +47,9 @@ namespace DevHive.Web.Controllers public async Task Update(Guid languageId, [FromBody] UpdateLanguageWebModel updateModel) { UpdateLanguageServiceModel updatelanguageServiceModel = this._languageMapper.Map(updateModel); + updatelanguageServiceModel.Id = languageId; - bool result = await this._languageService.UpdateLanguage(languageId, updatelanguageServiceModel); + bool result = await this._languageService.UpdateLanguage(updatelanguageServiceModel); if (!result) return new BadRequestObjectResult("Could not update Language"); diff --git a/src/DevHive.Web/Controllers/TechnologyController.cs b/src/DevHive.Web/Controllers/TechnologyController.cs index 3be3b8a..7f2f400 100644 --- a/src/DevHive.Web/Controllers/TechnologyController.cs +++ b/src/DevHive.Web/Controllers/TechnologyController.cs @@ -46,9 +46,10 @@ namespace DevHive.Web.Controllers [HttpPut] public async Task Update(Guid technologyId, [FromBody] UpdateTechnologyWebModel updateModel) { - UpdateTechnologyServiceModel updateTechnologyWebModel = this._technologyMapper.Map(updateModel); + UpdateTechnologyServiceModel updateTechnologyServiceModel = this._technologyMapper.Map(updateModel); + updateTechnologyServiceModel.Id = technologyId; - bool result = await this._technologyService.UpdateTechnology(technologyId, updateTechnologyWebModel); + bool result = await this._technologyService.UpdateTechnology(updateTechnologyServiceModel); if (!result) return new BadRequestObjectResult("Could not update Technology"); diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index b33c3b9..8d48705 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -57,40 +57,6 @@ namespace DevHive.Web.Controllers } #endregion - #region Create - - [HttpPost] - [Route("AddAFriend")] - public async Task AddAFriend(Guid userId, [FromBody] IdModel friendIdModel) - { - return await this._userService.AddFriend(userId, friendIdModel.Id) ? - new OkResult() : - new BadRequestResult(); - } - - [HttpPost] - [Route("AddLanguageToUser")] - public async Task AddLanguageToUser(Guid userId, [FromBody] LanguageWebModel languageWebModel) - { - LanguageServiceModel languageServiceModel = this._userMapper.Map(languageWebModel); - - return await this._userService.AddLanguageToUser(userId, languageServiceModel) ? - new OkResult() : - new BadRequestResult(); - } - - [HttpPost] - [Route("AddTechnologyToUser")] - public async Task AddTechnologyToUser(Guid userId, [FromBody] TechnologyWebModel technologyWebModel) - { - TechnologyServiceModel technologyServiceModel = this._userMapper.Map(technologyWebModel); - - return await this._userService.AddTechnologyToUser(userId, technologyServiceModel) ? - new OkResult() : - new BadRequestResult(); - } - #endregion - #region Read [HttpGet] @@ -107,9 +73,10 @@ namespace DevHive.Web.Controllers [HttpGet] [Route("GetAFriend")] - public async Task GetAFriend(Guid friendId) + [AllowAnonymous] + public async Task GetAFriend(string username) { - UserServiceModel friendServiceModel = await this._userService.GetFriendById(friendId); + UserServiceModel friendServiceModel = await this._userService.GetFriend(username); UserWebModel friend = this._userMapper.Map(friendServiceModel); return new OkObjectResult(friend); @@ -134,7 +101,6 @@ namespace DevHive.Web.Controllers #endregion #region Delete - [HttpDelete] public async Task Delete(Guid id, [FromHeader] string authorization) { @@ -144,36 +110,6 @@ 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(); - } - - [HttpDelete] - [Route("RemoveLanguageFromUser")] - public async Task RemoveLanguageFromUser(Guid userId, [FromBody] LanguageWebModel languageWebModel) - { - LanguageServiceModel languageServiceModel = this._userMapper.Map(languageWebModel); - - return await this._userService.RemoveLanguageFromUser(userId, languageServiceModel) ? - new OkResult() : - new BadRequestResult(); - } - - [HttpDelete] - [Route("RemoveTechnologyFromUser")] - public async Task RemoveTechnologyFromUser(Guid userId, [FromBody] TechnologyWebModel technologyWebModel) - { - TechnologyServiceModel technologyServiceModel = this._userMapper.Map(technologyWebModel); - - return await this._userService.RemoveTechnologyFromUser(userId, technologyServiceModel) ? - new OkResult() : - new BadRequestResult(); - } #endregion } } diff --git a/src/DevHive.Web/Models/Identity/User/FriendWebModel.cs b/src/DevHive.Web/Models/Identity/User/FriendWebModel.cs new file mode 100644 index 0000000..681529a --- /dev/null +++ b/src/DevHive.Web/Models/Identity/User/FriendWebModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Web.Models.Identity.User +{ + public class FriendWebModel + { + public string Username { get; set; } + } +} diff --git a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs index 9e41eb6..782c558 100644 --- a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs @@ -1,5 +1,8 @@ +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using DevHive.Web.Models.Identity.Validation; +using DevHive.Web.Models.Language; +using DevHive.Web.Models.Technology; namespace DevHive.Web.Models.Identity.User { @@ -8,5 +11,11 @@ namespace DevHive.Web.Models.Identity.User [Required] [GoodPassword] public string Password { get; set; } + + public IList Friends { get; set; } + + public IList Languages { get; set; } + + public IList Technologies { get; set; } } } diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 8f7995c..3b243e7 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using DevHive.Common.Models.Identity; using DevHive.Web.Models.Identity.Role; using DevHive.Web.Models.Language; using DevHive.Web.Models.Technology; @@ -9,8 +8,11 @@ namespace DevHive.Web.Models.Identity.User public class UserWebModel : BaseUserWebModel { public IList Roles { get; set; } = new List(); + public IList Friends { get; set; } = new List(); + public IList Languages { get; set; } = new List(); + public IList Technologies { get; set; } = new List(); } } diff --git a/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs b/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs index ed3b37c..18d945f 100644 --- a/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs +++ b/src/DevHive.Web/Models/Language/UpdateLanguageWebModel.cs @@ -2,7 +2,7 @@ using System; namespace DevHive.Web.Models.Language { - public class UpdateLanguageWebModel : LanguageWebModel + public class UpdateLanguageWebModel { public string Name { get; set; } } diff --git a/src/DevHive.Web/Models/Technology/UpdateTechnologyWebModel.cs b/src/DevHive.Web/Models/Technology/UpdateTechnologyWebModel.cs index 8bf48bf..4651b9e 100644 --- a/src/DevHive.Web/Models/Technology/UpdateTechnologyWebModel.cs +++ b/src/DevHive.Web/Models/Technology/UpdateTechnologyWebModel.cs @@ -2,7 +2,7 @@ using System; namespace DevHive.Web.Models.Technology { - public class UpdateTechnologyWebModel : TechnologyWebModel + public class UpdateTechnologyWebModel { public string Name { get; set; } } -- cgit v1.2.3 From 8d1d0b40d56f90248f948e474330258bf57cf0b6 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sun, 17 Jan 2021 14:45:48 +0200 Subject: Fixed role implementation by bringing back and improving all role models --- src/DevHive.Common/Models/Identity/RoleModel.cs | 10 -------- .../Configurations/Mapping/RoleMapings.cs | 8 +++---- src/DevHive.Services/Interfaces/IRoleService.cs | 10 ++++---- .../Models/Identity/Role/RoleServiceModel.cs | 10 ++++++++ .../Models/Identity/Role/UpdateRoleServiceModel.cs | 7 ++++++ .../Models/Identity/User/UserServiceModel.cs | 6 ++--- src/DevHive.Services/Services/RoleService.cs | 24 +++++++++++++------ .../Configurations/Mapping/RoleMappings.cs | 12 +++++----- src/DevHive.Web/Controllers/RoleController.cs | 28 +++++++++++----------- .../Models/Identity/Role/CreateRoleWebModel.cs | 2 +- .../Models/Identity/Role/RoleWebModel.cs | 2 -- .../Models/Identity/Role/UpdateRoleWebModel.cs | 2 +- 12 files changed, 68 insertions(+), 53 deletions(-) delete mode 100644 src/DevHive.Common/Models/Identity/RoleModel.cs create mode 100644 src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/Role/UpdateRoleServiceModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Common/Models/Identity/RoleModel.cs b/src/DevHive.Common/Models/Identity/RoleModel.cs deleted file mode 100644 index 5db8df9..0000000 --- a/src/DevHive.Common/Models/Identity/RoleModel.cs +++ /dev/null @@ -1,10 +0,0 @@ -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/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index 65b0b5a..4ddd253 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -1,15 +1,15 @@ using DevHive.Data.Models; using AutoMapper; -using DevHive.Common.Models.Identity; +using DevHive.Services.Models.Identity.Role; namespace DevHive.Services.Configurations.Mapping { - public class RoleMappings : Profile + public class RoleMappings : Profile { public RoleMappings() { - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Services/Interfaces/IRoleService.cs b/src/DevHive.Services/Interfaces/IRoleService.cs index 2c7195c..a7a0e47 100644 --- a/src/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/DevHive.Services/Interfaces/IRoleService.cs @@ -1,16 +1,16 @@ using System; using System.Threading.Tasks; -using DevHive.Common.Models.Identity; +using DevHive.Services.Models.Identity.Role; namespace DevHive.Services.Interfaces { - public interface IRoleService + public interface IRoleService { - Task CreateRole(RoleModel roleServiceModel); + Task CreateRole(RoleServiceModel roleServiceModel); - Task GetRoleById(Guid id); + Task GetRoleById(Guid id); - Task UpdateRole(RoleModel roleServiceModel); + Task UpdateRole(RoleServiceModel roleServiceModel); Task DeleteRole(Guid id); } diff --git a/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs new file mode 100644 index 0000000..3f834ef --- /dev/null +++ b/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs @@ -0,0 +1,10 @@ +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/Role/UpdateRoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/UpdateRoleServiceModel.cs new file mode 100644 index 0000000..be71771 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/Role/UpdateRoleServiceModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Services.Models.Identity.Role +{ + public class UpdateRoleServiceModel + { + 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 ecf8c42..aa77a0c 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; -using DevHive.Common.Models.Identity; +using DevHive.Services.Models.Identity.Role; using DevHive.Services.Models.Language; using DevHive.Services.Models.Technology; namespace DevHive.Services.Models.Identity.User { - public class UserServiceModel : BaseUserServiceModel + public class UserServiceModel : BaseUserServiceModel { - public IList Roles { get; set; } = new List(); + public IList Roles { get; set; } = new List(); public IList Friends { get; set; } = new List(); diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index c38ac74..0945624 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -1,14 +1,15 @@ using System; using System.Threading.Tasks; using AutoMapper; -using DevHive.Common.Models.Identity; using DevHive.Data.Interfaces.Repositories; using DevHive.Data.Models; using DevHive.Services.Interfaces; +using DevHive.Services.Models.Identity.Role; +using DevHive.Services.Models.Language; namespace DevHive.Services.Services { - public class RoleService : IRoleService + public class RoleService : IRoleService { private readonly IRoleRepository _roleRepository; private readonly IMapper _roleMapper; @@ -19,25 +20,34 @@ namespace DevHive.Services.Services this._roleMapper = mapper; } - public async Task CreateRole(RoleModel roleServiceModel) + public async Task CreateRole(RoleServiceModel roleServiceModel) { if (await this._roleRepository.DoesNameExist(roleServiceModel.Name)) throw new ArgumentException("Role already exists!"); + Role role = this._roleMapper.Map(roleServiceModel); + bool success = await this._roleRepository.AddAsync(role); + + if(success) + { + Role newRole = await this._roleRepository.GetByNameAsync(roleServiceModel.Name); + return newRole.Id; + } + else + return Guid.Empty; - return await this._roleRepository.AddAsync(role); } - public async Task GetRoleById(Guid id) + public async Task GetRoleById(Guid id) { Role role = await this._roleRepository.GetByIdAsync(id) ?? throw new ArgumentException("Role does not exist!"); - return this._roleMapper.Map(role); + return this._roleMapper.Map(role); } - public async Task UpdateRole(RoleModel roleServiceModel) + public async Task UpdateRole(RoleServiceModel roleServiceModel) { if (!await this._roleRepository.DoesRoleExist(roleServiceModel.Id)) throw new ArgumentException("Role does not exist!"); diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs index afa3a94..bce7c07 100644 --- a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -1,18 +1,18 @@ using AutoMapper; using DevHive.Web.Models.Identity.Role; -using DevHive.Common.Models.Identity; +using DevHive.Services.Models.Identity.Role; namespace DevHive.Web.Configurations.Mapping { - public class RoleMappings : Profile + public class RoleMappings : Profile { public RoleMappings() { - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index 8ea2711..5b3dca5 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -3,12 +3,12 @@ using Microsoft.AspNetCore.Mvc; using DevHive.Web.Models.Identity.Role; using AutoMapper; using System; -using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; +using DevHive.Services.Models.Identity.Role; namespace DevHive.Web.Controllers { - [ApiController] + [ApiController] [Route("/api/[controller]")] //[Authorize(Roles = "Admin")] public class RoleController @@ -23,33 +23,33 @@ namespace DevHive.Web.Controllers } [HttpPost] - public async Task Create([FromBody] CreateRoleModel createRoleModel) + public async Task Create([FromBody] CreateRoleWebModel createRoleWebModel) { - RoleModel roleServiceModel = - this._roleMapper.Map(createRoleModel); + RoleServiceModel roleServiceModel = + this._roleMapper.Map(createRoleWebModel); - bool result = await this._roleService.CreateRole(roleServiceModel); + Guid id = await this._roleService.CreateRole(roleServiceModel); - if (!result) - return new BadRequestObjectResult("Could not create role!"); + return id == Guid.Empty ? + new BadRequestObjectResult($"Could not create role {createRoleWebModel.Name}") : + new OkObjectResult(new { Id = id }); - return new OkResult(); } [HttpGet] public async Task GetById(Guid id) { - RoleModel roleServiceModel = await this._roleService.GetRoleById(id); - RoleModel roleWebModel = this._roleMapper.Map(roleServiceModel); + RoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); + RoleWebModel roleWebModel = this._roleMapper.Map(roleServiceModel); return new OkObjectResult(roleWebModel); } [HttpPut] - public async Task Update(Guid id, [FromBody] UpdateRoleModel updateRoleModel) + public async Task Update(Guid id, [FromBody] UpdateRoleWebModel updateRoleWebModel) { - RoleModel roleServiceModel = - this._roleMapper.Map(updateRoleModel); + RoleServiceModel roleServiceModel = + this._roleMapper.Map(updateRoleWebModel); roleServiceModel.Id = id; bool result = await this._roleService.UpdateRole(roleServiceModel); diff --git a/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs index becb3c9..e872428 100644 --- a/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs +++ b/src/DevHive.Web/Models/Identity/Role/CreateRoleWebModel.cs @@ -1,6 +1,6 @@ namespace DevHive.Web.Models.Identity.Role { - public class CreateRoleModel + public class CreateRoleWebModel { public string Name { get; set; } } diff --git a/src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs index 9e97ffc..41ade23 100644 --- a/src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs +++ b/src/DevHive.Web/Models/Identity/Role/RoleWebModel.cs @@ -1,5 +1,3 @@ -using System; - namespace DevHive.Web.Models.Identity.Role { public class RoleWebModel diff --git a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs index 1eaad57..213ec55 100644 --- a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs +++ b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs @@ -1,6 +1,6 @@ namespace DevHive.Web.Models.Identity.Role { - public class UpdateRoleModel : CreateRoleModel + public class UpdateRoleWebModel : CreateRoleWebModel { } } -- cgit v1.2.3 From 8f6a50566a069c782482a167f601e6eca9588e73 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sun, 17 Jan 2021 15:30:09 +0200 Subject: User update now updates languages, roles and friends --- .../Configurations/Mapping/UserMappings.cs | 3 ++ .../User/UpdateUserCollectionServiceModel.cs | 7 +++++ .../Models/Identity/User/UpdateUserServiceModel.cs | 12 +++++++- src/DevHive.Services/Services/UserService.cs | 33 +++++++++++++++++++++- .../Configurations/Mapping/UserMappings.cs | 7 +++++ 5 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index d57c6ba..97355d6 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -11,6 +11,9 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap(); CreateMap(); + CreateMap() + .ForMember(up => up.UserName, u => u.MapFrom(src => src.Name)); + CreateMap(); } diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs new file mode 100644 index 0000000..c40a980 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class UpdateUserCollectionServiceModel + { + public string Name { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs index 96d1ff0..5b5a178 100644 --- a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs @@ -1,9 +1,19 @@ using System; +using System.Collections.Generic; namespace DevHive.Services.Models.Identity.User { - public class UpdateUserServiceModel : UserServiceModel + public class UpdateUserServiceModel : BaseUserServiceModel { public Guid Id { get; set; } + + public IList Roles { get; set; } = new List(); + + public IList Friends { get; set; } = new List(); + + public IList Languages { get; set; } = new List(); + + public IList Technologies { get; set; } = new List(); + } } diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 1dc1bd5..3dd030a 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -13,6 +13,7 @@ using System.Collections.Generic; using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; using DevHive.Data.Interfaces.Repositories; +using DevHive.Services.Models.Language; namespace DevHive.Services.Services { @@ -139,7 +140,7 @@ namespace DevHive.Services.Services && await this._userRepository.DoesUsernameExistAsync(updateModel.UserName)) throw new ArgumentException("Username already exists!"); - //Add validations for everything else + await this.ValidateUserCollections(updateModel); User user = this._userMapper.Map(updateModel); bool result = await this._userRepository.EditAsync(user); @@ -149,6 +150,36 @@ namespace DevHive.Services.Services return this._userMapper.Map(user); ; } + + private async Task ValidateUserCollections(UpdateUserServiceModel updateUserServiceModel) + { + // Friends + foreach (UpdateUserCollectionServiceModel friend in updateUserServiceModel.Friends) + { + User returnedFriend = await this._userRepository.GetByUsernameAsync(friend.Name); + + if (default(User) == returnedFriend) + throw new ArgumentException($"User {friend.Name} does not exist!"); + } + + // Languages + foreach (UpdateUserCollectionServiceModel language in updateUserServiceModel.Languages) + { + Language returnedLanguage = await this._languageRepository.GetByNameAsync(language.Name); + + if (default(Language) == returnedLanguage) + throw new ArgumentException($"Language {language.Name} does not exist!"); + } + + // Technology + foreach (UpdateUserCollectionServiceModel technology in updateUserServiceModel.Technologies) + { + Technology returnedTechnology = await this._technologyRepository.GetByNameAsync(technology.Name); + + if (default(Technology) == returnedTechnology) + throw new ArgumentException($"Technology {technology.Name} does not exist!"); + } + } #endregion #region Delete diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index 59003ea..aa22ce2 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -2,6 +2,8 @@ using AutoMapper; using DevHive.Services.Models.Identity.User; using DevHive.Web.Models.Identity.User; using DevHive.Common.Models.Identity; +using DevHive.Web.Models.Language; +using DevHive.Web.Models.Technology; namespace DevHive.Web.Configurations.Mapping { @@ -17,6 +19,11 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap(); + + CreateMap() + .ForMember(f => f.Name, u => u.MapFrom(src => src.Username)); + CreateMap(); + CreateMap(); } } } -- cgit v1.2.3 From 163827d4a8dbc4b41bfa0f78edc7dd30626e95d3 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 19 Jan 2021 19:02:37 +0200 Subject: Fixed role id creeping up the chain --- src/DevHive.Services/Interfaces/IRoleService.cs | 2 +- src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs | 3 --- .../Models/Identity/Role/UpdateRoleServiceModel.cs | 3 +++ src/DevHive.Services/Services/RoleService.cs | 8 ++++---- 4 files changed, 8 insertions(+), 8 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Interfaces/IRoleService.cs b/src/DevHive.Services/Interfaces/IRoleService.cs index a7a0e47..fd661be 100644 --- a/src/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/DevHive.Services/Interfaces/IRoleService.cs @@ -10,7 +10,7 @@ namespace DevHive.Services.Interfaces Task GetRoleById(Guid id); - Task UpdateRole(RoleServiceModel roleServiceModel); + Task UpdateRole(UpdateRoleServiceModel roleServiceModel); Task DeleteRole(Guid id); } diff --git a/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs index 3f834ef..07249fe 100644 --- a/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/Role/RoleServiceModel.cs @@ -1,10 +1,7 @@ -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/Role/UpdateRoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/UpdateRoleServiceModel.cs index be71771..e21e6b4 100644 --- a/src/DevHive.Services/Models/Identity/Role/UpdateRoleServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/Role/UpdateRoleServiceModel.cs @@ -1,7 +1,10 @@ +using System; + namespace DevHive.Services.Models.Identity.Role { public class UpdateRoleServiceModel { + public Guid Id { get; set; } public string Name { get; set; } } } diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index 0945624..3ebb7c8 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -47,15 +47,15 @@ namespace DevHive.Services.Services return this._roleMapper.Map(role); } - public async Task UpdateRole(RoleServiceModel roleServiceModel) + public async Task UpdateRole(UpdateRoleServiceModel updateRoleServiceModel) { - if (!await this._roleRepository.DoesRoleExist(roleServiceModel.Id)) + if (!await this._roleRepository.DoesRoleExist(updateRoleServiceModel.Id)) throw new ArgumentException("Role does not exist!"); - if (await this._roleRepository.DoesNameExist(roleServiceModel.Name)) + if (await this._roleRepository.DoesNameExist(updateRoleServiceModel.Name)) throw new ArgumentException("Role name already exists!"); - Role role = this._roleMapper.Map(roleServiceModel); + Role role = this._roleMapper.Map(updateRoleServiceModel); return await this._roleRepository.EditAsync(role); } -- 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.Services/Models/Identity') 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 8179af787a7bf375753a178b89111a91d84a8bb8 Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 20 Jan 2021 18:07:58 +0200 Subject: Changed List to HashSet for "no duplicates" scenario --- src/DevHive.Data/Interfaces/Models/ILanguage.cs | 2 +- src/DevHive.Data/Interfaces/Models/IRole.cs | 2 +- src/DevHive.Data/Interfaces/Models/ITechnology.cs | 2 +- src/DevHive.Data/Interfaces/Models/IUser.cs | 8 ++++---- .../Interfaces/Repositories/IUserRepository.cs | 4 ++-- src/DevHive.Data/Models/Language.cs | 2 +- src/DevHive.Data/Models/Role.cs | 2 +- src/DevHive.Data/Models/Technology.cs | 2 +- src/DevHive.Data/Models/User.cs | 8 ++++---- src/DevHive.Data/Repositories/UserRepository.cs | 4 ++-- .../Models/Identity/User/RegisterServiceModel.cs | 4 ++-- .../Models/Identity/User/UpdateUserServiceModel.cs | 8 ++++---- .../Models/Identity/User/UserServiceModel.cs | 8 ++++---- src/DevHive.Services/Services/PostService.cs | 5 +++-- src/DevHive.Services/Services/UserService.cs | 12 ++++++------ .../DevHive.Data.Tests/UserRepositoryTests.cs | 18 +++++++++--------- .../Models/Identity/User/UpdateUserWebModel.cs | 6 +++--- src/DevHive.Web/Models/Identity/User/UserWebModel.cs | 8 ++++---- 18 files changed, 53 insertions(+), 52 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/Interfaces/Models/ILanguage.cs b/src/DevHive.Data/Interfaces/Models/ILanguage.cs index 9549777..b77d5ae 100644 --- a/src/DevHive.Data/Interfaces/Models/ILanguage.cs +++ b/src/DevHive.Data/Interfaces/Models/ILanguage.cs @@ -6,7 +6,7 @@ namespace DevHive.Data.Interfaces.Models public interface ILanguage : IModel { string Name { get; set; } - List Users { get; set; } + HashSet Users { get; set; } } } diff --git a/src/DevHive.Data/Interfaces/Models/IRole.cs b/src/DevHive.Data/Interfaces/Models/IRole.cs index 0623f07..c8b7068 100644 --- a/src/DevHive.Data/Interfaces/Models/IRole.cs +++ b/src/DevHive.Data/Interfaces/Models/IRole.cs @@ -5,6 +5,6 @@ namespace DevHive.Data.Interfaces.Models { public interface IRole { - List Users { get; set; } + HashSet Users { get; set; } } } diff --git a/src/DevHive.Data/Interfaces/Models/ITechnology.cs b/src/DevHive.Data/Interfaces/Models/ITechnology.cs index 159a21a..153f75f 100644 --- a/src/DevHive.Data/Interfaces/Models/ITechnology.cs +++ b/src/DevHive.Data/Interfaces/Models/ITechnology.cs @@ -6,6 +6,6 @@ namespace DevHive.Data.Interfaces.Models public interface ITechnology : IModel { string Name { get; set; } - List Users { get; set; } + HashSet Users { get; set; } } } diff --git a/src/DevHive.Data/Interfaces/Models/IUser.cs b/src/DevHive.Data/Interfaces/Models/IUser.cs index ef8c927..08ce385 100644 --- a/src/DevHive.Data/Interfaces/Models/IUser.cs +++ b/src/DevHive.Data/Interfaces/Models/IUser.cs @@ -8,9 +8,9 @@ namespace DevHive.Data.Interfaces.Models string FirstName { get; set; } string LastName { get; set; } string ProfilePictureUrl { get; set; } - IList Languages { get; set; } - IList Technologies { get; set; } - IList Roles { get; set; } - IList Friends { get; set; } + HashSet Languages { get; set; } + HashSet Technologies { get; set; } + HashSet Roles { get; set; } + HashSet Friends { get; set; } } } diff --git a/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs b/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs index eca6adb..456eb94 100644 --- a/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs +++ b/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs @@ -14,8 +14,8 @@ namespace DevHive.Data.Interfaces.Repositories Task GetByUsernameAsync(string username); Language GetUserLanguage(User user, Language language); - IList GetUserLanguages(User user); - IList GetUserTechnologies(User user); + HashSet GetUserLanguages(User user); + HashSet GetUserTechnologies(User user); Technology GetUserTechnology(User user, Technology technology); IEnumerable QueryAll(); diff --git a/src/DevHive.Data/Models/Language.cs b/src/DevHive.Data/Models/Language.cs index 0db8cb6..f2b2786 100644 --- a/src/DevHive.Data/Models/Language.cs +++ b/src/DevHive.Data/Models/Language.cs @@ -8,6 +8,6 @@ namespace DevHive.Data.Models { public Guid Id { get; set; } public string Name { get; set; } - public List Users { get; set; } + public HashSet Users { get; set; } } } diff --git a/src/DevHive.Data/Models/Role.cs b/src/DevHive.Data/Models/Role.cs index e63f007..e0855aa 100644 --- a/src/DevHive.Data/Models/Role.cs +++ b/src/DevHive.Data/Models/Role.cs @@ -12,6 +12,6 @@ namespace DevHive.Data.Models public const string DefaultRole = "User"; public const string AdminRole = "Admin"; - public List Users { get; set; } + public HashSet Users { get; set; } } } diff --git a/src/DevHive.Data/Models/Technology.cs b/src/DevHive.Data/Models/Technology.cs index 9096cbe..a0728d5 100644 --- a/src/DevHive.Data/Models/Technology.cs +++ b/src/DevHive.Data/Models/Technology.cs @@ -8,6 +8,6 @@ namespace DevHive.Data.Models { public Guid Id { get; set; } public string Name { get; set; } - public List Users { get; set; } + public HashSet Users { get; set; } } } diff --git a/src/DevHive.Data/Models/User.cs b/src/DevHive.Data/Models/User.cs index cf779f5..2ac7adf 100644 --- a/src/DevHive.Data/Models/User.cs +++ b/src/DevHive.Data/Models/User.cs @@ -19,15 +19,15 @@ namespace DevHive.Data.Models /// Languages that the user uses or is familiar with /// // [Unique] - public IList Languages { get; set; } + public HashSet Languages { get; set; } /// /// Technologies that the user uses or is familiar with /// - public IList Technologies { get; set; } = new List(); + public HashSet Technologies { get; set; } = new HashSet(); - public IList Roles { get; set; } = new List(); + public HashSet Roles { get; set; } = new HashSet(); - public IList Friends { get; set; } = new List(); + public HashSet Friends { get; set; } = new HashSet(); } } diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 2ca8099..492d46b 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -82,7 +82,7 @@ namespace DevHive.Data.Repositories .FirstOrDefaultAsync(x => x.UserName == username); } - public IList GetUserLanguages(User user) + public HashSet GetUserLanguages(User user) { return user.Languages; } @@ -93,7 +93,7 @@ namespace DevHive.Data.Repositories .FirstOrDefault(x => x.Id == language.Id); } - public IList GetUserTechnologies(User user) + public HashSet GetUserTechnologies(User user) { return user.Technologies; } diff --git a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs index 74f66b4..3171ea6 100644 --- a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs @@ -6,8 +6,8 @@ namespace DevHive.Services.Models.Identity.User { public class RegisterServiceModel : BaseUserServiceModel { - public IList Languages { get; set; } - public IList Technologies { get; set; } + public HashSet Languages { get; set; } + public HashSet Technologies { get; set; } public string Password { get; set; } } } diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs index 5b5a178..87af43a 100644 --- a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs @@ -7,13 +7,13 @@ namespace DevHive.Services.Models.Identity.User { public Guid Id { get; set; } - public IList Roles { get; set; } = new List(); + public HashSet Roles { get; set; } = new HashSet(); - public IList Friends { get; set; } = new List(); + public HashSet Friends { get; set; } = new HashSet(); - public IList Languages { get; set; } = new List(); + public HashSet Languages { get; set; } = new HashSet(); - public IList Technologies { get; set; } = new List(); + public HashSet Technologies { get; set; } = new HashSet(); } } diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 913b5c0..5fcd494 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -7,12 +7,12 @@ namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { - public IList Roles { get; set; } = new List(); + public HashSet Roles { get; set; } = new HashSet(); - public IList Friends { get; set; } = new List(); + public HashSet Friends { get; set; } = new HashSet(); - public IList Languages { get; set; } = new List(); + public HashSet Languages { get; set; } = new HashSet(); - public IList Technologies { get; set; } = new List(); + public HashSet Technologies { get; set; } = new HashSet(); } } diff --git a/src/DevHive.Services/Services/PostService.cs b/src/DevHive.Services/Services/PostService.cs index f2f60d1..9503b8a 100644 --- a/src/DevHive.Services/Services/PostService.cs +++ b/src/DevHive.Services/Services/PostService.cs @@ -9,6 +9,7 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using DevHive.Services.Interfaces; using DevHive.Data.Interfaces.Repositories; +using System.Linq; namespace DevHive.Services.Services { @@ -131,8 +132,8 @@ namespace DevHive.Services.Services { var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); - string jwtUserName = this.GetClaimTypeValues("unique_name", jwt.Claims)[0]; - //List jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims); + string jwtUserName = this.GetClaimTypeValues("unique_name", jwt.Claims).First(); + //HashSet jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims); User user = await this._userRepository.GetByUsernameAsync(jwtUserName) ?? throw new ArgumentException("User does not exist!"); diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index ee4b24d..51c4432 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -75,7 +75,7 @@ namespace DevHive.Services.Services // Set the default role to the user Role defaultRole = await this._roleRepository.GetByNameAsync(Role.DefaultRole); - user.Roles = new List() { defaultRole }; + user.Roles = new HashSet() { defaultRole }; await this._userRepository.AddAsync(user); @@ -144,12 +144,12 @@ namespace DevHive.Services.Services await this.ValidateUserCollections(updateUserServiceModel); - List languages = new(); + HashSet languages = new(); foreach (UpdateUserCollectionServiceModel lang in updateUserServiceModel.Languages) languages.Add(await this._languageRepository.GetByNameAsync(lang.Name) ?? throw new ArgumentException("Invalid language name!")); - List technologies = new(); + HashSet technologies = new(); foreach (UpdateUserCollectionServiceModel tech in updateUserServiceModel.Technologies) technologies.Add(await this._technologyRepository.GetByNameAsync(tech.Name) ?? throw new ArgumentException("Invalid technology name!")); @@ -257,7 +257,7 @@ namespace DevHive.Services.Services // There is authorization name in the beginning, i.e. "Bearer eyJh..." var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); - Guid jwtUserID = new Guid(this.GetClaimTypeValues("ID", jwt.Claims)[0]); + Guid jwtUserID = new Guid(this.GetClaimTypeValues("ID", jwt.Claims).First()); List jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims); User user = await this._userRepository.GetByIdAsync(jwtUserID) @@ -326,11 +326,11 @@ namespace DevHive.Services.Services } } - private string WriteJWTSecurityToken(Guid userId, IList roles) + private string WriteJWTSecurityToken(Guid userId, HashSet roles) { byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret); - List claims = new() + HashSet claims = new() { new Claim("ID", $"{userId}"), }; diff --git a/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs b/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs index b0a5b93..be116b0 100644 --- a/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs +++ b/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs @@ -165,10 +165,10 @@ namespace DevHive.Data.Tests //Arrange User dummyUser = CreateDummyUser(); await this._userRepository.AddAsync(dummyUser); - IList dummyUserLanguages = dummyUser.Languages; + HashSet dummyUserLanguages = dummyUser.Languages; //Act - IList languages = this._userRepository.GetUserLanguages(dummyUser); + HashSet languages = this._userRepository.GetUserLanguages(dummyUser); //Assert Assert.AreEqual(dummyUserLanguages, languages, "Method doesn't query languages properly"); @@ -185,7 +185,7 @@ namespace DevHive.Data.Tests // Language dummyLang = await this._languageRepository.GetByNameAsync("csharp"); // //Act - // IList languages = this._userRepository.GetUserLanguage(dummyUser, dummyLang); + // HashSet languages = this._userRepository.GetUserLanguage(dummyUser, dummyLang); // //Assert // Assert.AreEqual(dummyUserLanguages, languages, "Method doesn't query languages properly"); @@ -195,7 +195,7 @@ namespace DevHive.Data.Tests #region HelperMethods private User CreateDummyUser() { - List languages = new() + HashSet languages = new() { new Language() { @@ -204,7 +204,7 @@ namespace DevHive.Data.Tests }, }; - List technologies = new() + HashSet technologies = new() { new Technology() { @@ -213,7 +213,7 @@ namespace DevHive.Data.Tests }, }; - List roles = new() + HashSet roles = new() { new Role() { @@ -237,7 +237,7 @@ namespace DevHive.Data.Tests private User CreateAnotherDummyUser() { - List languages = new() + HashSet languages = new() { new Language() { @@ -246,7 +246,7 @@ namespace DevHive.Data.Tests }, }; - List technologies = new() + HashSet technologies = new() { new Technology() { @@ -255,7 +255,7 @@ namespace DevHive.Data.Tests }, }; - List roles = new() + HashSet roles = new() { new Role() { diff --git a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs index 724930c..3c38ab6 100644 --- a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs @@ -16,14 +16,14 @@ namespace DevHive.Web.Models.Identity.User [NotNull] [Required] - public IList Friends { get; set; } + public HashSet Friends { get; set; } [NotNull] [Required] - public IList Languages { get; set; } + public HashSet Languages { get; set; } [NotNull] [Required] - public IList Technologies { get; set; } + public HashSet Technologies { get; set; } } } diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 1d2d17b..5b80ba3 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -11,18 +11,18 @@ namespace DevHive.Web.Models.Identity.User { [NotNull] [Required] - public IList Roles { get; set; } = new List(); + public HashSet Roles { get; set; } = new HashSet(); [NotNull] [Required] - public IList Friends { get; set; } = new List(); + public HashSet Friends { get; set; } = new HashSet(); [NotNull] [Required] - public IList Languages { get; set; } = new List(); + public HashSet Languages { get; set; } = new HashSet(); [NotNull] [Required] - public IList Technologies { get; set; } = new List(); + public HashSet Technologies { get; set; } = new HashSet(); } } -- cgit v1.2.3 From 009e01dc3dc2f78db6a660c65bf0d20bae702348 Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 21 Jan 2021 09:23:06 +0200 Subject: Tryed implementing the http patch --- .../Models/Misc/PasswordModifications.cs | 13 ++++ src/DevHive.Common/Models/Misc/Patch.cs | 9 +++ src/DevHive.Data/Repositories/UserRepository.cs | 7 -- .../Configurations/Mapping/RoleMapings.cs | 3 + .../Mapping/UserCollectionMappings.cs | 17 ++--- .../Configurations/Mapping/UserMappings.cs | 6 +- src/DevHive.Services/Interfaces/IUserService.cs | 6 +- .../Models/Identity/User/BaseUserServiceModel.cs | 1 + .../Technology/ReadTechnologyServiceModel.cs | 7 ++ src/DevHive.Services/Services/UserService.cs | 78 ++++++++++++---------- .../Configurations/Mapping/TechnologyMappings.cs | 2 + src/DevHive.Web/Controllers/UserController.cs | 19 ++---- .../Models/Technology/ReadTechnologyWebModel.cs | 14 ++++ 13 files changed, 113 insertions(+), 69 deletions(-) create mode 100644 src/DevHive.Common/Models/Misc/PasswordModifications.cs create mode 100644 src/DevHive.Common/Models/Misc/Patch.cs create mode 100644 src/DevHive.Services/Models/Technology/ReadTechnologyServiceModel.cs create mode 100644 src/DevHive.Web/Models/Technology/ReadTechnologyWebModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Common/Models/Misc/PasswordModifications.cs b/src/DevHive.Common/Models/Misc/PasswordModifications.cs new file mode 100644 index 0000000..f10a334 --- /dev/null +++ b/src/DevHive.Common/Models/Misc/PasswordModifications.cs @@ -0,0 +1,13 @@ +using System.Security.Cryptography; +using System.Text; + +namespace DevHive.Common.Models.Misc +{ + public static class PasswordModifications + { + public static string GeneratePasswordHash(string password) + { + return string.Join(string.Empty, SHA512.HashData(Encoding.ASCII.GetBytes(password))); + } + } +} diff --git a/src/DevHive.Common/Models/Misc/Patch.cs b/src/DevHive.Common/Models/Misc/Patch.cs new file mode 100644 index 0000000..ea5a4f1 --- /dev/null +++ b/src/DevHive.Common/Models/Misc/Patch.cs @@ -0,0 +1,9 @@ +namespace DevHive.Common.Models.Misc +{ + public class Patch + { + public string Name { get; set; } + public object Value { get; set; } + public string Action { get; set; } + } +} diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 492d46b..3f9af70 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -109,13 +109,6 @@ namespace DevHive.Data.Repositories public async Task EditAsync(User newEntity) { - // User user = await this.GetByIdAsync(newEntity.Id); - - // 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/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index 4ddd253..b5541f9 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -9,6 +9,9 @@ namespace DevHive.Services.Configurations.Mapping public RoleMappings() { CreateMap(); + CreateMap(); + + CreateMap(); CreateMap(); } } diff --git a/src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs index ee505a2..7a773e8 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs @@ -8,14 +8,15 @@ namespace DevHive.Services.Configurations.Mapping { public UserCollectionMappings() { - CreateMap() - .ForMember(up => up.UserName, u => u.MapFrom(src => src.Name)); - CreateMap() - .ForMember(r => r.Name, u => u.MapFrom(src => src.Name)); - CreateMap() - .ForMember(r => r.Name, u => u.MapFrom(src => src.Name)); - CreateMap() - .ForMember(r => r.Name, u => u.MapFrom(src => src.Name)); + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); + + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index 541e16e..5d9e41c 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -1,6 +1,7 @@ using DevHive.Data.Models; using AutoMapper; using DevHive.Services.Models.Identity.User; +using DevHive.Common.Models.Misc; namespace DevHive.Services.Configurations.Mapping { @@ -10,10 +11,13 @@ namespace DevHive.Services.Configurations.Mapping { CreateMap(); CreateMap(); - CreateMap(); + CreateMap() + .AfterMap((src, dest) => dest.PasswordHash = PasswordModifications.GeneratePasswordHash(src.Password)); CreateMap(); CreateMap(); + CreateMap() + .ForMember(x => x.Password, opt => opt.Ignore()); CreateMap(); } } diff --git a/src/DevHive.Services/Interfaces/IUserService.cs b/src/DevHive.Services/Interfaces/IUserService.cs index 121fec3..88be0c8 100644 --- a/src/DevHive.Services/Interfaces/IUserService.cs +++ b/src/DevHive.Services/Interfaces/IUserService.cs @@ -1,9 +1,9 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using DevHive.Common.Models.Identity; -using DevHive.Data.Models; +using DevHive.Common.Models.Misc; using DevHive.Services.Models.Identity.User; -using Microsoft.AspNetCore.JsonPatch; namespace DevHive.Services.Interfaces { @@ -18,7 +18,7 @@ namespace DevHive.Services.Interfaces Task GetUserById(Guid id); Task UpdateUser(UpdateUserServiceModel updateModel); - Task PatchUser(Guid id, JsonPatchDocument jsonPatch); + Task PatchUser(Guid id, List patch); Task DeleteUser(Guid id); Task RemoveFriend(Guid userId, Guid friendId); diff --git a/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs index 514f82a..7a160f8 100644 --- a/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs @@ -6,5 +6,6 @@ namespace DevHive.Services.Models.Identity.User public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } + public string Password { get; set; } } } diff --git a/src/DevHive.Services/Models/Technology/ReadTechnologyServiceModel.cs b/src/DevHive.Services/Models/Technology/ReadTechnologyServiceModel.cs new file mode 100644 index 0000000..cbfdc7d --- /dev/null +++ b/src/DevHive.Services/Models/Technology/ReadTechnologyServiceModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Services.Models.Technology +{ + public class ReadTechnologyServiceModel + { + public string Name { get; set; } + } +} diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 51c4432..629b489 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -7,15 +7,14 @@ using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; -using System.Security.Cryptography; using System.Text; using System.Collections.Generic; using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; using DevHive.Data.Interfaces.Repositories; -using Microsoft.AspNetCore.JsonPatch; using System.Linq; -using Newtonsoft.Json; +using DevHive.Common.Models.Misc; +using System.Reflection; namespace DevHive.Services.Services { @@ -52,7 +51,7 @@ namespace DevHive.Services.Services User user = await this._userRepository.GetByUsernameAsync(loginModel.UserName); - if (user.PasswordHash != GeneratePasswordHash(loginModel.Password)) + if (user.PasswordHash != PasswordModifications.GeneratePasswordHash(loginModel.Password)) throw new ArgumentException("Incorrect password!"); return new TokenModel(WriteJWTSecurityToken(user.Id, user.Roles)); @@ -67,7 +66,7 @@ namespace DevHive.Services.Services throw new ArgumentException("Email already exists!"); User user = this._userMapper.Map(registerModel); - user.PasswordHash = GeneratePasswordHash(registerModel.Password); + user.PasswordHash = PasswordModifications.GeneratePasswordHash(registerModel.Password); // Make sure the default role exists if (!await this._roleRepository.DoesNameExist(Role.DefaultRole)) @@ -135,6 +134,7 @@ namespace DevHive.Services.Services public async Task UpdateUser(UpdateUserServiceModel updateUserServiceModel) { + //Method: ValidateUserOnUpdate if (!await this._userRepository.DoesUserExistAsync(updateUserServiceModel.Id)) throw new ArgumentException("User does not exist!"); @@ -144,6 +144,7 @@ namespace DevHive.Services.Services await this.ValidateUserCollections(updateUserServiceModel); + //Method: Insert collections to user HashSet languages = new(); foreach (UpdateUserCollectionServiceModel lang in updateUserServiceModel.Languages) languages.Add(await this._languageRepository.GetByNameAsync(lang.Name) ?? @@ -159,51 +160,35 @@ namespace DevHive.Services.Services user.Languages = languages; user.Technologies = technologies; - bool success = await this._userRepository.EditAsync(user); + bool successful = await this._userRepository.EditAsync(user); - if (!success) + if (!successful) throw new InvalidOperationException("Unable to edit user!"); return this._userMapper.Map(user); ; } - public async Task PatchUser(Guid id, JsonPatchDocument jsonPatch) + public async Task PatchUser(Guid id, List patchList) { User user = await this._userRepository.GetByIdAsync(id) ?? throw new ArgumentException("User does not exist!"); - 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; - } + UpdateUserServiceModel updateUserServiceModel = this._userMapper.Map(user); - if (friends != null) + foreach (Patch patch in patchList) { - foreach (object friendObj in friends) + bool successful = patch.Action switch { - 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); - } + "replace" => ReplacePatch(updateUserServiceModel, patch), + "add" => AddPatch(updateUserServiceModel, patch), + "remove" => RemovePatch(updateUserServiceModel, patch), + _ => throw new ArgumentException("Invalid patch operation!"), + }; + + if (!successful) + throw new ArgumentException("A problem occurred while applying patch"); } - //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) { @@ -326,6 +311,11 @@ namespace DevHive.Services.Services } } + private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel) + { + + } + private string WriteJWTSecurityToken(Guid userId, HashSet roles) { byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret); @@ -354,9 +344,23 @@ namespace DevHive.Services.Services return tokenHandler.WriteToken(token); } - private string GeneratePasswordHash(string password) + private bool AddPatch(UpdateUserServiceModel updateUserServiceModel, Patch patch) + { + // Type type = typeof(UpdateUserServiceModel); + // PropertyInfo property = type.GetProperty(patch.Name); + + // property.SetValue(updateUserServiceModel, patch.Value); + throw new NotImplementedException(); + } + + private bool RemovePatch(UpdateUserServiceModel updateUserServiceModel, Patch patch) + { + throw new NotImplementedException(); + } + + private bool ReplacePatch(UpdateUserServiceModel updateUserServiceModel, Patch patch) { - return string.Join(string.Empty, SHA512.HashData(Encoding.ASCII.GetBytes(password))); + throw new NotImplementedException(); } #endregion } diff --git a/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs b/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs index 828dac1..4ecd5f3 100644 --- a/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs @@ -9,10 +9,12 @@ namespace DevHive.Web.Configurations.Mapping public TechnologyMappings() { CreateMap(); + CreateMap(); CreateMap(); CreateMap(); CreateMap(); + CreateMap(); CreateMap(); CreateMap(); } diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index 471d2bb..7121ac8 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -6,14 +6,10 @@ using DevHive.Web.Models.Identity.User; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using DevHive.Common.Models.Identity; -using DevHive.Common.Models.Misc; -using DevHive.Web.Models.Language; -using DevHive.Services.Models.Language; -using DevHive.Web.Models.Technology; -using DevHive.Services.Models.Technology; using DevHive.Services.Interfaces; -using DevHive.Data.Models; using Microsoft.AspNetCore.JsonPatch; +using DevHive.Common.Models.Misc; +using System.Collections.Generic; namespace DevHive.Web.Controllers { @@ -87,15 +83,12 @@ namespace DevHive.Web.Controllers #region Update [HttpPut] - public async Task Update(Guid id, [FromBody] UpdateUserWebModel updateModel, [FromHeader] string authorization) + public async Task Update(Guid id, [FromBody] UpdateUserWebModel updateUserWebModel, [FromHeader] string authorization) { if (!await this._userService.ValidJWT(id, authorization)) return new UnauthorizedResult(); - // if (!ModelState.IsValid) - // return BadRequest("Not a valid model!"); - - UpdateUserServiceModel updateUserServiceModel = this._userMapper.Map(updateModel); + UpdateUserServiceModel updateUserServiceModel = this._userMapper.Map(updateUserWebModel); updateUserServiceModel.Id = id; UserServiceModel userServiceModel = await this._userService.UpdateUser(updateUserServiceModel); @@ -105,12 +98,12 @@ namespace DevHive.Web.Controllers } [HttpPatch] - public async Task Patch(Guid id, [FromBody] JsonPatchDocument jsonPatch, [FromHeader] string authorization) + public async Task Patch(Guid id, [FromBody] List patch, [FromHeader] string authorization) { if (!await this._userService.ValidJWT(id, authorization)) return new UnauthorizedResult(); - UserServiceModel userServiceModel = await this._userService.PatchUser(id, jsonPatch); + UserServiceModel userServiceModel = await this._userService.PatchUser(id, patch); if (userServiceModel == null) return new BadRequestObjectResult("Wrong patch properties"); diff --git a/src/DevHive.Web/Models/Technology/ReadTechnologyWebModel.cs b/src/DevHive.Web/Models/Technology/ReadTechnologyWebModel.cs new file mode 100644 index 0000000..edaaaef --- /dev/null +++ b/src/DevHive.Web/Models/Technology/ReadTechnologyWebModel.cs @@ -0,0 +1,14 @@ +using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; + +namespace DevHive.Web.Models.Technology +{ + public class ReadTechnologyWebModel + { + [NotNull] + [Required] + [MinLength(3)] + [MaxLength(50)] + public string Name { get; set; } + } +} -- cgit v1.2.3 From 0d4ec399e6c9246dd0d3050dda2c81043cf7f51d Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 21 Jan 2021 09:29:50 +0200 Subject: Fixed Password property positioning --- src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs | 1 - src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs | 4 +++- src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs | 2 ++ src/DevHive.Services/Services/UserService.cs | 3 ++- 4 files changed, 7 insertions(+), 3 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs index 7a160f8..514f82a 100644 --- a/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/BaseUserServiceModel.cs @@ -6,6 +6,5 @@ namespace DevHive.Services.Models.Identity.User public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } - public string Password { get; set; } } } diff --git a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs index 3171ea6..adc4119 100644 --- a/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/RegisterServiceModel.cs @@ -6,8 +6,10 @@ namespace DevHive.Services.Models.Identity.User { public class RegisterServiceModel : BaseUserServiceModel { + public string Password { get; set; } + public HashSet Languages { get; set; } + public HashSet Technologies { get; set; } - public string Password { get; set; } } } diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs index 87af43a..835bf54 100644 --- a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs @@ -7,6 +7,8 @@ namespace DevHive.Services.Models.Identity.User { public Guid Id { get; set; } + public string Password { get; set; } + public HashSet Roles { get; set; } = new HashSet(); public HashSet Friends { get; set; } = new HashSet(); diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 629b489..dca00fa 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -15,6 +15,7 @@ using DevHive.Data.Interfaces.Repositories; using System.Linq; using DevHive.Common.Models.Misc; using System.Reflection; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace DevHive.Services.Services { @@ -313,7 +314,7 @@ namespace DevHive.Services.Services private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel) { - + throw new NotImplementedException(); } private string WriteJWTSecurityToken(Guid userId, HashSet roles) -- cgit v1.2.3 From 9e86699c9b3aff17e0c4d19850b41b792a9625ef Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 21 Jan 2021 19:12:04 +0200 Subject: Removed HTTP Patch; Refactored HTTP Put; Fixed Update bug --- .../Repositories/LanguageRepository.cs | 7 +- .../Repositories/TechnologyRepository.cs | 1 + src/DevHive.Data/Repositories/UserRepository.cs | 15 ++- .../Configurations/Mapping/RoleMapings.cs | 2 +- .../Configurations/Mapping/TechnologyMappings.cs | 2 + .../Mapping/UserCollectionMappings.cs | 22 ---- src/DevHive.Services/Interfaces/IUserService.cs | 1 - .../Models/Identity/Role/CreateRoleServiceModel.cs | 14 +++ .../Models/Identity/User/FriendServiceModel.cs | 3 + .../Identity/User/UpdateFriendServiceModel.cs | 10 ++ .../User/UpdateUserCollectionServiceModel.cs | 7 -- .../Models/Identity/User/UpdateUserServiceModel.cs | 11 +- src/DevHive.Services/Services/UserService.cs | 135 +++++++++------------ .../Configurations/Mapping/LanguageMappings.cs | 7 +- .../Configurations/Mapping/RoleMappings.cs | 9 +- .../Configurations/Mapping/TechnologyMappings.cs | 3 +- .../Configurations/Mapping/UserMappings.cs | 13 +- src/DevHive.Web/Controllers/UserController.cs | 14 --- .../Models/Identity/User/UpdateUserWebModel.cs | 5 + 19 files changed, 132 insertions(+), 149 deletions(-) delete mode 100644 src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs create mode 100644 src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs delete mode 100644 src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/Repositories/LanguageRepository.cs b/src/DevHive.Data/Repositories/LanguageRepository.cs index 108b307..4c51cf3 100644 --- a/src/DevHive.Data/Repositories/LanguageRepository.cs +++ b/src/DevHive.Data/Repositories/LanguageRepository.cs @@ -20,8 +20,7 @@ namespace DevHive.Data.Repositories public async Task AddAsync(Language entity) { - await this._context - .Set() + await this._context.Languages .AddAsync(entity); return await this.SaveChangesAsync(this._context); @@ -32,14 +31,14 @@ namespace DevHive.Data.Repositories public async Task GetByIdAsync(Guid id) { - return await this._context - .Set() + return await this._context.Languages .FindAsync(id); } public async Task GetByNameAsync(string languageName) { return await this._context.Languages + .AsNoTracking() .FirstOrDefaultAsync(x => x.Name == languageName); } #endregion diff --git a/src/DevHive.Data/Repositories/TechnologyRepository.cs b/src/DevHive.Data/Repositories/TechnologyRepository.cs index 390ad3f..a41d4fb 100644 --- a/src/DevHive.Data/Repositories/TechnologyRepository.cs +++ b/src/DevHive.Data/Repositories/TechnologyRepository.cs @@ -40,6 +40,7 @@ namespace DevHive.Data.Repositories public async Task GetByNameAsync(string technologyName) { return await this._context.Technologies + .AsNoTracking() .FirstOrDefaultAsync(x => x.Name == technologyName); } #endregion diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 3f9af70..c769f7e 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -6,6 +6,7 @@ using DevHive.Common.Models.Misc; using DevHive.Data.Interfaces.Repositories; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; namespace DevHive.Data.Repositories { @@ -78,7 +79,9 @@ namespace DevHive.Data.Repositories public async Task GetByUsernameAsync(string username) { return await this._context.Users - .Include(u => u.Roles) + .AsNoTracking() + .Include(x => x.Languages) + .Include(x => x.Technologies) .FirstOrDefaultAsync(x => x.UserName == username); } @@ -107,9 +110,13 @@ namespace DevHive.Data.Repositories #region Update - public async Task EditAsync(User newEntity) + public async Task EditAsync(User entity) { - this._context.Update(newEntity); + User user = await this._context.Users + .FirstOrDefaultAsync(x => x.Id == entity.Id); + + this._context.Update(user); + this._context.Entry(entity).CurrentValues.SetValues(entity); return await this.SaveChangesAsync(this._context); } @@ -177,6 +184,7 @@ namespace DevHive.Data.Repositories public async Task DoesUserExistAsync(Guid id) { return await this._context.Users + .AsNoTracking() .AnyAsync(x => x.Id == id); } @@ -208,6 +216,7 @@ namespace DevHive.Data.Repositories public bool DoesUserHaveThisUsername(Guid id, string username) { return this._context.Users + .AsNoTracking() .Any(x => x.Id == id && x.UserName == username); } diff --git a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index b5541f9..d6c8511 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -12,7 +12,7 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap(); - CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Services/Configurations/Mapping/TechnologyMappings.cs b/src/DevHive.Services/Configurations/Mapping/TechnologyMappings.cs index 079ec3e..0103ccf 100644 --- a/src/DevHive.Services/Configurations/Mapping/TechnologyMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/TechnologyMappings.cs @@ -11,8 +11,10 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap(); CreateMap(); + CreateMap(); CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs deleted file mode 100644 index 7a773e8..0000000 --- a/src/DevHive.Services/Configurations/Mapping/UserCollectionMappings.cs +++ /dev/null @@ -1,22 +0,0 @@ -using AutoMapper; -using DevHive.Data.Models; -using DevHive.Services.Models.Identity.User; - -namespace DevHive.Services.Configurations.Mapping -{ - public class UserCollectionMappings : Profile - { - public UserCollectionMappings() - { - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - } - } -} diff --git a/src/DevHive.Services/Interfaces/IUserService.cs b/src/DevHive.Services/Interfaces/IUserService.cs index 88be0c8..923e9bb 100644 --- a/src/DevHive.Services/Interfaces/IUserService.cs +++ b/src/DevHive.Services/Interfaces/IUserService.cs @@ -18,7 +18,6 @@ namespace DevHive.Services.Interfaces Task GetUserById(Guid id); Task UpdateUser(UpdateUserServiceModel updateModel); - Task PatchUser(Guid id, List patch); Task DeleteUser(Guid id); Task RemoveFriend(Guid userId, Guid friendId); diff --git a/src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs new file mode 100644 index 0000000..53bea9e --- /dev/null +++ b/src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs @@ -0,0 +1,14 @@ +using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; + +namespace DevHive.Services.Models.Identity.Role +{ + public class CreateRoleServiceModel + { + [NotNull] + [Required] + [MinLength(3)] + [MaxLength(50)] + public string Name { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs b/src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs index 63d57f7..a784f5c 100644 --- a/src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/FriendServiceModel.cs @@ -1,7 +1,10 @@ +using System; + namespace DevHive.Services.Models.Identity.User { public class FriendServiceModel { + public Guid Id { get; set; } public string UserName { get; set; } } } diff --git a/src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs new file mode 100644 index 0000000..83fcc34 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs @@ -0,0 +1,10 @@ +using System; + +namespace DevHive.Services.Models.Identity.User +{ + public class UpdateFriendServiceModel + { + public Guid Id { get; set; } + public string Name { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs deleted file mode 100644 index c40a980..0000000 --- a/src/DevHive.Services/Models/Identity/User/UpdateUserCollectionServiceModel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace DevHive.Services.Models.Identity.User -{ - public class UpdateUserCollectionServiceModel - { - public string Name { get; set; } - } -} diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs index 835bf54..9277e3e 100644 --- a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs @@ -1,5 +1,8 @@ using System; using System.Collections.Generic; +using DevHive.Services.Models.Identity.Role; +using DevHive.Services.Models.Language; +using DevHive.Services.Models.Technology; namespace DevHive.Services.Models.Identity.User { @@ -9,13 +12,13 @@ namespace DevHive.Services.Models.Identity.User public string Password { get; set; } - public HashSet Roles { get; set; } = new HashSet(); + public HashSet Roles { get; set; } = new HashSet(); - public HashSet Friends { get; set; } = new HashSet(); + public HashSet Friends { get; set; } = new HashSet(); - public HashSet Languages { get; set; } = new HashSet(); + public HashSet Languages { get; set; } = new HashSet(); - public HashSet Technologies { get; set; } = new HashSet(); + public HashSet Technologies { get; set; } = new HashSet(); } } diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index dca00fa..a57fd23 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -14,8 +14,9 @@ using DevHive.Services.Interfaces; using DevHive.Data.Interfaces.Repositories; using System.Linq; using DevHive.Common.Models.Misc; -using System.Reflection; -using Microsoft.CodeAnalysis.CSharp.Syntax; +using DevHive.Services.Models.Language; +using DevHive.Services.Models.Technology; +using DevHive.Services.Models.Identity.Role; namespace DevHive.Services.Services { @@ -135,69 +136,57 @@ namespace DevHive.Services.Services public async Task UpdateUser(UpdateUserServiceModel updateUserServiceModel) { - //Method: ValidateUserOnUpdate - if (!await this._userRepository.DoesUserExistAsync(updateUserServiceModel.Id)) - throw new ArgumentException("User does not exist!"); - - if (!this._userRepository.DoesUserHaveThisUsername(updateUserServiceModel.Id, updateUserServiceModel.UserName) - && await this._userRepository.DoesUsernameExistAsync(updateUserServiceModel.UserName)) - throw new ArgumentException("Username already exists!"); + await this.ValidateUserOnUpdate(updateUserServiceModel); await this.ValidateUserCollections(updateUserServiceModel); - //Method: Insert collections to user - HashSet languages = new(); - foreach (UpdateUserCollectionServiceModel lang in updateUserServiceModel.Languages) - languages.Add(await this._languageRepository.GetByNameAsync(lang.Name) ?? - throw new ArgumentException("Invalid language name!")); + //Preserve roles + int roleCount = updateUserServiceModel.Roles.Count; + for (int i = 0; i < roleCount; i++) + { + Role role = await this._roleRepository.GetByNameAsync(updateUserServiceModel.Roles.ElementAt(i).Name) ?? + throw new ArgumentException("Invalid role name!"); - HashSet technologies = new(); - foreach (UpdateUserCollectionServiceModel tech in updateUserServiceModel.Technologies) - technologies.Add(await this._technologyRepository.GetByNameAsync(tech.Name) ?? - throw new ArgumentException("Invalid technology name!")); + UpdateRoleServiceModel updateRoleServiceModel = this._userMapper.Map(role); - User user = this._userMapper.Map(updateUserServiceModel); + updateUserServiceModel.Roles.Add(updateRoleServiceModel); + } - user.Languages = languages; - user.Technologies = technologies; + int langCount = updateUserServiceModel.Languages.Count; + for (int i = 0; i < langCount; i++) + { + Language language = await this._languageRepository.GetByNameAsync(updateUserServiceModel.Languages.ElementAt(i).Name) ?? + throw new ArgumentException("Invalid language name!"); - bool successful = await this._userRepository.EditAsync(user); + UpdateLanguageServiceModel updateLanguageServiceModel = this._userMapper.Map(language); - if (!successful) - throw new InvalidOperationException("Unable to edit user!"); + updateUserServiceModel.Languages.Add(updateLanguageServiceModel); + } - return this._userMapper.Map(user); ; - } + //Clean the already replaced languages + updateUserServiceModel.Languages.RemoveWhere(x => x.Id == Guid.Empty); - public async Task PatchUser(Guid id, List patchList) - { - User user = await this._userRepository.GetByIdAsync(id) ?? - throw new ArgumentException("User does not exist!"); + int techCount = updateUserServiceModel.Technologies.Count; + for (int i = 0; i < techCount; i++) + { + Technology technology = await this._technologyRepository.GetByNameAsync(updateUserServiceModel.Technologies.ElementAt(i).Name) ?? + throw new ArgumentException("Invalid technology name!"); - UpdateUserServiceModel updateUserServiceModel = this._userMapper.Map(user); + UpdateTechnologyServiceModel updateTechnologyServiceModel = this._userMapper.Map(technology); - foreach (Patch patch in patchList) - { - bool successful = patch.Action switch - { - "replace" => ReplacePatch(updateUserServiceModel, patch), - "add" => AddPatch(updateUserServiceModel, patch), - "remove" => RemovePatch(updateUserServiceModel, patch), - _ => throw new ArgumentException("Invalid patch operation!"), - }; - - if (!successful) - throw new ArgumentException("A problem occurred while applying patch"); + updateUserServiceModel.Technologies.Add(updateTechnologyServiceModel); } - bool success = await this._userRepository.EditAsync(user); - if (success) - { - user = await this._userRepository.GetByIdAsync(id); - return this._userMapper.Map(user); - } - else - return null; + //Clean the already replaced technologies + updateUserServiceModel.Technologies.RemoveWhere(x => x.Id == Guid.Empty); + + User user = this._userMapper.Map(updateUserServiceModel); + bool successful = await this._userRepository.EditAsync(user); + + if (!successful) + throw new InvalidOperationException("Unable to edit user!"); + + return this._userMapper.Map(user); } #endregion @@ -282,10 +271,20 @@ namespace DevHive.Services.Services return toReturn; } + private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel) + { + if (!await this._userRepository.DoesUserExistAsync(updateUserServiceModel.Id)) + throw new ArgumentException("User does not exist!"); + + if (!this._userRepository.DoesUserHaveThisUsername(updateUserServiceModel.Id, updateUserServiceModel.UserName) + && await this._userRepository.DoesUsernameExistAsync(updateUserServiceModel.UserName)) + throw new ArgumentException("Username already exists!"); + } + private async Task ValidateUserCollections(UpdateUserServiceModel updateUserServiceModel) { // Friends - foreach (UpdateUserCollectionServiceModel friend in updateUserServiceModel.Friends) + foreach (var friend in updateUserServiceModel.Friends) { User returnedFriend = await this._userRepository.GetByUsernameAsync(friend.Name); @@ -294,29 +293,24 @@ namespace DevHive.Services.Services } // Languages - foreach (UpdateUserCollectionServiceModel language in updateUserServiceModel.Languages) + foreach (var language in updateUserServiceModel.Languages) { Language returnedLanguage = await this._languageRepository.GetByNameAsync(language.Name); - if (default(Language) == returnedLanguage) + if (returnedLanguage == null) throw new ArgumentException($"Language {language.Name} does not exist!"); } // Technology - foreach (UpdateUserCollectionServiceModel technology in updateUserServiceModel.Technologies) + foreach (var technology in updateUserServiceModel.Technologies) { Technology returnedTechnology = await this._technologyRepository.GetByNameAsync(technology.Name); - if (default(Technology) == returnedTechnology) + if (returnedTechnology == null) throw new ArgumentException($"Technology {technology.Name} does not exist!"); } } - private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel) - { - throw new NotImplementedException(); - } - private string WriteJWTSecurityToken(Guid userId, HashSet roles) { byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret); @@ -344,25 +338,6 @@ namespace DevHive.Services.Services SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } - - private bool AddPatch(UpdateUserServiceModel updateUserServiceModel, Patch patch) - { - // Type type = typeof(UpdateUserServiceModel); - // PropertyInfo property = type.GetProperty(patch.Name); - - // property.SetValue(updateUserServiceModel, patch.Value); - throw new NotImplementedException(); - } - - private bool RemovePatch(UpdateUserServiceModel updateUserServiceModel, Patch patch) - { - throw new NotImplementedException(); - } - - private bool ReplacePatch(UpdateUserServiceModel updateUserServiceModel, Patch patch) - { - throw new NotImplementedException(); - } #endregion } } diff --git a/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs b/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs index 8cac3ca..eca0d1a 100644 --- a/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/LanguageMappings.cs @@ -8,10 +8,11 @@ namespace DevHive.Web.Configurations.Mapping { public LanguageMappings() { - CreateMap(); - CreateMap(); CreateMap(); - CreateMap(); + CreateMap(); + CreateMap() + .ForMember(src => src.Id, dest => dest.Ignore()); + CreateMap(); CreateMap(); CreateMap(); diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs index 66ae8e3..2ea2742 100644 --- a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -8,11 +8,14 @@ namespace DevHive.Web.Configurations.Mapping { public RoleMappings() { - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap() + .ForMember(src => src.Id, dest => dest.Ignore()); + CreateMap(); + CreateMap(); + CreateMap(); CreateMap(); - CreateMap(); } } } diff --git a/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs b/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs index 4ecd5f3..708b6ac 100644 --- a/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/TechnologyMappings.cs @@ -10,7 +10,8 @@ namespace DevHive.Web.Configurations.Mapping { CreateMap(); CreateMap(); - CreateMap(); + CreateMap() + .ForMember(src => src.Id, dest => dest.Ignore()); CreateMap(); CreateMap(); diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index 5faf4b5..9dbf613 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -20,13 +20,14 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); - CreateMap(); - CreateMap(); + //Update + CreateMap() + .ForMember(src => src.Id, dest => dest.Ignore()); + CreateMap() + .ForMember(src => src.Id, dest => dest.Ignore()); - CreateMap() - .ForMember(f => f.Name, u => u.MapFrom(src => src.UserName)); - CreateMap(); - CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index 7121ac8..fbbbbff 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -96,20 +96,6 @@ namespace DevHive.Web.Controllers return new AcceptedResult("UpdateUser", userWebModel); } - - [HttpPatch] - public async Task Patch(Guid id, [FromBody] List patch, [FromHeader] string authorization) - { - if (!await this._userService.ValidJWT(id, authorization)) - return new UnauthorizedResult(); - - UserServiceModel userServiceModel = await this._userService.PatchUser(id, patch); - - if (userServiceModel == null) - return new BadRequestObjectResult("Wrong patch properties"); - else - return new OkObjectResult(this._userMapper.Map(userServiceModel)); - } #endregion #region Delete diff --git a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs index 3c38ab6..30c66fb 100644 --- a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using DevHive.Web.Attributes; +using DevHive.Web.Models.Identity.Role; using DevHive.Web.Models.Language; using DevHive.Web.Models.Technology; @@ -18,6 +19,10 @@ namespace DevHive.Web.Models.Identity.User [Required] public HashSet Friends { get; set; } + [NotNull] + [Required] + public HashSet Roles { get; set; } + [NotNull] [Required] public HashSet Languages { get; set; } -- cgit v1.2.3 From 1f8d51c5393ea2f413de4f3e05f77d360d096ff3 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 23 Jan 2021 16:01:05 +0200 Subject: The beginning of role based authorization --- src/DevHive.Services/Configurations/Mapping/RoleMapings.cs | 1 + src/DevHive.Services/Interfaces/IRoleService.cs | 2 +- .../Models/Identity/Role/CreateRoleServiceModel.cs | 4 ---- src/DevHive.Services/Services/RoleService.cs | 3 +-- src/DevHive.Services/Services/UserService.cs | 2 ++ .../Configurations/Extensions/ConfigureDatabase.cs | 12 ++++++++++++ src/DevHive.Web/Controllers/LanguageController.cs | 3 +++ src/DevHive.Web/Controllers/PostController.cs | 2 +- src/DevHive.Web/Controllers/RoleController.cs | 11 +++++++---- src/DevHive.Web/Controllers/TechnologyController.cs | 3 +++ src/DevHive.Web/Controllers/UserController.cs | 7 +------ 11 files changed, 32 insertions(+), 18 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index d6c8511..5f9452f 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -8,6 +8,7 @@ namespace DevHive.Services.Configurations.Mapping { public RoleMappings() { + CreateMap(); CreateMap(); CreateMap(); diff --git a/src/DevHive.Services/Interfaces/IRoleService.cs b/src/DevHive.Services/Interfaces/IRoleService.cs index fd661be..3a498d2 100644 --- a/src/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/DevHive.Services/Interfaces/IRoleService.cs @@ -6,7 +6,7 @@ namespace DevHive.Services.Interfaces { public interface IRoleService { - Task CreateRole(RoleServiceModel roleServiceModel); + Task CreateRole(CreateRoleServiceModel roleServiceModel); Task GetRoleById(Guid id); diff --git a/src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs b/src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs index 53bea9e..3bed3fd 100644 --- a/src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/Role/CreateRoleServiceModel.cs @@ -5,10 +5,6 @@ namespace DevHive.Services.Models.Identity.Role { public class CreateRoleServiceModel { - [NotNull] - [Required] - [MinLength(3)] - [MaxLength(50)] public string Name { get; set; } } } diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index 896946d..91a8c73 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -20,12 +20,11 @@ namespace DevHive.Services.Services this._roleMapper = mapper; } - public async Task CreateRole(RoleServiceModel roleServiceModel) + public async Task CreateRole(CreateRoleServiceModel roleServiceModel) { if (await this._roleRepository.DoesNameExist(roleServiceModel.Name)) throw new ArgumentException("Role already exists!"); - Role role = this._roleMapper.Map(roleServiceModel); bool success = await this._roleRepository.AddAsync(role); diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 533f422..cf33644 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -194,6 +194,8 @@ namespace DevHive.Services.Services return false; /* Check roles */ + if(jwtRoleNames.Contains(Role.AdminRole)) + return true; // Check if jwt contains all user roles (if it doesn't, jwt is either old or tampered with) foreach (var role in user.Roles) diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 4831435..6e92a65 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -8,6 +8,8 @@ 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 { @@ -19,6 +21,7 @@ namespace DevHive.Web.Configurations.Extensions options.UseNpgsql(configuration.GetConnectionString("DEV"))); services.AddIdentity() + .AddRoles() .AddEntityFrameworkStores(); services.Configure(options => @@ -47,6 +50,15 @@ namespace DevHive.Web.Configurations.Extensions options.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); options.RequireRole("User"); }); + + options.AddPolicy("Administrator", options => + { + options.RequireAuthenticatedUser(); + options.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); + options.RequireRole("Admin"); + }); + + // options.DefaultPolicy = ; }); } diff --git a/src/DevHive.Web/Controllers/LanguageController.cs b/src/DevHive.Web/Controllers/LanguageController.cs index e2d0dec..c0c5fd1 100644 --- a/src/DevHive.Web/Controllers/LanguageController.cs +++ b/src/DevHive.Web/Controllers/LanguageController.cs @@ -4,12 +4,14 @@ using AutoMapper; using DevHive.Services.Interfaces; using DevHive.Services.Models.Language; using DevHive.Web.Models.Language; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] + [Authorize(Policy = "Administrator")] public class LanguageController { private readonly ILanguageService _languageService; @@ -34,6 +36,7 @@ namespace DevHive.Web.Controllers } [HttpGet] + [Authorize(Policy = "User")] public async Task GetById(Guid id) { ReadLanguageServiceModel languageServiceModel = await this._languageService.GetLanguageById(id); diff --git a/src/DevHive.Web/Controllers/PostController.cs b/src/DevHive.Web/Controllers/PostController.cs index 50923d2..8b7344b 100644 --- a/src/DevHive.Web/Controllers/PostController.cs +++ b/src/DevHive.Web/Controllers/PostController.cs @@ -13,7 +13,6 @@ namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] - [Authorize(Roles = "User")] public class PostController { private readonly IPostService _postService; @@ -27,6 +26,7 @@ namespace DevHive.Web.Controllers //Create [HttpPost] + [Authorize(Roles = "User")] public async Task Create([FromBody] CreatePostWebModel createPostModel) { CreatePostServiceModel postServiceModel = diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index 227b877..0206542 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -5,12 +5,12 @@ using AutoMapper; using System; using DevHive.Services.Interfaces; using DevHive.Services.Models.Identity.Role; +using Microsoft.AspNetCore.Authorization; namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] - //[Authorize(Roles = "Admin")] public class RoleController { private readonly IRoleService _roleService; @@ -23,20 +23,21 @@ namespace DevHive.Web.Controllers } [HttpPost] + [Authorize(Policy = "Administrator")] public async Task Create([FromBody] CreateRoleWebModel createRoleWebModel) { - RoleServiceModel roleServiceModel = - this._roleMapper.Map(createRoleWebModel); + CreateRoleServiceModel roleServiceModel = + this._roleMapper.Map(createRoleWebModel); Guid id = await this._roleService.CreateRole(roleServiceModel); return id == Guid.Empty ? new BadRequestObjectResult($"Could not create role {createRoleWebModel.Name}") : new OkObjectResult(new { Id = id }); - } [HttpGet] + [Authorize(Policy = "User")] public async Task GetById(Guid id) { RoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); @@ -46,6 +47,7 @@ namespace DevHive.Web.Controllers } [HttpPut] + [Authorize(Policy = "Administrator")] public async Task Update(Guid id, [FromBody] UpdateRoleWebModel updateRoleWebModel) { UpdateRoleServiceModel updateRoleServiceModel = @@ -61,6 +63,7 @@ namespace DevHive.Web.Controllers } [HttpDelete] + [Authorize(Policy = "Administrator")] public async Task Delete(Guid id) { bool result = await this._roleService.DeleteRole(id); diff --git a/src/DevHive.Web/Controllers/TechnologyController.cs b/src/DevHive.Web/Controllers/TechnologyController.cs index ba2ffdc..9c6c094 100644 --- a/src/DevHive.Web/Controllers/TechnologyController.cs +++ b/src/DevHive.Web/Controllers/TechnologyController.cs @@ -4,12 +4,14 @@ using AutoMapper; using DevHive.Services.Interfaces; using DevHive.Services.Models.Technology; using DevHive.Web.Models.Technology; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] + [Authorize(Policy = "Administrator")] public class TechnologyController { private readonly ITechnologyService _technologyService; @@ -34,6 +36,7 @@ namespace DevHive.Web.Controllers } [HttpGet] + [Authorize(Policy = "User")] public async Task GetById(Guid id) { CreateTechnologyServiceModel createTechnologyServiceModel = await this._technologyService.GetTechnologyById(id); diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index fbbbbff..dd94089 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -7,15 +7,12 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; -using Microsoft.AspNetCore.JsonPatch; -using DevHive.Common.Models.Misc; -using System.Collections.Generic; namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] - [Authorize(Roles = "User")] + [Authorize(Policy = "User")] public class UserController : ControllerBase { private readonly IUserService _userService; @@ -56,7 +53,6 @@ namespace DevHive.Web.Controllers #endregion #region Read - [HttpGet] public async Task GetById(Guid id, [FromHeader] string authorization) { @@ -71,7 +67,6 @@ namespace DevHive.Web.Controllers [HttpGet] [Route("GetUser")] - [AllowAnonymous] public async Task GetUser(string username) { UserServiceModel friendServiceModel = await this._userService.GetUserByUsername(username); -- cgit v1.2.3 From 9d7489b4958a5e6e5b0cd38a61e5bf4ff12f23da Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 23 Jan 2021 16:03:59 +0200 Subject: Fixed formatting --- .../Migrations/20210121083441_UserRefactor.cs | 808 ++++++++++----------- .../Repositories/LanguageRepository.cs | 2 +- src/DevHive.Data/Repositories/RoleRepository.cs | 2 +- .../Repositories/TechnologyRepository.cs | 2 +- src/DevHive.Data/Repositories/UserRepository.cs | 2 +- .../Configurations/Mapping/RoleMapings.cs | 2 +- src/DevHive.Services/Interfaces/IRoleService.cs | 2 +- .../Models/Identity/User/UpdateUserServiceModel.cs | 2 +- .../Models/Identity/User/UserServiceModel.cs | 2 +- src/DevHive.Services/Services/PostService.cs | 4 +- src/DevHive.Services/Services/RoleService.cs | 4 +- src/DevHive.Services/Services/UserService.cs | 2 +- 12 files changed, 417 insertions(+), 417 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/Migrations/20210121083441_UserRefactor.cs b/src/DevHive.Data/Migrations/20210121083441_UserRefactor.cs index ea1af2e..6eb1e38 100644 --- a/src/DevHive.Data/Migrations/20210121083441_UserRefactor.cs +++ b/src/DevHive.Data/Migrations/20210121083441_UserRefactor.cs @@ -4,408 +4,408 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace DevHive.Data.Migrations { - public partial class UserRefactor : 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), - ProfilePictureUrl = 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: "Posts", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - IssuerId = table.Column(type: "uuid", nullable: false), - TimeCreated = table.Column(type: "timestamp without time zone", nullable: false), - Message = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Posts", 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.CreateTable( - name: "LanguageUser", - columns: table => new - { - LanguagesId = table.Column(type: "uuid", nullable: false), - UsersId = table.Column(type: "uuid", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_LanguageUser", x => new { x.LanguagesId, x.UsersId }); - table.ForeignKey( - name: "FK_LanguageUser_AspNetUsers_UsersId", - column: x => x.UsersId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_LanguageUser_Languages_LanguagesId", - column: x => x.LanguagesId, - principalTable: "Languages", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Comments", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - IssuerId = table.Column(type: "uuid", nullable: false), - Message = table.Column(type: "text", nullable: true), - TimeCreated = table.Column(type: "timestamp without time zone", nullable: false), - PostId = table.Column(type: "uuid", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Comments", x => x.Id); - table.ForeignKey( - name: "FK_Comments_Posts_PostId", - column: x => x.PostId, - principalTable: "Posts", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - migrationBuilder.CreateTable( - name: "TechnologyUser", - columns: table => new - { - TechnologiesId = table.Column(type: "uuid", nullable: false), - UsersId = table.Column(type: "uuid", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_TechnologyUser", x => new { x.TechnologiesId, x.UsersId }); - table.ForeignKey( - name: "FK_TechnologyUser_AspNetUsers_UsersId", - column: x => x.UsersId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_TechnologyUser_Technologies_TechnologiesId", - column: x => x.TechnologiesId, - principalTable: "Technologies", - 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_Comments_PostId", - table: "Comments", - column: "PostId"); - - migrationBuilder.CreateIndex( - name: "IX_LanguageUser_UsersId", - table: "LanguageUser", - column: "UsersId"); - - migrationBuilder.CreateIndex( - name: "IX_RoleUser_UsersId", - table: "RoleUser", - column: "UsersId"); - - migrationBuilder.CreateIndex( - name: "IX_TechnologyUser_UsersId", - table: "TechnologyUser", - 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: "Comments"); - - migrationBuilder.DropTable( - name: "LanguageUser"); - - migrationBuilder.DropTable( - name: "RoleUser"); - - migrationBuilder.DropTable( - name: "TechnologyUser"); - - migrationBuilder.DropTable( - name: "Posts"); - - migrationBuilder.DropTable( - name: "Languages"); - - migrationBuilder.DropTable( - name: "AspNetRoles"); - - migrationBuilder.DropTable( - name: "AspNetUsers"); - - migrationBuilder.DropTable( - name: "Technologies"); - } - } + public partial class UserRefactor : 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), + ProfilePictureUrl = 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: "Posts", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + IssuerId = table.Column(type: "uuid", nullable: false), + TimeCreated = table.Column(type: "timestamp without time zone", nullable: false), + Message = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Posts", 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.CreateTable( + name: "LanguageUser", + columns: table => new + { + LanguagesId = table.Column(type: "uuid", nullable: false), + UsersId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LanguageUser", x => new { x.LanguagesId, x.UsersId }); + table.ForeignKey( + name: "FK_LanguageUser_AspNetUsers_UsersId", + column: x => x.UsersId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_LanguageUser_Languages_LanguagesId", + column: x => x.LanguagesId, + principalTable: "Languages", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Comments", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + IssuerId = table.Column(type: "uuid", nullable: false), + Message = table.Column(type: "text", nullable: true), + TimeCreated = table.Column(type: "timestamp without time zone", nullable: false), + PostId = table.Column(type: "uuid", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Comments", x => x.Id); + table.ForeignKey( + name: "FK_Comments_Posts_PostId", + column: x => x.PostId, + principalTable: "Posts", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "TechnologyUser", + columns: table => new + { + TechnologiesId = table.Column(type: "uuid", nullable: false), + UsersId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TechnologyUser", x => new { x.TechnologiesId, x.UsersId }); + table.ForeignKey( + name: "FK_TechnologyUser_AspNetUsers_UsersId", + column: x => x.UsersId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_TechnologyUser_Technologies_TechnologiesId", + column: x => x.TechnologiesId, + principalTable: "Technologies", + 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_Comments_PostId", + table: "Comments", + column: "PostId"); + + migrationBuilder.CreateIndex( + name: "IX_LanguageUser_UsersId", + table: "LanguageUser", + column: "UsersId"); + + migrationBuilder.CreateIndex( + name: "IX_RoleUser_UsersId", + table: "RoleUser", + column: "UsersId"); + + migrationBuilder.CreateIndex( + name: "IX_TechnologyUser_UsersId", + table: "TechnologyUser", + 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: "Comments"); + + migrationBuilder.DropTable( + name: "LanguageUser"); + + migrationBuilder.DropTable( + name: "RoleUser"); + + migrationBuilder.DropTable( + name: "TechnologyUser"); + + migrationBuilder.DropTable( + name: "Posts"); + + migrationBuilder.DropTable( + name: "Languages"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + + migrationBuilder.DropTable( + name: "Technologies"); + } + } } diff --git a/src/DevHive.Data/Repositories/LanguageRepository.cs b/src/DevHive.Data/Repositories/LanguageRepository.cs index d7ee609..c28ef31 100644 --- a/src/DevHive.Data/Repositories/LanguageRepository.cs +++ b/src/DevHive.Data/Repositories/LanguageRepository.cs @@ -11,7 +11,7 @@ namespace DevHive.Data.Repositories private readonly DevHiveContext _context; public LanguageRepository(DevHiveContext context) - :base(context) + : base(context) { this._context = context; } diff --git a/src/DevHive.Data/Repositories/RoleRepository.cs b/src/DevHive.Data/Repositories/RoleRepository.cs index 156792d..e5cb959 100644 --- a/src/DevHive.Data/Repositories/RoleRepository.cs +++ b/src/DevHive.Data/Repositories/RoleRepository.cs @@ -11,7 +11,7 @@ namespace DevHive.Data.Repositories private readonly DevHiveContext _context; public RoleRepository(DevHiveContext context) - :base(context) + : base(context) { this._context = context; } diff --git a/src/DevHive.Data/Repositories/TechnologyRepository.cs b/src/DevHive.Data/Repositories/TechnologyRepository.cs index 83cc7aa..87540fb 100644 --- a/src/DevHive.Data/Repositories/TechnologyRepository.cs +++ b/src/DevHive.Data/Repositories/TechnologyRepository.cs @@ -11,7 +11,7 @@ namespace DevHive.Data.Repositories private readonly DevHiveContext _context; public TechnologyRepository(DevHiveContext context) - :base(context) + : base(context) { this._context = context; } diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 258c010..a2298db 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -13,7 +13,7 @@ namespace DevHive.Data.Repositories private readonly DevHiveContext _context; public UserRepository(DevHiveContext context) - :base(context) + : base(context) { this._context = context; } diff --git a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index 5f9452f..e61a107 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -4,7 +4,7 @@ using DevHive.Services.Models.Identity.Role; namespace DevHive.Services.Configurations.Mapping { - public class RoleMappings : Profile + public class RoleMappings : Profile { public RoleMappings() { diff --git a/src/DevHive.Services/Interfaces/IRoleService.cs b/src/DevHive.Services/Interfaces/IRoleService.cs index 3a498d2..d47728c 100644 --- a/src/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/DevHive.Services/Interfaces/IRoleService.cs @@ -4,7 +4,7 @@ using DevHive.Services.Models.Identity.Role; namespace DevHive.Services.Interfaces { - public interface IRoleService + public interface IRoleService { Task CreateRole(CreateRoleServiceModel roleServiceModel); diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs index 9277e3e..5b197e4 100644 --- a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs @@ -6,7 +6,7 @@ using DevHive.Services.Models.Technology; namespace DevHive.Services.Models.Identity.User { - public class UpdateUserServiceModel : BaseUserServiceModel + public class UpdateUserServiceModel : BaseUserServiceModel { public Guid Id { get; set; } diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 5fcd494..3aa0d44 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -5,7 +5,7 @@ using DevHive.Services.Models.Technology; namespace DevHive.Services.Models.Identity.User { - public class UserServiceModel : BaseUserServiceModel + public class UserServiceModel : BaseUserServiceModel { public HashSet Roles { get; set; } = new HashSet(); diff --git a/src/DevHive.Services/Services/PostService.cs b/src/DevHive.Services/Services/PostService.cs index 4757937..2df3b41 100644 --- a/src/DevHive.Services/Services/PostService.cs +++ b/src/DevHive.Services/Services/PostService.cs @@ -33,7 +33,7 @@ namespace DevHive.Services.Services bool success = await this._postRepository.AddAsync(post); - if(success) + if (success) { Post newPost = await this._postRepository.GetPostByIssuerAndTimeCreatedAsync(postServiceModel.IssuerId, postServiceModel.TimeCreated); return newPost.Id; @@ -49,7 +49,7 @@ namespace DevHive.Services.Services bool success = await this._postRepository.AddCommentAsync(comment); - if(success) + if (success) { Comment newComment = await this._postRepository.GetCommentByIssuerAndTimeCreatedAsync(commentServiceModel.IssuerId, commentServiceModel.TimeCreated); return newComment.Id; diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index 91a8c73..a8b8e17 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -9,7 +9,7 @@ using DevHive.Services.Models.Language; namespace DevHive.Services.Services { - public class RoleService : IRoleService + public class RoleService : IRoleService { private readonly IRoleRepository _roleRepository; private readonly IMapper _roleMapper; @@ -28,7 +28,7 @@ namespace DevHive.Services.Services Role role = this._roleMapper.Map(roleServiceModel); bool success = await this._roleRepository.AddAsync(role); - if(success) + if (success) { Role newRole = await this._roleRepository.GetByNameAsync(roleServiceModel.Name); return newRole.Id; diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index cf33644..d7013e1 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -194,7 +194,7 @@ namespace DevHive.Services.Services return false; /* Check roles */ - if(jwtRoleNames.Contains(Role.AdminRole)) + if (jwtRoleNames.Contains(Role.AdminRole)) return true; // Check if jwt contains all user roles (if it doesn't, jwt is either old or tampered with) -- cgit v1.2.3 From d2bc08c0dcd6f0dc0822333bbb00c9fc851f49cb Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 26 Jan 2021 10:55:25 +0200 Subject: Brief testing of GetPost --- .../Interfaces/Repositories/IFeedRepository.cs | 12 +++++ src/DevHive.Data/Repositories/FeedRepository.cs | 35 ++++++++++++++ .../Configurations/Mapping/FeedMappings.cs | 11 +++++ .../Configurations/Mapping/PostMappings.cs | 1 + .../Configurations/Mapping/RoleMapings.cs | 4 +- .../Configurations/Mapping/UserMappings.cs | 2 + src/DevHive.Services/Interfaces/IFeedService.cs | 10 ++++ src/DevHive.Services/Interfaces/IRoleService.cs | 2 +- src/DevHive.Services/Interfaces/IUserService.cs | 2 + .../Models/Feed/GetPageServiceModel.cs | 15 ++++++ .../Models/Feed/ReadPageServiceModel.cs | 10 ++++ .../Models/Identity/User/UserServiceModel.cs | 2 +- src/DevHive.Services/Services/FeedService.cs | 47 +++++++++++++++++++ src/DevHive.Services/Services/RoleService.cs | 4 +- src/DevHive.Services/Services/UserService.cs | 53 +++++++++++++++++++--- .../Extensions/ConfigureDependencyInjection.cs | 2 + .../Configurations/Mapping/FeedMappings.cs | 18 ++++++++ .../Configurations/Mapping/RoleMappings.cs | 4 +- .../Configurations/Mapping/UserMappings.cs | 3 ++ src/DevHive.Web/Controllers/FeedController.cs | 36 +++++++++++++++ src/DevHive.Web/Controllers/PostController.cs | 2 +- src/DevHive.Web/Controllers/RoleController.cs | 2 +- src/DevHive.Web/Controllers/UserController.cs | 15 +++++- src/DevHive.Web/Models/Feed/GetPageWebModel.cs | 19 ++++++++ src/DevHive.Web/Models/Feed/ReadPageWebModel.cs | 10 ++++ 25 files changed, 303 insertions(+), 18 deletions(-) create mode 100644 src/DevHive.Data/Interfaces/Repositories/IFeedRepository.cs create mode 100644 src/DevHive.Data/Repositories/FeedRepository.cs create mode 100644 src/DevHive.Services/Configurations/Mapping/FeedMappings.cs create mode 100644 src/DevHive.Services/Interfaces/IFeedService.cs create mode 100644 src/DevHive.Services/Models/Feed/GetPageServiceModel.cs create mode 100644 src/DevHive.Services/Models/Feed/ReadPageServiceModel.cs create mode 100644 src/DevHive.Services/Services/FeedService.cs create mode 100644 src/DevHive.Web/Configurations/Mapping/FeedMappings.cs create mode 100644 src/DevHive.Web/Controllers/FeedController.cs create mode 100644 src/DevHive.Web/Models/Feed/GetPageWebModel.cs create mode 100644 src/DevHive.Web/Models/Feed/ReadPageWebModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/Interfaces/Repositories/IFeedRepository.cs b/src/DevHive.Data/Interfaces/Repositories/IFeedRepository.cs new file mode 100644 index 0000000..e9fd48a --- /dev/null +++ b/src/DevHive.Data/Interfaces/Repositories/IFeedRepository.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using DevHive.Data.Models; + +namespace DevHive.Data.Interfaces.Repositories +{ + public interface IFeedRepository + { + Task> GetFriendsPosts(List friendsList, DateTime firstRequestIssued, int pageNumber, int pageSize); + } +} diff --git a/src/DevHive.Data/Repositories/FeedRepository.cs b/src/DevHive.Data/Repositories/FeedRepository.cs new file mode 100644 index 0000000..8bf1f9a --- /dev/null +++ b/src/DevHive.Data/Repositories/FeedRepository.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using AutoMapper.Internal; +using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Models; +using Microsoft.EntityFrameworkCore; + +namespace DevHive.Data.Repositories +{ + public class FeedRepository : IFeedRepository + { + private readonly DevHiveContext _context; + + public FeedRepository(DevHiveContext context) + { + this._context = context; + } + public async Task> GetFriendsPosts(List friendsList, DateTime firstRequestIssued, int pageNumber, int pageSize) + { + List friendsIds = friendsList.Select(f => f.Id).ToList(); + + List posts = await this._context.Posts + .Where(post => post.TimeCreated < firstRequestIssued) + .Where(p => friendsIds.Contains(p.CreatorId)) + .OrderByDescending(x => x.TimeCreated) + .Skip((pageNumber - 1) * pageSize) + .Take(pageSize) + .ToListAsync(); + + return posts; + } + } +} diff --git a/src/DevHive.Services/Configurations/Mapping/FeedMappings.cs b/src/DevHive.Services/Configurations/Mapping/FeedMappings.cs new file mode 100644 index 0000000..952e480 --- /dev/null +++ b/src/DevHive.Services/Configurations/Mapping/FeedMappings.cs @@ -0,0 +1,11 @@ +using AutoMapper; + +namespace DevHive.Services.Configurations.Mapping +{ + public class FeedMappings : Profile + { + public FeedMappings() + { + } + } +} diff --git a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs index cea7b1c..d8dcc84 100644 --- a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs @@ -20,6 +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 /\ } } } diff --git a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index e61a107..23bd46f 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -9,10 +9,10 @@ namespace DevHive.Services.Configurations.Mapping public RoleMappings() { CreateMap(); - CreateMap(); + CreateMap(); CreateMap(); - CreateMap(); + CreateMap(); CreateMap(); } } diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index 5d9e41c..6797ce1 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -14,6 +14,8 @@ namespace DevHive.Services.Configurations.Mapping CreateMap() .AfterMap((src, dest) => dest.PasswordHash = PasswordModifications.GeneratePasswordHash(src.Password)); CreateMap(); + CreateMap() + .ForMember(dest => dest.UserName, src => src.MapFrom(p => p.Name)); CreateMap(); CreateMap() diff --git a/src/DevHive.Services/Interfaces/IFeedService.cs b/src/DevHive.Services/Interfaces/IFeedService.cs new file mode 100644 index 0000000..1edba5a --- /dev/null +++ b/src/DevHive.Services/Interfaces/IFeedService.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; +using DevHive.Services.Models; + +namespace DevHive.Services.Interfaces +{ + public interface IFeedService + { + Task GetPage(GetPageServiceModel getPageServiceModel); + } +} diff --git a/src/DevHive.Services/Interfaces/IRoleService.cs b/src/DevHive.Services/Interfaces/IRoleService.cs index d47728c..d3a45e5 100644 --- a/src/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/DevHive.Services/Interfaces/IRoleService.cs @@ -8,7 +8,7 @@ namespace DevHive.Services.Interfaces { Task CreateRole(CreateRoleServiceModel roleServiceModel); - Task GetRoleById(Guid id); + Task GetRoleById(Guid id); Task UpdateRole(UpdateRoleServiceModel roleServiceModel); diff --git a/src/DevHive.Services/Interfaces/IUserService.cs b/src/DevHive.Services/Interfaces/IUserService.cs index 51e3cf9..9372517 100644 --- a/src/DevHive.Services/Interfaces/IUserService.cs +++ b/src/DevHive.Services/Interfaces/IUserService.cs @@ -18,5 +18,7 @@ namespace DevHive.Services.Interfaces Task DeleteUser(Guid id); Task ValidJWT(Guid id, string rawTokenData); + + Task SuperSecretPromotionToAdmin(Guid userId); } } diff --git a/src/DevHive.Services/Models/Feed/GetPageServiceModel.cs b/src/DevHive.Services/Models/Feed/GetPageServiceModel.cs new file mode 100644 index 0000000..745039f --- /dev/null +++ b/src/DevHive.Services/Models/Feed/GetPageServiceModel.cs @@ -0,0 +1,15 @@ +using System; + +namespace DevHive.Services.Models +{ + public class GetPageServiceModel + { + public Guid UserId { get; set; } + + public int PageNumber { get; set; } + + public DateTime FirstRequestIssued { get; set; } + + public int PageSize { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Feed/ReadPageServiceModel.cs b/src/DevHive.Services/Models/Feed/ReadPageServiceModel.cs new file mode 100644 index 0000000..f291de7 --- /dev/null +++ b/src/DevHive.Services/Models/Feed/ReadPageServiceModel.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using DevHive.Services.Models.Post.Post; + +namespace DevHive.Services.Models +{ + public class ReadPageServiceModel + { + public List Posts { get; set; } = new(); + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 3aa0d44..3e41057 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -7,7 +7,7 @@ namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { - public HashSet Roles { get; set; } = new HashSet(); + public HashSet Roles { get; set; } = new HashSet(); public HashSet Friends { get; set; } = new HashSet(); diff --git a/src/DevHive.Services/Services/FeedService.cs b/src/DevHive.Services/Services/FeedService.cs new file mode 100644 index 0000000..cae986f --- /dev/null +++ b/src/DevHive.Services/Services/FeedService.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Models; +using DevHive.Services.Interfaces; +using DevHive.Services.Models; +using DevHive.Services.Models.Post.Post; + +namespace DevHive.Services.Services +{ + public class FeedService : IFeedService + { + private readonly IMapper _mapper; + private readonly IFeedRepository _feedRepository; + private readonly IUserRepository _userRepository; + + public FeedService(IFeedRepository feedRepository, IUserRepository userRepository, IMapper mapper) + { + this._feedRepository = feedRepository; + this._userRepository = userRepository; + this._mapper = mapper; + } + + public async Task GetPage(GetPageServiceModel model) + { + User user = await this._userRepository.GetByIdAsync(model.UserId) ?? + throw new ArgumentException("User doesn't exist!"); + + List friendsList = user.Friends.ToList(); + // if(friendsList.Count == 0) + // throw new ArgumentException("This user does not have any friends!"); + + List posts = await this._feedRepository + .GetFriendsPosts(friendsList, model.FirstRequestIssued, model.PageNumber, model.PageSize) ?? + throw new ArgumentException("No posts to query."); + + ReadPageServiceModel readPageServiceModel = new(); + foreach (Post post in posts) + readPageServiceModel.Posts.Add(this._mapper.Map(post)); + + return readPageServiceModel; + } + } +} diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index a8b8e17..9f7a5ac 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -38,12 +38,12 @@ namespace DevHive.Services.Services } - public async Task GetRoleById(Guid id) + public async Task GetRoleById(Guid id) { Role role = await this._roleRepository.GetByIdAsync(id) ?? throw new ArgumentException("Role does not exist!"); - return this._roleMapper.Map(role); + return this._roleMapper.Map(role); } public async Task UpdateRole(UpdateRoleServiceModel updateRoleServiceModel) diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index d7013e1..1beb07f 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -111,7 +111,7 @@ namespace DevHive.Services.Services await this.ValidateUserCollections(updateUserServiceModel); - //Preserve roles + /* Roles */ int roleCount = updateUserServiceModel.Roles.Count; for (int i = 0; i < roleCount; i++) { @@ -123,6 +123,7 @@ namespace DevHive.Services.Services updateUserServiceModel.Roles.Add(updateRoleServiceModel); } + /* Languages */ int langCount = updateUserServiceModel.Languages.Count; for (int i = 0; i < langCount; i++) { @@ -133,10 +134,10 @@ namespace DevHive.Services.Services updateUserServiceModel.Languages.Add(updateLanguageServiceModel); } - //Clean the already replaced languages updateUserServiceModel.Languages.RemoveWhere(x => x.Id == Guid.Empty); + /* Technologies */ int techCount = updateUserServiceModel.Technologies.Count; for (int i = 0; i < techCount; i++) { @@ -147,11 +148,25 @@ namespace DevHive.Services.Services updateUserServiceModel.Technologies.Add(updateTechnologyServiceModel); } - //Clean the already replaced technologies updateUserServiceModel.Technologies.RemoveWhere(x => x.Id == Guid.Empty); + /* Friends */ + HashSet friends = new(); + int friendsCount = updateUserServiceModel.Friends.Count; + for (int i = 0; i < friendsCount; i++) + { + User friend = await this._userRepository.GetByUsernameAsync(updateUserServiceModel.Friends.ElementAt(i).Name) ?? + throw new ArgumentException("Invalid friend's username!"); + + friends.Add(friend); + } + //Clean the already replaced technologies + updateUserServiceModel.Friends.RemoveWhere(x => x.Id == Guid.Empty); + User user = this._userMapper.Map(updateUserServiceModel); + user.Friends = friends; + bool successful = await this._userRepository.EditAsync(updateUserServiceModel.Id, user); if (!successful) @@ -189,14 +204,14 @@ namespace DevHive.Services.Services /* Check if user is trying to do something to himself, unless he's an admin */ - if (!jwtRoleNames.Contains(Role.AdminRole)) - if (user.Id != id) - return false; - /* Check roles */ if (jwtRoleNames.Contains(Role.AdminRole)) return true; + if (!jwtRoleNames.Contains(Role.AdminRole)) + if (user.Id != id) + return false; + // Check if jwt contains all user roles (if it doesn't, jwt is either old or tampered with) foreach (var role in user.Roles) { @@ -290,5 +305,29 @@ namespace DevHive.Services.Services return tokenHandler.WriteToken(token); } #endregion + + public async Task SuperSecretPromotionToAdmin(Guid userId) + { + User user = await this._userRepository.GetByIdAsync(userId) ?? + throw new ArgumentException("User does not exist! Can't promote shit in this country..."); + + if(!await this._roleRepository.DoesNameExist("Admin")) + { + Role adminRole = new() + { + Name = Role.AdminRole + }; + adminRole.Users.Add(user); + + await this._roleRepository.AddAsync(adminRole); + } + + Role admin = await this._roleRepository.GetByNameAsync(Role.AdminRole); + + user.Roles.Add(admin); + await this._userRepository.EditAsync(user.Id, user); + + return admin.Id; + } } } diff --git a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs index bcf16ac..d7c859e 100644 --- a/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs +++ b/src/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -17,12 +17,14 @@ 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(); } } } diff --git a/src/DevHive.Web/Configurations/Mapping/FeedMappings.cs b/src/DevHive.Web/Configurations/Mapping/FeedMappings.cs new file mode 100644 index 0000000..159582d --- /dev/null +++ b/src/DevHive.Web/Configurations/Mapping/FeedMappings.cs @@ -0,0 +1,18 @@ +using AutoMapper; +using DevHive.Services.Models; +using DevHive.Web.Controllers; +using DevHive.Web.Models.Feed; + +namespace DevHive.Web.Configurations.Mapping +{ + public class FeedMappings : Profile + { + public FeedMappings() + { + CreateMap() + .ForMember(dest => dest.FirstRequestIssued, src => src.MapFrom(p => p.FirstPageTimeIssued)); + + CreateMap(); + } + } +} diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs index 2ea2742..2f01f77 100644 --- a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -11,11 +11,11 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap() .ForMember(src => src.Id, dest => dest.Ignore()); - CreateMap(); + CreateMap(); CreateMap(); CreateMap(); - CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index 9dbf613..e80a69a 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -25,6 +25,9 @@ namespace DevHive.Web.Configurations.Mapping .ForMember(src => src.Id, dest => dest.Ignore()); CreateMap() .ForMember(src => src.Id, dest => dest.Ignore()); + CreateMap() + .ForMember(src => src.Id, dest => dest.Ignore()) + .ForMember(src => src.Name, dest => dest.MapFrom(p => p.UserName)); CreateMap(); CreateMap(); diff --git a/src/DevHive.Web/Controllers/FeedController.cs b/src/DevHive.Web/Controllers/FeedController.cs new file mode 100644 index 0000000..7d0269b --- /dev/null +++ b/src/DevHive.Web/Controllers/FeedController.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Services.Interfaces; +using DevHive.Services.Models; +using DevHive.Web.Models.Feed; +using Microsoft.AspNetCore.Mvc; + +namespace DevHive.Web.Controllers +{ + [ApiController] + [Route("/api/[controller]")] + public class FeedController + { + private readonly IFeedService _feedService; + private readonly IMapper _mapper; + + public FeedController(IFeedService feedService, IMapper mapper) + { + this._feedService = feedService; + this._mapper = mapper; + } + + [HttpGet] + public async Task GetPosts(Guid userId, [FromBody] GetPageWebModel getPageWebModel) + { + GetPageServiceModel getPageServiceModel = this._mapper.Map(getPageWebModel); + getPageServiceModel.UserId = userId; + + ReadPageServiceModel readPageServiceModel = await this._feedService.GetPage(getPageServiceModel); + ReadPageWebModel readPageWebModel = this._mapper.Map(readPageServiceModel); + + return new OkObjectResult(readPageWebModel); + } + } +} diff --git a/src/DevHive.Web/Controllers/PostController.cs b/src/DevHive.Web/Controllers/PostController.cs index b5e1c98..151c688 100644 --- a/src/DevHive.Web/Controllers/PostController.cs +++ b/src/DevHive.Web/Controllers/PostController.cs @@ -13,7 +13,7 @@ namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] - // [Authorize(Roles = "User")] + [Authorize(Roles = "User,Admin")] public class PostController { private readonly IPostService _postService; diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index c68a32b..d8bb60c 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -40,7 +40,7 @@ namespace DevHive.Web.Controllers [Authorize(Policy = "User")] public async Task GetById(Guid id) { - RoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); + ReadRoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); RoleWebModel roleWebModel = this._roleMapper.Map(roleServiceModel); return new OkObjectResult(roleWebModel); diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index dd94089..e409eea 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -12,7 +12,7 @@ namespace DevHive.Web.Controllers { [ApiController] [Route("/api/[controller]")] - [Authorize(Policy = "User")] + [Authorize(Roles = "User,Admin")] public class UserController : ControllerBase { private readonly IUserService _userService; @@ -104,5 +104,18 @@ namespace DevHive.Web.Controllers return new OkResult(); } #endregion + + [HttpPost] + [Route("SuperSecretPromotionToAdmin")] + public async Task SuperSecretPromotionToAdmin(Guid userId) + { + object obj = new + { + UserId = userId, + AdminRoleId = await this._userService.SuperSecretPromotionToAdmin(userId) + }; + + return new OkObjectResult(obj); + } } } diff --git a/src/DevHive.Web/Models/Feed/GetPageWebModel.cs b/src/DevHive.Web/Models/Feed/GetPageWebModel.cs new file mode 100644 index 0000000..4ea44cc --- /dev/null +++ b/src/DevHive.Web/Models/Feed/GetPageWebModel.cs @@ -0,0 +1,19 @@ +using System; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace DevHive.Web.Models.Feed +{ + public class GetPageWebModel + { + [Range(1, int.MaxValue)] + public int PageNumber { get; set; } + + [Required] + public DateTime FirstPageTimeIssued { get; set; } + + [DefaultValue(5)] + [Range(1, int.MaxValue)] + public int PageSize { get; set; } + } +} diff --git a/src/DevHive.Web/Models/Feed/ReadPageWebModel.cs b/src/DevHive.Web/Models/Feed/ReadPageWebModel.cs new file mode 100644 index 0000000..40d29c9 --- /dev/null +++ b/src/DevHive.Web/Models/Feed/ReadPageWebModel.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using DevHive.Web.Models.Post.Post; + +namespace DevHive.Web.Controllers +{ + public class ReadPageWebModel + { + public List Posts { get; set; } = new(); + } +} -- cgit v1.2.3 From df52b1068e16adc50ffd365e2e8b8ea19b59fac3 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 26 Jan 2021 11:44:41 +0200 Subject: UserUpdate does not allow updating roles if not admin; HTTP Put now works properly; UserUpdate validates properly --- .../Configurations/Mapping/RoleMapings.cs | 4 +- .../Configurations/Mapping/UserMappings.cs | 5 +- src/DevHive.Services/Interfaces/IRoleService.cs | 2 +- .../Identity/User/UpdateFriendServiceModel.cs | 2 +- .../Models/Identity/User/UserServiceModel.cs | 8 +- .../Models/Language/UpdateLanguageServiceModel.cs | 4 +- .../Technology/UpdateTechnologyServiceModel.cs | 4 +- src/DevHive.Services/Services/RoleService.cs | 4 +- src/DevHive.Services/Services/UserService.cs | 142 +++++++++++---------- .../Configurations/Mapping/RoleMappings.cs | 4 +- .../Configurations/Mapping/UserMappings.cs | 14 +- src/DevHive.Web/Controllers/RoleController.cs | 2 +- .../Models/Identity/Role/UpdateRoleWebModel.cs | 6 +- .../Models/Identity/User/FriendWebModel.cs | 16 --- .../Models/Identity/User/UpdateUserWebModel.cs | 2 +- .../Models/Identity/User/UserWebModel.cs | 2 +- .../Models/Identity/User/UsernameWebModel.cs | 16 +++ 17 files changed, 125 insertions(+), 112 deletions(-) delete mode 100644 src/DevHive.Web/Models/Identity/User/FriendWebModel.cs create mode 100644 src/DevHive.Web/Models/Identity/User/UsernameWebModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs index 23bd46f..e61a107 100644 --- a/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs +++ b/src/DevHive.Services/Configurations/Mapping/RoleMapings.cs @@ -9,10 +9,10 @@ namespace DevHive.Services.Configurations.Mapping public RoleMappings() { CreateMap(); - CreateMap(); + CreateMap(); CreateMap(); - CreateMap(); + CreateMap(); CreateMap(); } } diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index 6797ce1..096af38 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -11,11 +11,10 @@ namespace DevHive.Services.Configurations.Mapping { CreateMap(); CreateMap(); + CreateMap(); CreateMap() .AfterMap((src, dest) => dest.PasswordHash = PasswordModifications.GeneratePasswordHash(src.Password)); - CreateMap(); - CreateMap() - .ForMember(dest => dest.UserName, src => src.MapFrom(p => p.Name)); + CreateMap(); CreateMap(); CreateMap() diff --git a/src/DevHive.Services/Interfaces/IRoleService.cs b/src/DevHive.Services/Interfaces/IRoleService.cs index d3a45e5..d47728c 100644 --- a/src/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/DevHive.Services/Interfaces/IRoleService.cs @@ -8,7 +8,7 @@ namespace DevHive.Services.Interfaces { Task CreateRole(CreateRoleServiceModel roleServiceModel); - Task GetRoleById(Guid id); + Task GetRoleById(Guid id); Task UpdateRole(UpdateRoleServiceModel roleServiceModel); diff --git a/src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs index 83fcc34..b0efe10 100644 --- a/src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UpdateFriendServiceModel.cs @@ -5,6 +5,6 @@ namespace DevHive.Services.Models.Identity.User public class UpdateFriendServiceModel { public Guid Id { get; set; } - public string Name { get; set; } + 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 3e41057..7da54b8 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -7,12 +7,12 @@ namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { - public HashSet Roles { get; set; } = new HashSet(); + public HashSet Roles { get; set; } = new(); - public HashSet Friends { get; set; } = new HashSet(); + public HashSet Friends { get; set; } = new(); - public HashSet Languages { get; set; } = new HashSet(); + public HashSet Languages { get; set; } = new(); - public HashSet Technologies { get; set; } = new HashSet(); + public HashSet Technologies { get; set; } = new(); } } diff --git a/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs b/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs index 8536693..84b7f27 100644 --- a/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs +++ b/src/DevHive.Services/Models/Language/UpdateLanguageServiceModel.cs @@ -2,8 +2,10 @@ using System; namespace DevHive.Services.Models.Language { - public class UpdateLanguageServiceModel : LanguageServiceModel + public class UpdateLanguageServiceModel { + public Guid Id { get; set; } + public string Name { get; set; } } } diff --git a/src/DevHive.Services/Models/Technology/UpdateTechnologyServiceModel.cs b/src/DevHive.Services/Models/Technology/UpdateTechnologyServiceModel.cs index a18e286..f4c7921 100644 --- a/src/DevHive.Services/Models/Technology/UpdateTechnologyServiceModel.cs +++ b/src/DevHive.Services/Models/Technology/UpdateTechnologyServiceModel.cs @@ -2,8 +2,10 @@ using System; namespace DevHive.Services.Models.Technology { - public class UpdateTechnologyServiceModel : TechnologyServiceModel + public class UpdateTechnologyServiceModel { + public Guid Id { get; set; } + public string Name { get; set; } } } diff --git a/src/DevHive.Services/Services/RoleService.cs b/src/DevHive.Services/Services/RoleService.cs index 9f7a5ac..a8b8e17 100644 --- a/src/DevHive.Services/Services/RoleService.cs +++ b/src/DevHive.Services/Services/RoleService.cs @@ -38,12 +38,12 @@ namespace DevHive.Services.Services } - public async Task GetRoleById(Guid id) + public async Task GetRoleById(Guid id) { Role role = await this._roleRepository.GetByIdAsync(id) ?? throw new ArgumentException("Role does not exist!"); - return this._roleMapper.Map(role); + return this._roleMapper.Map(role); } public async Task UpdateRole(UpdateRoleServiceModel updateRoleServiceModel) diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 1beb07f..960630e 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -111,61 +111,9 @@ namespace DevHive.Services.Services await this.ValidateUserCollections(updateUserServiceModel); - /* Roles */ - int roleCount = updateUserServiceModel.Roles.Count; - for (int i = 0; i < roleCount; i++) - { - Role role = await this._roleRepository.GetByNameAsync(updateUserServiceModel.Roles.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid role name!"); - - UpdateRoleServiceModel updateRoleServiceModel = this._userMapper.Map(role); - - updateUserServiceModel.Roles.Add(updateRoleServiceModel); - } - - /* Languages */ - int langCount = updateUserServiceModel.Languages.Count; - for (int i = 0; i < langCount; i++) - { - Language language = await this._languageRepository.GetByNameAsync(updateUserServiceModel.Languages.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid language name!"); - - UpdateLanguageServiceModel updateLanguageServiceModel = this._userMapper.Map(language); - - updateUserServiceModel.Languages.Add(updateLanguageServiceModel); - } - //Clean the already replaced languages - updateUserServiceModel.Languages.RemoveWhere(x => x.Id == Guid.Empty); - - /* Technologies */ - int techCount = updateUserServiceModel.Technologies.Count; - for (int i = 0; i < techCount; i++) - { - Technology technology = await this._technologyRepository.GetByNameAsync(updateUserServiceModel.Technologies.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid technology name!"); - - UpdateTechnologyServiceModel updateTechnologyServiceModel = this._userMapper.Map(technology); - - updateUserServiceModel.Technologies.Add(updateTechnologyServiceModel); - } - //Clean the already replaced technologies - updateUserServiceModel.Technologies.RemoveWhere(x => x.Id == Guid.Empty); - - /* Friends */ - HashSet friends = new(); - int friendsCount = updateUserServiceModel.Friends.Count; - for (int i = 0; i < friendsCount; i++) - { - User friend = await this._userRepository.GetByUsernameAsync(updateUserServiceModel.Friends.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid friend's username!"); - - friends.Add(friend); - } - //Clean the already replaced technologies - updateUserServiceModel.Friends.RemoveWhere(x => x.Id == Guid.Empty); + updateUserServiceModel = await this.PopulateUpdateModelWithIds(updateUserServiceModel); User user = this._userMapper.Map(updateUserServiceModel); - user.Friends = friends; bool successful = await this._userRepository.EditAsync(updateUserServiceModel.Id, user); @@ -249,30 +197,49 @@ namespace DevHive.Services.Services private async Task ValidateUserCollections(UpdateUserServiceModel updateUserServiceModel) { + //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); + + if (isAdmin) + { + // Roles + foreach (var role in updateUserServiceModel.Roles) + { + Role returnedRole = await this._roleRepository.GetByNameAsync(role.Name) ?? + throw new ArgumentException($"Role {role.Name} does not exist!"); + } + } + //Preserve original user roles + else + { + HashSet roles = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id)).Roles; + + foreach (var role in roles) + { + Role returnedRole = await this._roleRepository.GetByNameAsync(role.Name) ?? + throw new ArgumentException($"Role {role.Name} does not exist!"); + } + } + // Friends foreach (var friend in updateUserServiceModel.Friends) { - User returnedFriend = await this._userRepository.GetByUsernameAsync(friend.Name); - - if (returnedFriend == null) - throw new ArgumentException($"User {friend.Name} does not exist!"); + User returnedFriend = await this._userRepository.GetByUsernameAsync(friend.UserName) ?? + throw new ArgumentException($"User {friend.UserName} does not exist!"); } // Languages foreach (var language in updateUserServiceModel.Languages) { - Language returnedLanguage = await this._languageRepository.GetByNameAsync(language.Name); - - if (returnedLanguage == null) + Language returnedLanguage = await this._languageRepository.GetByNameAsync(language.Name) ?? throw new ArgumentException($"Language {language.Name} does not exist!"); } // Technology foreach (var technology in updateUserServiceModel.Technologies) { - Technology returnedTechnology = await this._technologyRepository.GetByNameAsync(technology.Name); - - if (returnedTechnology == null) + Technology returnedTechnology = await this._technologyRepository.GetByNameAsync(technology.Name) ?? throw new ArgumentException($"Technology {technology.Name} does not exist!"); } } @@ -306,12 +273,13 @@ namespace DevHive.Services.Services } #endregion + #region Misc public async Task SuperSecretPromotionToAdmin(Guid userId) { User user = await this._userRepository.GetByIdAsync(userId) ?? throw new ArgumentException("User does not exist! Can't promote shit in this country..."); - if(!await this._roleRepository.DoesNameExist("Admin")) + if (!await this._roleRepository.DoesNameExist("Admin")) { Role adminRole = new() { @@ -329,5 +297,51 @@ namespace DevHive.Services.Services return admin.Id; } + + private async Task PopulateUpdateModelWithIds(UpdateUserServiceModel updateUserServiceModel) + { + /* Roles */ + int roleCount = updateUserServiceModel.Roles.Count; + for (int i = 0; i < roleCount; i++) + { + Role role = await this._roleRepository.GetByNameAsync(updateUserServiceModel.Roles.ElementAt(i).Name) ?? + throw new ArgumentException("Invalid role name!"); + + updateUserServiceModel.Roles.ElementAt(i).Id = role.Id; + } + + /* Languages */ + int langCount = updateUserServiceModel.Languages.Count; + for (int i = 0; i < langCount; i++) + { + Language language = await this._languageRepository.GetByNameAsync(updateUserServiceModel.Languages.ElementAt(i).Name) ?? + throw new ArgumentException("Invalid language name!"); + + updateUserServiceModel.Languages.ElementAt(i).Id = language.Id; + } + + /* Technologies */ + int techCount = updateUserServiceModel.Technologies.Count; + for (int i = 0; i < techCount; i++) + { + Technology technology = await this._technologyRepository.GetByNameAsync(updateUserServiceModel.Technologies.ElementAt(i).Name) ?? + throw new ArgumentException("Invalid technology name!"); + + updateUserServiceModel.Technologies.ElementAt(i).Id = technology.Id; + } + + /* Friends */ + int friendsCount = updateUserServiceModel.Friends.Count; + for (int i = 0; i < friendsCount; i++) + { + User friend = await this._userRepository.GetByUsernameAsync(updateUserServiceModel.Friends.ElementAt(i).UserName) ?? + throw new ArgumentException("Invalid friend's username!"); + + updateUserServiceModel.Friends.ElementAt(i).Id = friend.Id; + } + + return updateUserServiceModel; + } + #endregion } } diff --git a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs index 2f01f77..2ea2742 100644 --- a/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/RoleMappings.cs @@ -11,11 +11,11 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap() .ForMember(src => src.Id, dest => dest.Ignore()); - CreateMap(); + CreateMap(); CreateMap(); CreateMap(); - CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index e80a69a..1b26cc9 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -2,8 +2,6 @@ using AutoMapper; using DevHive.Services.Models.Identity.User; using DevHive.Web.Models.Identity.User; using DevHive.Common.Models.Identity; -using DevHive.Web.Models.Language; -using DevHive.Web.Models.Technology; namespace DevHive.Web.Configurations.Mapping { @@ -21,16 +19,12 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); //Update - CreateMap() - .ForMember(src => src.Id, dest => dest.Ignore()); - CreateMap() - .ForMember(src => src.Id, dest => dest.Ignore()); - CreateMap() - .ForMember(src => src.Id, dest => dest.Ignore()) - .ForMember(src => src.Name, dest => dest.MapFrom(p => p.UserName)); + CreateMap(); + CreateMap(); + CreateMap(); CreateMap(); - CreateMap(); + CreateMap(); } } } diff --git a/src/DevHive.Web/Controllers/RoleController.cs b/src/DevHive.Web/Controllers/RoleController.cs index d8bb60c..c68a32b 100644 --- a/src/DevHive.Web/Controllers/RoleController.cs +++ b/src/DevHive.Web/Controllers/RoleController.cs @@ -40,7 +40,7 @@ namespace DevHive.Web.Controllers [Authorize(Policy = "User")] public async Task GetById(Guid id) { - ReadRoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); + RoleServiceModel roleServiceModel = await this._roleService.GetRoleById(id); RoleWebModel roleWebModel = this._roleMapper.Map(roleServiceModel); return new OkObjectResult(roleWebModel); diff --git a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs index 254affc..3870481 100644 --- a/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs +++ b/src/DevHive.Web/Models/Identity/Role/UpdateRoleWebModel.cs @@ -4,10 +4,12 @@ using System.Diagnostics.CodeAnalysis; namespace DevHive.Web.Models.Identity.Role { - public class UpdateRoleWebModel : RoleWebModel + public class UpdateRoleWebModel { [NotNull] [Required] - public Guid Id { get; set; } + [MinLength(3)] + [MaxLength(50)] + public string Name { get; set; } } } diff --git a/src/DevHive.Web/Models/Identity/User/FriendWebModel.cs b/src/DevHive.Web/Models/Identity/User/FriendWebModel.cs deleted file mode 100644 index d59bff5..0000000 --- a/src/DevHive.Web/Models/Identity/User/FriendWebModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.Diagnostics.CodeAnalysis; -using DevHive.Web.Attributes; - -namespace DevHive.Web.Models.Identity.User -{ - public class FriendWebModel - { - [NotNull] - [Required] - [MinLength(3)] - [MaxLength(50)] - [OnlyAlphanumerics(ErrorMessage = "Username can only contain letters and digits!")] - public string UserName { get; set; } - } -} diff --git a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs index 30c66fb..62901f6 100644 --- a/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UpdateUserWebModel.cs @@ -17,7 +17,7 @@ namespace DevHive.Web.Models.Identity.User [NotNull] [Required] - public HashSet Friends { get; set; } + public HashSet Friends { get; set; } [NotNull] [Required] diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 5b80ba3..4097901 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 HashSet Friends { get; set; } = new HashSet(); + public HashSet Friends { get; set; } = new HashSet(); [NotNull] [Required] diff --git a/src/DevHive.Web/Models/Identity/User/UsernameWebModel.cs b/src/DevHive.Web/Models/Identity/User/UsernameWebModel.cs new file mode 100644 index 0000000..a20c1bf --- /dev/null +++ b/src/DevHive.Web/Models/Identity/User/UsernameWebModel.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; +using DevHive.Web.Attributes; + +namespace DevHive.Web.Models.Identity.User +{ + public class UsernameWebModel + { + [NotNull] + [Required] + [MinLength(3)] + [MaxLength(50)] + [OnlyAlphanumerics(ErrorMessage = "Username can only contain letters and digits!")] + public string UserName { get; set; } + } +} -- cgit v1.2.3 From 6f7c7adced972944f5648b3714baa053037a4160 Mon Sep 17 00:00:00 2001 From: transtrike Date: Mon, 1 Feb 2021 18:28:55 +0200 Subject: GetByUsername & GetById return post Ids; Read POst returns URLs --- src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs | 2 ++ src/DevHive.Data/Repositories/PostRepository.cs | 13 ++++++++++++- src/DevHive.Data/Repositories/UserRepository.cs | 2 ++ src/DevHive.Services/Configurations/Mapping/PostMappings.cs | 4 ++++ .../Models/Identity/User/UserServiceModel.cs | 3 +++ src/DevHive.Services/Services/PostService.cs | 4 +++- src/DevHive.Web/Models/Identity/User/UserWebModel.cs | 11 +++++++---- 7 files changed, 33 insertions(+), 6 deletions(-) (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs b/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs index 5022df5..9f7cf85 100644 --- a/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs +++ b/src/DevHive.Data/Interfaces/Repositories/IPostRepository.cs @@ -8,6 +8,8 @@ namespace DevHive.Data.Interfaces.Repositories { public interface IPostRepository : IRepository { + Task AddNewPostToCreator(Guid userId, Post post); + Task GetPostByCreatorAndTimeCreatedAsync(Guid issuerId, DateTime timeCreated); Task> GetFileUrls(Guid postId); diff --git a/src/DevHive.Data/Repositories/PostRepository.cs b/src/DevHive.Data/Repositories/PostRepository.cs index 31eb7d0..623a8f8 100644 --- a/src/DevHive.Data/Repositories/PostRepository.cs +++ b/src/DevHive.Data/Repositories/PostRepository.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using DevHive.Data.Interfaces.Models; using DevHive.Data.Interfaces.Repositories; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; @@ -11,11 +12,21 @@ namespace DevHive.Data.Repositories public class PostRepository : BaseRepository, IPostRepository { private readonly DevHiveContext _context; + private readonly IUserRepository _userRepository; - public PostRepository(DevHiveContext context) + public PostRepository(DevHiveContext context, IUserRepository userRepository) : base(context) { this._context = context; + this._userRepository = userRepository; + } + + public async Task AddNewPostToCreator(Guid userId, Post post) + { + User user = await this._userRepository.GetByIdAsync(userId); + user.Posts.Add(post); + + return await this.SaveChangesAsync(); } #region Read diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index 4bf919e..6f33570 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -38,6 +38,7 @@ namespace DevHive.Data.Repositories .Include(x => x.Roles) .Include(x => x.Languages) .Include(x => x.Technologies) + .Include(x => x.Posts) .FirstOrDefaultAsync(x => x.Id == id); } @@ -48,6 +49,7 @@ namespace DevHive.Data.Repositories .Include(x => x.Roles) .Include(x => x.Languages) .Include(x => x.Technologies) + .Include(x => x.Posts) .FirstOrDefaultAsync(x => x.UserName == username); } #endregion diff --git a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs index d36dbdd..13c9736 100644 --- a/src/DevHive.Services/Configurations/Mapping/PostMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/PostMappings.cs @@ -1,6 +1,7 @@ using DevHive.Data.Models; using AutoMapper; using DevHive.Services.Models.Post; +using DevHive.Common.Models.Misc; namespace DevHive.Services.Configurations.Mapping { @@ -20,6 +21,9 @@ namespace DevHive.Services.Configurations.Mapping .ForMember(dest => dest.CreatorFirstName, src => src.MapFrom(p => p.Creator.FirstName)) .ForMember(dest => dest.CreatorLastName, src => src.MapFrom(p => p.Creator.LastName)) .ForMember(dest => dest.CreatorUsername, src => src.MapFrom(p => p.Creator.UserName)); + + CreateMap() + .ForMember(dest => dest.Id, src => src.MapFrom(x => x.Id)); } } } diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 7da54b8..5bf58ec 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.Misc; using DevHive.Services.Models.Identity.Role; using DevHive.Services.Models.Language; using DevHive.Services.Models.Technology; @@ -14,5 +15,7 @@ namespace DevHive.Services.Models.Identity.User public HashSet Languages { get; set; } = new(); public HashSet Technologies { get; set; } = new(); + + public List Posts { get; set; } = new(); } } diff --git a/src/DevHive.Services/Services/PostService.cs b/src/DevHive.Services/Services/PostService.cs index 8a37acd..3206479 100644 --- a/src/DevHive.Services/Services/PostService.cs +++ b/src/DevHive.Services/Services/PostService.cs @@ -9,6 +9,7 @@ using System.Security.Claims; using DevHive.Services.Interfaces; using DevHive.Data.Interfaces.Repositories; using System.Linq; +using Microsoft.CodeAnalysis.CSharp; namespace DevHive.Services.Services { @@ -49,6 +50,8 @@ namespace DevHive.Services.Services Post newPost = await this._postRepository .GetPostByCreatorAndTimeCreatedAsync(post.Creator.Id, post.TimeCreated); + await this._postRepository.AddNewPostToCreator(createPostServiceModel.CreatorId, newPost); + return newPost.Id; } else @@ -69,7 +72,6 @@ namespace DevHive.Services.Services readPostServiceModel.CreatorFirstName = user.FirstName; readPostServiceModel.CreatorLastName = user.LastName; readPostServiceModel.CreatorUsername = user.UserName; - // readPostServiceModel.Files = await this._cloudService.GetFilesFromCloud(post.FileUrls); return readPostServiceModel; } diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 4097901..1a5484a 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; +using DevHive.Common.Models.Misc; using DevHive.Web.Models.Identity.Role; using DevHive.Web.Models.Language; using DevHive.Web.Models.Technology; @@ -11,18 +12,20 @@ namespace DevHive.Web.Models.Identity.User { [NotNull] [Required] - public HashSet Roles { get; set; } = new HashSet(); + public HashSet Roles { get; set; } = new(); [NotNull] [Required] - public HashSet Friends { get; set; } = new HashSet(); + public HashSet Friends { get; set; } = new(); [NotNull] [Required] - public HashSet Languages { get; set; } = new HashSet(); + public HashSet Languages { get; set; } = new(); [NotNull] [Required] - public HashSet Technologies { get; set; } = new HashSet(); + public HashSet Technologies { get; set; } = new(); + + public List Posts { get; set; } = new(); } } -- cgit v1.2.3 From 01ad75fa5a871a0c9f8cd0c5291312286ae4d52d Mon Sep 17 00:00:00 2001 From: Syndamia Date: Wed, 3 Feb 2021 10:22:37 +0200 Subject: Implemented profile picture table functionality; added models and interfaces for profile picture; added ability for user layers to update the profile picture; added migrations; updated mappings --- src/DevHive.Data/DevHiveContext.cs | 5 + .../Interfaces/Models/IProfilePicture.cs | 13 + src/DevHive.Data/Interfaces/Models/IUser.cs | 2 +- .../Interfaces/Repositories/IUserRepository.cs | 1 + .../20210203071720_ProfilePicture.Designer.cs | 633 +++++++++++++++++++++ .../Migrations/20210203071720_ProfilePicture.cs | 52 ++ .../Migrations/DevHiveContextModelSnapshot.cs | 36 +- src/DevHive.Data/Models/ProfilePicture.cs | 14 + src/DevHive.Data/Models/User.cs | 2 +- src/DevHive.Data/Repositories/UserRepository.cs | 10 + .../Configurations/Mapping/UserMappings.cs | 6 +- src/DevHive.Services/Interfaces/IUserService.cs | 1 + .../Identity/User/ProfilePictureServiceModel.cs | 7 + .../User/UpdateProfilePictureServiceModel.cs | 12 + .../Models/Identity/User/UpdateUserServiceModel.cs | 2 + .../Models/Identity/User/UserServiceModel.cs | 2 + src/DevHive.Services/Services/UserService.cs | 29 +- .../Configurations/Mapping/UserMappings.cs | 3 + src/DevHive.Web/Controllers/UserController.cs | 17 + .../Models/Identity/User/ProfilePictureWebModel.cs | 7 + .../Identity/User/UpdateProfilePictureWebModel.cs | 9 + .../Models/Identity/User/UserWebModel.cs | 2 + 22 files changed, 857 insertions(+), 8 deletions(-) create mode 100644 src/DevHive.Data/Interfaces/Models/IProfilePicture.cs create mode 100644 src/DevHive.Data/Migrations/20210203071720_ProfilePicture.Designer.cs create mode 100644 src/DevHive.Data/Migrations/20210203071720_ProfilePicture.cs create mode 100644 src/DevHive.Data/Models/ProfilePicture.cs create mode 100644 src/DevHive.Services/Models/Identity/User/ProfilePictureServiceModel.cs create mode 100644 src/DevHive.Services/Models/Identity/User/UpdateProfilePictureServiceModel.cs create mode 100644 src/DevHive.Web/Models/Identity/User/ProfilePictureWebModel.cs create mode 100644 src/DevHive.Web/Models/Identity/User/UpdateProfilePictureWebModel.cs (limited to 'src/DevHive.Services/Models/Identity') diff --git a/src/DevHive.Data/DevHiveContext.cs b/src/DevHive.Data/DevHiveContext.cs index 417de7f..b3ebd73 100644 --- a/src/DevHive.Data/DevHiveContext.cs +++ b/src/DevHive.Data/DevHiveContext.cs @@ -27,6 +27,11 @@ namespace DevHive.Data .HasIndex(x => x.UserName) .IsUnique(); + builder.Entity() + .HasOne(x => x.ProfilePicture) + .WithOne(x => x.User) + .HasForeignKey(x => x.UserId); + /* Roles */ builder.Entity() .HasMany(x => x.Roles) diff --git a/src/DevHive.Data/Interfaces/Models/IProfilePicture.cs b/src/DevHive.Data/Interfaces/Models/IProfilePicture.cs new file mode 100644 index 0000000..c3fcbea --- /dev/null +++ b/src/DevHive.Data/Interfaces/Models/IProfilePicture.cs @@ -0,0 +1,13 @@ +using System; +using DevHive.Data.Models; + +namespace DevHive.Data.Interfaces.Models +{ + public interface IProfilePicture : IModel + { + Guid UserId { get; set; } + User User { get; set; } + + string PictureURL { get; set; } + } +} diff --git a/src/DevHive.Data/Interfaces/Models/IUser.cs b/src/DevHive.Data/Interfaces/Models/IUser.cs index eb262fd..fcd741c 100644 --- a/src/DevHive.Data/Interfaces/Models/IUser.cs +++ b/src/DevHive.Data/Interfaces/Models/IUser.cs @@ -10,7 +10,7 @@ namespace DevHive.Data.Interfaces.Models string LastName { get; set; } - string ProfilePictureUrl { get; set; } + ProfilePicture ProfilePicture { get; set; } HashSet Languages { get; set; } diff --git a/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs b/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs index 4346e9c..5b6ab9e 100644 --- a/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs +++ b/src/DevHive.Data/Interfaces/Repositories/IUserRepository.cs @@ -11,6 +11,7 @@ namespace DevHive.Data.Interfaces.Repositories //Read Task GetByUsernameAsync(string username); IEnumerable QueryAll(); + Task UpdateProfilePicture(Guid userId, string pictureUrl); //Validations Task DoesEmailExistAsync(string email); diff --git a/src/DevHive.Data/Migrations/20210203071720_ProfilePicture.Designer.cs b/src/DevHive.Data/Migrations/20210203071720_ProfilePicture.Designer.cs new file mode 100644 index 0000000..b8dbd8e --- /dev/null +++ b/src/DevHive.Data/Migrations/20210203071720_ProfilePicture.Designer.cs @@ -0,0 +1,633 @@ +// +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("20210203071720_ProfilePicture")] + partial class ProfilePicture + { + 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("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + 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.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("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.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("FriendsOf"); + + b.Navigation("MyFriends"); + + b.Navigation("Posts"); + + b.Navigation("ProfilePicture"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/DevHive.Data/Migrations/20210203071720_ProfilePicture.cs b/src/DevHive.Data/Migrations/20210203071720_ProfilePicture.cs new file mode 100644 index 0000000..1b0c2c6 --- /dev/null +++ b/src/DevHive.Data/Migrations/20210203071720_ProfilePicture.cs @@ -0,0 +1,52 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DevHive.Data.Migrations +{ + public partial class ProfilePicture : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ProfilePictureUrl", + table: "AspNetUsers"); + + migrationBuilder.CreateTable( + name: "ProfilePicture", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + PictureURL = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ProfilePicture", x => x.Id); + table.ForeignKey( + name: "FK_ProfilePicture_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ProfilePicture_UserId", + table: "ProfilePicture", + column: "UserId", + unique: true); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ProfilePicture"); + + migrationBuilder.AddColumn( + name: "ProfilePictureUrl", + table: "AspNetUsers", + type: "text", + nullable: true); + } + } +} diff --git a/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs index 96cabad..0450670 100644 --- a/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs +++ b/src/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs @@ -86,6 +86,26 @@ namespace DevHive.Data.Migrations 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") @@ -190,9 +210,6 @@ namespace DevHive.Data.Migrations b.Property("PhoneNumberConfirmed") .HasColumnType("boolean"); - b.Property("ProfilePictureUrl") - .HasColumnType("text"); - b.Property("SecurityStamp") .HasColumnType("text"); @@ -437,6 +454,17 @@ namespace DevHive.Data.Migrations 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.RelationModels.RatedPost", b => { b.HasOne("DevHive.Data.Models.Post", "Post") @@ -594,6 +622,8 @@ namespace DevHive.Data.Migrations b.Navigation("MyFriends"); b.Navigation("Posts"); + + b.Navigation("ProfilePicture"); }); #pragma warning restore 612, 618 } diff --git a/src/DevHive.Data/Models/ProfilePicture.cs b/src/DevHive.Data/Models/ProfilePicture.cs new file mode 100644 index 0000000..e2ef04b --- /dev/null +++ b/src/DevHive.Data/Models/ProfilePicture.cs @@ -0,0 +1,14 @@ +using System; + +namespace DevHive.Data.Models +{ + public class ProfilePicture + { + public Guid Id { get; set; } + + public Guid UserId { get; set; } + public User User { get; set; } + + public string PictureURL { get; set; } + } +} diff --git a/src/DevHive.Data/Models/User.cs b/src/DevHive.Data/Models/User.cs index 1c365e4..d73f989 100644 --- a/src/DevHive.Data/Models/User.cs +++ b/src/DevHive.Data/Models/User.cs @@ -14,7 +14,7 @@ namespace DevHive.Data.Models public string LastName { get; set; } - public string ProfilePictureUrl { get; set; } + public ProfilePicture ProfilePicture { get; set; } public HashSet Languages { get; set; } = new(); diff --git a/src/DevHive.Data/Repositories/UserRepository.cs b/src/DevHive.Data/Repositories/UserRepository.cs index b46198c..466b123 100644 --- a/src/DevHive.Data/Repositories/UserRepository.cs +++ b/src/DevHive.Data/Repositories/UserRepository.cs @@ -38,6 +38,7 @@ namespace DevHive.Data.Repositories .Include(x => x.Languages) .Include(x => x.Technologies) .Include(x => x.Posts) + .Include(x => x.ProfilePicture) .FirstOrDefaultAsync(x => x.Id == id); } @@ -48,6 +49,7 @@ namespace DevHive.Data.Repositories .Include(x => x.Languages) .Include(x => x.Technologies) .Include(x => x.Posts) + .Include(x => x.ProfilePicture) .FirstOrDefaultAsync(x => x.UserName == username); } #endregion @@ -93,6 +95,14 @@ namespace DevHive.Data.Repositories return await this.SaveChangesAsync(); } + + public async Task UpdateProfilePicture(Guid userId, string pictureUrl) { + User user = await this.GetByIdAsync(userId); + + user.ProfilePicture.PictureURL = pictureUrl; + + return await this.SaveChangesAsync(); + } #endregion #region Validations diff --git a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs index 5223d84..6922cd7 100644 --- a/src/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -22,10 +22,12 @@ namespace DevHive.Services.Configurations.Mapping CreateMap(); CreateMap() - .ForMember(dest => dest.Friends, src => src.MapFrom(p => p.MyFriends)); + .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)); CreateMap() - .ForMember(x => x.Password, opt => opt.Ignore()); + .ForMember(x => x.Password, opt => opt.Ignore()) + .ForMember(dest => dest.ProfilePictureURL, src => src.MapFrom(p => p.ProfilePicture.PictureURL)); CreateMap(); CreateMap() diff --git a/src/DevHive.Services/Interfaces/IUserService.cs b/src/DevHive.Services/Interfaces/IUserService.cs index b701e4a..9e2b4e3 100644 --- a/src/DevHive.Services/Interfaces/IUserService.cs +++ b/src/DevHive.Services/Interfaces/IUserService.cs @@ -14,6 +14,7 @@ namespace DevHive.Services.Interfaces Task GetUserById(Guid id); Task UpdateUser(UpdateUserServiceModel updateModel); + Task UpdateProfilePicture(UpdateProfilePictureServiceModel updateProfilePictureServiceModel); Task DeleteUser(Guid id); diff --git a/src/DevHive.Services/Models/Identity/User/ProfilePictureServiceModel.cs b/src/DevHive.Services/Models/Identity/User/ProfilePictureServiceModel.cs new file mode 100644 index 0000000..ad81057 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/ProfilePictureServiceModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Services.Models.Identity.User +{ + public class ProfilePictureServiceModel + { + public string ProfilePictureURL { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UpdateProfilePictureServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateProfilePictureServiceModel.cs new file mode 100644 index 0000000..8563953 --- /dev/null +++ b/src/DevHive.Services/Models/Identity/User/UpdateProfilePictureServiceModel.cs @@ -0,0 +1,12 @@ +using System; +using Microsoft.AspNetCore.Http; + +namespace DevHive.Services.Models.Identity.User +{ + public class UpdateProfilePictureServiceModel + { + public Guid UserId { get; set; } + + public IFormFile Picture { get; set; } + } +} diff --git a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs index 5b197e4..b4e4400 100644 --- a/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UpdateUserServiceModel.cs @@ -12,6 +12,8 @@ namespace DevHive.Services.Models.Identity.User public string Password { get; set; } + public string ProfilePictureURL { get; set; } + public HashSet Roles { get; set; } = new HashSet(); public HashSet Friends { get; set; } = new HashSet(); diff --git a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs index 5bf58ec..ac7bba2 100644 --- a/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs +++ b/src/DevHive.Services/Models/Identity/User/UserServiceModel.cs @@ -8,6 +8,8 @@ namespace DevHive.Services.Models.Identity.User { public class UserServiceModel : BaseUserServiceModel { + public string ProfilePictureURL { get; set; } + public HashSet Roles { get; set; } = new(); public HashSet Friends { get; set; } = new(); diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index 09b56c1..d8c4ee5 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -15,6 +15,7 @@ using DevHive.Data.Interfaces.Repositories; using System.Linq; using DevHive.Common.Models.Misc; using DevHive.Data.RelationModels; +using Microsoft.AspNetCore.Http; namespace DevHive.Services.Services { @@ -26,13 +27,15 @@ namespace DevHive.Services.Services private readonly ITechnologyRepository _technologyRepository; private readonly IMapper _userMapper; private readonly JWTOptions _jwtOptions; + private readonly ICloudService _cloudService; public UserService(IUserRepository userRepository, ILanguageRepository languageRepository, IRoleRepository roleRepository, ITechnologyRepository technologyRepository, IMapper mapper, - JWTOptions jwtOptions) + JWTOptions jwtOptions, + ICloudService cloudService) { this._userRepository = userRepository; this._roleRepository = roleRepository; @@ -40,6 +43,7 @@ namespace DevHive.Services.Services this._jwtOptions = jwtOptions; this._languageRepository = languageRepository; this._technologyRepository = technologyRepository; + this._cloudService = cloudService; } #region Authentication @@ -66,6 +70,7 @@ namespace DevHive.Services.Services User user = this._userMapper.Map(registerModel); user.PasswordHash = PasswordModifications.GeneratePasswordHash(registerModel.Password); + user.ProfilePicture = new ProfilePicture() { PictureURL = String.Empty }; // Make sure the default role exists //TODO: Move when project starts @@ -119,6 +124,28 @@ namespace DevHive.Services.Services return this._userMapper.Map( await this._userRepository.GetByIdAsync(user.Id)); } + + public async Task UpdateProfilePicture(UpdateProfilePictureServiceModel updateProfilePictureServiceModel) + { + User user = await this._userRepository.GetByIdAsync(updateProfilePictureServiceModel.UserId); + + if (!String.IsNullOrEmpty(user.ProfilePicture.PictureURL)) + { + bool success = await _cloudService.RemoveFilesFromCloud(new List { user.ProfilePicture.PictureURL }); + if (!success) + throw new InvalidCastException("Could not delete old profile picture!"); + } + + string fileUrl = (await this._cloudService.UploadFilesToCloud(new List { updateProfilePictureServiceModel.Picture }))[0] ?? + throw new ArgumentNullException("Unable to upload profile picture to cloud"); + + bool successful = await this._userRepository.UpdateProfilePicture(updateProfilePictureServiceModel.UserId, fileUrl); + + if (!successful) + throw new InvalidOperationException("Unable to change profile picture!"); + + return new ProfilePictureServiceModel() { ProfilePictureURL = fileUrl }; + } #endregion #region Delete diff --git a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs index 1b26cc9..f58e7ca 100644 --- a/src/DevHive.Web/Configurations/Mapping/UserMappings.cs +++ b/src/DevHive.Web/Configurations/Mapping/UserMappings.cs @@ -23,6 +23,9 @@ namespace DevHive.Web.Configurations.Mapping CreateMap(); CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); CreateMap(); } diff --git a/src/DevHive.Web/Controllers/UserController.cs b/src/DevHive.Web/Controllers/UserController.cs index fdf317c..109bbaa 100644 --- a/src/DevHive.Web/Controllers/UserController.cs +++ b/src/DevHive.Web/Controllers/UserController.cs @@ -94,6 +94,23 @@ namespace DevHive.Web.Controllers return new AcceptedResult("UpdateUser", userWebModel); } + + [HttpPut] + [Route("ProfilePicture")] + [Authorize(Roles = "User,Admin")] + public async Task UpdateProfilePicture(Guid userId, [FromForm] UpdateProfilePictureWebModel updateProfilePictureWebModel, [FromHeader] string authorization) + { + if (!await this._userService.ValidJWT(userId, authorization)) + return new UnauthorizedResult(); + + UpdateProfilePictureServiceModel updateProfilePictureServiceModel = this._userMapper.Map(updateProfilePictureWebModel); + updateProfilePictureServiceModel.UserId = userId; + + ProfilePictureServiceModel profilePictureServiceModel = await this._userService.UpdateProfilePicture(updateProfilePictureServiceModel); + ProfilePictureWebModel profilePictureWebModel = this._userMapper.Map(profilePictureServiceModel); + + return new AcceptedResult("UpdateProfilePicture", profilePictureWebModel); + } #endregion #region Delete diff --git a/src/DevHive.Web/Models/Identity/User/ProfilePictureWebModel.cs b/src/DevHive.Web/Models/Identity/User/ProfilePictureWebModel.cs new file mode 100644 index 0000000..9fb1516 --- /dev/null +++ b/src/DevHive.Web/Models/Identity/User/ProfilePictureWebModel.cs @@ -0,0 +1,7 @@ +namespace DevHive.Web.Models.Identity.User +{ + public class ProfilePictureWebModel + { + public string ProfilePictureURL { get; set; } + } +} diff --git a/src/DevHive.Web/Models/Identity/User/UpdateProfilePictureWebModel.cs b/src/DevHive.Web/Models/Identity/User/UpdateProfilePictureWebModel.cs new file mode 100644 index 0000000..6efe968 --- /dev/null +++ b/src/DevHive.Web/Models/Identity/User/UpdateProfilePictureWebModel.cs @@ -0,0 +1,9 @@ +using Microsoft.AspNetCore.Http; + +namespace DevHive.Web.Models.Identity.User +{ + public class UpdateProfilePictureWebModel + { + public IFormFile Picture { get; set; } + } +} diff --git a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs index 1a5484a..7ab8cca 100644 --- a/src/DevHive.Web/Models/Identity/User/UserWebModel.cs +++ b/src/DevHive.Web/Models/Identity/User/UserWebModel.cs @@ -10,6 +10,8 @@ namespace DevHive.Web.Models.Identity.User { public class UserWebModel : BaseUserWebModel { + public string ProfilePictureURL { get; set; } + [NotNull] [Required] public HashSet Roles { get; set; } = new(); -- cgit v1.2.3