aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/.editorconfig9
-rw-r--r--src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj (renamed from src/Common/DevHive.Common.Models/DevHive.Common.csproj)0
-rw-r--r--src/Common/DevHive.Common/DevHive.Common.csproj11
-rw-r--r--src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs28
-rw-r--r--src/Common/DevHive.Common/Jwt/JwtService.cs86
-rw-r--r--src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj4
-rw-r--r--src/DevHive.code-workspace10
-rw-r--r--src/DevHive.sln49
-rw-r--r--src/Dockerfile21
-rw-r--r--src/Services/DevHive.Services.Models/DevHive.Services.Models.csproj9
-rw-r--r--src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj18
-rw-r--r--src/Services/DevHive.Services/DevHive.Services.csproj20
-rw-r--r--src/Services/DevHive.Services/Interfaces/IUserService.cs49
-rw-r--r--src/Services/DevHive.Services/Options/JwtOptions.cs14
-rw-r--r--src/Services/DevHive.Services/Services/UserService.cs125
-rw-r--r--src/Web/DevHive.Web.Models/DevHive.Web.Models.csproj9
-rw-r--r--src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj16
-rw-r--r--src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs11
-rw-r--r--src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs14
-rw-r--r--src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs36
-rw-r--r--src/Web/DevHive.Web/Controllers/CommentController.cs10
-rw-r--r--src/Web/DevHive.Web/Controllers/PostController.cs10
-rw-r--r--src/Web/DevHive.Web/Controllers/ProfilePictureController.cs32
-rw-r--r--src/Web/DevHive.Web/Controllers/UserController.cs29
-rw-r--r--src/Web/DevHive.Web/DevHive.Web.csproj29
-rw-r--r--src/Web/DevHive.Web/appsettings.json26
26 files changed, 419 insertions, 256 deletions
diff --git a/src/.editorconfig b/src/.editorconfig
index 7fa9b2a..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
@@ -143,6 +144,7 @@ dotnet_naming_style.pascal_case_style.capitalization = pascal_case
# error RS2008: Enable analyzer release tracking for the analyzer project containing rule '{0}'
dotnet_diagnostic.RS2008.severity = none
+dotnet_diagnostic.CS1591.severity = none
# IDE0073: File header
dotnet_diagnostic.IDE0073.severity = warning
@@ -228,3 +230,6 @@ csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
+
+[/Data/DevHive.Data/Migrations/**]
+dotnet_diagnostic.IDE0055.severity = none
diff --git a/src/Common/DevHive.Common.Models/DevHive.Common.csproj b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj
index f6d662c..f6d662c 100644
--- a/src/Common/DevHive.Common.Models/DevHive.Common.csproj
+++ b/src/Common/DevHive.Common.Models/DevHive.Common.Models.csproj
diff --git a/src/Common/DevHive.Common/DevHive.Common.csproj b/src/Common/DevHive.Common/DevHive.Common.csproj
new file mode 100644
index 0000000..cd60d85
--- /dev/null
+++ b/src/Common/DevHive.Common/DevHive.Common.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <ItemGroup>
+ <ProjectReference Include="..\DevHive.Common.Models\DevHive.Common.Models.csproj"/>
+ </ItemGroup>
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0"/>
+ </ItemGroup>
+</Project>
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..352a7d5
--- /dev/null
+++ b/src/Common/DevHive.Common/Jwt/Interfaces/IJwtService.cs
@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+
+namespace DevHive.Common.Jwt.Interfaces
+{
+ public interface IJwtService
+ {
+ /// <summary>
+ /// The generation of a JWT, when a new user registers or log ins
+ /// Tokens have an expiration time of 7 days.
+ /// </summary>
+ /// <param name="userId">User's Guid</param>
+ /// <param name="username">Users's username</param>
+ /// <param name="roleNames">List of user's roles</param>
+ /// <returns>Return a new JWT, containing the user id, username and roles.</returns>
+ string GenerateJwtToken(Guid userId, string username, List<string> roleNames);
+
+ /// <summary>
+ /// 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
+ /// </summary>
+ /// <param name="userId">Guid of the user being validated</param>
+ /// <param name="rawToken">The raw token coming from the request</param>
+ /// <returns>Bool result of is the user authenticated to do an action</returns>
+ bool ValidateToken(Guid userId, string rawToken);
+ }
+}
diff --git a/src/Common/DevHive.Common/Jwt/JwtService.cs b/src/Common/DevHive.Common/Jwt/JwtService.cs
new file mode 100644
index 0000000..9f316da
--- /dev/null
+++ b/src/Common/DevHive.Common/Jwt/JwtService.cs
@@ -0,0 +1,86 @@
+using System;
+using System.Collections.Generic;
+using System.IdentityModel.Tokens.Jwt;
+using System.Linq;
+using System.Security.Claims;
+using System.Security.Principal;
+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<string> roleNames)
+ {
+ var securityKey = new SymmetricSecurityKey(this._signingKey);
+ var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
+
+ HashSet<Claim> 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(Guid userId, string rawToken)
+ {
+ var tokenHandler = new JwtSecurityTokenHandler();
+ var validationParameters = GetValidationParameters();
+ string actualToken = rawToken.Remove(0, 7);
+
+ IPrincipal principal = tokenHandler.ValidateToken(actualToken, validationParameters, out SecurityToken validatedToken);
+ JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(actualToken);
+
+ 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()
+ {
+ return new TokenValidationParameters()
+ {
+ ValidateLifetime = true,
+ ValidateAudience = true,
+ ValidateIssuer = true,
+ ValidIssuer = this._validationIssuer,
+ ValidAudience = this._audience,
+ IssuerSigningKey = new SymmetricSecurityKey(this._signingKey)
+ };
+ }
+ }
+}
diff --git a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj
index 2af369f..46c7b83 100644
--- a/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj
+++ b/src/Data/DevHive.Data.Tests/DevHive.Data.Tests.csproj
@@ -5,10 +5,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.3"/>
- <PackageReference Include="Moq" Version="4.16.0"/>
+ <PackageReference Include="Moq" Version="4.16.1"/>
<PackageReference Include="NUnit" Version="3.13.1"/>
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0"/>
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3"/>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1"/>
<PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296"/>
</ItemGroup>
<ItemGroup>
diff --git a/src/DevHive.code-workspace b/src/DevHive.code-workspace
index 8511609..72c2301 100644
--- a/src/DevHive.code-workspace
+++ b/src/DevHive.code-workspace
@@ -15,7 +15,7 @@
{
"name": "Common",
"path": "./Common"
- },
+ }
],
"settings": {
"files.exclude": {
@@ -23,14 +23,14 @@
"**/bin": true,
"**/obj": true,
- ".gitignore" : true,
+ ".gitignore": true
},
"code-runner.fileDirectoryAsCwd": true,
"dotnet-test-explorer.runInParallel": true,
"dotnet-test-explorer.testProjectPath": "**/*.Tests.csproj",
"omnisharp.enableEditorConfigSupport": true,
"omnisharp.enableRoslynAnalyzers": true,
- "prettier.useEditorConfig": true,
+ "prettier.useEditorConfig": true
},
"launch": {
"configurations": [
@@ -45,8 +45,8 @@
"stopAtEntry": false,
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
- },
- },
+ }
+ }
// {
// "name": "Launch Data Tests",
// "type": "coreclr",
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/Dockerfile b/src/Dockerfile
index f99804c..0491463 100644
--- a/src/Dockerfile
+++ b/src/Dockerfile
@@ -1,16 +1,11 @@
-FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
-FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
-EXPOSE 80
+FROM mcr.microsoft.com/dotnet/sdk:5.0 AS sdk
-COPY . /app
-WORKDIR /app
+COPY . ./Build
+WORKDIR /Build
+RUN [ "dotnet", "publish", "-f", "net5.0", "-c", "Release", "Web/DevHive.Web/DevHive.Web.csproj", "-o", "/Out"]
-RUN dotnet restore
-RUN dotnet build -c Release -o /app/build
+FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS runtime
+COPY --from=sdk /Out /App
-FROM build AS publish
-RUN dotnet publish "DevHive.sln" -c Release -o /app/publish
-
-FROM base AS final
-COPY --from=publish /app/publish .
-ENTRYPOINT ["dotnet", "DevHive.Web.dll"]
+WORKDIR /App
+ENTRYPOINT [ "dotnet", "DevHive.Web.dll" ]
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 @@
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2"/>
- <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296"/>
+ <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
+ <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.csproj"/>
+ <ProjectReference Include="..\..\Common\DevHive.Common\DevHive.Common.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.Models.csproj" />
</ItemGroup>
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj b/src/Services/DevHive.Services.Tests/DevHive.Services.Tests.csproj
index bdfb2bb..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 @@
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.3"/>
- <PackageReference Include="Moq" Version="4.16.0"/>
- <PackageReference Include="NUnit" Version="3.13.1"/>
- <PackageReference Include="NUnit3TestAdapter" Version="3.17.0"/>
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3"/>
- <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296"/>
+ <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.3" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="NUnit" Version="3.13.1" />
+ <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
+ <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\DevHive.Services\DevHive.Services.csproj"/>
+ <ProjectReference Include="..\DevHive.Services\DevHive.Services.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common\DevHive.Common.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.Models.csproj" />
</ItemGroup>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>
-</Project> \ No newline at end of file
+</Project>
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 @@
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0"/>
+ <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
- <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0"/>
- <PackageReference Include="AutoMapper" Version="10.1.1"/>
- <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1"/>
- <PackageReference Include="CloudinaryDotNet" Version="1.14.0"/>
- <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296"/>
+ <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
+ <PackageReference Include="AutoMapper" Version="10.1.1" />
+ <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
+ <PackageReference Include="CloudinaryDotNet" Version="1.14.0" />
+ <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\..\Data\DevHive.Data\DevHive.Data.csproj"/>
- <ProjectReference Include="..\DevHive.Services.Models\DevHive.Services.Models.csproj"/>
+ <ProjectReference Include="..\..\Data\DevHive.Data\DevHive.Data.csproj" />
+ <ProjectReference Include="..\DevHive.Services.Models\DevHive.Services.Models.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common\DevHive.Common.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.Models.csproj" />
</ItemGroup>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>
-</Project> \ No newline at end of file
+</Project>
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
{
+ /// <summary>
+ /// Log ins an existing user and gives him/her a JWT Token for further authorization
+ /// </summary>
+ /// <param name="loginModel">Login service model, conaining user's username and password</param>
+ /// <returns>A JWT Token for authorization</returns>
Task<TokenModel> LoginUser(LoginServiceModel loginModel);
+
+ /// <summary>
+ /// Registers a new user and gives him/her a JWT Token for further authorization
+ /// </summary>
+ /// <param name="registerModel">Register service model, containing the new user's data</param>
+ /// <returns>A JWT Token for authorization</returns>
Task<TokenModel> RegisterUser(RegisterServiceModel registerModel);
+ /// <summary>
+ /// Get a user by his username. Used for querying profiles without provided authentication
+ /// </summary>
+ /// <param name="username">User's username, who's to be queried</param>
+ /// <returns>The queried user or null, if non existant</returns>
Task<UserServiceModel> GetUserByUsername(string username);
+
+ /// <summary>
+ /// Get a user by his Guid. Used for querying full user's profile
+ /// Requires authenticated user
+ /// </summary>
+ /// <param name="id">User's username, who's to be queried</param>
+ /// <returns>The queried user or null, if non existant</returns>
Task<UserServiceModel> GetUserById(Guid id);
+ /// <summary>
+ /// Updates a user's data, provided a full model with new details
+ /// Requires authenticated user
+ /// </summary>
+ /// <param name="updateUserServiceModel">Full update user model for updating</param>
+ /// <returns>Read model of the new user</returns>
Task<UserServiceModel> UpdateUser(UpdateUserServiceModel updateUserServiceModel);
+
+ /// <summary>
+ /// Uploads the given picture and assigns it's link to the user in the database
+ /// Requires authenticated user
+ /// </summary>
+ /// <param name="updateProfilePictureServiceModel">Contains User's Guid and the new picture to be updated</param>
+ /// <returns>The new picture's URL</returns>
Task<ProfilePictureServiceModel> UpdateProfilePicture(UpdateProfilePictureServiceModel updateProfilePictureServiceModel);
+ /// <summary>
+ /// Deletes a user from the database and removes his data entirely
+ /// Requires authenticated user
+ /// </summary>
+ /// <param name="id">The user's Guid, who's to be deleted</param>
+ /// <returns>True if successfull, false otherwise</returns>
Task<bool> DeleteUser(Guid id);
- Task<bool> ValidJWT(Guid id, string rawTokenData);
-
+ /// <summary>
+ /// We don't talk about that!
+ /// </summary>
+ /// <param name="userId"></param>
+ /// <returns></returns>
Task<TokenModel> SuperSecretPromotionToAdmin(Guid userId);
}
}
diff --git a/src/Services/DevHive.Services/Options/JwtOptions.cs b/src/Services/DevHive.Services/Options/JwtOptions.cs
deleted file mode 100644
index d973f45..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/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs
index dfd45cc..4f74b06 100644
--- a/src/Services/DevHive.Services/Services/UserService.cs
+++ b/src/Services/DevHive.Services/Services/UserService.cs
@@ -1,21 +1,15 @@
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 DevHive.Common.Models.Misc;
using Microsoft.AspNetCore.Http;
-using Newtonsoft.Json;
+using DevHive.Common.Jwt.Interfaces;
namespace DevHive.Services.Services
{
@@ -26,31 +20,27 @@ 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;
public UserService(IUserRepository userRepository,
ILanguageRepository languageRepository,
IRoleRepository roleRepository,
ITechnologyRepository technologyRepository,
IMapper mapper,
- JwtOptions jwtOptions,
- ICloudService cloudService)
+ 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;
+ this._jwtService = jwtService;
}
#region Authentication
- /// <summary>
- /// 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)
- /// </summary>
public async Task<TokenModel> LoginUser(LoginServiceModel loginModel)
{
if (!await this._userRepository.DoesUsernameExistAsync(loginModel.UserName))
@@ -61,12 +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<string> roleNames = user.Roles.Select(x => x.Name).ToList();
+ return new TokenModel(this._jwtService.GenerateJwtToken(user.Id, user.UserName, roleNames));
}
- /// <summary>
- /// Returns a new JSON Web Token (that can be used for authorization) for the given user
- /// </summary>
public async Task<TokenModel> RegisterUser(RegisterServiceModel registerModel)
{
if (await this._userRepository.DoesUsernameExistAsync(registerModel.UserName))
@@ -86,7 +74,9 @@ 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<string> roleNames = createdUser.Roles.Select(x => x.Name).ToList();
+ return new TokenModel(this._jwtService.GenerateJwtToken(createdUser.Id, createdUser.UserName, roleNames));
}
#endregion
@@ -130,9 +120,6 @@ namespace DevHive.Services.Services
return this._userMapper.Map<UserServiceModel>(newUser);
}
- /// <summary>
- /// Uploads the given picture and assigns it's link to the user in the database
- /// </summary>
public async Task<ProfilePictureServiceModel> UpdateProfilePicture(UpdateProfilePictureServiceModel updateProfilePictureServiceModel)
{
User user = await this._userRepository.GetByIdAsync(updateProfilePictureServiceModel.UserId);
@@ -169,57 +156,7 @@ namespace DevHive.Services.Services
#region Validations
/// <summary>
- /// 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
- /// </summary>
- public async Task<bool> ValidJWT(Guid id, string 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<string> 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;
- }
-
- /// <summary>
- /// Returns all values from a given claim type
- /// </summary>
- private static List<string> GetClaimTypeValues(string type, IEnumerable<Claim> claims)
- {
- List<string> toReturn = new();
-
- foreach (var claim in claims)
- if (claim.Type == type)
- toReturn.Add(claim.Value);
-
- return toReturn;
- }
-
- /// <summary>
- /// 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
/// </summary>
private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel)
@@ -241,38 +178,6 @@ namespace DevHive.Services.Services
if (!await this._userRepository.ValidateFriendsCollectionAsync(usernames))
throw new ArgumentException("One or more friends do not exist!");
}
-
- /// <summary>
- /// Return a new JSON Web Token, containing the user id, username and roles.
- /// Tokens have an expiration time of 7 days.
- /// </summary>
- private string WriteJWTSecurityToken(Guid userId, string username, HashSet<Role> roles)
- {
- byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret);
- HashSet<Claim> 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
@@ -294,9 +199,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<string> 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.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 @@
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
- <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.csproj"/>
+ <ProjectReference Include="..\..\Common\DevHive.Common\DevHive.Common.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.Models.csproj" />
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2"/>
- <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296"/>
+ <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
+ <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296" />
</ItemGroup>
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj b/src/Web/DevHive.Web.Tests/DevHive.Web.Tests.csproj
index 465698c..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 @@
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Moq" Version="4.16.0"/>
- <PackageReference Include="NUnit" Version="3.13.1"/>
- <PackageReference Include="NUnit3TestAdapter" Version="3.17.0"/>
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3"/>
- <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296"/>
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="NUnit" Version="3.13.1" />
+ <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
+ <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\DevHive.Web\DevHive.Web.csproj"/>
+ <ProjectReference Include="..\DevHive.Web\DevHive.Web.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common\DevHive.Common.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.Models.csproj" />
</ItemGroup>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs
index 153b17f..6a5799f 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,11 +30,19 @@ namespace DevHive.Web.Configurations.Extensions
services.AddTransient<IPostService, PostService>();
services.AddTransient<ICommentService, CommentService>();
services.AddTransient<IFeedService, FeedService>();
+ services.AddTransient<IRateService, RateService>();
+
services.AddTransient<ICloudService, CloudinaryService>(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.AddSingleton<IJwtService, JwtService>(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));
services.AddTransient<IRatingService, RatingService>();
}
}
diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs
index 8d387bd..18127bc 100644
--- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs
+++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs
@@ -1,6 +1,5 @@
using System.Text;
using System.Threading.Tasks;
-using DevHive.Services.Options;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -12,15 +11,10 @@ namespace DevHive.Web.Configurations.Extensions
{
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")
+ var signingKey = Encoding.ASCII.GetBytes(configuration
+ .GetSection("Jwt")
+ .GetSection("signingKey")
.Value);
// Setup Jwt Authentication
@@ -42,7 +36,7 @@ namespace DevHive.Web.Configurations.Extensions
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
- IssuerSigningKey = new SymmetricSecurityKey(key),
+ IssuerSigningKey = new SymmetricSecurityKey(signingKey),
ValidateIssuer = false,
ValidateAudience = false
};
diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs
index a0641ab..bfa44b0 100644
--- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs
+++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs
@@ -1,23 +1,53 @@
+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;
namespace DevHive.Web.Configurations.Extensions
{
public static class SwaggerExtensions
{
+#pragma warning disable S1075
+ private const string LicenseName = "GPL-3.0 License";
+ private const string LicenseUri = "https://github.com/Team-Kaleidoscope/DevHive/blob/main/LICENSE";
+ private const string TermsOfServiceUri = "https://example.com/terms";
+#pragma warning restore S1075
+
public static void SwaggerConfiguration(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
+ c.SwaggerDoc("v0.1", new OpenApiInfo
+ {
+ Version = "v0.1",
+ Title = "API",
+ Description = "DevHive Social Media's first official API release",
+ TermsOfService = new Uri(TermsOfServiceUri),
+ License = new OpenApiLicense
+ {
+ Name = LicenseName,
+ Url = new Uri(LicenseUri)
+ }
+ });
+
+ string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
+ string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
+ c.IncludeXmlComments(xmlPath);
});
}
public static void UseSwaggerConfiguration(this IApplicationBuilder app)
{
app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
+ app.UseSwaggerUI(c =>
+ {
+ c.SwaggerEndpoint("/swagger/v0.1/swagger.json", "v0.1");
+ });
}
}
-} \ No newline at end of file
+}
diff --git a/src/Web/DevHive.Web/Controllers/CommentController.cs b/src/Web/DevHive.Web/Controllers/CommentController.cs
index 7273dda..1722801 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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/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<IActionResult> 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<UpdateProfilePictureServiceModel>(updateProfilePictureWebModel);
+ // updateProfilePictureServiceModel.UserId = userId;
+
+ // ProfilePictureServiceModel profilePictureServiceModel = await this._userService.UpdateProfilePicture(updateProfilePictureServiceModel);
+ // ProfilePictureWebModel profilePictureWebModel = this._userMapper.Map<ProfilePictureWebModel>(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..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<IActionResult> 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<IActionResult> 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<UpdateUserServiceModel>(updateUserWebModel);
@@ -93,23 +97,6 @@ namespace DevHive.Web.Controllers
return new AcceptedResult("UpdateUser", userWebModel);
}
-
- [HttpPut]
- [Route("ProfilePicture")]
- [Authorize(Roles = "User,Admin")]
- public async Task<IActionResult> UpdateProfilePicture(Guid userId, [FromForm] UpdateProfilePictureWebModel updateProfilePictureWebModel, [FromHeader] string authorization)
- {
- if (!await this._userService.ValidJWT(userId, authorization))
- return new UnauthorizedResult();
-
- UpdateProfilePictureServiceModel updateProfilePictureServiceModel = this._userMapper.Map<UpdateProfilePictureServiceModel>(updateProfilePictureWebModel);
- updateProfilePictureServiceModel.UserId = userId;
-
- ProfilePictureServiceModel profilePictureServiceModel = await this._userService.UpdateProfilePicture(updateProfilePictureServiceModel);
- ProfilePictureWebModel profilePictureWebModel = this._userMapper.Map<ProfilePictureWebModel>(profilePictureServiceModel);
-
- return new AcceptedResult("UpdateProfilePicture", profilePictureWebModel);
- }
#endregion
#region Delete
@@ -117,7 +104,7 @@ namespace DevHive.Web.Controllers
[Authorize(Roles = "User,Admin")]
public async Task<IActionResult> 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);
diff --git a/src/Web/DevHive.Web/DevHive.Web.csproj b/src/Web/DevHive.Web/DevHive.Web.csproj
index 7c0b262..ea9eee6 100644
--- a/src/Web/DevHive.Web/DevHive.Web.csproj
+++ b/src/Web/DevHive.Web/DevHive.Web.csproj
@@ -5,25 +5,32 @@
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest</AnalysisLevel>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AllowUntrustedCertificate>true</AllowUntrustedCertificate>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.3" NoWarn="NU1605"/>
- <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.3" NoWarn="NU1605"/>
+ <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.3" NoWarn="NU1605" />
+ <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.3" NoWarn="NU1605" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
- <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.2"/>
- <PackageReference Include="Swashbuckle.AspNetCore" Version="6.0.5"/>
- <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1"/>
- <PackageReference Include="AutoMapper" Version="10.1.1"/>
- <PackageReference Include="Newtonsoft.Json" Version="12.0.3"/>
- <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.3"/>
- <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296"/>
+ <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.2" />
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="6.0.7" />
+ <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
+ <PackageReference Include="AutoMapper" Version="10.1.1" />
+ <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.3" />
+ <PackageReference Include="SonarAnalyzer.CSharp" Version="8.18.0.27296" />
+ <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.0.7" />
+ <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.0.7" />
+ <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.0.7" />
+ <PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="6.1.0" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\DevHive.Web.Models\DevHive.Web.Models.csproj"/>
- <ProjectReference Include="..\..\Services\DevHive.Services\DevHive.Services.csproj"/>
+ <ProjectReference Include="..\DevHive.Web.Models\DevHive.Web.Models.csproj" />
+ <ProjectReference Include="..\..\Services\DevHive.Services\DevHive.Services.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common.Models\DevHive.Common.Models.csproj" />
+ <ProjectReference Include="..\..\Common\DevHive.Common\DevHive.Common.csproj" />
</ItemGroup>
</Project>
diff --git a/src/Web/DevHive.Web/appsettings.json b/src/Web/DevHive.Web/appsettings.json
index bcdcae7..fcf9805 100644
--- a/src/Web/DevHive.Web/appsettings.json
+++ b/src/Web/DevHive.Web/appsettings.json
@@ -1,20 +1,22 @@
{
- "AppSettings": {
- "Secret": "gXfQlU6qpDleFWyimscjYcT3tgFsQg3yoFjcvSLxG56n1Vu2yptdIUq254wlJWjm"
- },
- "ConnectionStrings": {
- "DEV": "Server=localhost;Port=5432;Database=API;User Id=postgres;Password=;"
+ "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"
+ }
+ }
}