From 98e17766b203734a1817eed94338e2d25f4395f7 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 13 Feb 2021 16:20:18 +0200 Subject: Project Restructure P.1 --- src/Common/DevHive.Common.Models/DevHive.Common.csproj | 15 +++++++++++++++ src/Common/DevHive.Common.Models/Identity/TokenModel.cs | 12 ++++++++++++ src/Common/DevHive.Common.Models/Misc/IdModel.cs | 9 +++++++++ .../DevHive.Common.Models/Misc/PasswordModifications.cs | 13 +++++++++++++ src/Common/DevHive.Common.Models/Misc/Patch.cs | 9 +++++++++ 5 files changed, 58 insertions(+) create mode 100644 src/Common/DevHive.Common.Models/DevHive.Common.csproj create mode 100644 src/Common/DevHive.Common.Models/Identity/TokenModel.cs create mode 100644 src/Common/DevHive.Common.Models/Misc/IdModel.cs create mode 100644 src/Common/DevHive.Common.Models/Misc/PasswordModifications.cs create mode 100644 src/Common/DevHive.Common.Models/Misc/Patch.cs (limited to 'src/Common') diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.csproj new file mode 100644 index 0000000..ace4997 --- /dev/null +++ b/src/Common/DevHive.Common.Models/DevHive.Common.csproj @@ -0,0 +1,15 @@ + + + + net5.0 + + + + + + + + true + latest + + diff --git a/src/Common/DevHive.Common.Models/Identity/TokenModel.cs b/src/Common/DevHive.Common.Models/Identity/TokenModel.cs new file mode 100644 index 0000000..0fb6c82 --- /dev/null +++ b/src/Common/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/Common/DevHive.Common.Models/Misc/IdModel.cs b/src/Common/DevHive.Common.Models/Misc/IdModel.cs new file mode 100644 index 0000000..a5c7b65 --- /dev/null +++ b/src/Common/DevHive.Common.Models/Misc/IdModel.cs @@ -0,0 +1,9 @@ +using System; + +namespace DevHive.Common.Models.Misc +{ + public class IdModel + { + public Guid Id { get; set; } + } +} \ No newline at end of file diff --git a/src/Common/DevHive.Common.Models/Misc/PasswordModifications.cs b/src/Common/DevHive.Common.Models/Misc/PasswordModifications.cs new file mode 100644 index 0000000..f10a334 --- /dev/null +++ b/src/Common/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/Common/DevHive.Common.Models/Misc/Patch.cs b/src/Common/DevHive.Common.Models/Misc/Patch.cs new file mode 100644 index 0000000..ea5a4f1 --- /dev/null +++ b/src/Common/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; } + } +} -- cgit v1.2.3 From ad3b8e0070c0abdf0b87bd50428e509e1bff2d8e Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 13 Feb 2021 18:16:37 +0200 Subject: Restructure Successful --- .../DevHive.Common.Models/DevHive.Common.csproj | 27 +- .../DevHive.Data.Models/DevHive.Data.Models.csproj | 6 +- src/Data/DevHive.Data.Models/Interfaces/IPost.cs | 2 +- src/Data/DevHive.Data.Models/Interfaces/IUser.cs | 2 +- src/Data/DevHive.Data.Models/Post.cs | 2 +- .../RelationalModels/PostAttachments.cs | 16 + .../RelationalModels/RatedPost.cs | 18 + .../RelationalModels/UserRate.cs | 18 + src/Data/DevHive.Data.Models/User.cs | 2 +- .../DevHive.Data.Tests/DevHive.Data.Tests.csproj | 13 +- .../DevHive.Data.Tests/PostRepository.Tests.cs | 4 +- src/Data/DevHive.Data/DevHive.Data.csproj | 25 +- src/Data/DevHive.Data/DevHiveContext.cs | 2 +- .../Migrations/20210205140955_rating.Designer.cs | 665 -------------------- .../Migrations/20210205140955_rating.cs | 581 ----------------- .../20210205150447_Friends_Init_Config.Designer.cs | 643 ------------------- .../20210205150447_Friends_Init_Config.cs | 45 -- .../20210205154810_PostFileAttachments.Designer.cs | 691 --------------------- .../20210205154810_PostFileAttachments.cs | 51 -- .../20210205160520_Friends_First_Tweek.Designer.cs | 609 ------------------ .../20210205160520_Friends_First_Tweek.cs | 46 -- .../Migrations/DevHiveContextModelSnapshot.cs | 658 -------------------- .../DevHive.Data/RelationModels/PostAttachments.cs | 16 - src/Data/DevHive.Data/RelationModels/RatedPost.cs | 18 - src/Data/DevHive.Data/RelationModels/UserRate.cs | 18 - .../DevHive.Data/Repositories/CommentRepository.cs | 2 +- .../DevHive.Data/Repositories/FeedRepository.cs | 2 +- .../Repositories/LanguageRepository.cs | 2 +- .../DevHive.Data/Repositories/PostRepository.cs | 4 +- .../DevHive.Data/Repositories/RatingRepository.cs | 2 +- .../DevHive.Data/Repositories/RoleRepository.cs | 2 +- .../Repositories/TechnologyRepository.cs | 2 +- .../DevHive.Data/Repositories/UserRepository.cs | 4 +- .../DevHive.Services.Models.csproj | 6 +- .../DevHive.Services.Tests/CommentService.Tests.cs | 2 +- .../DevHive.Services.Tests.csproj | 13 +- .../DevHive.Services.Tests/FeedService.Tests.cs | 2 +- .../LanguageService.Tests.cs | 2 +- .../DevHive.Services.Tests/PostService.Tests.cs | 2 +- .../DevHive.Services.Tests/RoleService.Tests.cs | 2 +- .../TechnologyServices.Tests.cs | 2 +- .../DevHive.Services.Tests/UserService.Tests.cs | 2 +- .../Configurations/Mapping/UserMappings.cs | 2 +- .../DevHive.Services/DevHive.Services.csproj | 13 +- .../DevHive.Services/Services/CommentService.cs | 2 +- .../DevHive.Services/Services/FeedService.cs | 2 +- .../DevHive.Services/Services/LanguageService.cs | 2 +- .../DevHive.Services/Services/PostService.cs | 4 +- .../DevHive.Services/Services/RateService.cs | 2 +- .../DevHive.Services/Services/RoleService.cs | 2 +- .../DevHive.Services/Services/TechnologyService.cs | 2 +- .../DevHive.Services/Services/UserService.cs | 2 +- .../Attributes/GoodPasswordModelValidation.cs | 24 + .../Attributes/OnlyLettersModelValidation.cs | 20 + .../DevHive.Web.Models/DevHive.Web.Models.csproj | 6 +- .../DevHive.Web.Models/User/BaseUserWebModel.cs | 2 +- src/Web/DevHive.Web.Models/User/LoginWebModel.cs | 2 +- .../DevHive.Web.Models/User/RegisterWebModel.cs | 2 +- .../DevHive.Web.Models/User/UpdateUserWebModel.cs | 2 +- .../DevHive.Web.Models/User/UsernameWebModel.cs | 2 +- src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj | 11 +- src/Web/DevHive.Web.Tests/RoleController.Tests.cs | 2 +- src/Web/DevHive.Web.Tests/UserController.Tests.cs | 6 +- .../Attributes/GoodPasswordModelValidation.cs | 24 - .../Attributes/OnlyLettersModelValidation.cs | 20 - .../Extensions/ConfigureDependencyInjection.cs | 2 +- .../Configurations/Mapping/RatingMappings.cs | 2 +- src/Web/DevHive.Web/Controllers/RateController.cs | 2 +- src/Web/DevHive.Web/DevHive.Web.csproj | 20 +- 69 files changed, 214 insertions(+), 4199 deletions(-) create mode 100644 src/Data/DevHive.Data.Models/RelationalModels/PostAttachments.cs create mode 100644 src/Data/DevHive.Data.Models/RelationalModels/RatedPost.cs create mode 100644 src/Data/DevHive.Data.Models/RelationalModels/UserRate.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205140955_rating.Designer.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205140955_rating.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.Designer.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs delete mode 100644 src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs delete mode 100644 src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs delete mode 100644 src/Data/DevHive.Data/RelationModels/PostAttachments.cs delete mode 100644 src/Data/DevHive.Data/RelationModels/RatedPost.cs delete mode 100644 src/Data/DevHive.Data/RelationModels/UserRate.cs create mode 100644 src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs create mode 100644 src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs delete mode 100644 src/Web/DevHive.Web/Attributes/GoodPasswordModelValidation.cs delete mode 100644 src/Web/DevHive.Web/Attributes/OnlyLettersModelValidation.cs (limited to 'src/Common') diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.csproj index ace4997..4829c80 100644 --- a/src/Common/DevHive.Common.Models/DevHive.Common.csproj +++ b/src/Common/DevHive.Common.Models/DevHive.Common.csproj @@ -1,15 +1,12 @@ - - - - net5.0 - - - - - - - - true - latest - - + + + net5.0 + + + + + + true + latest + + \ No newline at end of file diff --git a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj index 628e361..e58a6d8 100644 --- a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj +++ b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj @@ -2,4 +2,8 @@ net5.0 - + + + + + \ No newline at end of file diff --git a/src/Data/DevHive.Data.Models/Interfaces/IPost.cs b/src/Data/DevHive.Data.Models/Interfaces/IPost.cs index b1f0cb7..43b8290 100644 --- a/src/Data/DevHive.Data.Models/Interfaces/IPost.cs +++ b/src/Data/DevHive.Data.Models/Interfaces/IPost.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using DevHive.Data.Models; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; namespace DevHive.Data.Models.Interfaces { diff --git a/src/Data/DevHive.Data.Models/Interfaces/IUser.cs b/src/Data/DevHive.Data.Models/Interfaces/IUser.cs index 7606ba2..185dfa2 100644 --- a/src/Data/DevHive.Data.Models/Interfaces/IUser.cs +++ b/src/Data/DevHive.Data.Models/Interfaces/IUser.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using DevHive.Data.Models; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; namespace DevHive.Data.Models.Interfaces { diff --git a/src/Data/DevHive.Data.Models/Post.cs b/src/Data/DevHive.Data.Models/Post.cs index 5138d19..15b6b77 100644 --- a/src/Data/DevHive.Data.Models/Post.cs +++ b/src/Data/DevHive.Data.Models/Post.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using DevHive.Data.Models.Interfaces; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; namespace DevHive.Data.Models { diff --git a/src/Data/DevHive.Data.Models/RelationalModels/PostAttachments.cs b/src/Data/DevHive.Data.Models/RelationalModels/PostAttachments.cs new file mode 100644 index 0000000..8c814fc --- /dev/null +++ b/src/Data/DevHive.Data.Models/RelationalModels/PostAttachments.cs @@ -0,0 +1,16 @@ +using System; +using System.ComponentModel.DataAnnotations.Schema; +using DevHive.Data.Models; + +namespace DevHive.Data.Models.Relational +{ + [Table("PostAttachments")] + public class PostAttachments + { + public Guid Id { get; set; } + + public Post Post { get; set; } + + public string FileUrl { get; set; } + } +} diff --git a/src/Data/DevHive.Data.Models/RelationalModels/RatedPost.cs b/src/Data/DevHive.Data.Models/RelationalModels/RatedPost.cs new file mode 100644 index 0000000..fb63848 --- /dev/null +++ b/src/Data/DevHive.Data.Models/RelationalModels/RatedPost.cs @@ -0,0 +1,18 @@ +using System; +using System.ComponentModel.DataAnnotations.Schema; +using System.Reflection.Metadata.Ecma335; +using DevHive.Data.Models; +using Microsoft.EntityFrameworkCore; + +namespace DevHive.Data.Models.Relational +{ + [Table("RatedPosts")] + public class RatedPost + { + public Guid UserId { get; set; } + public User User { get; set; } + + public Guid PostId { get; set; } + public Post Post { get; set; } + } +} diff --git a/src/Data/DevHive.Data.Models/RelationalModels/UserRate.cs b/src/Data/DevHive.Data.Models/RelationalModels/UserRate.cs new file mode 100644 index 0000000..46bd605 --- /dev/null +++ b/src/Data/DevHive.Data.Models/RelationalModels/UserRate.cs @@ -0,0 +1,18 @@ +using System; +using System.ComponentModel.DataAnnotations.Schema; +using DevHive.Data.Models; + +namespace DevHive.Data.Models.Relational +{ + [Table("UserRates")] + public class UserRate + { + public Guid Id { get; set; } + + public User User { get; set; } + + public bool Liked { get; set; } + + public Post Post { get; set; } + } +} diff --git a/src/Data/DevHive.Data.Models/User.cs b/src/Data/DevHive.Data.Models/User.cs index 806397a..bf4ea50 100644 --- a/src/Data/DevHive.Data.Models/User.cs +++ b/src/Data/DevHive.Data.Models/User.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using DevHive.Data.Models.Interfaces; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; using Microsoft.AspNetCore.Identity; namespace DevHive.Data.Models diff --git a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj index d6d0876..568edda 100644 --- a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj +++ b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj @@ -1,21 +1,20 @@ - net5.0 - false - - + - + - + + + true latest - + \ No newline at end of file diff --git a/src/Data/DevHive.Data.Tests/PostRepository.Tests.cs b/src/Data/DevHive.Data.Tests/PostRepository.Tests.cs index 6dacf0b..6a0cccd 100644 --- a/src/Data/DevHive.Data.Tests/PostRepository.Tests.cs +++ b/src/Data/DevHive.Data.Tests/PostRepository.Tests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; using DevHive.Data.Repositories; using Microsoft.EntityFrameworkCore; using Moq; diff --git a/src/Data/DevHive.Data/DevHive.Data.csproj b/src/Data/DevHive.Data/DevHive.Data.csproj index e8f38ee..fac1581 100644 --- a/src/Data/DevHive.Data/DevHive.Data.csproj +++ b/src/Data/DevHive.Data/DevHive.Data.csproj @@ -1,26 +1,23 @@ - net5.0 - - - - - - - - + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - + + + + + - true latest - - + \ No newline at end of file diff --git a/src/Data/DevHive.Data/DevHiveContext.cs b/src/Data/DevHive.Data/DevHiveContext.cs index 9de33c3..ece3439 100644 --- a/src/Data/DevHive.Data/DevHiveContext.cs +++ b/src/Data/DevHive.Data/DevHiveContext.cs @@ -1,6 +1,6 @@ using System; using DevHive.Data.Models; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; diff --git a/src/Data/DevHive.Data/Migrations/20210205140955_rating.Designer.cs b/src/Data/DevHive.Data/Migrations/20210205140955_rating.Designer.cs deleted file mode 100644 index 8d2adc4..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205140955_rating.Designer.cs +++ /dev/null @@ -1,665 +0,0 @@ -// -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("20210205140955_rating")] - partial class rating - { - 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("PostId") - .HasColumnType("uuid"); - - b.Property("Rate") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("PostId") - .IsUnique(); - - 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("Liked") - .HasColumnType("boolean"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("PostId"); - - b.HasIndex("UserId"); - - b.ToTable("UserRates"); - }); - - modelBuilder.Entity("LanguageUser", b => - { - b.Property("LanguagesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("LanguagesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("LanguageUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("ProviderKey") - .HasColumnType("text"); - - b.Property("ProviderDisplayName") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("Name") - .HasColumnType("text"); - - b.Property("Value") - .HasColumnType("text"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens"); - }); - - modelBuilder.Entity("RoleUser", b => - { - b.Property("RolesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("RolesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("RoleUser"); - }); - - modelBuilder.Entity("TechnologyUser", b => - { - b.Property("TechnologiesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("TechnologiesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("TechnologyUser"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Comment", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Comments") - .HasForeignKey("CreatorId"); - - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany("Comments") - .HasForeignKey("PostId"); - - b.Navigation("Creator"); - - b.Navigation("Post"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Posts") - .HasForeignKey("CreatorId"); - - b.Navigation("Creator"); - }); - - modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => - { - b.HasOne("DevHive.Data.Models.User", "User") - .WithOne("ProfilePicture") - .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Rating", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithOne("Rating") - .HasForeignKey("DevHive.Data.Models.Rating", "PostId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Post"); - }); - - 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("RatedPosts") - .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.Post", "Post") - .WithMany() - .HasForeignKey("PostId"); - - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId"); - - b.Navigation("Post"); - - 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"); - - b.Navigation("Rating"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Navigation("Comments"); - - b.Navigation("FriendsOf"); - - b.Navigation("MyFriends"); - - b.Navigation("Posts"); - - b.Navigation("ProfilePicture"); - - b.Navigation("RatedPosts"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/20210205140955_rating.cs b/src/Data/DevHive.Data/Migrations/20210205140955_rating.cs deleted file mode 100644 index d507dae..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205140955_rating.cs +++ /dev/null @@ -1,581 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -namespace DevHive.Data.Migrations -{ - public partial class rating : 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), - 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); - }); - - migrationBuilder.CreateTable( - name: "Languages", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - Name = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Languages", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Technologies", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - Name = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Technologies", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AspNetRoleClaims", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - RoleId = table.Column(type: "uuid", nullable: false), - ClaimType = table.Column(type: "text", nullable: true), - ClaimValue = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); - table.ForeignKey( - name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", - column: x => x.RoleId, - principalTable: "AspNetRoles", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserClaims", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - UserId = table.Column(type: "uuid", nullable: false), - ClaimType = table.Column(type: "text", nullable: true), - ClaimValue = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); - table.ForeignKey( - name: "FK_AspNetUserClaims_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserLogins", - columns: table => new - { - LoginProvider = table.Column(type: "text", nullable: false), - ProviderKey = table.Column(type: "text", nullable: false), - ProviderDisplayName = table.Column(type: "text", nullable: true), - UserId = table.Column(type: "uuid", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); - table.ForeignKey( - name: "FK_AspNetUserLogins_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserRoles", - columns: table => new - { - UserId = table.Column(type: "uuid", nullable: false), - RoleId = table.Column(type: "uuid", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); - table.ForeignKey( - name: "FK_AspNetUserRoles_AspNetRoles_RoleId", - column: x => x.RoleId, - principalTable: "AspNetRoles", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_AspNetUserRoles_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserTokens", - columns: table => new - { - UserId = table.Column(type: "uuid", nullable: false), - LoginProvider = table.Column(type: "text", nullable: false), - Name = table.Column(type: "text", nullable: false), - Value = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); - table.ForeignKey( - name: "FK_AspNetUserTokens_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Posts", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - CreatorId = table.Column(type: "uuid", nullable: true), - Message = table.Column(type: "text", nullable: true), - TimeCreated = table.Column(type: "timestamp without time zone", nullable: false), - FileUrls = table.Column>(type: "text[]", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Posts", x => x.Id); - table.ForeignKey( - name: "FK_Posts_AspNetUsers_CreatorId", - column: x => x.CreatorId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - 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.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: "UserFriends", - columns: table => new - { - UserId = table.Column(type: "uuid", nullable: false), - FriendId = table.Column(type: "uuid", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_UserFriends", x => new { x.UserId, x.FriendId }); - table.ForeignKey( - name: "FK_UserFriends_AspNetUsers_FriendId", - column: x => x.FriendId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_UserFriends_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.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: "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.CreateTable( - name: "Comments", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - PostId = table.Column(type: "uuid", nullable: true), - CreatorId = table.Column(type: "uuid", nullable: true), - Message = table.Column(type: "text", nullable: true), - TimeCreated = table.Column(type: "timestamp without time zone", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Comments", x => x.Id); - table.ForeignKey( - name: "FK_Comments_AspNetUsers_CreatorId", - column: x => x.CreatorId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - table.ForeignKey( - name: "FK_Comments_Posts_PostId", - column: x => x.PostId, - principalTable: "Posts", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - migrationBuilder.CreateTable( - name: "RatedPosts", - columns: table => new - { - UserId = table.Column(type: "uuid", nullable: false), - PostId = table.Column(type: "uuid", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_RatedPosts", x => new { x.UserId, x.PostId }); - table.ForeignKey( - name: "FK_RatedPosts_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_RatedPosts_Posts_PostId", - column: x => x.PostId, - principalTable: "Posts", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Rating", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - PostId = table.Column(type: "uuid", nullable: false), - Rate = table.Column(type: "integer", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Rating", x => x.Id); - table.ForeignKey( - name: "FK_Rating_Posts_PostId", - column: x => x.PostId, - principalTable: "Posts", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "UserRates", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - UserId = table.Column(type: "uuid", nullable: true), - Liked = table.Column(type: "boolean", nullable: false), - PostId = table.Column(type: "uuid", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_UserRates", x => x.Id); - table.ForeignKey( - name: "FK_UserRates_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - table.ForeignKey( - name: "FK_UserRates_Posts_PostId", - column: x => x.PostId, - principalTable: "Posts", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - 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_UserName", - table: "AspNetUsers", - column: "UserName", - unique: true); - - migrationBuilder.CreateIndex( - name: "UserNameIndex", - table: "AspNetUsers", - column: "NormalizedUserName", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Comments_CreatorId", - table: "Comments", - column: "CreatorId"); - - migrationBuilder.CreateIndex( - name: "IX_Comments_PostId", - table: "Comments", - column: "PostId"); - - migrationBuilder.CreateIndex( - name: "IX_LanguageUser_UsersId", - table: "LanguageUser", - column: "UsersId"); - - migrationBuilder.CreateIndex( - name: "IX_Posts_CreatorId", - table: "Posts", - column: "CreatorId"); - - migrationBuilder.CreateIndex( - name: "IX_ProfilePicture_UserId", - table: "ProfilePicture", - column: "UserId", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_RatedPosts_PostId", - table: "RatedPosts", - column: "PostId"); - - migrationBuilder.CreateIndex( - name: "IX_Rating_PostId", - table: "Rating", - column: "PostId", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_RoleUser_UsersId", - table: "RoleUser", - column: "UsersId"); - - migrationBuilder.CreateIndex( - name: "IX_TechnologyUser_UsersId", - table: "TechnologyUser", - column: "UsersId"); - - migrationBuilder.CreateIndex( - name: "IX_UserFriends_FriendId", - table: "UserFriends", - column: "FriendId"); - - migrationBuilder.CreateIndex( - name: "IX_UserRates_PostId", - table: "UserRates", - column: "PostId"); - - migrationBuilder.CreateIndex( - name: "IX_UserRates_UserId", - table: "UserRates", - column: "UserId"); - } - - 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: "ProfilePicture"); - - migrationBuilder.DropTable( - name: "RatedPosts"); - - migrationBuilder.DropTable( - name: "Rating"); - - migrationBuilder.DropTable( - name: "RoleUser"); - - migrationBuilder.DropTable( - name: "TechnologyUser"); - - migrationBuilder.DropTable( - name: "UserFriends"); - - migrationBuilder.DropTable( - name: "UserRates"); - - migrationBuilder.DropTable( - name: "Languages"); - - migrationBuilder.DropTable( - name: "AspNetRoles"); - - migrationBuilder.DropTable( - name: "Technologies"); - - migrationBuilder.DropTable( - name: "Posts"); - - migrationBuilder.DropTable( - name: "AspNetUsers"); - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs b/src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs deleted file mode 100644 index c11374a..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.Designer.cs +++ /dev/null @@ -1,643 +0,0 @@ -// -using System; -using System.Collections.Generic; -using DevHive.Data; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -namespace DevHive.Data.Migrations -{ - [DbContext(typeof(DevHiveContext))] - [Migration("20210205150447_Friends_Init_Config")] - partial class Friends_Init_Config - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .UseIdentityByDefaultColumns() - .HasAnnotation("Relational:MaxIdentifierLength", 63) - .HasAnnotation("ProductVersion", "5.0.1"); - - modelBuilder.Entity("DevHive.Data.Models.Comment", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("CreatorId") - .HasColumnType("uuid"); - - b.Property("Message") - .HasColumnType("text"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.Property("TimeCreated") - .HasColumnType("timestamp without time zone"); - - b.HasKey("Id"); - - b.HasIndex("CreatorId"); - - b.HasIndex("PostId"); - - b.ToTable("Comments"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Language", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Name") - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Languages"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("CreatorId") - .HasColumnType("uuid"); - - b.Property>("FileUrls") - .HasColumnType("text[]"); - - b.Property("Message") - .HasColumnType("text"); - - b.Property("TimeCreated") - .HasColumnType("timestamp without time zone"); - - b.HasKey("Id"); - - b.HasIndex("CreatorId"); - - b.ToTable("Posts"); - }); - - modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("PictureURL") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId") - .IsUnique(); - - b.ToTable("ProfilePicture"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Rating", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Rate") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.ToTable("Rating"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Role", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Name") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("NormalizedName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedName") - .IsUnique() - .HasDatabaseName("RoleNameIndex"); - - b.ToTable("AspNetRoles"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Technology", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Name") - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Technologies"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("AccessFailedCount") - .HasColumnType("integer"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Email") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("EmailConfirmed") - .HasColumnType("boolean"); - - b.Property("FirstName") - .HasColumnType("text"); - - b.Property("LastName") - .HasColumnType("text"); - - b.Property("LockoutEnabled") - .HasColumnType("boolean"); - - b.Property("LockoutEnd") - .HasColumnType("timestamp with time zone"); - - b.Property("NormalizedEmail") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("NormalizedUserName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("PasswordHash") - .HasColumnType("text"); - - b.Property("PhoneNumber") - .HasColumnType("text"); - - b.Property("PhoneNumberConfirmed") - .HasColumnType("boolean"); - - b.Property("SecurityStamp") - .HasColumnType("text"); - - b.Property("TwoFactorEnabled") - .HasColumnType("boolean"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("UserName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedEmail") - .HasDatabaseName("EmailIndex"); - - b.HasIndex("NormalizedUserName") - .IsUnique() - .HasDatabaseName("UserNameIndex"); - - b.HasIndex("UserId"); - - b.HasIndex("UserName") - .IsUnique(); - - b.ToTable("AspNetUsers"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "PostId"); - - b.HasIndex("PostId"); - - b.ToTable("RatedPosts"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserFriend", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("FriendId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "FriendId"); - - b.HasIndex("FriendId"); - - b.ToTable("UserFriends"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Rate") - .HasColumnType("boolean"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("UserRates"); - }); - - modelBuilder.Entity("LanguageUser", b => - { - b.Property("LanguagesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("LanguagesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("LanguageUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("ProviderKey") - .HasColumnType("text"); - - b.Property("ProviderDisplayName") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("Name") - .HasColumnType("text"); - - b.Property("Value") - .HasColumnType("text"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens"); - }); - - modelBuilder.Entity("RoleUser", b => - { - b.Property("RolesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("RolesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("RoleUser"); - }); - - modelBuilder.Entity("TechnologyUser", b => - { - b.Property("TechnologiesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("TechnologiesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("TechnologyUser"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Comment", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Comments") - .HasForeignKey("CreatorId"); - - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany("Comments") - .HasForeignKey("PostId"); - - b.Navigation("Creator"); - - b.Navigation("Post"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Posts") - .HasForeignKey("CreatorId"); - - b.Navigation("Creator"); - }); - - modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => - { - b.HasOne("DevHive.Data.Models.User", "User") - .WithOne("ProfilePicture") - .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany("Friends") - .HasForeignKey("UserId"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany() - .HasForeignKey("PostId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Post"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserFriend", b => - { - b.HasOne("DevHive.Data.Models.User", "Friend") - .WithMany() - .HasForeignKey("FriendId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Friend"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => - { - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("LanguageUser", b => - { - b.HasOne("DevHive.Data.Models.Language", null) - .WithMany() - .HasForeignKey("LanguagesId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UsersId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.HasOne("DevHive.Data.Models.Role", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.HasOne("DevHive.Data.Models.Role", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("RoleUser", b => - { - b.HasOne("DevHive.Data.Models.Role", null) - .WithMany() - .HasForeignKey("RolesId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UsersId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("TechnologyUser", b => - { - b.HasOne("DevHive.Data.Models.Technology", null) - .WithMany() - .HasForeignKey("TechnologiesId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UsersId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.Navigation("Comments"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Navigation("Comments"); - - b.Navigation("Friends"); - - b.Navigation("Posts"); - - b.Navigation("ProfilePicture"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs b/src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs deleted file mode 100644 index 1fc970d..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205150447_Friends_Init_Config.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace DevHive.Data.Migrations -{ - public partial class Friends_Init_Config : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AddColumn( - name: "UserId", - table: "AspNetUsers", - type: "uuid", - nullable: true); - - migrationBuilder.CreateIndex( - name: "IX_AspNetUsers_UserId", - table: "AspNetUsers", - column: "UserId"); - - migrationBuilder.AddForeignKey( - name: "FK_AspNetUsers_AspNetUsers_UserId", - table: "AspNetUsers", - column: "UserId", - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropForeignKey( - name: "FK_AspNetUsers_AspNetUsers_UserId", - table: "AspNetUsers"); - - migrationBuilder.DropIndex( - name: "IX_AspNetUsers_UserId", - table: "AspNetUsers"); - - migrationBuilder.DropColumn( - name: "UserId", - table: "AspNetUsers"); - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.Designer.cs b/src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.Designer.cs deleted file mode 100644 index 5d8e13a..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.Designer.cs +++ /dev/null @@ -1,691 +0,0 @@ -// -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("20210205154810_PostFileAttachments")] - partial class PostFileAttachments - { - 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("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("PostId") - .HasColumnType("uuid"); - - b.Property("Rate") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("PostId") - .IsUnique(); - - 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.PostAttachments", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("FileUrl") - .HasColumnType("text"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("PostId"); - - b.ToTable("PostAttachments"); - }); - - 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("Liked") - .HasColumnType("boolean"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("PostId"); - - b.HasIndex("UserId"); - - b.ToTable("UserRates"); - }); - - modelBuilder.Entity("LanguageUser", b => - { - b.Property("LanguagesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("LanguagesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("LanguageUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("ProviderKey") - .HasColumnType("text"); - - b.Property("ProviderDisplayName") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("Name") - .HasColumnType("text"); - - b.Property("Value") - .HasColumnType("text"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens"); - }); - - modelBuilder.Entity("RoleUser", b => - { - b.Property("RolesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("RolesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("RoleUser"); - }); - - modelBuilder.Entity("TechnologyUser", b => - { - b.Property("TechnologiesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("TechnologiesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("TechnologyUser"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Comment", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Comments") - .HasForeignKey("CreatorId"); - - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany("Comments") - .HasForeignKey("PostId"); - - b.Navigation("Creator"); - - b.Navigation("Post"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Posts") - .HasForeignKey("CreatorId"); - - b.Navigation("Creator"); - }); - - modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => - { - b.HasOne("DevHive.Data.Models.User", "User") - .WithOne("ProfilePicture") - .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Rating", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithOne("Rating") - .HasForeignKey("DevHive.Data.Models.Rating", "PostId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Post"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.PostAttachments", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany("Attachments") - .HasForeignKey("PostId"); - - b.Navigation("Post"); - }); - - 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("RatedPosts") - .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.Post", "Post") - .WithMany() - .HasForeignKey("PostId"); - - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId"); - - b.Navigation("Post"); - - 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("Attachments"); - - b.Navigation("Comments"); - - b.Navigation("Rating"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Navigation("Comments"); - - b.Navigation("FriendsOf"); - - b.Navigation("MyFriends"); - - b.Navigation("Posts"); - - b.Navigation("ProfilePicture"); - - b.Navigation("RatedPosts"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.cs b/src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.cs deleted file mode 100644 index 7b7b933..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205154810_PostFileAttachments.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace DevHive.Data.Migrations -{ - public partial class PostFileAttachments : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropColumn( - name: "FileUrls", - table: "Posts"); - - migrationBuilder.CreateTable( - name: "PostAttachments", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - PostId = table.Column(type: "uuid", nullable: true), - FileUrl = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_PostAttachments", x => x.Id); - table.ForeignKey( - name: "FK_PostAttachments_Posts_PostId", - column: x => x.PostId, - principalTable: "Posts", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - migrationBuilder.CreateIndex( - name: "IX_PostAttachments_PostId", - table: "PostAttachments", - column: "PostId"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "PostAttachments"); - - migrationBuilder.AddColumn( - name: "FileUrls", - table: "Posts", - type: "text[]", - nullable: true); - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs b/src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs deleted file mode 100644 index 3ad3ec8..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.Designer.cs +++ /dev/null @@ -1,609 +0,0 @@ -// -using System; -using System.Collections.Generic; -using DevHive.Data; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -namespace DevHive.Data.Migrations -{ - [DbContext(typeof(DevHiveContext))] - [Migration("20210205160520_Friends_First_Tweek")] - partial class Friends_First_Tweek - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .UseIdentityByDefaultColumns() - .HasAnnotation("Relational:MaxIdentifierLength", 63) - .HasAnnotation("ProductVersion", "5.0.1"); - - modelBuilder.Entity("DevHive.Data.Models.Comment", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("CreatorId") - .HasColumnType("uuid"); - - b.Property("Message") - .HasColumnType("text"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.Property("TimeCreated") - .HasColumnType("timestamp without time zone"); - - b.HasKey("Id"); - - b.HasIndex("CreatorId"); - - b.HasIndex("PostId"); - - b.ToTable("Comments"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Language", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Name") - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Languages"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("CreatorId") - .HasColumnType("uuid"); - - b.Property>("FileUrls") - .HasColumnType("text[]"); - - b.Property("Message") - .HasColumnType("text"); - - b.Property("TimeCreated") - .HasColumnType("timestamp without time zone"); - - b.HasKey("Id"); - - b.HasIndex("CreatorId"); - - b.ToTable("Posts"); - }); - - modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("PictureURL") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId") - .IsUnique(); - - b.ToTable("ProfilePicture"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Rating", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Rate") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.ToTable("Rating"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Role", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Name") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("NormalizedName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedName") - .IsUnique() - .HasDatabaseName("RoleNameIndex"); - - b.ToTable("AspNetRoles"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Technology", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Name") - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Technologies"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("AccessFailedCount") - .HasColumnType("integer"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Email") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("EmailConfirmed") - .HasColumnType("boolean"); - - b.Property("FirstName") - .HasColumnType("text"); - - b.Property("LastName") - .HasColumnType("text"); - - b.Property("LockoutEnabled") - .HasColumnType("boolean"); - - b.Property("LockoutEnd") - .HasColumnType("timestamp with time zone"); - - b.Property("NormalizedEmail") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("NormalizedUserName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("PasswordHash") - .HasColumnType("text"); - - b.Property("PhoneNumber") - .HasColumnType("text"); - - b.Property("PhoneNumberConfirmed") - .HasColumnType("boolean"); - - b.Property("SecurityStamp") - .HasColumnType("text"); - - b.Property("TwoFactorEnabled") - .HasColumnType("boolean"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("UserName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedEmail") - .HasDatabaseName("EmailIndex"); - - b.HasIndex("NormalizedUserName") - .IsUnique() - .HasDatabaseName("UserNameIndex"); - - b.HasIndex("UserId"); - - b.HasIndex("UserName") - .IsUnique(); - - b.ToTable("AspNetUsers"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "PostId"); - - b.HasIndex("PostId"); - - b.ToTable("RatedPosts"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Rate") - .HasColumnType("boolean"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("UserRates"); - }); - - modelBuilder.Entity("LanguageUser", b => - { - b.Property("LanguagesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("LanguagesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("LanguageUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("ProviderKey") - .HasColumnType("text"); - - b.Property("ProviderDisplayName") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("Name") - .HasColumnType("text"); - - b.Property("Value") - .HasColumnType("text"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens"); - }); - - modelBuilder.Entity("RoleUser", b => - { - b.Property("RolesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("RolesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("RoleUser"); - }); - - modelBuilder.Entity("TechnologyUser", b => - { - b.Property("TechnologiesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("TechnologiesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("TechnologyUser"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Comment", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Comments") - .HasForeignKey("CreatorId"); - - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany("Comments") - .HasForeignKey("PostId"); - - b.Navigation("Creator"); - - b.Navigation("Post"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Posts") - .HasForeignKey("CreatorId"); - - b.Navigation("Creator"); - }); - - modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => - { - b.HasOne("DevHive.Data.Models.User", "User") - .WithOne("ProfilePicture") - .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany("Friends") - .HasForeignKey("UserId"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany() - .HasForeignKey("PostId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Post"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => - { - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("LanguageUser", b => - { - b.HasOne("DevHive.Data.Models.Language", null) - .WithMany() - .HasForeignKey("LanguagesId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UsersId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.HasOne("DevHive.Data.Models.Role", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.HasOne("DevHive.Data.Models.Role", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("RoleUser", b => - { - b.HasOne("DevHive.Data.Models.Role", null) - .WithMany() - .HasForeignKey("RolesId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UsersId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("TechnologyUser", b => - { - b.HasOne("DevHive.Data.Models.Technology", null) - .WithMany() - .HasForeignKey("TechnologiesId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("DevHive.Data.Models.User", null) - .WithMany() - .HasForeignKey("UsersId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.Navigation("Comments"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Navigation("Comments"); - - b.Navigation("Friends"); - - b.Navigation("Posts"); - - b.Navigation("ProfilePicture"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs b/src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs deleted file mode 100644 index 565f863..0000000 --- a/src/Data/DevHive.Data/Migrations/20210205160520_Friends_First_Tweek.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace DevHive.Data.Migrations -{ - public partial class Friends_First_Tweek : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "UserFriends"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "UserFriends", - columns: table => new - { - UserId = table.Column(type: "uuid", nullable: false), - FriendId = table.Column(type: "uuid", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_UserFriends", x => new { x.UserId, x.FriendId }); - table.ForeignKey( - name: "FK_UserFriends_AspNetUsers_FriendId", - column: x => x.FriendId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_UserFriends_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_UserFriends_FriendId", - table: "UserFriends", - column: "FriendId"); - } - } -} diff --git a/src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs b/src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs deleted file mode 100644 index dc5739c..0000000 --- a/src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs +++ /dev/null @@ -1,658 +0,0 @@ -// -using System; -using DevHive.Data; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -namespace DevHive.Data.Migrations -{ - [DbContext(typeof(DevHiveContext))] - partial class DevHiveContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .UseIdentityByDefaultColumns() - .HasAnnotation("Relational:MaxIdentifierLength", 63) - .HasAnnotation("ProductVersion", "5.0.1"); - - modelBuilder.Entity("DevHive.Data.Models.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("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("PostId") - .HasColumnType("uuid"); - - b.Property("Rate") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("PostId") - .IsUnique(); - - b.ToTable("Rating"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Role", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Name") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("NormalizedName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedName") - .IsUnique() - .HasDatabaseName("RoleNameIndex"); - - b.ToTable("AspNetRoles"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Technology", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Name") - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Technologies"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("AccessFailedCount") - .HasColumnType("integer"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Email") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("EmailConfirmed") - .HasColumnType("boolean"); - - b.Property("FirstName") - .HasColumnType("text"); - - b.Property("LastName") - .HasColumnType("text"); - - b.Property("LockoutEnabled") - .HasColumnType("boolean"); - - b.Property("LockoutEnd") - .HasColumnType("timestamp with time zone"); - - b.Property("NormalizedEmail") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("NormalizedUserName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("PasswordHash") - .HasColumnType("text"); - - b.Property("PhoneNumber") - .HasColumnType("text"); - - b.Property("PhoneNumberConfirmed") - .HasColumnType("boolean"); - - b.Property("SecurityStamp") - .HasColumnType("text"); - - b.Property("TwoFactorEnabled") - .HasColumnType("boolean"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("UserName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedEmail") - .HasDatabaseName("EmailIndex"); - - b.HasIndex("NormalizedUserName") - .IsUnique() - .HasDatabaseName("UserNameIndex"); - - b.HasIndex("UserId"); - - b.HasIndex("UserName") - .IsUnique(); - - b.ToTable("AspNetUsers"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.PostAttachments", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("FileUrl") - .HasColumnType("text"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("PostId"); - - b.ToTable("PostAttachments"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.RatedPost", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "PostId"); - - b.HasIndex("PostId"); - - b.ToTable("RatedPosts"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Liked") - .HasColumnType("boolean"); - - b.Property("PostId") - .HasColumnType("uuid"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("PostId"); - - b.HasIndex("UserId"); - - b.ToTable("UserRates"); - }); - - modelBuilder.Entity("LanguageUser", b => - { - b.Property("LanguagesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("LanguagesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("LanguageUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer") - .UseIdentityByDefaultColumn(); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("ProviderKey") - .HasColumnType("text"); - - b.Property("ProviderDisplayName") - .HasColumnType("text"); - - b.Property("UserId") - .HasColumnType("uuid"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("RoleId") - .HasColumnType("uuid"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("uuid"); - - b.Property("LoginProvider") - .HasColumnType("text"); - - b.Property("Name") - .HasColumnType("text"); - - b.Property("Value") - .HasColumnType("text"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens"); - }); - - modelBuilder.Entity("RoleUser", b => - { - b.Property("RolesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("RolesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("RoleUser"); - }); - - modelBuilder.Entity("TechnologyUser", b => - { - b.Property("TechnologiesId") - .HasColumnType("uuid"); - - b.Property("UsersId") - .HasColumnType("uuid"); - - b.HasKey("TechnologiesId", "UsersId"); - - b.HasIndex("UsersId"); - - b.ToTable("TechnologyUser"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Comment", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Comments") - .HasForeignKey("CreatorId"); - - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany("Comments") - .HasForeignKey("PostId"); - - b.Navigation("Creator"); - - b.Navigation("Post"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Post", b => - { - b.HasOne("DevHive.Data.Models.User", "Creator") - .WithMany("Posts") - .HasForeignKey("CreatorId"); - - b.Navigation("Creator"); - }); - - modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => - { - b.HasOne("DevHive.Data.Models.User", "User") - .WithOne("ProfilePicture") - .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.Models.Rating", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithOne("Rating") - .HasForeignKey("DevHive.Data.Models.Rating", "PostId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Post"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.PostAttachments", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany("Attachments") - .HasForeignKey("PostId"); - - b.Navigation("Post"); - }); - - 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("RatedPosts") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Post"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("DevHive.Data.RelationModels.UserRate", b => - { - b.HasOne("DevHive.Data.Models.Post", "Post") - .WithMany() - .HasForeignKey("PostId"); - - b.HasOne("DevHive.Data.Models.User", "User") - .WithMany() - .HasForeignKey("UserId"); - - b.Navigation("Post"); - - 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("Attachments"); - - b.Navigation("Comments"); - - b.Navigation("Rating"); - }); - - modelBuilder.Entity("DevHive.Data.Models.User", b => - { - b.Navigation("Comments"); - - b.Navigation("Friends"); - - b.Navigation("Posts"); - - b.Navigation("ProfilePicture"); - - b.Navigation("RatedPosts"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Data/DevHive.Data/RelationModels/PostAttachments.cs b/src/Data/DevHive.Data/RelationModels/PostAttachments.cs deleted file mode 100644 index 48aa8ff..0000000 --- a/src/Data/DevHive.Data/RelationModels/PostAttachments.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations.Schema; -using DevHive.Data.Models; - -namespace DevHive.Data.RelationModels -{ - [Table("PostAttachments")] - public class PostAttachments - { - public Guid Id { get; set; } - - public Post Post { get; set; } - - public string FileUrl { get; set; } - } -} diff --git a/src/Data/DevHive.Data/RelationModels/RatedPost.cs b/src/Data/DevHive.Data/RelationModels/RatedPost.cs deleted file mode 100644 index 7001d92..0000000 --- a/src/Data/DevHive.Data/RelationModels/RatedPost.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations.Schema; -using System.Reflection.Metadata.Ecma335; -using DevHive.Data.Models; -using Microsoft.EntityFrameworkCore; - -namespace DevHive.Data.RelationModels -{ - [Table("RatedPosts")] - public class RatedPost - { - public Guid UserId { get; set; } - public User User { get; set; } - - public Guid PostId { get; set; } - public Post Post { get; set; } - } -} diff --git a/src/Data/DevHive.Data/RelationModels/UserRate.cs b/src/Data/DevHive.Data/RelationModels/UserRate.cs deleted file mode 100644 index 696e6f3..0000000 --- a/src/Data/DevHive.Data/RelationModels/UserRate.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations.Schema; -using DevHive.Data.Models; - -namespace DevHive.Data.RelationModels -{ - [Table("UserRates")] - public class UserRate - { - public Guid Id { get; set; } - - public User User { get; set; } - - public bool Liked { get; set; } - - public Post Post { get; set; } - } -} diff --git a/src/Data/DevHive.Data/Repositories/CommentRepository.cs b/src/Data/DevHive.Data/Repositories/CommentRepository.cs index bee7624..c63fe65 100644 --- a/src/Data/DevHive.Data/Repositories/CommentRepository.cs +++ b/src/Data/DevHive.Data/Repositories/CommentRepository.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/Data/DevHive.Data/Repositories/FeedRepository.cs b/src/Data/DevHive.Data/Repositories/FeedRepository.cs index 8d3e5e1..8899675 100644 --- a/src/Data/DevHive.Data/Repositories/FeedRepository.cs +++ b/src/Data/DevHive.Data/Repositories/FeedRepository.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper.Internal; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/Data/DevHive.Data/Repositories/LanguageRepository.cs b/src/Data/DevHive.Data/Repositories/LanguageRepository.cs index 31d0b86..61f4792 100644 --- a/src/Data/DevHive.Data/Repositories/LanguageRepository.cs +++ b/src/Data/DevHive.Data/Repositories/LanguageRepository.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/Data/DevHive.Data/Repositories/PostRepository.cs b/src/Data/DevHive.Data/Repositories/PostRepository.cs index 52c5b4e..d35c475 100644 --- a/src/Data/DevHive.Data/Repositories/PostRepository.cs +++ b/src/Data/DevHive.Data/Repositories/PostRepository.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; using Microsoft.EntityFrameworkCore; namespace DevHive.Data.Repositories diff --git a/src/Data/DevHive.Data/Repositories/RatingRepository.cs b/src/Data/DevHive.Data/Repositories/RatingRepository.cs index 1be8fe8..b361693 100644 --- a/src/Data/DevHive.Data/Repositories/RatingRepository.cs +++ b/src/Data/DevHive.Data/Repositories/RatingRepository.cs @@ -1,7 +1,7 @@ using System; using System.Linq; using System.Threading.Tasks; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/Data/DevHive.Data/Repositories/RoleRepository.cs b/src/Data/DevHive.Data/Repositories/RoleRepository.cs index 441efef..7d07c1b 100644 --- a/src/Data/DevHive.Data/Repositories/RoleRepository.cs +++ b/src/Data/DevHive.Data/Repositories/RoleRepository.cs @@ -1,6 +1,6 @@ using System; using System.Threading.Tasks; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/Data/DevHive.Data/Repositories/TechnologyRepository.cs b/src/Data/DevHive.Data/Repositories/TechnologyRepository.cs index 6f0d10f..8cb7da1 100644 --- a/src/Data/DevHive.Data/Repositories/TechnologyRepository.cs +++ b/src/Data/DevHive.Data/Repositories/TechnologyRepository.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using Microsoft.EntityFrameworkCore; diff --git a/src/Data/DevHive.Data/Repositories/UserRepository.cs b/src/Data/DevHive.Data/Repositories/UserRepository.cs index 6e97e60..9fa6eca 100644 --- a/src/Data/DevHive.Data/Repositories/UserRepository.cs +++ b/src/Data/DevHive.Data/Repositories/UserRepository.cs @@ -4,9 +4,9 @@ using System.Globalization; using System.Linq; using System.Threading.Tasks; using AutoMapper.Mappers; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; diff --git a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj index 744a855..3f0eadf 100644 --- a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj +++ b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj @@ -4,6 +4,10 @@ - + + + + + diff --git a/src/Services/DevHive.Services.Tests/CommentService.Tests.cs b/src/Services/DevHive.Services.Tests/CommentService.Tests.cs index ac022ea..d511739 100644 --- a/src/Services/DevHive.Services.Tests/CommentService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/CommentService.Tests.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Models.Comment; using DevHive.Services.Services; diff --git a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj index d6d0876..eb33d07 100644 --- a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj +++ b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj @@ -1,21 +1,20 @@ - net5.0 - false - - + - + - + + + true latest - + \ No newline at end of file diff --git a/src/Services/DevHive.Services.Tests/FeedService.Tests.cs b/src/Services/DevHive.Services.Tests/FeedService.Tests.cs index e4020c5..1f21394 100644 --- a/src/Services/DevHive.Services.Tests/FeedService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/FeedService.Tests.cs @@ -2,7 +2,7 @@ //using System.Collections.Generic; //using System.Threading.Tasks; //using AutoMapper; -//using DevHive.Data.Interfaces.Repositories; +//using DevHive.Data.Interfaces; //using DevHive.Data.Models; //using DevHive.Services.Models; //using DevHive.Services.Models.Post; diff --git a/src/Services/DevHive.Services.Tests/LanguageService.Tests.cs b/src/Services/DevHive.Services.Tests/LanguageService.Tests.cs index 1b59f91..731091c 100644 --- a/src/Services/DevHive.Services.Tests/LanguageService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/LanguageService.Tests.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Models.Language; using DevHive.Services.Services; diff --git a/src/Services/DevHive.Services.Tests/PostService.Tests.cs b/src/Services/DevHive.Services.Tests/PostService.Tests.cs index 900608c..137b8d1 100644 --- a/src/Services/DevHive.Services.Tests/PostService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/PostService.Tests.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models.Post; diff --git a/src/Services/DevHive.Services.Tests/RoleService.Tests.cs b/src/Services/DevHive.Services.Tests/RoleService.Tests.cs index c4fac77..29d5df2 100644 --- a/src/Services/DevHive.Services.Tests/RoleService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/RoleService.Tests.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Models.Role; using DevHive.Services.Services; diff --git a/src/Services/DevHive.Services.Tests/TechnologyServices.Tests.cs b/src/Services/DevHive.Services.Tests/TechnologyServices.Tests.cs index e671adb..a43d4b9 100644 --- a/src/Services/DevHive.Services.Tests/TechnologyServices.Tests.cs +++ b/src/Services/DevHive.Services.Tests/TechnologyServices.Tests.cs @@ -1,5 +1,5 @@ using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Models.Technology; using DevHive.Services.Services; diff --git a/src/Services/DevHive.Services.Tests/UserService.Tests.cs b/src/Services/DevHive.Services.Tests/UserService.Tests.cs index aff34c9..8fddce7 100644 --- a/src/Services/DevHive.Services.Tests/UserService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/UserService.Tests.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using AutoMapper; using DevHive.Common.Models.Identity; using DevHive.Common.Models.Misc; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models.User; diff --git a/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs index 9a8e3d9..043fcb7 100644 --- a/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -2,7 +2,7 @@ using DevHive.Data.Models; using AutoMapper; using DevHive.Services.Models.User; using DevHive.Common.Models.Misc; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; namespace DevHive.Services.Configurations.Mapping { diff --git a/src/Services/DevHive.Services/DevHive.Services.csproj b/src/Services/DevHive.Services/DevHive.Services.csproj index 1380248..b09c46d 100644 --- a/src/Services/DevHive.Services/DevHive.Services.csproj +++ b/src/Services/DevHive.Services/DevHive.Services.csproj @@ -2,22 +2,21 @@ net5.0 - - + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - + - + + + + true latest diff --git a/src/Services/DevHive.Services/Services/CommentService.cs b/src/Services/DevHive.Services/Services/CommentService.cs index e2b54c4..e14f3bb 100644 --- a/src/Services/DevHive.Services/Services/CommentService.cs +++ b/src/Services/DevHive.Services/Services/CommentService.cs @@ -7,7 +7,7 @@ using DevHive.Services.Models.Comment; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using DevHive.Services.Interfaces; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using System.Linq; namespace DevHive.Services.Services diff --git a/src/Services/DevHive.Services/Services/FeedService.cs b/src/Services/DevHive.Services/Services/FeedService.cs index f2f4a3a..a0f1f1b 100644 --- a/src/Services/DevHive.Services/Services/FeedService.cs +++ b/src/Services/DevHive.Services/Services/FeedService.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models; diff --git a/src/Services/DevHive.Services/Services/LanguageService.cs b/src/Services/DevHive.Services/Services/LanguageService.cs index a6364d8..9d2041e 100644 --- a/src/Services/DevHive.Services/Services/LanguageService.cs +++ b/src/Services/DevHive.Services/Services/LanguageService.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models.Language; diff --git a/src/Services/DevHive.Services/Services/PostService.cs b/src/Services/DevHive.Services/Services/PostService.cs index fe91f23..c368ce6 100644 --- a/src/Services/DevHive.Services/Services/PostService.cs +++ b/src/Services/DevHive.Services/Services/PostService.cs @@ -7,9 +7,9 @@ using DevHive.Services.Models.Post; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using DevHive.Services.Interfaces; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using System.Linq; -using DevHive.Data.RelationModels; +using DevHive.Data.Models.Relational; namespace DevHive.Services.Services { diff --git a/src/Services/DevHive.Services/Services/RateService.cs b/src/Services/DevHive.Services/Services/RateService.cs index 204c550..d423d8c 100644 --- a/src/Services/DevHive.Services/Services/RateService.cs +++ b/src/Services/DevHive.Services/Services/RateService.cs @@ -2,7 +2,7 @@ using System; using System.Linq; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models.Post.Rating; diff --git a/src/Services/DevHive.Services/Services/RoleService.cs b/src/Services/DevHive.Services/Services/RoleService.cs index dbf8fcd..5472e44 100644 --- a/src/Services/DevHive.Services/Services/RoleService.cs +++ b/src/Services/DevHive.Services/Services/RoleService.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models.Role; diff --git a/src/Services/DevHive.Services/Services/TechnologyService.cs b/src/Services/DevHive.Services/Services/TechnologyService.cs index 6dd6286..09c4d20 100644 --- a/src/Services/DevHive.Services/Services/TechnologyService.cs +++ b/src/Services/DevHive.Services/Services/TechnologyService.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models.Technology; diff --git a/src/Services/DevHive.Services/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs index f68e3aa..f2c5a5b 100644 --- a/src/Services/DevHive.Services/Services/UserService.cs +++ b/src/Services/DevHive.Services/Services/UserService.cs @@ -11,7 +11,7 @@ using System.Text; using System.Collections.Generic; using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using System.Linq; using DevHive.Common.Models.Misc; using Microsoft.AspNetCore.Http; diff --git a/src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs b/src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs new file mode 100644 index 0000000..5ecb41a --- /dev/null +++ b/src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs @@ -0,0 +1,24 @@ +using System; +using System.ComponentModel.DataAnnotations; + +namespace DevHive.Web.Models.Attributes +{ + public class GoodPassword : ValidationAttribute + { + public override bool IsValid(object value) + { + var stringValue = (string)value; + + for (int i = 0; i < stringValue.Length; i++) + { + if (Char.IsDigit(stringValue[i])) + { + base.ErrorMessage = "Password must be atleast 5 characters long!"; + return stringValue.Length >= 5; + } + } + base.ErrorMessage = "Password must contain atleast 1 digit!"; + return false; + } + } +} diff --git a/src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs b/src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs new file mode 100644 index 0000000..0f6adb1 --- /dev/null +++ b/src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs @@ -0,0 +1,20 @@ +using System; +using System.ComponentModel.DataAnnotations; + +namespace DevHive.Web.Models.Attributes +{ + public class OnlyLetters : ValidationAttribute + { + public override bool IsValid(object value) + { + var stringValue = (string)value; + + foreach (char ch in stringValue) + { + if (!Char.IsLetter(ch)) + return false; + } + return true; + } + } +} diff --git a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj index 65892c5..ca49b8c 100644 --- a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj +++ b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj @@ -2,9 +2,11 @@ net5.0 - + + + - + diff --git a/src/Web/DevHive.Web.Models/User/BaseUserWebModel.cs b/src/Web/DevHive.Web.Models/User/BaseUserWebModel.cs index 9a2544d..5fdb757 100644 --- a/src/Web/DevHive.Web.Models/User/BaseUserWebModel.cs +++ b/src/Web/DevHive.Web.Models/User/BaseUserWebModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; -using DevHive.Web.Attributes; +using DevHive.Web.Models.Attributes; namespace DevHive.Web.Models.User { diff --git a/src/Web/DevHive.Web.Models/User/LoginWebModel.cs b/src/Web/DevHive.Web.Models/User/LoginWebModel.cs index c821721..7d4e93a 100644 --- a/src/Web/DevHive.Web.Models/User/LoginWebModel.cs +++ b/src/Web/DevHive.Web.Models/User/LoginWebModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; -using DevHive.Web.Attributes; +using DevHive.Web.Models.Attributes; namespace DevHive.Web.Models.User { diff --git a/src/Web/DevHive.Web.Models/User/RegisterWebModel.cs b/src/Web/DevHive.Web.Models/User/RegisterWebModel.cs index 754c8eb..999ff00 100644 --- a/src/Web/DevHive.Web.Models/User/RegisterWebModel.cs +++ b/src/Web/DevHive.Web.Models/User/RegisterWebModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; -using DevHive.Web.Attributes; +using DevHive.Web.Models.Attributes; namespace DevHive.Web.Models.User { diff --git a/src/Web/DevHive.Web.Models/User/UpdateUserWebModel.cs b/src/Web/DevHive.Web.Models/User/UpdateUserWebModel.cs index 86f6bfe..f74927e 100644 --- a/src/Web/DevHive.Web.Models/User/UpdateUserWebModel.cs +++ b/src/Web/DevHive.Web.Models/User/UpdateUserWebModel.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; -using DevHive.Web.Attributes; +using DevHive.Web.Models.Attributes; using DevHive.Web.Models.Role; using DevHive.Web.Models.Language; using DevHive.Web.Models.Technology; diff --git a/src/Web/DevHive.Web.Models/User/UsernameWebModel.cs b/src/Web/DevHive.Web.Models/User/UsernameWebModel.cs index fc0a7ff..638cb15 100644 --- a/src/Web/DevHive.Web.Models/User/UsernameWebModel.cs +++ b/src/Web/DevHive.Web.Models/User/UsernameWebModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; -using DevHive.Web.Attributes; +using DevHive.Web.Models.Attributes; namespace DevHive.Web.Models.User { diff --git a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj index ee390b5..f8390de 100644 --- a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj +++ b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj @@ -1,20 +1,19 @@ - net5.0 - false - - + - + + + true latest - + \ No newline at end of file diff --git a/src/Web/DevHive.Web.Tests/RoleController.Tests.cs b/src/Web/DevHive.Web.Tests/RoleController.Tests.cs index b5deba0..8e33bee 100644 --- a/src/Web/DevHive.Web.Tests/RoleController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/RoleController.Tests.cs @@ -111,7 +111,7 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); OkObjectResult okObjectResult = result as OkObjectResult; - RoleWebModel resultModel = okObjectResult.Value as Models.Identity.Role.RoleWebModel; + RoleWebModel resultModel = okObjectResult.Value as RoleWebModel; Assert.AreEqual(NAME, resultModel.Name); } diff --git a/src/Web/DevHive.Web.Tests/UserController.Tests.cs b/src/Web/DevHive.Web.Tests/UserController.Tests.cs index 3e858f6..efdfdbb 100644 --- a/src/Web/DevHive.Web.Tests/UserController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/UserController.Tests.cs @@ -113,7 +113,7 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); OkObjectResult okObjectResult = result as OkObjectResult; - UserWebModel resultModel = okObjectResult.Value as Models.Identity.User.UserWebModel; + UserWebModel resultModel = okObjectResult.Value as UserWebModel; Assert.AreEqual(USERNAME, resultModel.UserName); } @@ -155,7 +155,7 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); OkObjectResult okObjectResult = result as OkObjectResult; - UserWebModel resultModel = okObjectResult.Value as Models.Identity.User.UserWebModel; + UserWebModel resultModel = okObjectResult.Value as UserWebModel; Assert.AreEqual(USERNAME, resultModel.UserName); } @@ -214,7 +214,7 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); AcceptedResult acceptedResult = result as AcceptedResult; - ProfilePictureWebModel resultModel = acceptedResult.Value as Models.Identity.User.ProfilePictureWebModel; + ProfilePictureWebModel resultModel = acceptedResult.Value as ProfilePictureWebModel; Assert.AreEqual(profilePictureURL, resultModel.ProfilePictureURL); } diff --git a/src/Web/DevHive.Web/Attributes/GoodPasswordModelValidation.cs b/src/Web/DevHive.Web/Attributes/GoodPasswordModelValidation.cs deleted file mode 100644 index 7d6a1ea..0000000 --- a/src/Web/DevHive.Web/Attributes/GoodPasswordModelValidation.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; - -namespace DevHive.Web.Attributes -{ - public class GoodPassword : ValidationAttribute - { - public override bool IsValid(object value) - { - var stringValue = (string)value; - - for (int i = 0; i < stringValue.Length; i++) - { - if (Char.IsDigit(stringValue[i])) - { - base.ErrorMessage = "Password must be atleast 5 characters long!"; - return stringValue.Length >= 5; - } - } - base.ErrorMessage = "Password must contain atleast 1 digit!"; - return false; - } - } -} diff --git a/src/Web/DevHive.Web/Attributes/OnlyLettersModelValidation.cs b/src/Web/DevHive.Web/Attributes/OnlyLettersModelValidation.cs deleted file mode 100644 index 07afee9..0000000 --- a/src/Web/DevHive.Web/Attributes/OnlyLettersModelValidation.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; - -namespace DevHive.Web.Attributes -{ - public class OnlyLetters : ValidationAttribute - { - public override bool IsValid(object value) - { - var stringValue = (string)value; - - foreach (char ch in stringValue) - { - if (!Char.IsLetter(ch)) - return false; - } - return true; - } - } -} diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs index 88f21d4..c547951 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -1,4 +1,4 @@ -using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Interfaces; using DevHive.Data.Repositories; using DevHive.Services.Interfaces; using DevHive.Services.Services; diff --git a/src/Web/DevHive.Web/Configurations/Mapping/RatingMappings.cs b/src/Web/DevHive.Web/Configurations/Mapping/RatingMappings.cs index 4e071de..a29e06c 100644 --- a/src/Web/DevHive.Web/Configurations/Mapping/RatingMappings.cs +++ b/src/Web/DevHive.Web/Configurations/Mapping/RatingMappings.cs @@ -1,6 +1,6 @@ using AutoMapper; using DevHive.Services.Models.Post.Rating; -using DevHive.Web.Models.Post.Rating; +using DevHive.Web.Models.Rating; namespace DevHive.Web.Configurations.Mapping { diff --git a/src/Web/DevHive.Web/Controllers/RateController.cs b/src/Web/DevHive.Web/Controllers/RateController.cs index 68b859b..72eb932 100644 --- a/src/Web/DevHive.Web/Controllers/RateController.cs +++ b/src/Web/DevHive.Web/Controllers/RateController.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using AutoMapper; using DevHive.Services.Interfaces; using DevHive.Services.Models.Post.Rating; -using DevHive.Web.Models.Post.Rating; +using DevHive.Web.Models.Rating; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; diff --git a/src/Web/DevHive.Web/DevHive.Web.csproj b/src/Web/DevHive.Web/DevHive.Web.csproj index 7ba07b1..6f78b69 100644 --- a/src/Web/DevHive.Web/DevHive.Web.csproj +++ b/src/Web/DevHive.Web/DevHive.Web.csproj @@ -7,17 +7,21 @@ latest - - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - + + + - + - + + + + + \ No newline at end of file -- cgit v1.2.3 From 4c03712af14c37718b7be5b23fcadeb86f2a2191 Mon Sep 17 00:00:00 2001 From: transtrike Date: Mon, 15 Feb 2021 19:06:14 +0200 Subject: Code Analyzer added to all csproj; Removed unnessessary code; Fixed formatting --- .../DevHive.Common.Models/DevHive.Common.csproj | 1 + .../DevHive.Data.Models/DevHive.Data.Models.csproj | 1 + .../DevHive.Data.Tests/DevHive.Data.Tests.csproj | 13 +++--- src/Data/DevHive.Data/DevHive.Data.csproj | 1 + .../DevHive.Services.Models.csproj | 9 ++-- .../DevHive.Services.Tests.csproj | 13 +++--- .../DevHive.Services.Tests/UserService.Tests.cs | 8 ++-- .../Configurations/Mapping/PostMappings.cs | 1 - .../Configurations/Mapping/RatingMappings.cs | 2 - .../DevHive.Services/DevHive.Services.csproj | 17 +++---- .../DevHive.Services/Interfaces/ICloudService.cs | 2 - .../DevHive.Services/Interfaces/IRoleService.cs | 2 +- .../DevHive.Services/Options/JWTOptions.cs | 14 ------ .../DevHive.Services/Options/JwtOptions.cs | 14 ++++++ .../DevHive.Services/Services/FeedService.cs | 2 +- .../DevHive.Services/Services/PostService.cs | 15 +++--- .../DevHive.Services/Services/RateService.cs | 2 +- .../DevHive.Services/Services/RoleService.cs | 9 ++-- .../DevHive.Services/Services/UserService.cs | 15 +++--- .../Attributes/GoodPasswordAttribute.cs | 23 +++++++++ .../Attributes/GoodPasswordModelValidation.cs | 24 ---------- .../Attributes/OnlyLettersModelValidation.cs | 4 +- .../DevHive.Web.Models/DevHive.Web.Models.csproj | 8 ++-- .../DevHive.Web.Models/Post/ReadPostWebModel.cs | 1 - .../DevHive.Web.Tests/CommentController.Tests.cs | 35 +++++++------- src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj | 11 +++-- .../DevHive.Web.Tests/LanguageController.Tests.cs | 4 +- src/Web/DevHive.Web.Tests/PostController.Tests.cs | 29 ++++++------ src/Web/DevHive.Web.Tests/RoleController.Tests.cs | 4 +- .../TechnologyController.Tests.cs | 4 +- src/Web/DevHive.Web.Tests/UserController.Tests.cs | 46 ++++++++---------- .../Extensions/ConfigureAutoMapper.cs | 5 +- .../ConfigureExceptionHandlerMiddleware.cs | 2 - .../Configurations/Extensions/ConfigureJWT.cs | 54 ---------------------- .../Configurations/Extensions/ConfigureJwt.cs | 54 ++++++++++++++++++++++ src/Web/DevHive.Web/DevHive.Web.csproj | 21 +++++---- .../DevHive.Web/Middleware/ExceptionMiddleware.cs | 14 ++---- 37 files changed, 229 insertions(+), 255 deletions(-) delete mode 100644 src/Services/DevHive.Services/Options/JWTOptions.cs create mode 100644 src/Services/DevHive.Services/Options/JwtOptions.cs create mode 100644 src/Web/DevHive.Web.Models/Attributes/GoodPasswordAttribute.cs delete mode 100644 src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs delete mode 100644 src/Web/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs create mode 100644 src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs (limited to 'src/Common') diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.csproj index 4829c80..f6d662c 100644 --- a/src/Common/DevHive.Common.Models/DevHive.Common.csproj +++ b/src/Common/DevHive.Common.Models/DevHive.Common.csproj @@ -4,6 +4,7 @@ + true diff --git a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj index e58a6d8..e9dc644 100644 --- a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj +++ b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj @@ -5,5 +5,6 @@ + \ No newline at end of file diff --git a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj index 568edda..2af369f 100644 --- a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj +++ b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj @@ -4,14 +4,15 @@ false - - - - - + + + + + + - + true diff --git a/src/Data/DevHive.Data/DevHive.Data.csproj b/src/Data/DevHive.Data/DevHive.Data.csproj index fac1581..46928c6 100644 --- a/src/Data/DevHive.Data/DevHive.Data.csproj +++ b/src/Data/DevHive.Data/DevHive.Data.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj index 3f0eadf..914efe0 100644 --- a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj +++ b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj @@ -2,12 +2,11 @@ net5.0 - - + + - - + - + \ No newline at end of file diff --git a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj index eb33d07..bdfb2bb 100644 --- a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj +++ b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj @@ -4,14 +4,15 @@ false - - - - - + + + + + + - + true diff --git a/src/Services/DevHive.Services.Tests/UserService.Tests.cs b/src/Services/DevHive.Services.Tests/UserService.Tests.cs index 8fddce7..ce997c1 100644 --- a/src/Services/DevHive.Services.Tests/UserService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/UserService.Tests.cs @@ -29,7 +29,7 @@ namespace DevHive.Services.Tests private Mock LanguageRepositoryMock { get; set; } private Mock TechnologyRepositoryMock { get; set; } private Mock MapperMock { get; set; } - private JWTOptions JWTOptions { get; set; } + private JwtOptions JwtOptions { get; set; } private UserService UserService { get; set; } #region SetUps @@ -41,10 +41,10 @@ namespace DevHive.Services.Tests this.CloudServiceMock = new Mock(); this.LanguageRepositoryMock = new Mock(); this.TechnologyRepositoryMock = new Mock(); - this.JWTOptions = new JWTOptions("gXfQlU6qpDleFWyimscjYcT3tgFsQg3yoFjcvSLxG56n1Vu2yptdIUq254wlJWjm"); + this.JwtOptions = new JwtOptions("gXfQlU6qpDleFWyimscjYcT3tgFsQg3yoFjcvSLxG56n1Vu2yptdIUq254wlJWjm"); this.MapperMock = new Mock(); // TODO: give actual UserManager and RoleManager to UserService - this.UserService = new UserService(this.UserRepositoryMock.Object, this.LanguageRepositoryMock.Object, this.RoleRepositoryMock.Object, this.TechnologyRepositoryMock.Object, null, null, this.MapperMock.Object, this.JWTOptions, this.CloudServiceMock.Object); + this.UserService = new UserService(this.UserRepositoryMock.Object, this.LanguageRepositoryMock.Object, this.RoleRepositoryMock.Object, this.TechnologyRepositoryMock.Object, null, null, this.MapperMock.Object, this.JwtOptions, this.CloudServiceMock.Object); } #endregion @@ -364,7 +364,7 @@ namespace DevHive.Services.Tests #region HelperMethods private string WriteJWTSecurityToken(Guid userId, string username, HashSet roles) { - byte[] signingKey = Encoding.ASCII.GetBytes(this.JWTOptions.Secret); + byte[] signingKey = Encoding.ASCII.GetBytes(this.JwtOptions.Secret); HashSet claims = new() { new Claim("ID", $"{userId}"), diff --git a/src/Services/DevHive.Services/Configurations/Mapping/PostMappings.cs b/src/Services/DevHive.Services/Configurations/Mapping/PostMappings.cs index 9362f90..1d7d88b 100644 --- a/src/Services/DevHive.Services/Configurations/Mapping/PostMappings.cs +++ b/src/Services/DevHive.Services/Configurations/Mapping/PostMappings.cs @@ -12,7 +12,6 @@ namespace DevHive.Services.Configurations.Mapping public PostMappings() { CreateMap(); - // .ForMember(dest => dest.Files, src => src.Ignore()); CreateMap() .ForMember(dest => dest.Id, src => src.MapFrom(p => p.PostId)) // .ForMember(dest => dest.Files, src => src.Ignore()) diff --git a/src/Services/DevHive.Services/Configurations/Mapping/RatingMappings.cs b/src/Services/DevHive.Services/Configurations/Mapping/RatingMappings.cs index 1dbb7b4..fefa6d8 100644 --- a/src/Services/DevHive.Services/Configurations/Mapping/RatingMappings.cs +++ b/src/Services/DevHive.Services/Configurations/Mapping/RatingMappings.cs @@ -8,8 +8,6 @@ namespace DevHive.Services.Configurations.Mapping { public RatingMappings() { - // CreateMap() - // .ForMember(dest => dest.PostId, src => src.MapFrom(p => p.Post.Id)); } } } diff --git a/src/Services/DevHive.Services/DevHive.Services.csproj b/src/Services/DevHive.Services/DevHive.Services.csproj index b09c46d..650a304 100644 --- a/src/Services/DevHive.Services/DevHive.Services.csproj +++ b/src/Services/DevHive.Services/DevHive.Services.csproj @@ -3,22 +3,23 @@ net5.0 - + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - + + + + + - - + + true latest - + \ No newline at end of file diff --git a/src/Services/DevHive.Services/Interfaces/ICloudService.cs b/src/Services/DevHive.Services/Interfaces/ICloudService.cs index 3ae7a24..040729f 100644 --- a/src/Services/DevHive.Services/Interfaces/ICloudService.cs +++ b/src/Services/DevHive.Services/Interfaces/ICloudService.cs @@ -9,8 +9,6 @@ namespace DevHive.Services.Interfaces { Task> UploadFilesToCloud(List formFiles); - // Task> GetFilesFromCloud(List fileUrls); - Task RemoveFilesFromCloud(List fileUrls); } } diff --git a/src/Services/DevHive.Services/Interfaces/IRoleService.cs b/src/Services/DevHive.Services/Interfaces/IRoleService.cs index 2c31b06..05df917 100644 --- a/src/Services/DevHive.Services/Interfaces/IRoleService.cs +++ b/src/Services/DevHive.Services/Interfaces/IRoleService.cs @@ -6,7 +6,7 @@ namespace DevHive.Services.Interfaces { public interface IRoleService { - Task CreateRole(CreateRoleServiceModel roleServiceModel); + Task CreateRole(CreateRoleServiceModel createRoleServiceModel); Task GetRoleById(Guid id); diff --git a/src/Services/DevHive.Services/Options/JWTOptions.cs b/src/Services/DevHive.Services/Options/JWTOptions.cs deleted file mode 100644 index 95458f5..0000000 --- a/src/Services/DevHive.Services/Options/JWTOptions.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Microsoft.Extensions.Options; - -namespace DevHive.Services.Options -{ - public class JWTOptions - { - public JWTOptions(string secret) - { - this.Secret = secret; - } - - public string Secret { get; init; } - } -} diff --git a/src/Services/DevHive.Services/Options/JwtOptions.cs b/src/Services/DevHive.Services/Options/JwtOptions.cs new file mode 100644 index 0000000..d973f45 --- /dev/null +++ b/src/Services/DevHive.Services/Options/JwtOptions.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.Options; + +namespace DevHive.Services.Options +{ + public class JwtOptions + { + public JwtOptions(string secret) + { + this.Secret = secret; + } + + public string Secret { get; init; } + } +} diff --git a/src/Services/DevHive.Services/Services/FeedService.cs b/src/Services/DevHive.Services/Services/FeedService.cs index 5feef6e..17cc43f 100644 --- a/src/Services/DevHive.Services/Services/FeedService.cs +++ b/src/Services/DevHive.Services/Services/FeedService.cs @@ -57,7 +57,7 @@ namespace DevHive.Services.Services /// /// This method is used in the profile pages. - /// See the FeedRepository "GetUsersPosts" menthod for more information on how it works. + /// See the FeedRepository "GetUsersPosts" method for more information on how it works. /// public async Task GetUserPage(GetPageServiceModel model) { diff --git a/src/Services/DevHive.Services/Services/PostService.cs b/src/Services/DevHive.Services/Services/PostService.cs index 0becd9f..a3d5117 100644 --- a/src/Services/DevHive.Services/Services/PostService.cs +++ b/src/Services/DevHive.Services/Services/PostService.cs @@ -41,7 +41,7 @@ namespace DevHive.Services.Services if (createPostServiceModel.Files.Count != 0) { List fileUrls = await _cloudService.UploadFilesToCloud(createPostServiceModel.Files); - post.Attachments = this.GetPostAttachmentsFromUrls(post, fileUrls); + post.Attachments = GetPostAttachmentsFromUrls(post, fileUrls); } post.Creator = await this._userRepository.GetByIdAsync(createPostServiceModel.CreatorId); @@ -105,8 +105,8 @@ namespace DevHive.Services.Services } List fileUrls = await _cloudService.UploadFilesToCloud(updatePostServiceModel.Files) ?? - throw new ArgumentNullException("Unable to upload images to cloud"); - post.Attachments = this.GetPostAttachmentsFromUrls(post, fileUrls); + throw new ArgumentException("Unable to upload images to cloud!"); + post.Attachments = GetPostAttachmentsFromUrls(post, fileUrls); } post.Creator = await this._userRepository.GetByIdAsync(updatePostServiceModel.CreatorId); @@ -202,8 +202,7 @@ namespace DevHive.Services.Services { JwtSecurityToken jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); - Guid jwtUserId = Guid.Parse(this.GetClaimTypeValues("ID", jwt.Claims).First()); - //HashSet jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims); + Guid jwtUserId = Guid.Parse(GetClaimTypeValues("ID", jwt.Claims).First()); User user = await this._userRepository.GetByIdAsync(jwtUserId) ?? throw new ArgumentException("User does not exist!"); @@ -214,7 +213,7 @@ namespace DevHive.Services.Services /// /// Returns all values from a given claim type /// - private List GetClaimTypeValues(string type, IEnumerable claims) + private static List GetClaimTypeValues(string type, IEnumerable claims) { List toReturn = new(); @@ -227,9 +226,9 @@ namespace DevHive.Services.Services #endregion #region Misc - private List GetPostAttachmentsFromUrls(Post post, List fileUrls) + private static List GetPostAttachmentsFromUrls(Post post, List fileUrls) { - List postAttachments = new List(); + List postAttachments = new(); foreach (string url in fileUrls) postAttachments.Add(new PostAttachments { Post = post, FileUrl = url }); return postAttachments; diff --git a/src/Services/DevHive.Services/Services/RateService.cs b/src/Services/DevHive.Services/Services/RateService.cs index d423d8c..5e924ab 100644 --- a/src/Services/DevHive.Services/Services/RateService.cs +++ b/src/Services/DevHive.Services/Services/RateService.cs @@ -28,7 +28,7 @@ namespace DevHive.Services.Services { throw new NotImplementedException(); // if (!await this._postRepository.DoesPostExist(ratePostServiceModel.PostId)) - // throw new ArgumentException("Post does not exist!"); + // throw new ArgumentException("Post does not exist!"); // if (!await this._userRepository.DoesUserExistAsync(ratePostServiceModel.UserId)) // throw new ArgumentException("User does not exist!"); diff --git a/src/Services/DevHive.Services/Services/RoleService.cs b/src/Services/DevHive.Services/Services/RoleService.cs index 5472e44..1285421 100644 --- a/src/Services/DevHive.Services/Services/RoleService.cs +++ b/src/Services/DevHive.Services/Services/RoleService.cs @@ -5,7 +5,6 @@ using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; using DevHive.Services.Models.Role; -using DevHive.Services.Models.Language; namespace DevHive.Services.Services { @@ -20,17 +19,17 @@ namespace DevHive.Services.Services this._roleMapper = mapper; } - public async Task CreateRole(CreateRoleServiceModel roleServiceModel) + public async Task CreateRole(CreateRoleServiceModel createRoleServiceModel) { - if (await this._roleRepository.DoesNameExist(roleServiceModel.Name)) + if (await this._roleRepository.DoesNameExist(createRoleServiceModel.Name)) throw new ArgumentException("Role already exists!"); - Role role = this._roleMapper.Map(roleServiceModel); + Role role = this._roleMapper.Map(createRoleServiceModel); bool success = await this._roleRepository.AddAsync(role); if (success) { - Role newRole = await this._roleRepository.GetByNameAsync(roleServiceModel.Name); + Role newRole = await this._roleRepository.GetByNameAsync(createRoleServiceModel.Name); return newRole.Id; } else diff --git a/src/Services/DevHive.Services/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs index 9a63853..e31eb8d 100644 --- a/src/Services/DevHive.Services/Services/UserService.cs +++ b/src/Services/DevHive.Services/Services/UserService.cs @@ -28,7 +28,7 @@ namespace DevHive.Services.Services private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IMapper _userMapper; - private readonly JWTOptions _jwtOptions; + private readonly JwtOptions _jwtOptions; private readonly ICloudService _cloudService; public UserService(IUserRepository userRepository, @@ -38,7 +38,7 @@ namespace DevHive.Services.Services UserManager userManager, RoleManager roleManager, IMapper mapper, - JWTOptions jwtOptions, + JwtOptions jwtOptions, ICloudService cloudService) { this._userRepository = userRepository; @@ -128,7 +128,7 @@ namespace DevHive.Services.Services User currentUser = await this._userRepository.GetByIdAsync(updateUserServiceModel.Id); await this.PopulateUserModel(currentUser, updateUserServiceModel); - if (updateUserServiceModel.Friends.Count() > 0) + if (updateUserServiceModel.Friends.Count > 0) await this.CreateRelationToFriends(currentUser, updateUserServiceModel.Friends.ToList()); else currentUser.Friends.Clear(); @@ -157,7 +157,7 @@ namespace DevHive.Services.Services } string fileUrl = (await this._cloudService.UploadFilesToCloud(new List { updateProfilePictureServiceModel.Picture }))[0] ?? - throw new ArgumentNullException("Unable to upload profile picture to cloud"); + throw new ArgumentException("Unable to upload profile picture to cloud"); bool successful = await this._userRepository.UpdateProfilePicture(updateProfilePictureServiceModel.UserId, fileUrl); @@ -201,16 +201,13 @@ namespace DevHive.Services.Services /* Check if user is trying to do something to himself, unless he's an admin */ /* Check roles */ - if (!jwtRoleNames.Contains(Role.AdminRole)) - if (user.Id != id) - return false; + if (!jwtRoleNames.Contains(Role.AdminRole) && 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) - { if (!jwtRoleNames.Contains(role.Name)) return false; - } // Check if jwt contains only roles of user if (jwtRoleNames.Count != user.Roles.Count) diff --git a/src/Web/DevHive.Web.Models/Attributes/GoodPasswordAttribute.cs b/src/Web/DevHive.Web.Models/Attributes/GoodPasswordAttribute.cs new file mode 100644 index 0000000..c452499 --- /dev/null +++ b/src/Web/DevHive.Web.Models/Attributes/GoodPasswordAttribute.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations; + +namespace DevHive.Web.Models.Attributes +{ + public class GoodPasswordAttribute : ValidationAttribute + { + public override bool IsValid(object value) + { + var stringValue = (string)value; + + for (int i = 0; i < stringValue.Length; i++) + { + if (char.IsDigit(stringValue[i])) + { + base.ErrorMessage = "Password must be atleast 5 characters long!"; + return stringValue.Length >= 5; + } + } + base.ErrorMessage = "Password must contain atleast 1 digit!"; + return false; + } + } +} diff --git a/src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs b/src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs deleted file mode 100644 index 5ecb41a..0000000 --- a/src/Web/DevHive.Web.Models/Attributes/GoodPasswordModelValidation.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; - -namespace DevHive.Web.Models.Attributes -{ - public class GoodPassword : ValidationAttribute - { - public override bool IsValid(object value) - { - var stringValue = (string)value; - - for (int i = 0; i < stringValue.Length; i++) - { - if (Char.IsDigit(stringValue[i])) - { - base.ErrorMessage = "Password must be atleast 5 characters long!"; - return stringValue.Length >= 5; - } - } - base.ErrorMessage = "Password must contain atleast 1 digit!"; - return false; - } - } -} diff --git a/src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs b/src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs index 0f6adb1..faaeee4 100644 --- a/src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs +++ b/src/Web/DevHive.Web.Models/Attributes/OnlyLettersModelValidation.cs @@ -3,7 +3,7 @@ using System.ComponentModel.DataAnnotations; namespace DevHive.Web.Models.Attributes { - public class OnlyLetters : ValidationAttribute + public class OnlyLettersAttribute : ValidationAttribute { public override bool IsValid(object value) { @@ -11,7 +11,7 @@ namespace DevHive.Web.Models.Attributes foreach (char ch in stringValue) { - if (!Char.IsLetter(ch)) + if (!char.IsLetter(ch)) return false; } return true; diff --git a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj index ca49b8c..64d0bd0 100644 --- a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj +++ b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj @@ -3,10 +3,10 @@ net5.0 - + - - + + - + \ No newline at end of file diff --git a/src/Web/DevHive.Web.Models/Post/ReadPostWebModel.cs b/src/Web/DevHive.Web.Models/Post/ReadPostWebModel.cs index 8238f47..3ae93aa 100644 --- a/src/Web/DevHive.Web.Models/Post/ReadPostWebModel.cs +++ b/src/Web/DevHive.Web.Models/Post/ReadPostWebModel.cs @@ -21,6 +21,5 @@ namespace DevHive.Web.Models.Post public List Comments { get; set; } public List FileUrls { get; set; } - // public List Files { get; set; } } } diff --git a/src/Web/DevHive.Web.Tests/CommentController.Tests.cs b/src/Web/DevHive.Web.Tests/CommentController.Tests.cs index 3a03f1a..98397e7 100644 --- a/src/Web/DevHive.Web.Tests/CommentController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/CommentController.Tests.cs @@ -35,11 +35,11 @@ namespace DevHive.Web.Tests public void AddComment_ReturnsOkObjectResult_WhenCommentIsSuccessfullyCreated() { Guid id = Guid.NewGuid(); - CreateCommentWebModel createCommentWebModel = new CreateCommentWebModel + CreateCommentWebModel createCommentWebModel = new() { Message = MESSAGE }; - CreateCommentServiceModel createCommentServiceModel = new CreateCommentServiceModel + CreateCommentServiceModel createCommentServiceModel = new() { Message = MESSAGE }; @@ -67,11 +67,11 @@ namespace DevHive.Web.Tests public void AddComment_ReturnsBadRequestObjectResult_WhenCommentIsNotCreatedSuccessfully() { Guid id = Guid.NewGuid(); - CreateCommentWebModel createCommentWebModel = new CreateCommentWebModel + CreateCommentWebModel createCommentWebModel = new() { Message = MESSAGE }; - CreateCommentServiceModel createCommentServiceModel = new CreateCommentServiceModel + CreateCommentServiceModel createCommentServiceModel = new() { Message = MESSAGE }; @@ -86,8 +86,8 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); - BadRequestObjectResult badRequsetObjectResult = result as BadRequestObjectResult; - string resultMessage = badRequsetObjectResult.Value.ToString(); + BadRequestObjectResult badRequestObjectResult = result as BadRequestObjectResult; + string resultMessage = badRequestObjectResult.Value.ToString(); Assert.AreEqual(errorMessage, resultMessage); } @@ -95,8 +95,7 @@ namespace DevHive.Web.Tests [Test] public void AddComment_ReturnsUnauthorizedResult_WhenUserIsNotAuthorized() { - Guid id = Guid.NewGuid(); - CreateCommentWebModel createCommentWebModel = new CreateCommentWebModel + CreateCommentWebModel createCommentWebModel = new() { Message = MESSAGE }; @@ -115,11 +114,11 @@ namespace DevHive.Web.Tests { Guid id = Guid.NewGuid(); - ReadCommentServiceModel readCommentServiceModel = new ReadCommentServiceModel + ReadCommentServiceModel readCommentServiceModel = new() { Message = MESSAGE }; - ReadCommentWebModel readCommentWebModel = new ReadCommentWebModel + ReadCommentWebModel readCommentWebModel = new() { Message = MESSAGE }; @@ -132,7 +131,7 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); OkObjectResult okObjectResult = result as OkObjectResult; - ReadCommentWebModel resultModel = okObjectResult.Value as Models.Comment.ReadCommentWebModel; + ReadCommentWebModel resultModel = okObjectResult.Value as ReadCommentWebModel; Assert.AreEqual(MESSAGE, resultModel.Message); } @@ -143,11 +142,11 @@ namespace DevHive.Web.Tests public void Update_ShouldReturnOkResult_WhenCommentIsUpdatedSuccessfully() { Guid id = Guid.NewGuid(); - UpdateCommentWebModel updateCommentWebModel = new UpdateCommentWebModel + UpdateCommentWebModel updateCommentWebModel = new() { NewMessage = MESSAGE }; - UpdateCommentServiceModel updateCommentServiceModel = new UpdateCommentServiceModel + UpdateCommentServiceModel updateCommentServiceModel = new() { NewMessage = MESSAGE }; @@ -171,11 +170,11 @@ namespace DevHive.Web.Tests public void Update_ShouldReturnBadObjectResult_WhenCommentIsNotUpdatedSuccessfully() { string message = "Unable to update comment!"; - UpdateCommentWebModel updateCommentWebModel = new UpdateCommentWebModel + UpdateCommentWebModel updateCommentWebModel = new() { NewMessage = MESSAGE }; - UpdateCommentServiceModel updateCommentServiceModel = new UpdateCommentServiceModel + UpdateCommentServiceModel updateCommentServiceModel = new() { NewMessage = MESSAGE }; @@ -196,7 +195,7 @@ namespace DevHive.Web.Tests [Test] public void Update_ShouldReturnUnauthorizedResult_WhenUserIsNotAuthorized() { - UpdateCommentWebModel updateCommentWebModel = new UpdateCommentWebModel + UpdateCommentWebModel updateCommentWebModel = new() { NewMessage = MESSAGE }; @@ -224,7 +223,7 @@ namespace DevHive.Web.Tests } [Test] - public void DeletComment_ReturnsBadRequestObjectResult_WhenCommentIsNotDeletedSuccessfully() + public void DeleteComment_ReturnsBadRequestObjectResult_WhenCommentIsNotDeletedSuccessfully() { string message = "Could not delete Comment"; Guid id = Guid.NewGuid(); @@ -243,7 +242,7 @@ namespace DevHive.Web.Tests } [Test] - public void DeletComment_ReturnsUnauthorizedResult_WhenUserIsNotAuthorized() + public void DeleteComment_ReturnsUnauthorizedResult_WhenUserIsNotAuthorized() { this.CommentServiceMock.Setup(p => p.ValidateJwtForComment(It.IsAny(), It.IsAny())).Returns(Task.FromResult(false)); diff --git a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj index f8390de..465698c 100644 --- a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj +++ b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj @@ -4,13 +4,14 @@ false - - - - + + + + + - + true diff --git a/src/Web/DevHive.Web.Tests/LanguageController.Tests.cs b/src/Web/DevHive.Web.Tests/LanguageController.Tests.cs index 7c8d64e..af4672a 100644 --- a/src/Web/DevHive.Web.Tests/LanguageController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/LanguageController.Tests.cs @@ -81,8 +81,8 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); - BadRequestObjectResult badRequsetObjectResult = result as BadRequestObjectResult; - string resultMessage = badRequsetObjectResult.Value.ToString(); + BadRequestObjectResult badRequestObjectResult = result as BadRequestObjectResult; + string resultMessage = badRequestObjectResult.Value.ToString(); Assert.AreEqual(errorMessage, resultMessage); } diff --git a/src/Web/DevHive.Web.Tests/PostController.Tests.cs b/src/Web/DevHive.Web.Tests/PostController.Tests.cs index 96b0356..f10f8dd 100644 --- a/src/Web/DevHive.Web.Tests/PostController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/PostController.Tests.cs @@ -32,11 +32,11 @@ namespace DevHive.Web.Tests [Test] public void CreatePost_ReturnsOkObjectResult_WhenPostIsSuccessfullyCreated() { - CreatePostWebModel createPostWebModel = new CreatePostWebModel + CreatePostWebModel createPostWebModel = new() { Message = MESSAGE }; - CreatePostServiceModel createPostServiceModel = new CreatePostServiceModel + CreatePostServiceModel createPostServiceModel = new() { Message = MESSAGE }; @@ -64,11 +64,11 @@ namespace DevHive.Web.Tests [Test] public void CreatePost_ReturnsBadRequestObjectResult_WhenPostIsNotCreatedSuccessfully() { - CreatePostWebModel createTechnologyWebModel = new CreatePostWebModel + CreatePostWebModel createTechnologyWebModel = new() { Message = MESSAGE }; - CreatePostServiceModel createTechnologyServiceModel = new CreatePostServiceModel + CreatePostServiceModel createTechnologyServiceModel = new() { Message = MESSAGE }; @@ -83,8 +83,8 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); - BadRequestObjectResult badRequsetObjectResult = result as BadRequestObjectResult; - string resultMessage = badRequsetObjectResult.Value.ToString(); + BadRequestObjectResult badRequestObjectResult = result as BadRequestObjectResult; + string resultMessage = badRequestObjectResult.Value.ToString(); Assert.AreEqual(errorMessage, resultMessage); } @@ -92,8 +92,7 @@ namespace DevHive.Web.Tests [Test] public void CreatePost_ReturnsUnauthorizedResult_WhenUserIsNotAuthorized() { - Guid id = Guid.NewGuid(); - CreatePostWebModel createPostWebModel = new CreatePostWebModel + CreatePostWebModel createPostWebModel = new() { Message = MESSAGE }; @@ -112,11 +111,11 @@ namespace DevHive.Web.Tests { Guid id = Guid.NewGuid(); - ReadPostServiceModel readPostServiceModel = new ReadPostServiceModel + ReadPostServiceModel readPostServiceModel = new() { Message = MESSAGE }; - ReadPostWebModel readPostWebModel = new ReadPostWebModel + ReadPostWebModel readPostWebModel = new() { Message = MESSAGE }; @@ -140,11 +139,11 @@ namespace DevHive.Web.Tests public void Update_ShouldReturnOkResult_WhenPostIsUpdatedSuccessfully() { Guid id = Guid.NewGuid(); - UpdatePostWebModel updatePostWebModel = new UpdatePostWebModel + UpdatePostWebModel updatePostWebModel = new() { NewMessage = MESSAGE }; - UpdatePostServiceModel updatePostServiceModel = new UpdatePostServiceModel + UpdatePostServiceModel updatePostServiceModel = new() { NewMessage = MESSAGE }; @@ -163,11 +162,11 @@ namespace DevHive.Web.Tests { Guid id = Guid.NewGuid(); string message = "Could not update post!"; - UpdatePostWebModel updatePostWebModel = new UpdatePostWebModel + UpdatePostWebModel updatePostWebModel = new() { NewMessage = MESSAGE }; - UpdatePostServiceModel updatePostServiceModel = new UpdatePostServiceModel + UpdatePostServiceModel updatePostServiceModel = new() { NewMessage = MESSAGE }; @@ -188,7 +187,7 @@ namespace DevHive.Web.Tests [Test] public void Update_ShouldReturnUnauthorizedResult_WhenUserIsNotAuthorized() { - UpdatePostWebModel updatePostWebModel = new UpdatePostWebModel + UpdatePostWebModel updatePostWebModel = new() { NewMessage = MESSAGE }; diff --git a/src/Web/DevHive.Web.Tests/RoleController.Tests.cs b/src/Web/DevHive.Web.Tests/RoleController.Tests.cs index 64e3f11..ff80dc0 100644 --- a/src/Web/DevHive.Web.Tests/RoleController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/RoleController.Tests.cs @@ -81,8 +81,8 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); - BadRequestObjectResult badRequsetObjectResult = result as BadRequestObjectResult; - string resultMessage = badRequsetObjectResult.Value.ToString(); + BadRequestObjectResult badRequestObjectResult = result as BadRequestObjectResult; + string resultMessage = badRequestObjectResult.Value.ToString(); Assert.AreEqual(errorMessage, resultMessage); } diff --git a/src/Web/DevHive.Web.Tests/TechnologyController.Tests.cs b/src/Web/DevHive.Web.Tests/TechnologyController.Tests.cs index 164bcbf..a00f1db 100644 --- a/src/Web/DevHive.Web.Tests/TechnologyController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/TechnologyController.Tests.cs @@ -84,8 +84,8 @@ namespace DevHive.Web.Tests Assert.IsInstanceOf(result); - BadRequestObjectResult badRequsetObjectResult = result as BadRequestObjectResult; - string resultMessage = badRequsetObjectResult.Value.ToString(); + BadRequestObjectResult badRequestObjectResult = result as BadRequestObjectResult; + string resultMessage = badRequestObjectResult.Value.ToString(); Assert.AreEqual(errorMessage, resultMessage); } diff --git a/src/Web/DevHive.Web.Tests/UserController.Tests.cs b/src/Web/DevHive.Web.Tests/UserController.Tests.cs index 7457ad7..13f618e 100644 --- a/src/Web/DevHive.Web.Tests/UserController.Tests.cs +++ b/src/Web/DevHive.Web.Tests/UserController.Tests.cs @@ -33,17 +33,17 @@ namespace DevHive.Web.Tests public void LoginUser_ReturnsOkObjectResult_WhenUserIsSuccessfullyLoggedIn() { Guid id = Guid.NewGuid(); - LoginWebModel loginWebModel = new LoginWebModel + LoginWebModel loginWebModel = new() { UserName = USERNAME }; - LoginServiceModel loginServiceModel = new LoginServiceModel + LoginServiceModel loginServiceModel = new() { UserName = USERNAME }; string token = "goshotrapov"; - TokenModel tokenModel = new TokenModel(token); - TokenWebModel tokenWebModel = new TokenWebModel(token); + TokenModel tokenModel = new(token); + TokenWebModel tokenWebModel = new(token); this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(loginServiceModel); this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(tokenWebModel); @@ -61,18 +61,17 @@ namespace DevHive.Web.Tests [Test] public void RegisterUser_ReturnsOkObjectResult_WhenUserIsSuccessfullyRegistered() { - Guid id = Guid.NewGuid(); - RegisterWebModel registerWebModel = new RegisterWebModel + RegisterWebModel registerWebModel = new() { UserName = USERNAME }; - RegisterServiceModel registerServiceModel = new RegisterServiceModel + RegisterServiceModel registerServiceModel = new() { UserName = USERNAME }; string token = "goshotrapov"; - TokenModel tokenModel = new TokenModel(token); - TokenWebModel tokenWebModel = new TokenWebModel(token); + TokenModel tokenModel = new(token); + TokenWebModel tokenWebModel = new(token); this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(registerServiceModel); this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(tokenWebModel); @@ -95,11 +94,11 @@ namespace DevHive.Web.Tests { Guid id = Guid.NewGuid(); - UserServiceModel userServiceModel = new UserServiceModel + UserServiceModel userServiceModel = new() { UserName = USERNAME }; - UserWebModel userWebModel = new UserWebModel + UserWebModel userWebModel = new() { UserName = USERNAME }; @@ -121,12 +120,6 @@ namespace DevHive.Web.Tests [Test] public void GetById_ReturnsUnauthorizedResult_WhenUserIsNotAuthorized() { - Guid id = Guid.NewGuid(); - UserWebModel userWebModel = new UserWebModel - { - UserName = USERNAME - }; - this.UserServiceMock.Setup(p => p.ValidJWT(It.IsAny(), It.IsAny())).Returns(Task.FromResult(false)); IActionResult result = this.UserController.GetById(Guid.NewGuid(), null).Result; @@ -137,12 +130,11 @@ namespace DevHive.Web.Tests [Test] public void GetUser_ReturnsTheUser_WhenItExists() { - Guid id = Guid.NewGuid(); - UserWebModel userWebModel = new UserWebModel + UserWebModel userWebModel = new() { UserName = USERNAME }; - UserServiceModel userServiceModel = new UserServiceModel + UserServiceModel userServiceModel = new() { UserName = USERNAME }; @@ -166,15 +158,15 @@ namespace DevHive.Web.Tests public void Update_ShouldReturnOkResult_WhenUserIsUpdatedSuccessfully() { Guid id = Guid.NewGuid(); - UpdateUserWebModel updateUserWebModel = new UpdateUserWebModel + UpdateUserWebModel updateUserWebModel = new() { UserName = USERNAME }; - UpdateUserServiceModel updateUserServiceModel = new UpdateUserServiceModel + UpdateUserServiceModel updateUserServiceModel = new() { UserName = USERNAME }; - UserServiceModel userServiceModel = new UserServiceModel + UserServiceModel userServiceModel = new() { UserName = USERNAME }; @@ -192,13 +184,13 @@ namespace DevHive.Web.Tests public void UpdateProfilePicture_ShouldReturnOkObjectResult_WhenProfilePictureIsUpdatedSuccessfully() { string profilePictureURL = "goshotrapov"; - UpdateProfilePictureWebModel updateProfilePictureWebModel = new UpdateProfilePictureWebModel(); - UpdateProfilePictureServiceModel updateProfilePictureServiceModel = new UpdateProfilePictureServiceModel(); - ProfilePictureServiceModel profilePictureServiceModel = new ProfilePictureServiceModel + UpdateProfilePictureWebModel updateProfilePictureWebModel = new(); + UpdateProfilePictureServiceModel updateProfilePictureServiceModel = new(); + ProfilePictureServiceModel profilePictureServiceModel = new() { ProfilePictureURL = profilePictureURL }; - ProfilePictureWebModel profilePictureWebModel = new ProfilePictureWebModel + ProfilePictureWebModel profilePictureWebModel = new() { ProfilePictureURL = profilePictureURL }; diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs index 8b7d657..0b8194e 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs @@ -1,6 +1,5 @@ using System; using AutoMapper; -//using AutoMapper.Configuration; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; @@ -15,10 +14,10 @@ namespace DevHive.Web.Configurations.Extensions public static void UseAutoMapperConfiguration(this IApplicationBuilder app) { - var config = new MapperConfiguration(cfg => + _ = new MapperConfiguration(cfg => { cfg.AllowNullCollections = true; }); } } -} \ No newline at end of file +} diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs index 286727f..c017a8c 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs @@ -6,8 +6,6 @@ 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/Web/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs deleted file mode 100644 index d422bc8..0000000 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJWT.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Text; -using System.Threading.Tasks; -using DevHive.Services.Options; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.IdentityModel.Tokens; - -namespace DevHive.Web.Configurations.Extensions -{ - public static class JWTExtensions - { - public static void JWTConfiguration(this IServiceCollection services, IConfiguration configuration) - { - services.AddSingleton(new JWTOptions(configuration - .GetSection("AppSettings") - .GetSection("Secret") - .Value)); - - // Get key from appsettings.json - var key = Encoding.ASCII.GetBytes(configuration - .GetSection("AppSettings") - .GetSection("Secret") - .Value); - - // Setup Jwt Authentication - services.AddAuthentication(x => - { - x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddJwtBearer(x => - { - x.Events = new JwtBearerEvents - { - OnTokenValidated = context => - { - // TODO: add more authentication - return Task.CompletedTask; - } - }; - x.RequireHttpsMetadata = false; - x.SaveToken = true; - x.TokenValidationParameters = new TokenValidationParameters - { - //ValidateIssuerSigningKey = false, - IssuerSigningKey = new SymmetricSecurityKey(key), - ValidateIssuer = false, - ValidateAudience = false - }; - }); - } - } -} \ No newline at end of file diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs new file mode 100644 index 0000000..03d4b11 --- /dev/null +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs @@ -0,0 +1,54 @@ +using System.Text; +using System.Threading.Tasks; +using DevHive.Services.Options; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureJwt + { + public static void JWTConfiguration(this IServiceCollection services, IConfiguration configuration) + { + services.AddSingleton(new JwtOptions(configuration + .GetSection("AppSettings") + .GetSection("Secret") + .Value)); + + // Get key from appsettings.json + var key = Encoding.ASCII.GetBytes(configuration + .GetSection("AppSettings") + .GetSection("Secret") + .Value); + + // Setup Jwt Authentication + services.AddAuthentication(x => + { + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.Events = new JwtBearerEvents + { + OnTokenValidated = context => + { + // TODO: add more authentication + return Task.CompletedTask; + } + }; + x.RequireHttpsMetadata = false; + x.SaveToken = true; + x.TokenValidationParameters = new TokenValidationParameters + { + //ValidateIssuerSigningKey = false, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateAudience = false + }; + }); + } + } +} diff --git a/src/Web/DevHive.Web/DevHive.Web.csproj b/src/Web/DevHive.Web/DevHive.Web.csproj index 6f78b69..6511c37 100644 --- a/src/Web/DevHive.Web/DevHive.Web.csproj +++ b/src/Web/DevHive.Web/DevHive.Web.csproj @@ -7,21 +7,22 @@ latest - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - - + + + + + + + - - + + \ No newline at end of file diff --git a/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs b/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs index cb6d4ca..f159b69 100644 --- a/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs +++ b/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs @@ -9,18 +9,11 @@ namespace DevHive.Web.Middleware public class ExceptionMiddleware { private readonly RequestDelegate _next; - // private readonly ILogger _logger; public ExceptionMiddleware(RequestDelegate next) { this._next = next; - // this._logger = logger; } - // public ExceptionMiddleware(RequestDelegate next, ILogger logger) - // { - // this._logger = logger; - // this._next = next; - // } public async Task InvokeAsync(HttpContext httpContext) { @@ -30,20 +23,19 @@ namespace DevHive.Web.Middleware } catch (Exception ex) { - // this._logger.LogError($"Something went wrong: {ex}"); await HandleExceptionAsync(httpContext, ex); } } - private Task HandleExceptionAsync(HttpContext context, Exception exception) + private static Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return context.Response.WriteAsync(new { - StatusCode = context.Response.StatusCode, - Message = exception.Message + context.Response.StatusCode, + exception.Message }.ToString()); } } -- cgit v1.2.3 From 72502154725594cf31878aa944f4bc9d9f3521a3 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 16 Feb 2021 18:07:51 +0200 Subject: UserManager&RoleManager logic moved to Repo; Password hashing and validation moved to Repo and using ASPNET Core hashing methods; Added Migrations; Fixed Roles not added to user --- src/.stylecop.json | 25 + .../Misc/PasswordModifications.cs | 13 - src/Data/DevHive.Data.Models/User.cs | 2 +- src/Data/DevHive.Data.Tests/UserRepositoryTests.cs | 8 +- .../DevHive.Data/Interfaces/IUserRepository.cs | 8 +- .../Migrations/20210216152915_Inital.Designer.cs | 667 +++++++++++++++++++++ .../Migrations/20210216152915_Inital.cs | 586 ++++++++++++++++++ .../Migrations/DevHiveContextModelSnapshot.cs | 665 ++++++++++++++++++++ .../DevHive.Data/Repositories/RoleRepository.cs | 37 +- .../DevHive.Data/Repositories/UserRepository.cs | 82 ++- .../DevHive.Services.Tests/UserService.Tests.cs | 2 +- .../Configurations/Mapping/UserMappings.cs | 9 +- .../DevHive.Services/Services/RoleService.cs | 4 +- .../DevHive.Services/Services/UserService.cs | 74 +-- .../Configurations/Extensions/ConfigureDatabase.cs | 12 +- src/Web/DevHive.Web/Controllers/UserController.cs | 9 +- src/Web/DevHive.Web/Startup.cs | 1 + 17 files changed, 2081 insertions(+), 123 deletions(-) create mode 100644 src/.stylecop.json delete mode 100644 src/Common/DevHive.Common.Models/Misc/PasswordModifications.cs create mode 100644 src/Data/DevHive.Data/Migrations/20210216152915_Inital.Designer.cs create mode 100644 src/Data/DevHive.Data/Migrations/20210216152915_Inital.cs create mode 100644 src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs (limited to 'src/Common') diff --git a/src/.stylecop.json b/src/.stylecop.json new file mode 100644 index 0000000..6954967 --- /dev/null +++ b/src/.stylecop.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "indentation": { + "useTabs": true, + "tabSize": 4, + "indentationSize": 4 + }, + "orderingRules": { + "elementOrder": [ + "kind", + "accessibility", + "constant", + "static", + "readonly" + ], + "blankLinesBetweenUsingGroups": "require", + "systemUsingDirectivesFirst": true, + "usingDirectivesPlacement": "outsideNamespace" + }, + "namingRules": { + + } + } +} diff --git a/src/Common/DevHive.Common.Models/Misc/PasswordModifications.cs b/src/Common/DevHive.Common.Models/Misc/PasswordModifications.cs deleted file mode 100644 index f10a334..0000000 --- a/src/Common/DevHive.Common.Models/Misc/PasswordModifications.cs +++ /dev/null @@ -1,13 +0,0 @@ -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/Data/DevHive.Data.Models/User.cs b/src/Data/DevHive.Data.Models/User.cs index bf4ea50..bac5425 100644 --- a/src/Data/DevHive.Data.Models/User.cs +++ b/src/Data/DevHive.Data.Models/User.cs @@ -14,7 +14,7 @@ namespace DevHive.Data.Models public string LastName { get; set; } - public ProfilePicture ProfilePicture { get; set; } + public ProfilePicture ProfilePicture { get; set; } = new() { PictureURL = "/assets/images/feed/profile-pic.png" }; public HashSet Languages { get; set; } = new(); diff --git a/src/Data/DevHive.Data.Tests/UserRepositoryTests.cs b/src/Data/DevHive.Data.Tests/UserRepositoryTests.cs index 43e9a36..5f84e34 100644 --- a/src/Data/DevHive.Data.Tests/UserRepositoryTests.cs +++ b/src/Data/DevHive.Data.Tests/UserRepositoryTests.cs @@ -234,7 +234,7 @@ namespace DevHive.Data.Tests // } #endregion - #region DoesUserHaveThisUsername + #region DoesUserHaveThisUsernameAsync [Test] public async Task DoesUserHaveThisUsername_ReturnsTrue_WhenUserHasTheGivenUsername() { @@ -242,9 +242,9 @@ namespace DevHive.Data.Tests this._context.Users.Add(dummyUser); await this._context.SaveChangesAsync(); - bool result = this._userRepository.DoesUserHaveThisUsername(dummyUser.Id, dummyUser.UserName); + bool result = this._userRepository.DoesUserHaveThisUsernameAsync(dummyUser.Id, dummyUser.UserName); - Assert.IsTrue(result, "DoesUserHaveThisUsername does not return true when the user has the given name"); + Assert.IsTrue(result, "DoesUserHaveThisUsernameAsync does not return true when the user has the given name"); } [Test] @@ -255,7 +255,7 @@ namespace DevHive.Data.Tests this._context.Users.Add(dummyUser); await this._context.SaveChangesAsync(); - bool result = this._userRepository.DoesUserHaveThisUsername(dummyUser.Id, username); + bool result = this._userRepository.DoesUserHaveThisUsernameAsync(dummyUser.Id, username); Assert.IsFalse(result, "DoesUserNameExistAsync does not return false when user doesnt have the given name"); } diff --git a/src/Data/DevHive.Data/Interfaces/IUserRepository.cs b/src/Data/DevHive.Data/Interfaces/IUserRepository.cs index 917809d..aec0eb3 100644 --- a/src/Data/DevHive.Data/Interfaces/IUserRepository.cs +++ b/src/Data/DevHive.Data/Interfaces/IUserRepository.cs @@ -8,15 +8,17 @@ namespace DevHive.Data.Interfaces { public interface IUserRepository : IRepository { - //Read + Task AddRoleToUser(User user, string roleName); + Task GetByUsernameAsync(string username); Task UpdateProfilePicture(Guid userId, string pictureUrl); - //Validations + Task VerifyPassword(User user, string password); + Task IsInRoleAsync(User user, string roleName); Task ValidateFriendsCollectionAsync(List usernames); Task DoesEmailExistAsync(string email); Task DoesUserExistAsync(Guid id); Task DoesUsernameExistAsync(string username); - bool DoesUserHaveThisUsername(Guid id, string username); + Task DoesUserHaveThisUsernameAsync(Guid id, string username); } } diff --git a/src/Data/DevHive.Data/Migrations/20210216152915_Inital.Designer.cs b/src/Data/DevHive.Data/Migrations/20210216152915_Inital.Designer.cs new file mode 100644 index 0000000..a85f657 --- /dev/null +++ b/src/Data/DevHive.Data/Migrations/20210216152915_Inital.Designer.cs @@ -0,0 +1,667 @@ +// +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("20210216152915_Inital")] + partial class Inital + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 63) + .HasAnnotation("ProductVersion", "5.0.3") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + 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("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("PostId") + .HasColumnType("uuid"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PostId") + .IsUnique(); + + b.ToTable("Rating"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.PostAttachments", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FileUrl") + .HasColumnType("text"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PostId"); + + b.ToTable("PostAttachments"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.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.Models.Relational.UserRate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Liked") + .HasColumnType("boolean"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PostId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRates"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Technologies"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("FirstName") + .HasColumnType("text"); + + b.Property("LastName") + .HasColumnType("text"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.HasIndex("UserId"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("AspNetUsers"); + }); + + modelBuilder.Entity("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") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + 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") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.Property("RolesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("RolesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("RoleUser"); + }); + + modelBuilder.Entity("TechnologyUser", b => + { + b.Property("TechnologiesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("TechnologiesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("TechnologyUser"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Comment", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Comments") + .HasForeignKey("CreatorId"); + + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany("Comments") + .HasForeignKey("PostId"); + + b.Navigation("Creator"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Posts") + .HasForeignKey("CreatorId"); + + b.Navigation("Creator"); + }); + + modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => + { + b.HasOne("DevHive.Data.Models.User", "User") + .WithOne("ProfilePicture") + .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Rating", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithOne("Rating") + .HasForeignKey("DevHive.Data.Models.Rating", "PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.PostAttachments", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany("Attachments") + .HasForeignKey("PostId"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.RatedPost", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany("RatedPosts") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.UserRate", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId"); + + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany() + .HasForeignKey("UserId"); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Friends") + .HasForeignKey("UserId"); + }); + + 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("Attachments"); + + b.Navigation("Comments"); + + b.Navigation("Rating"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Navigation("Comments"); + + b.Navigation("Friends"); + + b.Navigation("Posts"); + + b.Navigation("ProfilePicture"); + + b.Navigation("RatedPosts"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Data/DevHive.Data/Migrations/20210216152915_Inital.cs b/src/Data/DevHive.Data/Migrations/20210216152915_Inital.cs new file mode 100644 index 0000000..131501e --- /dev/null +++ b/src/Data/DevHive.Data/Migrations/20210216152915_Inital.cs @@ -0,0 +1,586 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Data.Migrations +{ + public partial class Inital : 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), + UserId = table.Column(type: "uuid", nullable: true), + UserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "boolean", nullable: false), + PasswordHash = table.Column(type: "text", nullable: true), + SecurityStamp = table.Column(type: "text", nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true), + PhoneNumber = table.Column(type: "text", nullable: true), + PhoneNumberConfirmed = table.Column(type: "boolean", nullable: false), + TwoFactorEnabled = table.Column(type: "boolean", nullable: false), + LockoutEnd = table.Column(type: "timestamp with time zone", nullable: true), + LockoutEnabled = table.Column(type: "boolean", nullable: false), + AccessFailedCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUsers_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "Languages", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Languages", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Technologies", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Technologies", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RoleId = table.Column(type: "uuid", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserClaims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + UserId = table.Column(type: "uuid", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserLogins", + columns: table => new + { + LoginProvider = table.Column(type: "text", nullable: false), + ProviderKey = table.Column(type: "text", nullable: false), + ProviderDisplayName = table.Column(type: "text", nullable: true), + UserId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserRoles", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + RoleId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserTokens", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + LoginProvider = table.Column(type: "text", nullable: false), + Name = table.Column(type: "text", nullable: false), + Value = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Posts", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + CreatorId = table.Column(type: "uuid", nullable: true), + Message = table.Column(type: "text", nullable: true), + TimeCreated = table.Column(type: "timestamp without time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Posts", x => x.Id); + table.ForeignKey( + name: "FK_Posts_AspNetUsers_CreatorId", + column: x => x.CreatorId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + 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.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: "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.CreateTable( + name: "Comments", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + PostId = table.Column(type: "uuid", nullable: true), + CreatorId = table.Column(type: "uuid", nullable: true), + Message = table.Column(type: "text", nullable: true), + TimeCreated = table.Column(type: "timestamp without time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Comments", x => x.Id); + table.ForeignKey( + name: "FK_Comments_AspNetUsers_CreatorId", + column: x => x.CreatorId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_Comments_Posts_PostId", + column: x => x.PostId, + principalTable: "Posts", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "PostAttachments", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + PostId = table.Column(type: "uuid", nullable: true), + FileUrl = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PostAttachments", x => x.Id); + table.ForeignKey( + name: "FK_PostAttachments_Posts_PostId", + column: x => x.PostId, + principalTable: "Posts", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "RatedPosts", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + PostId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RatedPosts", x => new { x.UserId, x.PostId }); + table.ForeignKey( + name: "FK_RatedPosts_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_RatedPosts_Posts_PostId", + column: x => x.PostId, + principalTable: "Posts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Rating", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + PostId = table.Column(type: "uuid", nullable: false), + Rate = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Rating", x => x.Id); + table.ForeignKey( + name: "FK_Rating_Posts_PostId", + column: x => x.PostId, + principalTable: "Posts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "UserRates", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: true), + Liked = table.Column(type: "boolean", nullable: false), + PostId = table.Column(type: "uuid", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserRates", x => x.Id); + table.ForeignKey( + name: "FK_UserRates_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_UserRates_Posts_PostId", + column: x => x.PostId, + principalTable: "Posts", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + 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_CreatorId", + table: "Comments", + column: "CreatorId"); + + migrationBuilder.CreateIndex( + name: "IX_Comments_PostId", + table: "Comments", + column: "PostId"); + + migrationBuilder.CreateIndex( + name: "IX_LanguageUser_UsersId", + table: "LanguageUser", + column: "UsersId"); + + migrationBuilder.CreateIndex( + name: "IX_PostAttachments_PostId", + table: "PostAttachments", + column: "PostId"); + + migrationBuilder.CreateIndex( + name: "IX_Posts_CreatorId", + table: "Posts", + column: "CreatorId"); + + migrationBuilder.CreateIndex( + name: "IX_ProfilePicture_UserId", + table: "ProfilePicture", + column: "UserId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RatedPosts_PostId", + table: "RatedPosts", + column: "PostId"); + + migrationBuilder.CreateIndex( + name: "IX_Rating_PostId", + table: "Rating", + column: "PostId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleUser_UsersId", + table: "RoleUser", + column: "UsersId"); + + migrationBuilder.CreateIndex( + name: "IX_TechnologyUser_UsersId", + table: "TechnologyUser", + column: "UsersId"); + + migrationBuilder.CreateIndex( + name: "IX_UserRates_PostId", + table: "UserRates", + column: "PostId"); + + migrationBuilder.CreateIndex( + name: "IX_UserRates_UserId", + table: "UserRates", + column: "UserId"); + } + + 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: "PostAttachments"); + + migrationBuilder.DropTable( + name: "ProfilePicture"); + + migrationBuilder.DropTable( + name: "RatedPosts"); + + migrationBuilder.DropTable( + name: "Rating"); + + migrationBuilder.DropTable( + name: "RoleUser"); + + migrationBuilder.DropTable( + name: "TechnologyUser"); + + migrationBuilder.DropTable( + name: "UserRates"); + + migrationBuilder.DropTable( + name: "Languages"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "Technologies"); + + migrationBuilder.DropTable( + name: "Posts"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + } + } +} diff --git a/src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs b/src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs new file mode 100644 index 0000000..8db3abf --- /dev/null +++ b/src/Data/DevHive.Data/Migrations/DevHiveContextModelSnapshot.cs @@ -0,0 +1,665 @@ +// +using System; +using DevHive.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace DevHive.Data.Migrations +{ + [DbContext(typeof(DevHiveContext))] + partial class DevHiveContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 63) + .HasAnnotation("ProductVersion", "5.0.3") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + 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("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("PostId") + .HasColumnType("uuid"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PostId") + .IsUnique(); + + b.ToTable("Rating"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.PostAttachments", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FileUrl") + .HasColumnType("text"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PostId"); + + b.ToTable("PostAttachments"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.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.Models.Relational.UserRate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Liked") + .HasColumnType("boolean"); + + b.Property("PostId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PostId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRates"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Technology", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Technologies"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("FirstName") + .HasColumnType("text"); + + b.Property("LastName") + .HasColumnType("text"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.HasIndex("UserId"); + + b.HasIndex("UserName") + .IsUnique(); + + b.ToTable("AspNetUsers"); + }); + + modelBuilder.Entity("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") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + 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") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + modelBuilder.Entity("RoleUser", b => + { + b.Property("RolesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("RolesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("RoleUser"); + }); + + modelBuilder.Entity("TechnologyUser", b => + { + b.Property("TechnologiesId") + .HasColumnType("uuid"); + + b.Property("UsersId") + .HasColumnType("uuid"); + + b.HasKey("TechnologiesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("TechnologyUser"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Comment", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Comments") + .HasForeignKey("CreatorId"); + + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany("Comments") + .HasForeignKey("PostId"); + + b.Navigation("Creator"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Post", b => + { + b.HasOne("DevHive.Data.Models.User", "Creator") + .WithMany("Posts") + .HasForeignKey("CreatorId"); + + b.Navigation("Creator"); + }); + + modelBuilder.Entity("DevHive.Data.Models.ProfilePicture", b => + { + b.HasOne("DevHive.Data.Models.User", "User") + .WithOne("ProfilePicture") + .HasForeignKey("DevHive.Data.Models.ProfilePicture", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Rating", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithOne("Rating") + .HasForeignKey("DevHive.Data.Models.Rating", "PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.PostAttachments", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany("Attachments") + .HasForeignKey("PostId"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.RatedPost", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany("RatedPosts") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.Relational.UserRate", b => + { + b.HasOne("DevHive.Data.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId"); + + b.HasOne("DevHive.Data.Models.User", "User") + .WithMany() + .HasForeignKey("UserId"); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.HasOne("DevHive.Data.Models.User", null) + .WithMany("Friends") + .HasForeignKey("UserId"); + }); + + 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("Attachments"); + + b.Navigation("Comments"); + + b.Navigation("Rating"); + }); + + modelBuilder.Entity("DevHive.Data.Models.User", b => + { + b.Navigation("Comments"); + + b.Navigation("Friends"); + + b.Navigation("Posts"); + + b.Navigation("ProfilePicture"); + + b.Navigation("RatedPosts"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Data/DevHive.Data/Repositories/RoleRepository.cs b/src/Data/DevHive.Data/Repositories/RoleRepository.cs index 7d07c1b..99e0634 100644 --- a/src/Data/DevHive.Data/Repositories/RoleRepository.cs +++ b/src/Data/DevHive.Data/Repositories/RoleRepository.cs @@ -2,53 +2,54 @@ using System; using System.Threading.Tasks; using DevHive.Data.Interfaces; using DevHive.Data.Models; +using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace DevHive.Data.Repositories { public class RoleRepository : BaseRepository, IRoleRepository { - private readonly DevHiveContext _context; + private readonly RoleManager _roleManager; - public RoleRepository(DevHiveContext context) + public RoleRepository(DevHiveContext context, RoleManager roleManager) : base(context) { - this._context = context; + this._roleManager = roleManager; } + #region Create + public override async Task AddAsync(Role entity) + { + IdentityResult result = await this._roleManager.CreateAsync(entity); + + return result.Succeeded; + } + #endregion + #region Read public async Task GetByNameAsync(string name) { - return await this._context.Roles - .FirstOrDefaultAsync(x => x.Name == name); + return await this._roleManager.FindByNameAsync(name); } #endregion public override async Task EditAsync(Guid id, Role newEntity) { - Role role = await this.GetByIdAsync(id); - - this._context - .Entry(role) - .CurrentValues - .SetValues(newEntity); + newEntity.Id = id; + IdentityResult result = await this._roleManager.UpdateAsync(newEntity); - return await this.SaveChangesAsync(); + return result.Succeeded; } #region Validations public async Task DoesNameExist(string name) { - return await this._context.Roles - .AsNoTracking() - .AnyAsync(r => r.Name == name); + return await this._roleManager.RoleExistsAsync(name); } public async Task DoesRoleExist(Guid id) { - return await this._context.Roles - .AsNoTracking() - .AnyAsync(r => r.Id == id); + return await this._roleManager.Roles.AnyAsync(r => r.Id == id); } #endregion } diff --git a/src/Data/DevHive.Data/Repositories/UserRepository.cs b/src/Data/DevHive.Data/Repositories/UserRepository.cs index 9fa6eca..d570480 100644 --- a/src/Data/DevHive.Data/Repositories/UserRepository.cs +++ b/src/Data/DevHive.Data/Repositories/UserRepository.cs @@ -1,12 +1,8 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.Linq; using System.Threading.Tasks; -using AutoMapper.Mappers; using DevHive.Data.Interfaces; using DevHive.Data.Models; -using DevHive.Data.Models.Relational; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; @@ -14,18 +10,42 @@ namespace DevHive.Data.Repositories { public class UserRepository : BaseRepository, IUserRepository { - private readonly DevHiveContext _context; + private readonly UserManager _userManager; + private readonly RoleManager _roleManager; - public UserRepository(DevHiveContext context) + public UserRepository(DevHiveContext context, UserManager userManager, RoleManager roleManager) : base(context) { - this._context = context; + this._userManager = userManager; + this._roleManager = roleManager; } + #region Create + public override async Task AddAsync(User entity) + { + entity.PasswordHash = this._userManager.PasswordHasher.HashPassword(entity, entity.PasswordHash).ToString(); + IdentityResult result = await this._userManager.CreateAsync(entity); + + return result.Succeeded; + } + + public async Task AddRoleToUser(User user, string roleName) + { + bool succeeded = (await this._userManager.AddToRoleAsync(user, roleName)).Succeeded; + if (succeeded) + { + user.Roles.Add(await this._roleManager.FindByNameAsync(roleName)); + succeeded = await this.SaveChangesAsync(); + } + + return succeeded; + } + #endregion + #region Read public override async Task GetByIdAsync(Guid id) { - return await this._context.Users + return await this._userManager.Users .Include(x => x.Roles) .Include(x => x.Languages) .Include(x => x.Technologies) @@ -37,7 +57,7 @@ namespace DevHive.Data.Repositories public async Task GetByUsernameAsync(string username) { - return await this._context.Users + return await this._userManager.Users .Include(x => x.Roles) .Include(x => x.Languages) .Include(x => x.Technologies) @@ -49,6 +69,14 @@ namespace DevHive.Data.Repositories #endregion #region Update + public override async Task EditAsync(Guid id, User newEntity) + { + newEntity.Id = id; + IdentityResult result = await this._userManager.UpdateAsync(newEntity); + + return result.Succeeded; + } + public async Task UpdateProfilePicture(Guid userId, string pictureUrl) { User user = await this.GetByIdAsync(userId); @@ -59,24 +87,41 @@ namespace DevHive.Data.Repositories } #endregion + #region Delete + public override async Task DeleteAsync(User entity) + { + IdentityResult result = await this._userManager.DeleteAsync(entity); + + return result.Succeeded; + } + #endregion + #region Validations + public async Task VerifyPassword(User user, string password) + { + return await this._userManager.CheckPasswordAsync(user, password); + } + + public async Task IsInRoleAsync(User user, string roleName) + { + return await this._userManager.IsInRoleAsync(user, roleName); + } + public async Task DoesUserExistAsync(Guid id) { - return await this._context.Users - .AsNoTracking() - .AnyAsync(x => x.Id == id); + return await this._userManager.Users.AnyAsync(x => x.Id == id); } public async Task DoesUsernameExistAsync(string username) { - return await this._context.Users + return await this._userManager.Users .AsNoTracking() .AnyAsync(u => u.UserName == username); } public async Task DoesEmailExistAsync(string email) { - return await this._context.Users + return await this._userManager.Users .AsNoTracking() .AnyAsync(u => u.Email == email); } @@ -87,7 +132,7 @@ namespace DevHive.Data.Repositories foreach (var username in usernames) { - if (!await this._context.Users.AnyAsync(x => x.UserName == username)) + if (!await this.DoesUsernameExistAsync(username)) { valid = false; break; @@ -96,11 +141,10 @@ namespace DevHive.Data.Repositories return valid; } - public bool DoesUserHaveThisUsername(Guid id, string username) + public async Task DoesUserHaveThisUsernameAsync(Guid id, string username) { - return this._context.Users - .AsNoTracking() - .Any(x => x.Id == id && + return await this._userManager.Users + .AnyAsync(x => x.Id == id && x.UserName == username); } #endregion diff --git a/src/Services/DevHive.Services.Tests/UserService.Tests.cs b/src/Services/DevHive.Services.Tests/UserService.Tests.cs index ce997c1..550106f 100644 --- a/src/Services/DevHive.Services.Tests/UserService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/UserService.Tests.cs @@ -274,7 +274,7 @@ namespace DevHive.Services.Tests // // this.UserRepositoryMock.Setup(p => p.DoesUserExistAsync(It.IsAny())).Returns(Task.FromResult(true)); // this.UserRepositoryMock.Setup(p => p.DoesUsernameExistAsync(It.IsAny())).Returns(Task.FromResult(false)); - // this.UserRepositoryMock.Setup(p => p.DoesUserHaveThisUsername(It.IsAny(), It.IsAny())).Returns(true); + // this.UserRepositoryMock.Setup(p => p.DoesUserHaveThisUsernameAsync(It.IsAny(), It.IsAny())).Returns(true); // this.UserRepositoryMock.Setup(p => p.EditAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(shouldPass)); // this.UserRepositoryMock.Setup(p => p.GetByIdAsync(It.IsAny())).Returns(Task.FromResult(user)); // this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(user); diff --git a/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs b/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs index 043fcb7..99b41a8 100644 --- a/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs +++ b/src/Services/DevHive.Services/Configurations/Mapping/UserMappings.cs @@ -1,8 +1,6 @@ using DevHive.Data.Models; using AutoMapper; using DevHive.Services.Models.User; -using DevHive.Common.Models.Misc; -using DevHive.Data.Models.Relational; namespace DevHive.Services.Configurations.Mapping { @@ -11,19 +9,18 @@ namespace DevHive.Services.Configurations.Mapping public UserMappings() { CreateMap(); - CreateMap(); + CreateMap() + .ForMember(dest => dest.PasswordHash, src => src.MapFrom(p => p.Password)); CreateMap() .ForMember(dest => dest.Friends, src => src.Ignore()); CreateMap() - .ForMember(dest => dest.Friends, src => src.Ignore()) - .AfterMap((src, dest) => dest.PasswordHash = PasswordModifications.GeneratePasswordHash(src.Password)); + .ForMember(dest => dest.Friends, src => src.Ignore()); CreateMap(); CreateMap() .ForMember(dest => dest.ProfilePictureURL, src => src.MapFrom(p => p.ProfilePicture.PictureURL)) .ForMember(dest => dest.Friends, src => src.MapFrom(p => p.Friends)); CreateMap() - .ForMember(x => x.Password, opt => opt.Ignore()) .ForMember(dest => dest.ProfilePictureURL, src => src.MapFrom(p => p.ProfilePicture.PictureURL)); CreateMap(); } diff --git a/src/Services/DevHive.Services/Services/RoleService.cs b/src/Services/DevHive.Services/Services/RoleService.cs index 1285421..a5da759 100644 --- a/src/Services/DevHive.Services/Services/RoleService.cs +++ b/src/Services/DevHive.Services/Services/RoleService.cs @@ -39,8 +39,8 @@ namespace DevHive.Services.Services public async Task GetRoleById(Guid id) { - Role role = await this._roleRepository.GetByIdAsync(id) - ?? throw new ArgumentException("Role does not exist!"); + Role role = await this._roleRepository.GetByIdAsync(id) ?? + throw new ArgumentException("Role does not exist!"); return this._roleMapper.Map(role); } diff --git a/src/Services/DevHive.Services/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs index e31eb8d..dfd45cc 100644 --- a/src/Services/DevHive.Services/Services/UserService.cs +++ b/src/Services/DevHive.Services/Services/UserService.cs @@ -15,7 +15,7 @@ using DevHive.Data.Interfaces; using System.Linq; using DevHive.Common.Models.Misc; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Identity; +using Newtonsoft.Json; namespace DevHive.Services.Services { @@ -25,8 +25,6 @@ namespace DevHive.Services.Services private readonly IRoleRepository _roleRepository; private readonly ILanguageRepository _languageRepository; private readonly ITechnologyRepository _technologyRepository; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; private readonly IMapper _userMapper; private readonly JwtOptions _jwtOptions; private readonly ICloudService _cloudService; @@ -35,8 +33,6 @@ namespace DevHive.Services.Services ILanguageRepository languageRepository, IRoleRepository roleRepository, ITechnologyRepository technologyRepository, - UserManager userManager, - RoleManager roleManager, IMapper mapper, JwtOptions jwtOptions, ICloudService cloudService) @@ -47,8 +43,6 @@ namespace DevHive.Services.Services this._jwtOptions = jwtOptions; this._languageRepository = languageRepository; this._technologyRepository = technologyRepository; - this._userManager = userManager; - this._roleManager = roleManager; this._cloudService = cloudService; } @@ -64,7 +58,7 @@ namespace DevHive.Services.Services User user = await this._userRepository.GetByUsernameAsync(loginModel.UserName); - if (user.PasswordHash != PasswordModifications.GeneratePasswordHash(loginModel.Password)) + if (!await this._userRepository.VerifyPassword(user, loginModel.Password)) throw new ArgumentException("Incorrect password!"); return new TokenModel(WriteJWTSecurityToken(user.Id, user.UserName, user.Roles)); @@ -82,22 +76,16 @@ namespace DevHive.Services.Services throw new ArgumentException("Email already exists!"); User user = this._userMapper.Map(registerModel); - user.PasswordHash = PasswordModifications.GeneratePasswordHash(registerModel.Password); - user.ProfilePicture = new ProfilePicture() { PictureURL = "/assets/images/feed/profile-pic.png" }; - // Make sure the default role exists - //TODO: Move when project starts - if (!await this._roleRepository.DoesNameExist(Role.DefaultRole)) - await this._roleRepository.AddAsync(new Role { Name = Role.DefaultRole }); + bool userResult = await this._userRepository.AddAsync(user); + bool roleResult = await this._userRepository.AddRoleToUser(user, Role.DefaultRole); - user.Roles.Add(await this._roleRepository.GetByNameAsync(Role.DefaultRole)); - - IdentityResult userResult = await this._userManager.CreateAsync(user); - User createdUser = await this._userRepository.GetByUsernameAsync(registerModel.UserName); - - if (!userResult.Succeeded) + if (!userResult) throw new ArgumentException("Unable to create a user"); + if (!roleResult) + throw new ArgumentException("Unable to add role to user"); + User createdUser = await this._userRepository.GetByUsernameAsync(registerModel.UserName); return new TokenModel(WriteJWTSecurityToken(createdUser.Id, createdUser.UserName, createdUser.Roles)); } #endregion @@ -125,20 +113,20 @@ namespace DevHive.Services.Services { await this.ValidateUserOnUpdate(updateUserServiceModel); - User currentUser = await this._userRepository.GetByIdAsync(updateUserServiceModel.Id); - await this.PopulateUserModel(currentUser, updateUserServiceModel); + User user = await this._userRepository.GetByIdAsync(updateUserServiceModel.Id); + await this.PopulateUserModel(user, updateUserServiceModel); if (updateUserServiceModel.Friends.Count > 0) - await this.CreateRelationToFriends(currentUser, updateUserServiceModel.Friends.ToList()); + await this.CreateRelationToFriends(user, updateUserServiceModel.Friends.ToList()); else - currentUser.Friends.Clear(); + user.Friends.Clear(); - IdentityResult result = await this._userManager.UpdateAsync(currentUser); + bool result = await this._userRepository.EditAsync(user.Id, user); - if (!result.Succeeded) + if (!result) throw new InvalidOperationException("Unable to edit user!"); - User newUser = await this._userRepository.GetByIdAsync(currentUser.Id); + User newUser = await this._userRepository.GetByIdAsync(user.Id); return this._userMapper.Map(newUser); } @@ -175,16 +163,14 @@ namespace DevHive.Services.Services throw new ArgumentException("User does not exist!"); User user = await this._userRepository.GetByIdAsync(id); - IdentityResult result = await this._userManager.DeleteAsync(user); - - return result.Succeeded; + return await this._userRepository.DeleteAsync(user); } #endregion #region Validations /// /// Checks whether the given user, gotten by the "id" property, - /// is the same user as the one in the token (uness the user in the token has the admin role) + /// is the same user as the one in the token (unless the user in the token has the admin role) /// and the roles in the token are the same as those in the user, gotten by the id in the token /// public async Task ValidJWT(Guid id, string rawTokenData) @@ -192,15 +178,16 @@ 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).First()); - List jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims); + Guid jwtUserID = new(UserService.GetClaimTypeValues("ID", jwt.Claims).First()); + List jwtRoleNames = UserService.GetClaimTypeValues("role", jwt.Claims); User user = await this._userRepository.GetByIdAsync(jwtUserID) ?? throw new ArgumentException("User does not exist!"); - /* Check if user is trying to do something to himself, unless he's an admin */ + /* Check if he is an admin */ + if (user.Roles.Any(x => x.Name == Role.AdminRole)) + return true; - /* Check roles */ if (!jwtRoleNames.Contains(Role.AdminRole) && user.Id != id) return false; @@ -219,7 +206,7 @@ namespace DevHive.Services.Services /// /// Returns all values from a given claim type /// - private List GetClaimTypeValues(string type, IEnumerable claims) + private static List GetClaimTypeValues(string type, IEnumerable claims) { List toReturn = new(); @@ -243,7 +230,7 @@ namespace DevHive.Services.Services if (updateUserServiceModel.Friends.Any(x => x.UserName == updateUserServiceModel.UserName)) throw new ArgumentException("You cant add yourself as a friend(sry, bro)!"); - if (!this._userRepository.DoesUserHaveThisUsername(updateUserServiceModel.Id, updateUserServiceModel.UserName) + if (!await this._userRepository.DoesUserHaveThisUsernameAsync(updateUserServiceModel.Id, updateUserServiceModel.UserName) && await this._userRepository.DoesUsernameExistAsync(updateUserServiceModel.UserName)) throw new ArgumentException("Username already exists!"); @@ -296,19 +283,16 @@ namespace DevHive.Services.Services if (!await this._roleRepository.DoesNameExist(Role.AdminRole)) { - Role adminRole = new() - { - Name = Role.AdminRole - }; + Role adminRole = new() { Name = Role.AdminRole }; adminRole.Users.Add(user); await this._roleRepository.AddAsync(adminRole); } - Role admin = await this._roleManager.FindByNameAsync(Role.AdminRole); + Role admin = await this._roleRepository.GetByNameAsync(Role.AdminRole); user.Roles.Add(admin); - await this._userManager.UpdateAsync(user); + await this._userRepository.EditAsync(user.Id, user); User newUser = await this._userRepository.GetByIdAsync(userId); @@ -323,7 +307,7 @@ namespace DevHive.Services.Services user.Email = updateUserServiceModel.Email; //Do NOT allow a user to change his roles, unless he is an Admin - bool isAdmin = await this._userManager.IsInRoleAsync(user, Role.AdminRole); + bool isAdmin = await this._userRepository.IsInRoleAsync(user, Role.AdminRole); if (isAdmin) { @@ -371,7 +355,7 @@ namespace DevHive.Services.Services user.Friends.Add(amigo); amigo.Friends.Add(user); - await this._userManager.UpdateAsync(amigo); + await this._userRepository.EditAsync(amigo.Id, amigo); } } #endregion diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 84108ae..687e83f 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -60,7 +60,7 @@ namespace DevHive.Web.Configurations.Extensions }); } - public static async Task UseDatabaseConfiguration(this IApplicationBuilder app) + public static void UseDatabaseConfiguration(this IApplicationBuilder app) { app.UseHttpsRedirection(); app.UseRouting(); @@ -75,21 +75,21 @@ namespace DevHive.Web.Configurations.Extensions var roleManager = (RoleManager)serviceScope.ServiceProvider.GetService(typeof(RoleManager)); - if (!await dbContext.Roles.AnyAsync(x => x.Name == Role.DefaultRole)) + if (!dbContext.Roles.Any(x => x.Name == Role.DefaultRole)) { Role defaultRole = new() { Name = Role.DefaultRole }; - await roleManager.CreateAsync(defaultRole); + roleManager.CreateAsync(defaultRole).Wait(); } - if (!await dbContext.Roles.AnyAsync(x => x.Name == Role.AdminRole)) + if (!dbContext.Roles.Any(x => x.Name == Role.AdminRole)) { Role adminRole = new() { Name = Role.AdminRole }; - await roleManager.CreateAsync(adminRole); + roleManager.CreateAsync(adminRole).Wait(); } - await dbContext.SaveChangesAsync(); + dbContext.SaveChanges(); } } } diff --git a/src/Web/DevHive.Web/Controllers/UserController.cs b/src/Web/DevHive.Web/Controllers/UserController.cs index 25faa8a..214fba7 100644 --- a/src/Web/DevHive.Web/Controllers/UserController.cs +++ b/src/Web/DevHive.Web/Controllers/UserController.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; -using Microsoft.Extensions.Hosting; namespace DevHive.Web.Controllers { @@ -32,8 +31,8 @@ namespace DevHive.Web.Controllers { LoginServiceModel loginServiceModel = this._userMapper.Map(loginModel); - TokenModel TokenModel = await this._userService.LoginUser(loginServiceModel); - TokenWebModel tokenWebModel = this._userMapper.Map(TokenModel); + TokenModel tokenModel = await this._userService.LoginUser(loginServiceModel); + TokenWebModel tokenWebModel = this._userMapper.Map(tokenModel); return new OkObjectResult(tokenWebModel); } @@ -45,8 +44,8 @@ namespace DevHive.Web.Controllers { RegisterServiceModel registerServiceModel = this._userMapper.Map(registerModel); - TokenModel TokenModel = await this._userService.RegisterUser(registerServiceModel); - TokenWebModel tokenWebModel = this._userMapper.Map(TokenModel); + TokenModel tokenModel = await this._userService.RegisterUser(registerServiceModel); + TokenWebModel tokenWebModel = this._userMapper.Map(tokenModel); return new CreatedResult("Register", tokenWebModel); } diff --git a/src/Web/DevHive.Web/Startup.cs b/src/Web/DevHive.Web/Startup.cs index 46521cf..dbcf131 100644 --- a/src/Web/DevHive.Web/Startup.cs +++ b/src/Web/DevHive.Web/Startup.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using DevHive.Web.Configurations.Extensions; using Newtonsoft.Json; +using System.Threading.Tasks; namespace DevHive.Web { -- cgit v1.2.3 From 4ff76dba5bc0c2db50629d4aae2aeb2281e60155 Mon Sep 17 00:00:00 2001 From: transtrike Date: Fri, 26 Feb 2021 17:59:37 +0200 Subject: Fixed Common project mistakes --- .../DevHive.Common.Models/DevHive.Common.Models.csproj | 13 +++++++++++++ src/Common/DevHive.Common/DevHive.Common.csproj | 11 +++++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj create mode 100644 src/Common/DevHive.Common/DevHive.Common.csproj (limited to 'src/Common') diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj new file mode 100644 index 0000000..f6d662c --- /dev/null +++ b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj @@ -0,0 +1,13 @@ + + + net5.0 + + + + + + + true + latest + + \ No newline at end of file diff --git a/src/Common/DevHive.Common/DevHive.Common.csproj b/src/Common/DevHive.Common/DevHive.Common.csproj new file mode 100644 index 0000000..7ec20b1 --- /dev/null +++ b/src/Common/DevHive.Common/DevHive.Common.csproj @@ -0,0 +1,11 @@ + + + + + + net5.0 + + + + + \ No newline at end of file -- cgit v1.2.3 From 784b5fc621f71fa94eddf276b0b932ba7d1aa873 Mon Sep 17 00:00:00 2001 From: transtrike Date: Fri, 26 Feb 2021 23:23:38 +0200 Subject: Fixed Project Restore Problem "Not Found" --- src/Common/DevHive.Common/DevHive.Common.csproj | 4 +-- .../DevHive.Services.Models.csproj | 9 +++--- .../DevHive.Services.Tests.csproj | 18 ++++++------ .../DevHive.Services/DevHive.Services.csproj | 20 ++++++++------ .../DevHive.Web.Models/DevHive.Web.Models.csproj | 9 +++--- src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj | 16 ++++++----- src/Web/DevHive.Web/DevHive.Web.csproj | 32 ++++++++++++---------- 7 files changed, 59 insertions(+), 49 deletions(-) (limited to 'src/Common') diff --git a/src/Common/DevHive.Common/DevHive.Common.csproj b/src/Common/DevHive.Common/DevHive.Common.csproj index 7ec20b1..cd60d85 100644 --- a/src/Common/DevHive.Common/DevHive.Common.csproj +++ b/src/Common/DevHive.Common/DevHive.Common.csproj @@ -1,6 +1,6 @@ - + net5.0 @@ -8,4 +8,4 @@ - \ No newline at end of file + diff --git a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj index 914efe0..6bbc60e 100644 --- a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj +++ b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj @@ -3,10 +3,11 @@ net5.0 - - + + - + + - \ No newline at end of file + diff --git a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj index 747a730..b3d0a32 100644 --- a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj +++ b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj @@ -4,18 +4,20 @@ false - - - - - - + + + + + + - + + + true latest - \ No newline at end of file + diff --git a/src/Services/DevHive.Services/DevHive.Services.csproj b/src/Services/DevHive.Services/DevHive.Services.csproj index 650a304..55d9d4e 100644 --- a/src/Services/DevHive.Services/DevHive.Services.csproj +++ b/src/Services/DevHive.Services/DevHive.Services.csproj @@ -3,23 +3,25 @@ net5.0 - + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - + + + + + - - + + + + true latest - \ No newline at end of file + diff --git a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj index 64d0bd0..7f3f577 100644 --- a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj +++ b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj @@ -3,10 +3,11 @@ net5.0 - + + - - + + - \ No newline at end of file + diff --git a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj index 22173ee..41afbd4 100644 --- a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj +++ b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj @@ -4,17 +4,19 @@ false - - - - - + + + + + - + + + true latest - \ No newline at end of file + diff --git a/src/Web/DevHive.Web/DevHive.Web.csproj b/src/Web/DevHive.Web/DevHive.Web.csproj index 6956613..a5b68ce 100644 --- a/src/Web/DevHive.Web/DevHive.Web.csproj +++ b/src/Web/DevHive.Web/DevHive.Web.csproj @@ -8,26 +8,28 @@ true - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - - - - - - - + + + + + + + + + + + - - + + + + -- cgit v1.2.3 From 83ae76a1b93c91cf7cfb5fc9ea1ef728ee47c839 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 27 Feb 2021 11:18:09 +0200 Subject: JWT Validations works; Introduced more bugs to fix later --- .../DevHive.Common.Models/DevHive.Common.csproj | 13 ---- .../DevHive.Common/Jwt/Interfaces/IJwtService.cs | 11 +++ src/Common/DevHive.Common/Jwt/JwtService.cs | 79 ++++++++++++++++++++++ src/DevHive.sln | 49 +++++++++----- .../DevHive.Services/Services/UserService.cs | 68 ++++++++++++------- .../Extensions/ConfigureDependencyInjection.cs | 12 +++- .../Controllers/ProfilePictureController.cs | 32 +++++++++ src/Web/DevHive.Web/Controllers/UserController.cs | 17 ----- src/Web/DevHive.Web/appsettings.json | 29 ++++---- 9 files changed, 225 insertions(+), 85 deletions(-) delete mode 100644 src/Common/DevHive.Common.Models/DevHive.Common.csproj create mode 100644 src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs create mode 100644 src/Common/DevHive.Common/Jwt/JwtService.cs create mode 100644 src/Web/DevHive.Web/Controllers/ProfilePictureController.cs (limited to 'src/Common') diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.csproj deleted file mode 100644 index f6d662c..0000000 --- a/src/Common/DevHive.Common.Models/DevHive.Common.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - net5.0 - - - - - - - true - latest - - \ No newline at end of file diff --git a/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs b/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs new file mode 100644 index 0000000..d2f1756 --- /dev/null +++ b/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace DevHive.Common.Jwt.Interfaces +{ + public interface IJwtService + { + string GenerateJwtToken(Guid userId, string username, List roleNames); + bool ValidateToken(string authToken); + } +} diff --git a/src/Common/DevHive.Common/Jwt/JwtService.cs b/src/Common/DevHive.Common/Jwt/JwtService.cs new file mode 100644 index 0000000..677353a --- /dev/null +++ b/src/Common/DevHive.Common/Jwt/JwtService.cs @@ -0,0 +1,79 @@ +using System; +using System.Buffers.Text; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Security.Principal; +using System.Text; +using DevHive.Common.Jwt.Interfaces; +using Microsoft.IdentityModel.Tokens; + +namespace DevHive.Common.Jwt +{ + public class JwtService : IJwtService + { + private readonly string _validationIssuer; + private readonly string _audience; + private readonly byte[] _signingKey; + + public JwtService(byte[] signingKey, string validationIssuer, string audience) + { + this._signingKey = signingKey; + this._validationIssuer = validationIssuer; + this._audience = audience; + } + + public string GenerateJwtToken(Guid userId, string username, List roleNames) + { + var securityKey = new SymmetricSecurityKey(this._signingKey); + var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); + + HashSet claims = new() + { + new Claim("ID", $"{userId}"), + new Claim("Username", username) + }; + + foreach (var roleName in roleNames) + claims.Add(new Claim(ClaimTypes.Role, roleName)); + + SecurityTokenDescriptor securityTokenDescriptor = new() + { + Issuer = this._validationIssuer, + Audience = this._audience, + Subject = new ClaimsIdentity(claims), + Expires = DateTime.Today.AddDays(7), + SigningCredentials = credentials, + }; + + JwtSecurityTokenHandler tokenHandler = new(); + SecurityToken token = tokenHandler.CreateToken(securityTokenDescriptor); + + return tokenHandler.WriteToken(token); + } + + public bool ValidateToken(string authToken) + { + var tokenHandler = new JwtSecurityTokenHandler(); + var validationParameters = GetValidationParameters(); + + //Validate edge case where user can delete other users + + IPrincipal principal = tokenHandler.ValidateToken(authToken.Remove(0, 7), validationParameters, out _); + return principal.Identity.IsAuthenticated; + } + + private TokenValidationParameters GetValidationParameters() + { + return new TokenValidationParameters() + { + ValidateLifetime = true, + ValidateAudience = true, + ValidateIssuer = true, + ValidIssuer = this._validationIssuer, + ValidAudience = this._audience, + IssuerSigningKey = new SymmetricSecurityKey(this._signingKey) + }; + } + } +} diff --git a/src/DevHive.sln b/src/DevHive.sln index 05bdcda..a202180 100644 --- a/src/DevHive.sln +++ b/src/DevHive.sln @@ -11,10 +11,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Data.Models", "Data EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Data.Tests", "Data\DevHive.Data.Tests\DevHive.Data.Tests.csproj", "{F056B3F1-B72D-4935-87EA-F7BFEA96AFB0}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{F2864A9D-70F1-452F-AAAC-AAFD8102ABAD}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Common", "Common\DevHive.Common.Models\DevHive.Common.csproj", "{5C3DFE9B-9690-475E-A0AE-D62315D38337}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Services", "Services", "{7CA79114-C359-4871-BFA7-0EA898B50AE4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Services", "Services\DevHive.Services\DevHive.Services.csproj", "{B5F22590-E3CE-4595-BE48-AA7F1797A6B8}" @@ -31,6 +27,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Web.Models", "Web\D EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Web.Tests", "Web\DevHive.Web.Tests\DevHive.Web.Tests.csproj", "{608273FF-01ED-48B3-B912-66CCDBF5572E}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{49B4EAF5-8F45-493F-A25A-7F37DAAE6B1E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Common", "Common\DevHive.Common\DevHive.Common.csproj", "{AAEC0516-A943-449E-A1E8-E0628BFFAA2E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevHive.Common.Models", "Common\DevHive.Common.Models\DevHive.Common.Models.csproj", "{3D63C965-A734-45D6-B75D-AFDCAB511293}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -80,18 +82,6 @@ Global {F056B3F1-B72D-4935-87EA-F7BFEA96AFB0}.Release|x64.Build.0 = Release|Any CPU {F056B3F1-B72D-4935-87EA-F7BFEA96AFB0}.Release|x86.ActiveCfg = Release|Any CPU {F056B3F1-B72D-4935-87EA-F7BFEA96AFB0}.Release|x86.Build.0 = Release|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Debug|x64.ActiveCfg = Debug|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Debug|x64.Build.0 = Debug|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Debug|x86.ActiveCfg = Debug|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Debug|x86.Build.0 = Debug|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Release|Any CPU.Build.0 = Release|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Release|x64.ActiveCfg = Release|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Release|x64.Build.0 = Release|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Release|x86.ActiveCfg = Release|Any CPU - {5C3DFE9B-9690-475E-A0AE-D62315D38337}.Release|x86.Build.0 = Release|Any CPU {B5F22590-E3CE-4595-BE48-AA7F1797A6B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B5F22590-E3CE-4595-BE48-AA7F1797A6B8}.Debug|Any CPU.Build.0 = Debug|Any CPU {B5F22590-E3CE-4595-BE48-AA7F1797A6B8}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -164,17 +154,42 @@ Global {608273FF-01ED-48B3-B912-66CCDBF5572E}.Release|x64.Build.0 = Release|Any CPU {608273FF-01ED-48B3-B912-66CCDBF5572E}.Release|x86.ActiveCfg = Release|Any CPU {608273FF-01ED-48B3-B912-66CCDBF5572E}.Release|x86.Build.0 = Release|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Debug|x64.ActiveCfg = Debug|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Debug|x64.Build.0 = Debug|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Debug|x86.ActiveCfg = Debug|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Debug|x86.Build.0 = Debug|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Release|Any CPU.Build.0 = Release|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Release|x64.ActiveCfg = Release|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Release|x64.Build.0 = Release|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Release|x86.ActiveCfg = Release|Any CPU + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E}.Release|x86.Build.0 = Release|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Debug|x64.ActiveCfg = Debug|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Debug|x64.Build.0 = Debug|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Debug|x86.ActiveCfg = Debug|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Debug|x86.Build.0 = Debug|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Release|Any CPU.Build.0 = Release|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Release|x64.ActiveCfg = Release|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Release|x64.Build.0 = Release|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Release|x86.ActiveCfg = Release|Any CPU + {3D63C965-A734-45D6-B75D-AFDCAB511293}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {70D0903D-C65F-4600-B6F8-F7BD00500A51} = {0C2AC7A9-AC68-4668-B88E-9370C596F498} {56F85916-3955-4558-8809-376D20902B94} = {0C2AC7A9-AC68-4668-B88E-9370C596F498} {F056B3F1-B72D-4935-87EA-F7BFEA96AFB0} = {0C2AC7A9-AC68-4668-B88E-9370C596F498} - {5C3DFE9B-9690-475E-A0AE-D62315D38337} = {F2864A9D-70F1-452F-AAAC-AAFD8102ABAD} {B5F22590-E3CE-4595-BE48-AA7F1797A6B8} = {7CA79114-C359-4871-BFA7-0EA898B50AE4} {2FFF985B-A26F-443D-A159-62ED2FD5A2BC} = {7CA79114-C359-4871-BFA7-0EA898B50AE4} {6E58003B-E5E8-4AA4-8F70-A9442BBFC110} = {7CA79114-C359-4871-BFA7-0EA898B50AE4} {A6D35BD9-A2A4-4937-89A8-DCB0D610B04A} = {768A592D-58EA-4CD3-A053-2E8F2DC7708A} {D8C898F7-A0DE-4939-8708-3D4A5C383EFC} = {768A592D-58EA-4CD3-A053-2E8F2DC7708A} {608273FF-01ED-48B3-B912-66CCDBF5572E} = {768A592D-58EA-4CD3-A053-2E8F2DC7708A} + {AAEC0516-A943-449E-A1E8-E0628BFFAA2E} = {49B4EAF5-8F45-493F-A25A-7F37DAAE6B1E} + {3D63C965-A734-45D6-B75D-AFDCAB511293} = {49B4EAF5-8F45-493F-A25A-7F37DAAE6B1E} EndGlobalSection EndGlobal diff --git a/src/Services/DevHive.Services/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs index dfd45cc..cbcb116 100644 --- a/src/Services/DevHive.Services/Services/UserService.cs +++ b/src/Services/DevHive.Services/Services/UserService.cs @@ -13,9 +13,9 @@ using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; using DevHive.Data.Interfaces; using System.Linq; -using DevHive.Common.Models.Misc; using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; +using DevHive.Common.Jwt; +using DevHive.Common.Jwt.Interfaces; namespace DevHive.Services.Services { @@ -28,6 +28,7 @@ namespace DevHive.Services.Services private readonly IMapper _userMapper; private readonly JwtOptions _jwtOptions; private readonly ICloudService _cloudService; + private readonly IJwtService _jwtService; public UserService(IUserRepository userRepository, ILanguageRepository languageRepository, @@ -35,7 +36,8 @@ namespace DevHive.Services.Services ITechnologyRepository technologyRepository, IMapper mapper, JwtOptions jwtOptions, - ICloudService cloudService) + ICloudService cloudService, + IJwtService jwtService) { this._userRepository = userRepository; this._roleRepository = roleRepository; @@ -44,6 +46,7 @@ namespace DevHive.Services.Services this._languageRepository = languageRepository; this._technologyRepository = technologyRepository; this._cloudService = cloudService; + this._jwtService = jwtService; } #region Authentication @@ -65,8 +68,10 @@ namespace DevHive.Services.Services } /// - /// Returns a new JSON Web Token (that can be used for authorization) for the given user + /// Register a user in the database and return a /// + /// Register model, containing registration information + /// A Token model, containing JWT Token for further verification public async Task RegisterUser(RegisterServiceModel registerModel) { if (await this._userRepository.DoesUsernameExistAsync(registerModel.UserName)) @@ -86,7 +91,12 @@ namespace DevHive.Services.Services throw new ArgumentException("Unable to add role to user"); User createdUser = await this._userRepository.GetByUsernameAsync(registerModel.UserName); - return new TokenModel(WriteJWTSecurityToken(createdUser.Id, createdUser.UserName, createdUser.Roles)); + List roleNames = createdUser + .Roles + .Select(x => x.Name) + .ToList(); + + return new TokenModel(this._jwtService.GenerateJwtToken(createdUser.Id, createdUser.UserName, roleNames)); } #endregion @@ -173,34 +183,38 @@ namespace DevHive.Services.Services /// is the same user as the one in the token (unless the user in the token has the admin role) /// and the roles in the token are the same as those in the user, gotten by the id in the token /// + /// + /// + /// public async Task ValidJWT(Guid id, string rawTokenData) { + return this._jwtService.ValidateToken(rawTokenData); // There is authorization name in the beginning, i.e. "Bearer eyJh..." - var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); + // var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); - Guid jwtUserID = new(UserService.GetClaimTypeValues("ID", jwt.Claims).First()); - List jwtRoleNames = UserService.GetClaimTypeValues("role", jwt.Claims); + // Guid jwtUserID = new(UserService.GetClaimTypeValues("ID", jwt.Claims).First()); + // List jwtRoleNames = UserService.GetClaimTypeValues("role", jwt.Claims); - User user = await this._userRepository.GetByIdAsync(jwtUserID) - ?? throw new ArgumentException("User does not exist!"); + // User user = await this._userRepository.GetByIdAsync(jwtUserID) + // ?? throw new ArgumentException("User does not exist!"); - /* Check if he is an admin */ - if (user.Roles.Any(x => x.Name == Role.AdminRole)) - return true; + // /* Check if he is an admin */ + // if (user.Roles.Any(x => x.Name == Role.AdminRole)) + // return true; - if (!jwtRoleNames.Contains(Role.AdminRole) && user.Id != id) - return false; + // if (!jwtRoleNames.Contains(Role.AdminRole) && 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) - if (!jwtRoleNames.Contains(role.Name)) - 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) + // if (!jwtRoleNames.Contains(role.Name)) + // return false; - // Check if jwt contains only roles of user - if (jwtRoleNames.Count != user.Roles.Count) - return false; + // // Check if jwt contains only roles of user + // if (jwtRoleNames.Count != user.Roles.Count) + // return false; - return true; + // return true; } /// @@ -294,9 +308,13 @@ namespace DevHive.Services.Services user.Roles.Add(admin); await this._userRepository.EditAsync(user.Id, user); - User newUser = await this._userRepository.GetByIdAsync(userId); + User createdUser = await this._userRepository.GetByIdAsync(userId); + List roleNames = createdUser + .Roles + .Select(x => x.Name) + .ToList(); - return new TokenModel(WriteJWTSecurityToken(newUser.Id, newUser.UserName, newUser.Roles)); + return new TokenModel(this._jwtService.GenerateJwtToken(createdUser.Id, createdUser.UserName, roleNames)); } private async Task PopulateUserModel(User user, UpdateUserServiceModel updateUserServiceModel) diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs index c547951..660a416 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -1,3 +1,6 @@ +using System.Text; +using DevHive.Common.Jwt; +using DevHive.Common.Jwt.Interfaces; using DevHive.Data.Interfaces; using DevHive.Data.Repositories; using DevHive.Services.Interfaces; @@ -27,12 +30,19 @@ namespace DevHive.Web.Configurations.Extensions services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(options => new CloudinaryService( cloudName: configuration.GetSection("Cloud").GetSection("cloudName").Value, apiKey: configuration.GetSection("Cloud").GetSection("apiKey").Value, apiSecret: configuration.GetSection("Cloud").GetSection("apiSecret").Value)); - services.AddTransient(); + + services.AddSingleton(options => + new JwtService( + signingKey: Encoding.ASCII.GetBytes(configuration.GetSection("Jwt").GetSection("signingKey").Value), + validationIssuer: configuration.GetSection("Jwt").GetSection("validationIssuer").Value, + audience: configuration.GetSection("Jwt").GetSection("audience").Value)); } } } diff --git a/src/Web/DevHive.Web/Controllers/ProfilePictureController.cs b/src/Web/DevHive.Web/Controllers/ProfilePictureController.cs new file mode 100644 index 0000000..d3971ff --- /dev/null +++ b/src/Web/DevHive.Web/Controllers/ProfilePictureController.cs @@ -0,0 +1,32 @@ +using System; +using System.Threading.Tasks; +using DevHive.Services.Models.User; +using DevHive.Web.Models.User; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace DevHive.Web.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class ProfilePictureController + { + [HttpPut] + [Route("ProfilePicture")] + [Authorize(Roles = "User,Admin")] + public async Task UpdateProfilePicture(Guid userId, [FromForm] UpdateProfilePictureWebModel updateProfilePictureWebModel, [FromHeader] string authorization) + { + throw new NotImplementedException(); + // 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); + } + } +} diff --git a/src/Web/DevHive.Web/Controllers/UserController.cs b/src/Web/DevHive.Web/Controllers/UserController.cs index 214fba7..a1e87f4 100644 --- a/src/Web/DevHive.Web/Controllers/UserController.cs +++ b/src/Web/DevHive.Web/Controllers/UserController.cs @@ -93,23 +93,6 @@ 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/Web/DevHive.Web/appsettings.json b/src/Web/DevHive.Web/appsettings.json index bcdcae7..b7e0ce5 100644 --- a/src/Web/DevHive.Web/appsettings.json +++ b/src/Web/DevHive.Web/appsettings.json @@ -1,20 +1,25 @@ { - "AppSettings": { - "Secret": "gXfQlU6qpDleFWyimscjYcT3tgFsQg3yoFjcvSLxG56n1Vu2yptdIUq254wlJWjm" - }, - "ConnectionStrings": { - "DEV": "Server=localhost;Port=5432;Database=API;User Id=postgres;Password=;" + "AppSettings": { + "Secret": "" + }, + "Jwt": { + "signingKey": "", + "validationIssuer": "", + "audience": "" + }, + "ConnectionStrings": { + "DEV": "Server=localhost;Port=5432;Database=API;User Id=postgres;Password=;" }, "Cloud": { "cloudName": "devhive", "apiKey": "488664116365813", "apiSecret": "" }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - } + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } } -- cgit v1.2.3 From e4331fe503547df8f17095540cbd4170bbaf2b25 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sun, 28 Feb 2021 10:31:37 +0200 Subject: JWT Working like a charm --- src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs | 2 +- src/Common/DevHive.Common/Jwt/JwtService.cs | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) (limited to 'src/Common') diff --git a/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs b/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs index d2f1756..6f844f5 100644 --- a/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs +++ b/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs @@ -6,6 +6,6 @@ namespace DevHive.Common.Jwt.Interfaces public interface IJwtService { string GenerateJwtToken(Guid userId, string username, List roleNames); - bool ValidateToken(string authToken); + bool ValidateToken(Guid userId, string rawToken); } } diff --git a/src/Common/DevHive.Common/Jwt/JwtService.cs b/src/Common/DevHive.Common/Jwt/JwtService.cs index 677353a..a0c49db 100644 --- a/src/Common/DevHive.Common/Jwt/JwtService.cs +++ b/src/Common/DevHive.Common/Jwt/JwtService.cs @@ -2,6 +2,7 @@ using System; using System.Buffers.Text; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; +using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Text; @@ -52,15 +53,23 @@ namespace DevHive.Common.Jwt return tokenHandler.WriteToken(token); } - public bool ValidateToken(string authToken) + public bool ValidateToken(Guid userId, string rawToken) { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = GetValidationParameters(); + string actualToken = rawToken.Remove(0, 7); - //Validate edge case where user can delete other users + IPrincipal principal = tokenHandler.ValidateToken(actualToken, validationParameters, out SecurityToken validatedToken); + JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(actualToken); - IPrincipal principal = tokenHandler.ValidateToken(authToken.Remove(0, 7), validationParameters, out _); - return principal.Identity.IsAuthenticated; + if (!principal.Identity.IsAuthenticated) + return false; + else if (principal.IsInRole("Admin")) + return true; + else if (jwtToken.Claims.FirstOrDefault(x => x.Type == "ID").Value != userId.ToString()) + return false; + else + return true; } private TokenValidationParameters GetValidationParameters() -- cgit v1.2.3 From 26b18fe3727507d1b47ffb53ed773f133122eee8 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sun, 28 Feb 2021 13:00:16 +0200 Subject: Integrated new JWT validation where needed --- src/.editorconfig | 5 +- .../DevHive.Common/Jwt/Interfaces/IJwtService.cs | 17 +++ src/Common/DevHive.Common/Jwt/JwtService.cs | 2 - .../DevHive.Services/Interfaces/IUserService.cs | 49 ++++++++- .../DevHive.Services/Services/UserService.cs | 117 +-------------------- .../DevHive.Web/Controllers/CommentController.cs | 10 +- src/Web/DevHive.Web/Controllers/PostController.cs | 10 +- src/Web/DevHive.Web/Controllers/UserController.cs | 12 ++- 8 files changed, 95 insertions(+), 127 deletions(-) (limited to 'src/Common') diff --git a/src/.editorconfig b/src/.editorconfig index ea2af21..9f0e74b 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -44,9 +44,10 @@ dotnet_diagnostic.IDE0055.severity = warning # Sort using and Import directives with System.* appearing first dotnet_sort_system_directives_first = true dotnet_separate_import_directive_groups = false + # Avoid "this." and "Me." if not necessary -dotnet_style_qualification_for_field = false:refactoring -dotnet_style_qualification_for_property = false:refactoring +dotnet_style_qualification_for_field = true:refactoring +dotnet_style_qualification_for_property = true:refactoring dotnet_style_qualification_for_method = false:refactoring dotnet_style_qualification_for_event = false:refactoring diff --git a/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs b/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs index 6f844f5..352a7d5 100644 --- a/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs +++ b/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs @@ -5,7 +5,24 @@ namespace DevHive.Common.Jwt.Interfaces { public interface IJwtService { + /// + /// The generation of a JWT, when a new user registers or log ins + /// Tokens have an expiration time of 7 days. + /// + /// User's Guid + /// Users's username + /// List of user's roles + /// Return a new JWT, containing the user id, username and roles. string GenerateJwtToken(Guid userId, string username, List roleNames); + + /// + /// Checks whether the given user, gotten by the "id" property, + /// is the same user as the one in the token (unless the user in the token has the admin role) + /// and the roles in the token are the same as those in the user, gotten by the id in the token + /// + /// Guid of the user being validated + /// The raw token coming from the request + /// Bool result of is the user authenticated to do an action bool ValidateToken(Guid userId, string rawToken); } } diff --git a/src/Common/DevHive.Common/Jwt/JwtService.cs b/src/Common/DevHive.Common/Jwt/JwtService.cs index a0c49db..9f316da 100644 --- a/src/Common/DevHive.Common/Jwt/JwtService.cs +++ b/src/Common/DevHive.Common/Jwt/JwtService.cs @@ -1,11 +1,9 @@ using System; -using System.Buffers.Text; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Security.Principal; -using System.Text; using DevHive.Common.Jwt.Interfaces; using Microsoft.IdentityModel.Tokens; diff --git a/src/Services/DevHive.Services/Interfaces/IUserService.cs b/src/Services/DevHive.Services/Interfaces/IUserService.cs index 4a9ffc8..a55f9dd 100644 --- a/src/Services/DevHive.Services/Interfaces/IUserService.cs +++ b/src/Services/DevHive.Services/Interfaces/IUserService.cs @@ -7,19 +7,64 @@ namespace DevHive.Services.Interfaces { public interface IUserService { + /// + /// Log ins an existing user and gives him/her a JWT Token for further authorization + /// + /// Login service model, conaining user's username and password + /// A JWT Token for authorization Task LoginUser(LoginServiceModel loginModel); + + /// + /// Registers a new user and gives him/her a JWT Token for further authorization + /// + /// Register service model, containing the new user's data + /// A JWT Token for authorization Task RegisterUser(RegisterServiceModel registerModel); + /// + /// Get a user by his username. Used for querying profiles without provided authentication + /// + /// User's username, who's to be queried + /// The queried user or null, if non existant Task GetUserByUsername(string username); + + /// + /// Get a user by his Guid. Used for querying full user's profile + /// Requires authenticated user + /// + /// User's username, who's to be queried + /// The queried user or null, if non existant Task GetUserById(Guid id); + /// + /// Updates a user's data, provided a full model with new details + /// Requires authenticated user + /// + /// Full update user model for updating + /// Read model of the new user Task UpdateUser(UpdateUserServiceModel updateUserServiceModel); + + /// + /// Uploads the given picture and assigns it's link to the user in the database + /// Requires authenticated user + /// + /// Contains User's Guid and the new picture to be updated + /// The new picture's URL Task UpdateProfilePicture(UpdateProfilePictureServiceModel updateProfilePictureServiceModel); + /// + /// Deletes a user from the database and removes his data entirely + /// Requires authenticated user + /// + /// The user's Guid, who's to be deleted + /// True if successfull, false otherwise Task DeleteUser(Guid id); - Task ValidJWT(Guid id, string rawTokenData); - + /// + /// We don't talk about that! + /// + /// + /// Task SuperSecretPromotionToAdmin(Guid userId); } } diff --git a/src/Services/DevHive.Services/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs index cbcb116..4f74b06 100644 --- a/src/Services/DevHive.Services/Services/UserService.cs +++ b/src/Services/DevHive.Services/Services/UserService.cs @@ -1,20 +1,14 @@ using AutoMapper; -using DevHive.Services.Options; using DevHive.Services.Models.User; using System.Threading.Tasks; using DevHive.Data.Models; using System; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; -using Microsoft.IdentityModel.Tokens; -using System.Text; using System.Collections.Generic; using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; using DevHive.Data.Interfaces; using System.Linq; using Microsoft.AspNetCore.Http; -using DevHive.Common.Jwt; using DevHive.Common.Jwt.Interfaces; namespace DevHive.Services.Services @@ -26,7 +20,6 @@ namespace DevHive.Services.Services private readonly ILanguageRepository _languageRepository; private readonly ITechnologyRepository _technologyRepository; private readonly IMapper _userMapper; - private readonly JwtOptions _jwtOptions; private readonly ICloudService _cloudService; private readonly IJwtService _jwtService; @@ -35,14 +28,12 @@ namespace DevHive.Services.Services IRoleRepository roleRepository, ITechnologyRepository technologyRepository, IMapper mapper, - JwtOptions jwtOptions, ICloudService cloudService, IJwtService jwtService) { this._userRepository = userRepository; this._roleRepository = roleRepository; this._userMapper = mapper; - this._jwtOptions = jwtOptions; this._languageRepository = languageRepository; this._technologyRepository = technologyRepository; this._cloudService = cloudService; @@ -50,10 +41,6 @@ namespace DevHive.Services.Services } #region Authentication - /// - /// Adds a new user to the database with the values from the given model. - /// Returns a JSON Web Token (that can be used for authorization) - /// public async Task LoginUser(LoginServiceModel loginModel) { if (!await this._userRepository.DoesUsernameExistAsync(loginModel.UserName)) @@ -64,14 +51,10 @@ namespace DevHive.Services.Services if (!await this._userRepository.VerifyPassword(user, loginModel.Password)) throw new ArgumentException("Incorrect password!"); - return new TokenModel(WriteJWTSecurityToken(user.Id, user.UserName, user.Roles)); + List roleNames = user.Roles.Select(x => x.Name).ToList(); + return new TokenModel(this._jwtService.GenerateJwtToken(user.Id, user.UserName, roleNames)); } - /// - /// Register a user in the database and return a - /// - /// Register model, containing registration information - /// A Token model, containing JWT Token for further verification public async Task RegisterUser(RegisterServiceModel registerModel) { if (await this._userRepository.DoesUsernameExistAsync(registerModel.UserName)) @@ -91,11 +74,8 @@ namespace DevHive.Services.Services throw new ArgumentException("Unable to add role to user"); User createdUser = await this._userRepository.GetByUsernameAsync(registerModel.UserName); - List roleNames = createdUser - .Roles - .Select(x => x.Name) - .ToList(); + List roleNames = createdUser.Roles.Select(x => x.Name).ToList(); return new TokenModel(this._jwtService.GenerateJwtToken(createdUser.Id, createdUser.UserName, roleNames)); } #endregion @@ -140,9 +120,6 @@ namespace DevHive.Services.Services return this._userMapper.Map(newUser); } - /// - /// Uploads the given picture and assigns it's link to the user in the database - /// public async Task UpdateProfilePicture(UpdateProfilePictureServiceModel updateProfilePictureServiceModel) { User user = await this._userRepository.GetByIdAsync(updateProfilePictureServiceModel.UserId); @@ -179,61 +156,7 @@ namespace DevHive.Services.Services #region Validations /// - /// Checks whether the given user, gotten by the "id" property, - /// is the same user as the one in the token (unless the user in the token has the admin role) - /// and the roles in the token are the same as those in the user, gotten by the id in the token - /// - /// - /// - /// - public async Task ValidJWT(Guid id, string rawTokenData) - { - return this._jwtService.ValidateToken(rawTokenData); - // There is authorization name in the beginning, i.e. "Bearer eyJh..." - // var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); - - // Guid jwtUserID = new(UserService.GetClaimTypeValues("ID", jwt.Claims).First()); - // List jwtRoleNames = UserService.GetClaimTypeValues("role", jwt.Claims); - - // User user = await this._userRepository.GetByIdAsync(jwtUserID) - // ?? throw new ArgumentException("User does not exist!"); - - // /* Check if he is an admin */ - // if (user.Roles.Any(x => x.Name == Role.AdminRole)) - // return true; - - // if (!jwtRoleNames.Contains(Role.AdminRole) && 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) - // if (!jwtRoleNames.Contains(role.Name)) - // return false; - - // // Check if jwt contains only roles of user - // if (jwtRoleNames.Count != user.Roles.Count) - // return false; - - // return true; - } - - /// - /// Returns all values from a given claim type - /// - private static List GetClaimTypeValues(string type, IEnumerable claims) - { - List toReturn = new(); - - foreach (var claim in claims) - if (claim.Type == type) - toReturn.Add(claim.Value); - - return toReturn; - } - - /// - /// Checks whether the user in the model exists - /// and whether the username in the model is already taken. + /// Checks whether the user in the model exists and whether the username in the model is already taken. /// If the check fails (is false), it throws an exception, otherwise nothing happens /// private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel) @@ -255,38 +178,6 @@ namespace DevHive.Services.Services if (!await this._userRepository.ValidateFriendsCollectionAsync(usernames)) throw new ArgumentException("One or more friends do not exist!"); } - - /// - /// Return a new JSON Web Token, containing the user id, username and roles. - /// Tokens have an expiration time of 7 days. - /// - private string WriteJWTSecurityToken(Guid userId, string username, HashSet roles) - { - byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret); - HashSet claims = new() - { - new Claim("ID", $"{userId}"), - new Claim("Username", username) - }; - - foreach (var role in roles) - { - claims.Add(new Claim(ClaimTypes.Role, role.Name)); - } - - SecurityTokenDescriptor tokenDescriptor = new() - { - Subject = new ClaimsIdentity(claims), - Expires = DateTime.Today.AddDays(7), - SigningCredentials = new SigningCredentials( - new SymmetricSecurityKey(signingKey), - SecurityAlgorithms.HmacSha512Signature) - }; - - JwtSecurityTokenHandler tokenHandler = new(); - SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); - return tokenHandler.WriteToken(token); - } #endregion #region Misc diff --git a/src/Web/DevHive.Web/Controllers/CommentController.cs b/src/Web/DevHive.Web/Controllers/CommentController.cs index c38e300..b4fae5c 100644 --- a/src/Web/DevHive.Web/Controllers/CommentController.cs +++ b/src/Web/DevHive.Web/Controllers/CommentController.cs @@ -6,6 +6,7 @@ using DevHive.Web.Models.Comment; using DevHive.Services.Models.Comment; using Microsoft.AspNetCore.Authorization; using DevHive.Services.Interfaces; +using DevHive.Common.Jwt.Interfaces; namespace DevHive.Web.Controllers { @@ -16,16 +17,21 @@ namespace DevHive.Web.Controllers { private readonly ICommentService _commentService; private readonly IMapper _commentMapper; + private readonly IJwtService _jwtService; - public CommentController(ICommentService commentService, IMapper commentMapper) + public CommentController(ICommentService commentService, IMapper commentMapper, IJwtService jwtService) { this._commentService = commentService; this._commentMapper = commentMapper; + this._jwtService = jwtService; } [HttpPost] public async Task AddComment(Guid userId, [FromBody] CreateCommentWebModel createCommentWebModel, [FromHeader] string authorization) { + if (!this._jwtService.ValidateToken(userId, authorization)) + return new UnauthorizedResult(); + if (!await this._commentService.ValidateJwtForCreating(userId, authorization)) return new UnauthorizedResult(); @@ -53,7 +59,7 @@ namespace DevHive.Web.Controllers [HttpPut] public async Task UpdateComment(Guid userId, [FromBody] UpdateCommentWebModel updateCommentWebModel, [FromHeader] string authorization) { - if (!await this._commentService.ValidateJwtForComment(updateCommentWebModel.CommentId, authorization)) + if (!this._jwtService.ValidateToken(userId, authorization)) return new UnauthorizedResult(); UpdateCommentServiceModel updateCommentServiceModel = diff --git a/src/Web/DevHive.Web/Controllers/PostController.cs b/src/Web/DevHive.Web/Controllers/PostController.cs index d3fdbf6..309070c 100644 --- a/src/Web/DevHive.Web/Controllers/PostController.cs +++ b/src/Web/DevHive.Web/Controllers/PostController.cs @@ -6,6 +6,7 @@ using DevHive.Web.Models.Post; using DevHive.Services.Models.Post; using Microsoft.AspNetCore.Authorization; using DevHive.Services.Interfaces; +using DevHive.Common.Jwt.Interfaces; namespace DevHive.Web.Controllers { @@ -16,18 +17,20 @@ namespace DevHive.Web.Controllers { private readonly IPostService _postService; private readonly IMapper _postMapper; + private readonly IJwtService _jwtService; - public PostController(IPostService postService, IMapper postMapper) + public PostController(IPostService postService, IMapper postMapper, IJwtService jwtService) { this._postService = postService; this._postMapper = postMapper; + this._jwtService = jwtService; } #region Create [HttpPost] public async Task Create(Guid userId, [FromForm] CreatePostWebModel createPostWebModel, [FromHeader] string authorization) { - if (!await this._postService.ValidateJwtForCreating(userId, authorization)) + if (!this._jwtService.ValidateToken(userId, authorization)) return new UnauthorizedResult(); CreatePostServiceModel createPostServiceModel = @@ -58,6 +61,9 @@ namespace DevHive.Web.Controllers [HttpPut] public async Task Update(Guid userId, [FromForm] UpdatePostWebModel updatePostWebModel, [FromHeader] string authorization) { + if (!this._jwtService.ValidateToken(userId, authorization)) + return new UnauthorizedResult(); + if (!await this._postService.ValidateJwtForPost(updatePostWebModel.PostId, authorization)) return new UnauthorizedResult(); diff --git a/src/Web/DevHive.Web/Controllers/UserController.cs b/src/Web/DevHive.Web/Controllers/UserController.cs index a1e87f4..b01ecc1 100644 --- a/src/Web/DevHive.Web/Controllers/UserController.cs +++ b/src/Web/DevHive.Web/Controllers/UserController.cs @@ -7,6 +7,8 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using DevHive.Common.Models.Identity; using DevHive.Services.Interfaces; +using DevHive.Common.Jwt.Interfaces; +using DevHive.Web.Models.Attributes; namespace DevHive.Web.Controllers { @@ -16,11 +18,13 @@ namespace DevHive.Web.Controllers { private readonly IUserService _userService; private readonly IMapper _userMapper; + private readonly IJwtService _jwtService; - public UserController(IUserService userService, IMapper mapper) + public UserController(IUserService userService, IMapper mapper, IJwtService jwtService) { this._userService = userService; this._userMapper = mapper; + this._jwtService = jwtService; } #region Authentication @@ -56,7 +60,7 @@ namespace DevHive.Web.Controllers [Authorize(Roles = "User,Admin")] public async Task GetById(Guid id, [FromHeader] string authorization) { - if (!await this._userService.ValidJWT(id, authorization)) + if (!this._jwtService.ValidateToken(id, authorization)) return new UnauthorizedResult(); UserServiceModel userServiceModel = await this._userService.GetUserById(id); @@ -82,7 +86,7 @@ namespace DevHive.Web.Controllers [Authorize(Roles = "User,Admin")] public async Task Update(Guid id, [FromBody] UpdateUserWebModel updateUserWebModel, [FromHeader] string authorization) { - if (!await this._userService.ValidJWT(id, authorization)) + if (!this._jwtService.ValidateToken(id, authorization)) return new UnauthorizedResult(); UpdateUserServiceModel updateUserServiceModel = this._userMapper.Map(updateUserWebModel); @@ -100,7 +104,7 @@ namespace DevHive.Web.Controllers [Authorize(Roles = "User,Admin")] public async Task Delete(Guid id, [FromHeader] string authorization) { - if (!await this._userService.ValidJWT(id, authorization)) + if (!this._jwtService.ValidateToken(id, authorization)) return new UnauthorizedResult(); bool result = await this._userService.DeleteUser(id); -- cgit v1.2.3 From b9a9d63418d728560b17c23d49255328d16ccb11 Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 3 Mar 2021 18:35:12 +0200 Subject: NSwag replaced Swagger; Doc prep configured --- .../DevHive.Common.Models.csproj | 2 +- .../DevHive.Data.Models/DevHive.Data.Models.csproj | 2 +- .../DevHive.Data.Tests/DevHive.Data.Tests.csproj | 2 +- src/Data/DevHive.Data/DevHive.Data.csproj | 2 +- .../DevHive.Services.Models.csproj | 10 ++-- .../DevHive.Services.Tests.csproj | 20 ++++---- .../DevHive.Services/DevHive.Services.csproj | 22 ++++----- .../DevHive.Web.Models/DevHive.Web.Models.csproj | 10 ++-- src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj | 18 +++---- .../Configurations/Extensions/ConfigureSwagger.cs | 56 +++++++++++++--------- src/Web/DevHive.Web/DevHive.Web.csproj | 37 +++++++------- src/Web/DevHive.Web/Startup.cs | 2 +- 12 files changed, 97 insertions(+), 86 deletions(-) (limited to 'src/Common') diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj index f6d662c..a952c59 100644 --- a/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj +++ b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj @@ -4,7 +4,7 @@ - + true diff --git a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj index e9dc644..d249c77 100644 --- a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj +++ b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj index 46c7b83..25b2b39 100644 --- a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj +++ b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/Data/DevHive.Data/DevHive.Data.csproj b/src/Data/DevHive.Data/DevHive.Data.csproj index 46928c6..fcdb7ae 100644 --- a/src/Data/DevHive.Data/DevHive.Data.csproj +++ b/src/Data/DevHive.Data/DevHive.Data.csproj @@ -12,7 +12,7 @@ - + diff --git a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj index 6bbc60e..a55972a 100644 --- a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj +++ b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj @@ -3,11 +3,11 @@ net5.0 - - + + - - + + - + \ No newline at end of file diff --git a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj index b3d0a32..d85eea2 100644 --- a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj +++ b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj @@ -4,20 +4,20 @@ false - - - - - - + + + + + + - - - + + + true latest - + \ No newline at end of file diff --git a/src/Services/DevHive.Services/DevHive.Services.csproj b/src/Services/DevHive.Services/DevHive.Services.csproj index 55d9d4e..f51c1b6 100644 --- a/src/Services/DevHive.Services/DevHive.Services.csproj +++ b/src/Services/DevHive.Services/DevHive.Services.csproj @@ -3,25 +3,25 @@ net5.0 - + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - + + + + + - - - - + + + + true latest - + \ No newline at end of file diff --git a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj index 7f3f577..9d62eee 100644 --- a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj +++ b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj @@ -3,11 +3,11 @@ net5.0 - - + + - - + + - + \ No newline at end of file diff --git a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj index 41afbd4..5099119 100644 --- a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj +++ b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj @@ -4,19 +4,19 @@ false - - - - - + + + + + - - - + + + true latest - + \ No newline at end of file diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs index bfa44b0..9387561 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs @@ -1,12 +1,8 @@ -using System; -using System.IO; using System.Linq; -using System.Reflection; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; +using NSwag; +using NSwag.Generation.Processors.Security; namespace DevHive.Web.Configurations.Extensions { @@ -20,33 +16,49 @@ namespace DevHive.Web.Configurations.Extensions public static void SwaggerConfiguration(this IServiceCollection services) { - services.AddSwaggerGen(c => + services.AddOpenApiDocument(c => { - c.SwaggerDoc("v0.1", new OpenApiInfo + c.GenerateXmlObjects = true; + c.UseControllerSummaryAsTagDescription = true; + + c.AllowNullableBodyParameters = false; + c.Description = "DevHive Social Media's API Endpoints"; + + c.PostProcess = doc => { - Version = "v0.1", - Title = "API", - Description = "DevHive Social Media's first official API release", - TermsOfService = new Uri(TermsOfServiceUri), - License = new OpenApiLicense + doc.Info.Version = "v0.1"; + doc.Info.Title = "API"; + doc.Info.Description = "DevHive Social Media's first official API release"; + doc.Info.TermsOfService = TermsOfServiceUri; + doc.Info.License = new NSwag.OpenApiLicense { Name = LicenseName, - Url = new Uri(LicenseUri) - } - }); + Url = LicenseUri + }; + }; - string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - c.IncludeXmlComments(xmlPath); + c.AddSecurity("Bearer", Enumerable.Empty(), new OpenApiSecurityScheme + { + Type = OpenApiSecuritySchemeType.ApiKey, + Name = "Authorization", + In = OpenApiSecurityApiKeyLocation.Header, + Description = "Type into the textbox: Bearer {your JWT token}." + }); + c.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("Bearer")); }); } public static void UseSwaggerConfiguration(this IApplicationBuilder app) { - app.UseSwagger(); - app.UseSwaggerUI(c => + app.UseOpenApi(c => + { + c.DocumentName = "v0.1"; + }); + app.UseSwaggerUi3(c => { - c.SwaggerEndpoint("/swagger/v0.1/swagger.json", "v0.1"); + c.DocumentTitle = "DevHive API"; + c.EnableTryItOut = false; + c.DocExpansion = "list"; }); } } diff --git a/src/Web/DevHive.Web/DevHive.Web.csproj b/src/Web/DevHive.Web/DevHive.Web.csproj index ea9eee6..38f21e6 100644 --- a/src/Web/DevHive.Web/DevHive.Web.csproj +++ b/src/Web/DevHive.Web/DevHive.Web.csproj @@ -5,32 +5,31 @@ true latest - true - true + true + true - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - - - - - - - + + + + + + + + + + - - - - + + + + diff --git a/src/Web/DevHive.Web/Startup.cs b/src/Web/DevHive.Web/Startup.cs index 40f674d..ebd091e 100644 --- a/src/Web/DevHive.Web/Startup.cs +++ b/src/Web/DevHive.Web/Startup.cs @@ -48,7 +48,6 @@ namespace DevHive.Web if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); - app.UseSwaggerConfiguration(); } else { @@ -56,6 +55,7 @@ namespace DevHive.Web app.UseExceptionHandlerMiddlewareConfiguration(); } + app.UseSwaggerConfiguration(); app.UseDatabaseConfiguration(); app.UseAutoMapperConfiguration(); -- cgit v1.2.3 From fb421f1ab78c1358af5dddc467db7ab02a59110d Mon Sep 17 00:00:00 2001 From: transtrike Date: Fri, 2 Apr 2021 11:30:02 +0300 Subject: Introduced Logger; Replaced DevExcHandler with Custom; Logging Errors to file; Replaced Console logger for requests --- .../DevHive.Common.Models.csproj | 2 +- src/Common/DevHive.Common/DevHive.Common.csproj | 4 +-- .../DevHive.Data.Models/DevHive.Data.Models.csproj | 4 +-- .../DevHive.Data.Tests/DevHive.Data.Tests.csproj | 4 +-- src/Data/DevHive.Data/DevHive.Data.csproj | 6 ++-- .../DevHive.Services.Models.csproj | 2 +- .../DevHive.Services.Tests.csproj | 4 +-- .../DevHive.Services/DevHive.Services.csproj | 8 ++--- .../DevHive.Web.Models/DevHive.Web.Models.csproj | 2 +- src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj | 2 +- .../Configurations/Extensions/ConfigureDatabase.cs | 2 +- src/Web/DevHive.Web/DevHive.Web.csproj | 31 ++++++++++-------- .../DevHive.Web/Middleware/ExceptionMiddleware.cs | 8 ++--- src/Web/DevHive.Web/Program.cs | 26 ++++++++++++++- src/Web/DevHive.Web/Startup.cs | 6 +++- src/Web/DevHive.Web/appsettings.json | 38 +++++++++++++++++++--- 16 files changed, 103 insertions(+), 46 deletions(-) (limited to 'src/Common') diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj index a952c59..db8d1c9 100644 --- a/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj +++ b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj @@ -4,7 +4,7 @@ - + true diff --git a/src/Common/DevHive.Common/DevHive.Common.csproj b/src/Common/DevHive.Common/DevHive.Common.csproj index cd60d85..a5758f4 100644 --- a/src/Common/DevHive.Common/DevHive.Common.csproj +++ b/src/Common/DevHive.Common/DevHive.Common.csproj @@ -6,6 +6,6 @@ net5.0 - + - + \ No newline at end of file diff --git a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj index d249c77..2958f86 100644 --- a/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj +++ b/src/Data/DevHive.Data.Models/DevHive.Data.Models.csproj @@ -4,7 +4,7 @@ - - + + \ No newline at end of file diff --git a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj index 25b2b39..e9b33e5 100644 --- a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj +++ b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj @@ -4,12 +4,12 @@ false - + - + diff --git a/src/Data/DevHive.Data/DevHive.Data.csproj b/src/Data/DevHive.Data/DevHive.Data.csproj index fcdb7ae..62320f7 100644 --- a/src/Data/DevHive.Data/DevHive.Data.csproj +++ b/src/Data/DevHive.Data/DevHive.Data.csproj @@ -5,14 +5,14 @@ - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj index a55972a..2345a8e 100644 --- a/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj +++ b/src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj @@ -4,7 +4,7 @@ - + diff --git a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj index d85eea2..4a7237b 100644 --- a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj +++ b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj @@ -4,12 +4,12 @@ false - + - + diff --git a/src/Services/DevHive.Services/DevHive.Services.csproj b/src/Services/DevHive.Services/DevHive.Services.csproj index f51c1b6..2468711 100644 --- a/src/Services/DevHive.Services/DevHive.Services.csproj +++ b/src/Services/DevHive.Services/DevHive.Services.csproj @@ -4,15 +4,15 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive all - + - - + + diff --git a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj index 9d62eee..79c856f 100644 --- a/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj +++ b/src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj @@ -8,6 +8,6 @@ - + \ No newline at end of file diff --git a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj index 5099119..49a9173 100644 --- a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj +++ b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 1bd8df0..b4c49b4 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -18,7 +18,7 @@ namespace DevHive.Web.Configurations.Extensions { services.AddDbContext(options => { - options.EnableSensitiveDataLogging(true); + // options.EnableSensitiveDataLogging(true); options.UseNpgsql(configuration.GetConnectionString("DEV"), options => { options.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); diff --git a/src/Web/DevHive.Web/DevHive.Web.csproj b/src/Web/DevHive.Web/DevHive.Web.csproj index 39322ae..5b3a920 100644 --- a/src/Web/DevHive.Web/DevHive.Web.csproj +++ b/src/Web/DevHive.Web/DevHive.Web.csproj @@ -9,25 +9,30 @@ true - - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs b/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs index e2521bd..ebec5e8 100644 --- a/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs +++ b/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs @@ -32,12 +32,8 @@ namespace DevHive.Web.Middleware context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.BadRequest; - // Made to ressemble the formatting of property validation errors (like [MinLength(3)]) - string message = JsonConvert.SerializeObject(new { - errors = new { - Exception = new String[] { exception.Message } - } - }); + // Made to resemble the formatting of property validation errors (like [MinLength(3)]) + string message = JsonConvert.SerializeObject(new { Error = exception.Message }); return context.Response.WriteAsync(message); } diff --git a/src/Web/DevHive.Web/Program.cs b/src/Web/DevHive.Web/Program.cs index fdb6889..e7c47a9 100644 --- a/src/Web/DevHive.Web/Program.cs +++ b/src/Web/DevHive.Web/Program.cs @@ -1,5 +1,8 @@ +using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Configuration; +using Serilog; namespace DevHive.Web { @@ -11,11 +14,32 @@ namespace DevHive.Web public static void Main(string[] args) { - CreateHostBuilder(args).Build().Run(); + var config = new ConfigurationBuilder() + .AddJsonFile("appsettings.json") + .Build(); + + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(config) + .CreateLogger(); + + try + { + Log.Information("Application Starting Up"); + CreateHostBuilder(args).Build().Run(); + } + catch (Exception ex) + { + Log.Fatal(ex, "The application failed to start correctly."); + } + finally + { + Log.CloseAndFlush(); + } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .UseSerilog() .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(opt => opt.ListenLocalhost(HTTP_PORT)); diff --git a/src/Web/DevHive.Web/Startup.cs b/src/Web/DevHive.Web/Startup.cs index 002c718..05a75d9 100644 --- a/src/Web/DevHive.Web/Startup.cs +++ b/src/Web/DevHive.Web/Startup.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using DevHive.Web.Configurations.Extensions; using Newtonsoft.Json; +using Serilog; namespace DevHive.Web { @@ -46,7 +47,8 @@ namespace DevHive.Web if (env.IsDevelopment()) { - app.UseDeveloperExceptionPage(); + app.UseExceptionHandlerMiddlewareConfiguration(); + // app.UseDeveloperExceptionPage(); } else { @@ -58,6 +60,8 @@ namespace DevHive.Web app.UseDatabaseConfiguration(); app.UseAutoMapperConfiguration(); + app.UseSerilogRequestLogging(); + app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( diff --git a/src/Web/DevHive.Web/appsettings.json b/src/Web/DevHive.Web/appsettings.json index 036af82..84d534d 100644 --- a/src/Web/DevHive.Web/appsettings.json +++ b/src/Web/DevHive.Web/appsettings.json @@ -12,11 +12,39 @@ "apiKey": "488664116365813", "apiSecret": "" }, - "Logging": { - "LogLevel": { + "Serilog": { + "Using": [], + "LevelSwitches": { + "$consoleSwitch": "Verbose", + "$fileSwitch": "Error" + }, + "MinimumLevel": { "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } + "Override": { + "Microsoft": "Warning", + "System": "Warning" + } + }, + "Enrich": [ + "FromLogContext", + "WithMachineName", + "WithProcessId", + "WithThreadId" + ], + "WriteTo": [ + { + "Name": "Console", + "Args": { + "levelSwitch": "$consoleSwitch" + } + }, + { + "Name": "File", + "Args": { + "path": "./Logs/errors.log", + "levelSwitch": "$fileSwitch" + } + } + ] } } -- cgit v1.2.3 From da7d6223c261aac8e8f18458c11fb48cf9ca4cfe Mon Sep 17 00:00:00 2001 From: transtrike Date: Mon, 5 Apr 2021 13:41:31 +0300 Subject: Introduced consts for every string possible. FML --- .../DevHive.Common/Constants/ClassesConstants.cs | 22 +++++++ .../DevHive.Common/Constants/ErrorMessages.cs | 16 +++++ src/Data/DevHive.Data.Models/Comment.cs | 4 -- .../DevHive.Data/Repositories/RatingRepository.cs | 10 ++-- .../DevHive.Services.Tests/UserService.Tests.cs | 2 +- .../DevHive.Services/Services/CloudinaryService.cs | 30 +++++----- .../DevHive.Services/Services/CommentService.cs | 29 ++++----- .../DevHive.Services/Services/FeedService.cs | 14 +++-- .../DevHive.Services/Services/LanguageService.cs | 12 ++-- .../DevHive.Services/Services/PostService.cs | 41 ++++++------- .../Services/ProfilePictureService.cs | 18 +++--- .../DevHive.Services/Services/RatingService.cs | 17 +++--- .../DevHive.Services/Services/RoleService.cs | 12 ++-- .../DevHive.Services/Services/TechnologyService.cs | 12 ++-- .../DevHive.Services/Services/UserService.cs | 69 ++++++++++++---------- 15 files changed, 177 insertions(+), 131 deletions(-) create mode 100644 src/Common/DevHive.Common/Constants/ClassesConstants.cs create mode 100644 src/Common/DevHive.Common/Constants/ErrorMessages.cs (limited to 'src/Common') diff --git a/src/Common/DevHive.Common/Constants/ClassesConstants.cs b/src/Common/DevHive.Common/Constants/ClassesConstants.cs new file mode 100644 index 0000000..825f737 --- /dev/null +++ b/src/Common/DevHive.Common/Constants/ClassesConstants.cs @@ -0,0 +1,22 @@ +namespace DevHive.Common.Constants +{ + public static class ClassesConstants + { + public const string Data = "Data"; + + public const string Post = "The Post"; + public const string Comment = "The Comment"; + public const string User = "The User"; + public const string Language = "The Language"; + public const string Picture = "The Picture"; + public const string Files = "The Files"; + public const string Rating = "The Rating"; + public const string Role = "The Role"; + public const string Technology = "The Technology"; + + public const string Username = "The Username"; + public const string Email = "The Email"; + public const string Password = "Password"; + public const string OneOrMoreFriends = "One or more Friends"; + } +} diff --git a/src/Common/DevHive.Common/Constants/ErrorMessages.cs b/src/Common/DevHive.Common/Constants/ErrorMessages.cs new file mode 100644 index 0000000..30ca544 --- /dev/null +++ b/src/Common/DevHive.Common/Constants/ErrorMessages.cs @@ -0,0 +1,16 @@ +namespace DevHive.Common.Constants +{ + public static class ErrorMessages + { + public const string InvalidData = "Invalid {0}!"; + public const string IncorrectData = "Incorrect {0}!"; + public const string DoesNotExist = "{0} does not exist!"; + public const string AlreadyExists = "{0} already exists!"; + + public const string CannotAdd = "Could not add {0}!"; + public const string CannotCreate = "Could not create {0}!"; + public const string CannotDelete = "Could not delete {0}!"; + public const string CannotUpload = "Could not upload {0}!"; + public const string CannotEdit = "Could not edit {0}!"; + } +} diff --git a/src/Data/DevHive.Data.Models/Comment.cs b/src/Data/DevHive.Data.Models/Comment.cs index 0af40bf..8a58edd 100644 --- a/src/Data/DevHive.Data.Models/Comment.cs +++ b/src/Data/DevHive.Data.Models/Comment.cs @@ -6,12 +6,8 @@ namespace DevHive.Data.Models { public Guid Id { get; set; } - // public Guid PostId { get; set; } - public Post Post { get; set; } - // public Guid CreatorId { get; set; } - public User Creator { get; set; } public string Message { get; set; } diff --git a/src/Data/DevHive.Data/Repositories/RatingRepository.cs b/src/Data/DevHive.Data/Repositories/RatingRepository.cs index c35f6d5..2048c3f 100644 --- a/src/Data/DevHive.Data/Repositories/RatingRepository.cs +++ b/src/Data/DevHive.Data/Repositories/RatingRepository.cs @@ -11,13 +11,11 @@ namespace DevHive.Data.Repositories public class RatingRepository : BaseRepository, IRatingRepository { private readonly DevHiveContext _context; - private readonly IPostRepository _postRepository; - public RatingRepository(DevHiveContext context, IPostRepository postRepository) + public RatingRepository(DevHiveContext context) : base(context) { this._context = context; - this._postRepository = postRepository; } public override async Task GetByIdAsync(Guid id) @@ -28,7 +26,7 @@ namespace DevHive.Data.Repositories .FirstOrDefaultAsync(x => x.Id == id); } /// - /// Gets all the ratings for a psot. + /// Gets all the ratings for a post. /// /// Id of the post. /// @@ -40,10 +38,10 @@ namespace DevHive.Data.Repositories .Where(x => x.Post.Id == postId).ToListAsync(); } /// - /// Checks if a user rated a given post. In DevHive every user has one or no rating for every post. + /// Checks if a user rated a given post. In DevHive every user has one or no rating for every post. /// /// Id of the user. - /// Id of the psot. + /// Id of the post. /// True if the user has already rated the post and false if he hasn't. public async Task UserRatedPost(Guid userId, Guid postId) { diff --git a/src/Services/DevHive.Services.Tests/UserService.Tests.cs b/src/Services/DevHive.Services.Tests/UserService.Tests.cs index 7990b32..9d1bca5 100644 --- a/src/Services/DevHive.Services.Tests/UserService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/UserService.Tests.cs @@ -344,7 +344,7 @@ namespace DevHive.Services.Tests // } // else // { - // const string EXCEPTION_MESSAGE = "Unable to edit user!"; + // const string EXCEPTION_MESSAGE = string.Format(ErrorMessages.CannotEdit, ClassesConstants.User.ToLower()); // // Exception ex = Assert.ThrowsAsync(() => this._userService.UpdateUser(updateUserServiceModel); // diff --git a/src/Services/DevHive.Services/Services/CloudinaryService.cs b/src/Services/DevHive.Services/Services/CloudinaryService.cs index 05600cc..078bb5d 100644 --- a/src/Services/DevHive.Services/Services/CloudinaryService.cs +++ b/src/Services/DevHive.Services/Services/CloudinaryService.cs @@ -14,7 +14,7 @@ namespace DevHive.Services.Services { // Regex for getting the filename without (final) filename extension // So, from image.png, it will match image, and from doc.my.txt will match doc.my - private static Regex _imageRegex = new Regex(".*(?=\\.)"); + private static readonly Regex s_imageRegex = new(".*(?=\\.)"); private readonly Cloudinary _cloudinary; @@ -28,23 +28,21 @@ namespace DevHive.Services.Services List fileUrls = new(); foreach (var formFile in formFiles) { - string fileName = _imageRegex.Match(formFile.FileName).ToString(); + string fileName = s_imageRegex.Match(formFile.FileName).ToString(); - using (var ms = new MemoryStream()) + using var ms = new MemoryStream(); + formFile.CopyTo(ms); + byte[] formBytes = ms.ToArray(); + + RawUploadParams rawUploadParams = new() { - formFile.CopyTo(ms); - byte[] formBytes = ms.ToArray(); - - RawUploadParams rawUploadParams = new() - { - File = new FileDescription(fileName, new MemoryStream(formBytes)), - PublicId = fileName, - UseFilename = true - }; - - RawUploadResult rawUploadResult = await this._cloudinary.UploadAsync(rawUploadParams); - fileUrls.Add(rawUploadResult.Url.AbsoluteUri); - } + File = new FileDescription(fileName, new MemoryStream(formBytes)), + PublicId = fileName, + UseFilename = true + }; + + RawUploadResult rawUploadResult = await this._cloudinary.UploadAsync(rawUploadParams); + fileUrls.Add(rawUploadResult.Url.AbsoluteUri); } return fileUrls; diff --git a/src/Services/DevHive.Services/Services/CommentService.cs b/src/Services/DevHive.Services/Services/CommentService.cs index b48bac8..1c388f6 100644 --- a/src/Services/DevHive.Services/Services/CommentService.cs +++ b/src/Services/DevHive.Services/Services/CommentService.cs @@ -1,14 +1,15 @@ using System; using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; +using DevHive.Data.Interfaces; using DevHive.Data.Models; -using DevHive.Services.Models.Comment; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; using DevHive.Services.Interfaces; -using DevHive.Data.Interfaces; -using System.Linq; +using DevHive.Services.Models.Comment; namespace DevHive.Services.Services { @@ -31,7 +32,7 @@ namespace DevHive.Services.Services public async Task AddComment(CreateCommentServiceModel createCommentServiceModel) { if (!await this._postRepository.DoesPostExist(createCommentServiceModel.PostId)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); Comment comment = this._postMapper.Map(createCommentServiceModel); comment.TimeCreated = DateTime.Now; @@ -56,10 +57,10 @@ namespace DevHive.Services.Services public async Task GetCommentById(Guid id) { Comment comment = await this._commentRepository.GetByIdAsync(id) ?? - throw new ArgumentException("The comment does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); User user = await this._userRepository.GetByIdAsync(comment.Creator.Id) ?? - throw new ArgumentException("The user does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); ReadCommentServiceModel readCommentServiceModel = this._postMapper.Map(comment); readCommentServiceModel.IssuerFirstName = user.FirstName; @@ -74,7 +75,7 @@ namespace DevHive.Services.Services public async Task UpdateComment(UpdateCommentServiceModel updateCommentServiceModel) { if (!await this._commentRepository.DoesCommentExist(updateCommentServiceModel.CommentId)) - throw new ArgumentException("Comment does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); Comment comment = this._postMapper.Map(updateCommentServiceModel); comment.TimeCreated = DateTime.Now; @@ -95,7 +96,7 @@ namespace DevHive.Services.Services public async Task DeleteComment(Guid id) { if (!await this._commentRepository.DoesCommentExist(id)) - throw new ArgumentException("Comment does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); Comment comment = await this._commentRepository.GetByIdAsync(id); return await this._commentRepository.DeleteAsync(comment); @@ -121,7 +122,7 @@ namespace DevHive.Services.Services public async Task ValidateJwtForComment(Guid commentId, string rawTokenData) { Comment comment = await this._commentRepository.GetByIdAsync(commentId) ?? - throw new ArgumentException("Comment does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); User user = await this.GetUserForValidation(rawTokenData); //If user made the comment @@ -141,10 +142,10 @@ namespace DevHive.Services.Services { JwtSecurityToken jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); - Guid jwtUserId = Guid.Parse(this.GetClaimTypeValues("ID", jwt.Claims).First()); + Guid jwtUserId = Guid.Parse(GetClaimTypeValues("ID", jwt.Claims).First()); User user = await this._userRepository.GetByIdAsync(jwtUserId) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return user; } @@ -152,7 +153,7 @@ namespace DevHive.Services.Services /// /// Returns all values from a given claim type /// - private List GetClaimTypeValues(string type, IEnumerable claims) + private static List GetClaimTypeValues(string type, IEnumerable claims) { List toReturn = new(); diff --git a/src/Services/DevHive.Services/Services/FeedService.cs b/src/Services/DevHive.Services/Services/FeedService.cs index 0af8093..9c622b3 100644 --- a/src/Services/DevHive.Services/Services/FeedService.cs +++ b/src/Services/DevHive.Services/Services/FeedService.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -26,10 +28,11 @@ namespace DevHive.Services.Services /// /// This method is used in the feed page. - /// See the FeedRepository "GetFriendsPosts" menthod for more information on how it works. + /// See the FeedRepository "GetFriendsPosts" method for more information on how it works. /// public async Task GetPage(GetPageServiceModel getPageServiceModel) { + //TODO: Rework the initialization of User User user = null; if (getPageServiceModel.UserId != Guid.Empty) @@ -37,10 +40,10 @@ namespace DevHive.Services.Services else if (!string.IsNullOrEmpty(getPageServiceModel.Username)) user = await this._userRepository.GetByUsernameAsync(getPageServiceModel.Username); else - throw new ArgumentException("Invalid given data!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, ClassesConstants.Data.ToLower())); if (user == null) - throw new ArgumentException("User doesn't exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); List posts = await this._feedRepository .GetFriendsPosts(user.Friends.ToList(), getPageServiceModel.FirstRequestIssued, getPageServiceModel.PageNumber, getPageServiceModel.PageSize); @@ -58,15 +61,16 @@ namespace DevHive.Services.Services /// public async Task GetUserPage(GetPageServiceModel model) { + //TODO: Rework the initialization of User User user = null; if (!string.IsNullOrEmpty(model.Username)) user = await this._userRepository.GetByUsernameAsync(model.Username); else - throw new ArgumentException("Invalid given data!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, ClassesConstants.Data.ToLower())); if (user == null) - throw new ArgumentException("User doesn't exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); List posts = await this._feedRepository .GetUsersPosts(user, model.FirstRequestIssued, model.PageNumber, model.PageSize); diff --git a/src/Services/DevHive.Services/Services/LanguageService.cs b/src/Services/DevHive.Services/Services/LanguageService.cs index 9d2041e..7ee7d9f 100644 --- a/src/Services/DevHive.Services/Services/LanguageService.cs +++ b/src/Services/DevHive.Services/Services/LanguageService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Data; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -24,7 +26,7 @@ namespace DevHive.Services.Services public async Task CreateLanguage(CreateLanguageServiceModel createLanguageServiceModel) { if (await this._languageRepository.DoesLanguageNameExistAsync(createLanguageServiceModel.Name)) - throw new ArgumentException("Language already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Language)); Language language = this._languageMapper.Map(createLanguageServiceModel); bool success = await this._languageRepository.AddAsync(language); @@ -45,7 +47,7 @@ namespace DevHive.Services.Services Language language = await this._languageRepository.GetByIdAsync(id); if (language == null) - throw new ArgumentException("The language does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Language)); return this._languageMapper.Map(language); } @@ -65,10 +67,10 @@ namespace DevHive.Services.Services bool newLangNameExists = await this._languageRepository.DoesLanguageNameExistAsync(languageServiceModel.Name); if (!langExists) - throw new ArgumentException("Language does not exist!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Language)); if (newLangNameExists) - throw new ArgumentException("Language name already exists in our data base!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Language)); Language lang = this._languageMapper.Map(languageServiceModel); return await this._languageRepository.EditAsync(languageServiceModel.Id, lang); @@ -79,7 +81,7 @@ namespace DevHive.Services.Services public async Task DeleteLanguage(Guid id) { if (!await this._languageRepository.DoesLanguageExistAsync(id)) - throw new ArgumentException("Language does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Language)); Language language = await this._languageRepository.GetByIdAsync(id); return await this._languageRepository.DeleteAsync(language); diff --git a/src/Services/DevHive.Services/Services/PostService.cs b/src/Services/DevHive.Services/Services/PostService.cs index a565473..8580e82 100644 --- a/src/Services/DevHive.Services/Services/PostService.cs +++ b/src/Services/DevHive.Services/Services/PostService.cs @@ -1,15 +1,16 @@ using System; using System.Collections.Generic; -using System.Threading.Tasks; -using AutoMapper; -using DevHive.Data.Models; -using DevHive.Services.Models.Post; using System.IdentityModel.Tokens.Jwt; +using System.Linq; using System.Security.Claims; -using DevHive.Services.Interfaces; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; -using System.Linq; +using DevHive.Data.Models; using DevHive.Data.Models.Relational; +using DevHive.Services.Interfaces; +using DevHive.Services.Models.Post; namespace DevHive.Services.Services { @@ -34,7 +35,7 @@ namespace DevHive.Services.Services public async Task CreatePost(CreatePostServiceModel createPostServiceModel) { if (!await this._userRepository.DoesUserExistAsync(createPostServiceModel.CreatorId)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); Post post = this._postMapper.Map(createPostServiceModel); @@ -66,7 +67,7 @@ namespace DevHive.Services.Services public async Task GetPostById(Guid id) { Post post = await this._postRepository.GetByIdAsync(id) ?? - throw new ArgumentException("The post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); // This can't happen in repo, because of how time is usually compared post.Comments = post.Comments @@ -74,7 +75,7 @@ namespace DevHive.Services.Services .ToList(); User user = await this._userRepository.GetByIdAsync(post.Creator.Id) ?? - throw new ArgumentException("The user does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); int currentRating = 0; foreach (Rating rating in post.Ratings) @@ -100,7 +101,7 @@ namespace DevHive.Services.Services public async Task UpdatePost(UpdatePostServiceModel updatePostServiceModel) { if (!await this._postRepository.DoesPostExist(updatePostServiceModel.PostId)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); Post post = this._postMapper.Map(updatePostServiceModel); @@ -111,11 +112,11 @@ namespace DevHive.Services.Services List fileUrlsToRemove = await this._postRepository.GetFileUrls(updatePostServiceModel.PostId); bool success = await _cloudService.RemoveFilesFromCloud(fileUrlsToRemove); if (!success) - throw new InvalidCastException("Could not delete files from the post!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Files.ToLower())); } List fileUrls = await _cloudService.UploadFilesToCloud(updatePostServiceModel.Files) ?? - throw new ArgumentException("Unable to upload images to cloud!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotUpload, ClassesConstants.Files.ToLower())); post.Attachments = GetPostAttachmentsFromUrls(post, fileUrls); } @@ -136,7 +137,7 @@ namespace DevHive.Services.Services public async Task DeletePost(Guid id) { if (!await this._postRepository.DoesPostExist(id)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); Post post = await this._postRepository.GetByIdAsync(id); @@ -145,7 +146,7 @@ namespace DevHive.Services.Services List fileUrls = await this._postRepository.GetFileUrls(id); bool success = await _cloudService.RemoveFilesFromCloud(fileUrls); if (!success) - throw new InvalidCastException("Could not delete files from the post. Please try again"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Files.ToLower())); } return await this._postRepository.DeleteAsync(post); @@ -158,7 +159,7 @@ namespace DevHive.Services.Services /// public async Task ValidateJwtForCreating(Guid userId, string rawTokenData) { - User user = await this.GetUserForValidation(rawTokenData); + User user = await GetUserForValidation(rawTokenData); return user.Id == userId; } @@ -171,8 +172,8 @@ namespace DevHive.Services.Services public async Task ValidateJwtForPost(Guid postId, string rawTokenData) { Post post = await this._postRepository.GetByIdAsync(postId) ?? - throw new ArgumentException("Post does not exist!"); - User user = await this.GetUserForValidation(rawTokenData); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); + User user = await GetUserForValidation(rawTokenData); //If user made the post if (post.Creator.Id == user.Id) @@ -192,8 +193,8 @@ namespace DevHive.Services.Services public async Task ValidateJwtForComment(Guid commentId, string rawTokenData) { Comment comment = await this._commentRepository.GetByIdAsync(commentId) ?? - throw new ArgumentException("Comment does not exist!"); - User user = await this.GetUserForValidation(rawTokenData); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); + User user = await GetUserForValidation(rawTokenData); //If user made the comment if (comment.Creator.Id == user.Id) @@ -215,7 +216,7 @@ namespace DevHive.Services.Services Guid jwtUserId = Guid.Parse(GetClaimTypeValues("ID", jwt.Claims).First()); User user = await this._userRepository.GetByIdAsync(jwtUserId) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return user; } diff --git a/src/Services/DevHive.Services/Services/ProfilePictureService.cs b/src/Services/DevHive.Services/Services/ProfilePictureService.cs index 1de2114..cafa7cb 100644 --- a/src/Services/DevHive.Services/Services/ProfilePictureService.cs +++ b/src/Services/DevHive.Services/Services/ProfilePictureService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -33,14 +34,13 @@ namespace DevHive.Services.Services await ValidateUserExistsAsync(profilePictureServiceModel.UserId); User user = await this._userRepository.GetByIdAsync(profilePictureServiceModel.UserId); - // if (user.ProfilePicture.PictureURL != ProfilePicture.DefaultURL) if (user.ProfilePicture.Id != Guid.Empty) { List file = new() { user.ProfilePicture.PictureURL }; bool removed = await this._cloudinaryService.RemoveFilesFromCloud(file); if (!removed) - throw new ArgumentException("Cannot delete old picture"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Picture.ToLower())); } return await SaveProfilePictureInDatabase(profilePictureServiceModel); @@ -49,16 +49,16 @@ namespace DevHive.Services.Services public async Task DeleteProfilePicture(Guid id) { ProfilePicture profilePic = await this._profilePictureRepository.GetByIdAsync(id) ?? - throw new ArgumentException("Such picture doesn't exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Picture)); bool removedFromDb = await this._profilePictureRepository.DeleteAsync(profilePic); if (!removedFromDb) - throw new ArgumentException("Cannot delete picture from database!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Picture.ToLower())); List file = new() { profilePic.PictureURL }; bool removedFromCloud = await this._cloudinaryService.RemoveFilesFromCloud(file); if (!removedFromCloud) - throw new ArgumentException("Cannot delete picture from cloud!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Picture.ToLower())); return true; } @@ -75,13 +75,13 @@ namespace DevHive.Services.Services bool success = await this._profilePictureRepository.AddAsync(profilePic); if (!success) - throw new ArgumentException("Unable to upload picture!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotUpload, ClassesConstants.Files.ToLower())); user.ProfilePicture = profilePic; bool userProfilePicAlter = await this._userRepository.EditAsync(user.Id, user); if (!userProfilePicAlter) - throw new ArgumentException("Unable to alter user's profile picture"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotEdit, "user's profile picture")); return picUrl; } @@ -89,13 +89,13 @@ namespace DevHive.Services.Services private static void ValidateProfPic(IFormFile profilePictureFormFile) { if (profilePictureFormFile.Length == 0) - throw new ArgumentException("Picture cannot be null"); + throw new ArgumentNullException(nameof(profilePictureFormFile), string.Format(ErrorMessages.InvalidData, ClassesConstants.Data.ToLower())); } private async Task ValidateUserExistsAsync(Guid userId) { if (!await this._userRepository.DoesUserExistAsync(userId)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); } } } diff --git a/src/Services/DevHive.Services/Services/RatingService.cs b/src/Services/DevHive.Services/Services/RatingService.cs index 9d8f4b0..d6b4299 100644 --- a/src/Services/DevHive.Services/Services/RatingService.cs +++ b/src/Services/DevHive.Services/Services/RatingService.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Security.Claims; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -19,6 +16,8 @@ namespace DevHive.Services.Services private readonly IRatingRepository _ratingRepository; private readonly IMapper _mapper; + private const string NotRated = "{0} has not rated" + ClassesConstants.Post; + public RatingService(IPostRepository postRepository, IRatingRepository ratingRepository, IUserRepository userRepository, IMapper mapper) { this._postRepository = postRepository; @@ -31,7 +30,7 @@ namespace DevHive.Services.Services public async Task RatePost(CreateRatingServiceModel createRatingServiceModel) { if (!await this._postRepository.DoesPostExist(createRatingServiceModel.PostId)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); if (await this._ratingRepository.UserRatedPost(createRatingServiceModel.UserId, createRatingServiceModel.PostId)) throw new ArgumentException("User already rated the post!"); @@ -84,13 +83,13 @@ namespace DevHive.Services.Services public async Task UpdateRating(UpdateRatingServiceModel updateRatingServiceModel) { Rating rating = await this._ratingRepository.GetRatingByUserAndPostId(updateRatingServiceModel.UserId, updateRatingServiceModel.PostId) ?? - throw new ArgumentException("Rating does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Rating)); User user = await this._userRepository.GetByIdAsync(updateRatingServiceModel.UserId) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); if (!await this._ratingRepository.UserRatedPost(updateRatingServiceModel.UserId, updateRatingServiceModel.PostId)) - throw new ArgumentException("User has not rated the post!"); + throw new ArgumentException(string.Format(NotRated, ClassesConstants.User)); rating.User = user; rating.IsLike = updateRatingServiceModel.IsLike; @@ -111,7 +110,7 @@ namespace DevHive.Services.Services public async Task DeleteRating(Guid ratingId) { if (!await this._ratingRepository.DoesRatingExist(ratingId)) - throw new ArgumentException("Rating does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Rating)); Rating rating = await this._ratingRepository.GetByIdAsync(ratingId); return await this._ratingRepository.DeleteAsync(rating); diff --git a/src/Services/DevHive.Services/Services/RoleService.cs b/src/Services/DevHive.Services/Services/RoleService.cs index a5da759..f61181a 100644 --- a/src/Services/DevHive.Services/Services/RoleService.cs +++ b/src/Services/DevHive.Services/Services/RoleService.cs @@ -1,6 +1,8 @@ using System; +using System.Data; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -22,7 +24,7 @@ namespace DevHive.Services.Services public async Task CreateRole(CreateRoleServiceModel createRoleServiceModel) { if (await this._roleRepository.DoesNameExist(createRoleServiceModel.Name)) - throw new ArgumentException("Role already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Role)); Role role = this._roleMapper.Map(createRoleServiceModel); bool success = await this._roleRepository.AddAsync(role); @@ -40,7 +42,7 @@ namespace DevHive.Services.Services public async Task GetRoleById(Guid id) { Role role = await this._roleRepository.GetByIdAsync(id) ?? - throw new ArgumentException("Role does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); return this._roleMapper.Map(role); } @@ -48,10 +50,10 @@ namespace DevHive.Services.Services public async Task UpdateRole(UpdateRoleServiceModel updateRoleServiceModel) { if (!await this._roleRepository.DoesRoleExist(updateRoleServiceModel.Id)) - throw new ArgumentException("Role does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); if (await this._roleRepository.DoesNameExist(updateRoleServiceModel.Name)) - throw new ArgumentException("Role name already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Role)); Role role = this._roleMapper.Map(updateRoleServiceModel); return await this._roleRepository.EditAsync(updateRoleServiceModel.Id, role); @@ -60,7 +62,7 @@ namespace DevHive.Services.Services public async Task DeleteRole(Guid id) { if (!await this._roleRepository.DoesRoleExist(id)) - throw new ArgumentException("Role does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); Role role = await this._roleRepository.GetByIdAsync(id); return await this._roleRepository.DeleteAsync(role); diff --git a/src/Services/DevHive.Services/Services/TechnologyService.cs b/src/Services/DevHive.Services/Services/TechnologyService.cs index 09c4d20..4cf84c5 100644 --- a/src/Services/DevHive.Services/Services/TechnologyService.cs +++ b/src/Services/DevHive.Services/Services/TechnologyService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Data; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -24,7 +26,7 @@ namespace DevHive.Services.Services public async Task CreateTechnology(CreateTechnologyServiceModel technologyServiceModel) { if (await this._technologyRepository.DoesTechnologyNameExistAsync(technologyServiceModel.Name)) - throw new ArgumentException("Technology already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Technology)); Technology technology = this._technologyMapper.Map(technologyServiceModel); bool success = await this._technologyRepository.AddAsync(technology); @@ -45,7 +47,7 @@ namespace DevHive.Services.Services Technology technology = await this._technologyRepository.GetByIdAsync(id); if (technology == null) - throw new ArgumentException("The technology does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Technology)); return this._technologyMapper.Map(technology); } @@ -62,10 +64,10 @@ namespace DevHive.Services.Services public async Task UpdateTechnology(UpdateTechnologyServiceModel updateTechnologyServiceModel) { if (!await this._technologyRepository.DoesTechnologyExistAsync(updateTechnologyServiceModel.Id)) - throw new ArgumentException("Technology does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Technology)); if (await this._technologyRepository.DoesTechnologyNameExistAsync(updateTechnologyServiceModel.Name)) - throw new ArgumentException("Technology name already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Technology)); Technology technology = this._technologyMapper.Map(updateTechnologyServiceModel); bool result = await this._technologyRepository.EditAsync(updateTechnologyServiceModel.Id, technology); @@ -78,7 +80,7 @@ namespace DevHive.Services.Services public async Task DeleteTechnology(Guid id) { if (!await this._technologyRepository.DoesTechnologyExistAsync(id)) - throw new ArgumentException("Technology does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Technology)); Technology technology = await this._technologyRepository.GetByIdAsync(id); bool result = await this._technologyRepository.DeleteAsync(technology); diff --git a/src/Services/DevHive.Services/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs index d487de4..62576d4 100644 --- a/src/Services/DevHive.Services/Services/UserService.cs +++ b/src/Services/DevHive.Services/Services/UserService.cs @@ -1,15 +1,17 @@ -using AutoMapper; -using DevHive.Services.Models.User; -using System.Threading.Tasks; -using DevHive.Data.Models; using System; using System.Collections.Generic; -using DevHive.Common.Models.Identity; -using DevHive.Services.Interfaces; -using DevHive.Data.Interfaces; +using System.Data; +using System.IO; using System.Linq; -using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Common.Constants; using DevHive.Common.Jwt.Interfaces; +using DevHive.Common.Models.Identity; +using DevHive.Data.Interfaces; +using DevHive.Data.Models; +using DevHive.Services.Interfaces; +using DevHive.Services.Models.User; namespace DevHive.Services.Services { @@ -20,15 +22,17 @@ namespace DevHive.Services.Services private readonly ILanguageRepository _languageRepository; private readonly ITechnologyRepository _technologyRepository; private readonly IMapper _userMapper; - private readonly ICloudService _cloudService; private readonly IJwtService _jwtService; + private const string NoYourselfAsFriend = "You cant add yourself as a friend(sry, bro)!"; + private const string Rant = "Can't promote shit in this country..."; + + public UserService(IUserRepository userRepository, ILanguageRepository languageRepository, IRoleRepository roleRepository, ITechnologyRepository technologyRepository, IMapper mapper, - ICloudService cloudService, IJwtService jwtService) { this._userRepository = userRepository; @@ -36,7 +40,6 @@ namespace DevHive.Services.Services this._userMapper = mapper; this._languageRepository = languageRepository; this._technologyRepository = technologyRepository; - this._cloudService = cloudService; this._jwtService = jwtService; } @@ -44,12 +47,12 @@ namespace DevHive.Services.Services public async Task LoginUser(LoginServiceModel loginModel) { if (!await this._userRepository.DoesUsernameExistAsync(loginModel.UserName)) - throw new ArgumentException("Invalid username!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, ClassesConstants.Username)); User user = await this._userRepository.GetByUsernameAsync(loginModel.UserName); if (!await this._userRepository.VerifyPassword(user, loginModel.Password)) - throw new ArgumentException("Incorrect password!"); + throw new InvalidDataException(string.Format(ErrorMessages.IncorrectData, ClassesConstants.Password.ToLower())); List roleNames = user.Roles.Select(x => x.Name).ToList(); return new TokenModel(this._jwtService.GenerateJwtToken(user.Id, user.UserName, roleNames)); @@ -58,10 +61,11 @@ namespace DevHive.Services.Services public async Task RegisterUser(RegisterServiceModel registerModel) { if (await this._userRepository.DoesUsernameExistAsync(registerModel.UserName)) - throw new ArgumentException("Username already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Username)); if (await this._userRepository.DoesEmailExistAsync(registerModel.Email)) - throw new ArgumentException("Email already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Email)); + User user = this._userMapper.Map(registerModel); @@ -69,9 +73,9 @@ namespace DevHive.Services.Services bool roleResult = await this._userRepository.AddRoleToUser(user, Role.DefaultRole); if (!userResult) - throw new ArgumentException("Unable to create a user"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotCreate, ClassesConstants.User.ToLower())); if (!roleResult) - throw new ArgumentException("Unable to add role to user"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotAdd, ClassesConstants.Role.ToLower())); User createdUser = await this._userRepository.GetByUsernameAsync(registerModel.UserName); @@ -84,7 +88,7 @@ namespace DevHive.Services.Services public async Task GetUserById(Guid id) { User user = await this._userRepository.GetByIdAsync(id) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return this._userMapper.Map(user); } @@ -92,7 +96,7 @@ namespace DevHive.Services.Services public async Task GetUserByUsername(string username) { User user = await this._userRepository.GetByUsernameAsync(username) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return this._userMapper.Map(user); } @@ -101,20 +105,20 @@ namespace DevHive.Services.Services #region Update public async Task UpdateUser(UpdateUserServiceModel updateUserServiceModel) { - await this.ValidateUserOnUpdate(updateUserServiceModel); + await ValidateUserOnUpdate(updateUserServiceModel); User user = await this._userRepository.GetByIdAsync(updateUserServiceModel.Id); - await this.PopulateUserModel(user, updateUserServiceModel); + await PopulateUserModel(user, updateUserServiceModel); if (updateUserServiceModel.Friends.Count > 0) - await this.CreateRelationToFriends(user, updateUserServiceModel.Friends.ToList()); + await CreateRelationToFriends(user, updateUserServiceModel.Friends.ToList()); else user.Friends.Clear(); bool result = await this._userRepository.EditAsync(user.Id, user); if (!result) - throw new InvalidOperationException("Unable to edit user!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotEdit, ClassesConstants.User.ToLower())); User newUser = await this._userRepository.GetByIdAsync(user.Id); return this._userMapper.Map(newUser); @@ -125,7 +129,7 @@ namespace DevHive.Services.Services public async Task DeleteUser(Guid id) { if (!await this._userRepository.DoesUserExistAsync(id)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); User user = await this._userRepository.GetByIdAsync(id); return await this._userRepository.DeleteAsync(user); @@ -140,21 +144,21 @@ namespace DevHive.Services.Services private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel) { if (!await this._userRepository.DoesUserExistAsync(updateUserServiceModel.Id)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); if (updateUserServiceModel.Friends.Any(x => x.UserName == updateUserServiceModel.UserName)) - throw new ArgumentException("You cant add yourself as a friend(sry, bro)!"); + throw new InvalidOperationException(NoYourselfAsFriend); if (!await this._userRepository.DoesUserHaveThisUsernameAsync(updateUserServiceModel.Id, updateUserServiceModel.UserName) && await this._userRepository.DoesUsernameExistAsync(updateUserServiceModel.UserName)) - throw new ArgumentException("Username already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Username.ToLower())); List usernames = new(); foreach (var friend in updateUserServiceModel.Friends) usernames.Add(friend.UserName); if (!await this._userRepository.ValidateFriendsCollectionAsync(usernames)) - throw new ArgumentException("One or more friends do not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.OneOrMoreFriends)); } #endregion @@ -162,7 +166,7 @@ namespace DevHive.Services.Services 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..."); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User) + " " + Rant); if (!await this._roleRepository.DoesNameExist(Role.AdminRole)) { @@ -202,7 +206,7 @@ namespace DevHive.Services.Services foreach (var role in updateUserServiceModel.Roles) { Role returnedRole = await this._roleRepository.GetByNameAsync(role.Name) ?? - throw new ArgumentException($"Role {role.Name} does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); roles.Add(returnedRole); } @@ -214,7 +218,7 @@ namespace DevHive.Services.Services for (int i = 0; i < languagesCount; i++) { Language language = await this._languageRepository.GetByNameAsync(updateUserServiceModel.Languages.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid language name!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, nameof(Language))); languages.Add(language); } @@ -226,7 +230,8 @@ namespace DevHive.Services.Services for (int i = 0; i < technologiesCount; i++) { Technology technology = await this._technologyRepository.GetByNameAsync(updateUserServiceModel.Technologies.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid technology name!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, nameof(Technology))); + technologies.Add(technology); } -- cgit v1.2.3