diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs
index fe225b6..8130de4 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs
@@ -1,7 +1,6 @@
using DamageAssesment.Api.Answers.Interfaces;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.OpenApi.Any;
namespace DamageAssesment.Api.Answers.Controllers
{
@@ -16,7 +15,7 @@ namespace DamageAssesment.Api.Answers.Controllers
///
/// Get all answers
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("answers")]
public async Task GetAnswersAsync() {
@@ -32,7 +31,7 @@ namespace DamageAssesment.Api.Answers.Controllers
/// Get an answer based on answerId.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("answers/{id}")]
public async Task GetAnswerByIdAsync(int id)
{
@@ -48,6 +47,7 @@ namespace DamageAssesment.Api.Answers.Controllers
///
/// Get all answers based on responseId.
///
+ [Authorize(Roles = "admin")]
[HttpGet("answers/byresponse/{responseid}")]
public async Task GetAnswersByResponseId(int responseid)
{
@@ -61,7 +61,7 @@ namespace DamageAssesment.Api.Answers.Controllers
///
/// Get all answers based on questionId.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("answers/byquestion/{questionid}")]
public async Task AnswersByQuestionId(int questionid)
{
@@ -75,7 +75,7 @@ namespace DamageAssesment.Api.Answers.Controllers
///
/// Update an existing answer.
///
-
+ [Authorize(Roles = "admin")]
[HttpPut("answers")]
public async Task UpdateAnswer(Models.Answer answer)
{
@@ -96,7 +96,7 @@ namespace DamageAssesment.Api.Answers.Controllers
///
/// Save a new answer.
///
-
+ [Authorize(Roles = "admin")]
[HttpPost("answers")]
public async Task CreateAnswer(Models.Answer answer)
{
@@ -114,7 +114,7 @@ namespace DamageAssesment.Api.Answers.Controllers
///
/// Delete an existing answer.
///
-
+ [Authorize(Roles = "admin")]
[HttpDelete("answers/{id}")]
public async Task DeleteAnswer(int id)
{
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs
index 7229cf9..95475fe 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs
@@ -1,23 +1,73 @@
using DamageAssesment.Api.Answers.Db;
using DamageAssesment.Api.Answers.Interfaces;
using DamageAssesment.Api.Answers.Providers;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
+using Microsoft.IdentityModel.Tokens;
+using Microsoft.OpenApi.Models;
using System.Reflection;
+using System.Text;
var builder = WebApplication.CreateBuilder(args);
-
+var authkey = builder.Configuration.GetValue("JwtSettings:securitykey");
+builder.Services.AddAuthentication(item =>
+{
+ item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+}).AddJwtBearer(item =>
+{
+ item.RequireHttpsMetadata = true;
+ item.SaveToken = true;
+ item.TokenValidationParameters = new TokenValidationParameters()
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
+ ValidateIssuer = false,
+ ValidateAudience = false,
+ ClockSkew = TimeSpan.Zero
+ };
+});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
-builder.Services.AddSwaggerGen(c =>
+builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
+ options.IncludeXmlComments(xmlPath);
+
+ OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
+ {
+ Name = "Bearer",
+ BearerFormat = "JWT",
+ Scheme = "bearer",
+ Description = "Specify the authorization token.",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.Http,
+ };
+
+ options.AddSecurityDefinition("jwt_auth", securityDefinition);
+
+ // Make sure swagger UI requires a Bearer token specified
+ OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
+ {
+ Reference = new OpenApiReference()
+ {
+ Id = "jwt_auth",
+ Type = ReferenceType.SecurityScheme
+ }
+ };
+
+ OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
+ {
+ {securityScheme, new string[] { }},
+ };
+
+ options.AddSecurityRequirement(securityRequirements);
});
builder.Services.AddScoped();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30
@@ -35,7 +85,7 @@ if (app.Environment.IsDevelopment())
app.UseSwagger();
app.UseSwaggerUI();
}
-
+app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs
index 16c223c..5e6a4eb 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs
@@ -1,6 +1,7 @@
using Azure;
using DamageAssesment.Api.Attachments.Interfaces;
using DamageAssesment.Api.Attachments.Models;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
@@ -21,7 +22,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
///
/// Get all attachments.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("attachments")]
public async Task GetAttachmentsAsync()
{
@@ -37,6 +38,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
///
/// Get all attachments by attachmentId.
///
+ [Authorize(Roles = "admin")]
[HttpGet("attachments/{id}")]
public async Task GetAttachmentbyIdAsync(int id)
{
@@ -80,7 +82,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
///
/// Save new Attachment(s)
///
-
+ [Authorize(Roles = "admin")]
[HttpPost("attachments"), DisableRequestSizeLimit]
public async Task UploadAttachmentAsync(AttachmentInfo attachmentInfo)
{
@@ -107,7 +109,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
///
/// Modify an new attachment.
///
-
+ [Authorize(Roles = "admin")]
[HttpPut("attachments"), DisableRequestSizeLimit]
public async Task UpdateAttachmentAsync(AttachmentInfo attachmentInfo)
{
@@ -138,6 +140,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
///
/// Delete an existing attachment.
///
+ [Authorize(Roles = "admin")]
[HttpDelete("attachments/{id}")]
public async Task DeleteAttachment(int id)
{
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs
index 61ce1c5..9368b21 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs
@@ -1,25 +1,75 @@
using DamageAssesment.Api.Attachments.Db;
using DamageAssesment.Api.Attachments.Interfaces;
using DamageAssesment.Api.Attachments.Providers;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
+using Microsoft.IdentityModel.Tokens;
+using Microsoft.OpenApi.Models;
using System.Reflection;
+using System.Text;
var builder = WebApplication.CreateBuilder(args);
-
+var authkey = builder.Configuration.GetValue("JwtSettings:securitykey");
+builder.Services.AddAuthentication(item =>
+{
+ item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+}).AddJwtBearer(item =>
+{
+ item.RequireHttpsMetadata = true;
+ item.SaveToken = true;
+ item.TokenValidationParameters = new TokenValidationParameters()
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
+ ValidateIssuer = false,
+ ValidateAudience = false,
+ ClockSkew = TimeSpan.Zero
+ };
+});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
-builder.Services.AddSwaggerGen(c =>
+builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
+ options.IncludeXmlComments(xmlPath);
+
+ OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
+ {
+ Name = "Bearer",
+ BearerFormat = "JWT",
+ Scheme = "bearer",
+ Description = "Specify the authorization token.",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.Http,
+ };
+
+ options.AddSecurityDefinition("jwt_auth", securityDefinition);
+
+ // Make sure swagger UI requires a Bearer token specified
+ OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
+ {
+ Reference = new OpenApiReference()
+ {
+ Id = "jwt_auth",
+ Type = ReferenceType.SecurityScheme
+ }
+ };
+
+ OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
+ {
+ {securityScheme, new string[] { }},
+ };
+
+ options.AddSecurityRequirement(securityRequirements);
});
builder.Services.AddScoped();
builder.Services.AddScoped();
@@ -45,6 +95,7 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
+app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
diff --git a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Controllers/DoculinkController.cs b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Controllers/DoculinkController.cs
index 99d00a8..b6552c3 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Controllers/DoculinkController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Controllers/DoculinkController.cs
@@ -2,8 +2,10 @@
using DamageAssesment.Api.DocuLinks.Interfaces;
using DamageAssesment.Api.DocuLinks.Models;
using DamageAssesment.Api.DocuLinks.Providers;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
+using System.Data;
namespace DamageAssesment.Api.DocuLinks.Controllers
{
@@ -24,6 +26,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
/// Get all Doculink type.
///
[HttpGet]
+ [Authorize(Roles = "admin")]
[Route("doculinks/types")]
[Route("doculinks/types/{language:alpha}")]
public async Task GetLinkTypesAsync(string? language)
@@ -38,9 +41,10 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Get a Doculink type by id.
///
- [HttpGet]
+ [Authorize(Roles = "admin")]
[Route("doculinks/types/{id}")]
[Route("doculinks/types/{id}/{language:alpha}")]
+ [HttpGet]
public async Task GetLinkTypeAsync(int id,string? language)
{
var result = await this.documentsProvider.GetLinkTypeAsync(id, language);
@@ -53,6 +57,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Update a existing Doculink type.
///
+ [Authorize(Roles = "admin")]
[HttpPut]
[Route("doculinks/types/{id}")]
public async Task UpdateLinkType(int id,Models.LinkType linkType)
@@ -74,6 +79,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Create a new Doculink type.
///
+ [Authorize(Roles = "admin")]
[HttpPost]
[Route("doculinks/types")]
public async Task CreateLinkType(Models.LinkType linkType)
@@ -92,6 +98,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Delete a existing Doculink type by id.
///
+ [Authorize(Roles = "admin")]
[HttpDelete]
[Route("doculinks/types/{id}")]
public async Task DeleteLinkType(int id)
@@ -104,9 +111,10 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
return NotFound();
}
///
- /// Get all Doculink.
+ /// Get all documents.
///
- ///
+
+ [Authorize(Roles = "admin")]
[Route("doculinks")]
[Route("doculinks/{linktype:alpha}")]
[Route("doculinks/{linktype:alpha}/{language:alpha}")]
@@ -123,6 +131,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Get all active Doculink.
///
+ [Authorize(Roles = "admin")]
[Route("doculinks/active")]
[Route("doculinks/active/{linktype:alpha}")]
[Route("doculinks/active/{linktype:alpha}/{language:alpha}")]
@@ -139,6 +148,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Get all active Doculink.
///
+ [Authorize(Roles = "admin")]
[Route("doculinks/active/{linktypeid:int}")]
[Route("doculinks/active/{linktypeid:int}/{language:alpha}")]
[HttpGet]
@@ -154,6 +164,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Get a Doculink by id.
///
+ [Authorize(Roles = "admin")]
[HttpGet]
[Route("doculinks/{id}")]
[Route("doculinks/{id}/{linktype:alpha}")]
@@ -168,8 +179,9 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
return NotFound();
}
///
- /// update existing doclink.
+ /// Upload new document.
///
+ [Authorize(Roles = "admin")]
[HttpPut]
[Route("doculinks/{id}")]
public async Task UpdateDocument(int id,ReqDoculink documentInfo)
@@ -195,6 +207,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
///
/// Create new doclink.
///
+ [Authorize(Roles = "admin")]
[HttpPost]
[Route("doculinks")]
public async Task CreateDocument(ReqDoculink documentInfo)
@@ -220,8 +233,9 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
}
}
///
- /// Delete Doculink by id.
+ /// Delete document by id.
///
+ [Authorize(Roles = "admin")]
[HttpDelete]
[Route("doculinks/{id}")]
public async Task DeleteDocument(int id)
diff --git a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/DamageAssesment.Api.DocuLinks.csproj b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/DamageAssesment.Api.DocuLinks.csproj
index b71afa9..a1d917b 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/DamageAssesment.Api.DocuLinks.csproj
+++ b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/DamageAssesment.Api.DocuLinks.csproj
@@ -10,6 +10,7 @@
+
diff --git a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Program.cs
index f25927c..9d480b2 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Program.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/Program.cs
@@ -2,19 +2,69 @@ using DamageAssesment.Api.DocuLinks.Db;
using DamageAssesment.Api.DocuLinks.Interfaces;
using DamageAssesment.Api.DocuLinks.Providers;
using Microsoft.EntityFrameworkCore;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.IdentityModel.Tokens;
using System.Reflection;
+using System.Text;
+using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
-
+var authkey = builder.Configuration.GetValue("JwtSettings:securitykey");
+builder.Services.AddAuthentication(item =>
+{
+ item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+}).AddJwtBearer(item =>
+{
+ item.RequireHttpsMetadata = true;
+ item.SaveToken = true;
+ item.TokenValidationParameters = new TokenValidationParameters()
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
+ ValidateIssuer = false,
+ ValidateAudience = false,
+ ClockSkew = TimeSpan.Zero
+ };
+});
builder.Services.AddControllers();
-builder.Services.AddSwaggerGen(c =>
+builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
+ options.IncludeXmlComments(xmlPath);
+
+ OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
+ {
+ Name = "Bearer",
+ BearerFormat = "JWT",
+ Scheme = "bearer",
+ Description = "Specify the authorization token.",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.Http,
+ };
+
+ options.AddSecurityDefinition("jwt_auth", securityDefinition);
+
+ // Make sure swagger UI requires a Bearer token specified
+ OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
+ {
+ Reference = new OpenApiReference()
+ {
+ Id = "jwt_auth",
+ Type = ReferenceType.SecurityScheme
+ }
+ };
+
+ OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
+ {
+ {securityScheme, new string[] { }},
+ };
+
+ options.AddSecurityRequirement(securityRequirements);
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
@@ -36,6 +86,7 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
+app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
diff --git a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/appsettings.json
index e38d9fb..9d665b2 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/appsettings.json
+++ b/DamageAssesmentApi/DamageAssesment.Api.DocuLinks/appsettings.json
@@ -6,8 +6,12 @@
}
},
"AllowedHosts": "*",
+ "JwtSettings": {
+ "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
+ },
"Fileupload": {
"folderpath": "DASA_Documents/Active",
"Deletepath": "DASA_Documents/Deleted"
}
}
+
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs
index 05901c5..f247d17 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs
@@ -1,4 +1,5 @@
using DamageAssesment.Api.Employees.Interfaces;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -18,7 +19,7 @@ namespace DamageAssesment.Api.Employees.Controllers
///
/// GET request for retrieving employees.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("employees")]
public async Task GetEmployeesAsync()
{
@@ -35,7 +36,7 @@ namespace DamageAssesment.Api.Employees.Controllers
///
/// GET request for retrieving an employee by ID.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("employees/{id}")]
public async Task GetEmployeeByIdAsync(int id)
{
@@ -48,11 +49,12 @@ namespace DamageAssesment.Api.Employees.Controllers
return NotFound();
}
-
+
///
/// PUT request for updating an existing employee.
///
/// The updated employee object.
+ [Authorize(Roles = "admin")]
[HttpPut("employees/{id}")]
public async Task UpdateEmployee(int id, Models.Employee Employee)
{
@@ -75,6 +77,7 @@ namespace DamageAssesment.Api.Employees.Controllers
/// POST request for creating a new employee.
///
/// The employee information for creating a new employee.
+ [Authorize(Roles = "admin")]
[HttpPost("employees")]
public async Task CreateEmployee(Models.Employee Employee)
{
@@ -93,6 +96,7 @@ namespace DamageAssesment.Api.Employees.Controllers
/// DELETE request for deleting an existing employee.
///
/// The ID of the employee to be deleted.
+ [Authorize(Roles = "admin")]
[HttpDelete("employees/{id}")]
public async Task DeleteEmployee(int id)
{
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs
index 1e88127..a4cf2df 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs
@@ -1,23 +1,74 @@
using DamageAssesment.Api.Employees.Db;
using DamageAssesment.Api.Employees.Interfaces;
using DamageAssesment.Api.Employees.Providers;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
+using Microsoft.IdentityModel.Tokens;
+using Microsoft.OpenApi.Models;
using System.Reflection;
+using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
+var authkey = builder.Configuration.GetValue("JwtSettings:securitykey");
+builder.Services.AddAuthentication(item =>
+{
+ item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+}).AddJwtBearer(item =>
+{
+ item.RequireHttpsMetadata = true;
+ item.SaveToken = true;
+ item.TokenValidationParameters = new TokenValidationParameters()
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
+ ValidateIssuer = false,
+ ValidateAudience = false,
+ ClockSkew = TimeSpan.Zero
+ };
+});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
-builder.Services.AddSwaggerGen(c =>
+builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
+ options.IncludeXmlComments(xmlPath);
+
+ OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
+ {
+ Name = "Bearer",
+ BearerFormat = "JWT",
+ Scheme = "bearer",
+ Description = "Specify the authorization token.",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.Http,
+ };
+
+ options.AddSecurityDefinition("jwt_auth", securityDefinition);
+
+ // Make sure swagger UI requires a Bearer token specified
+ OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
+ {
+ Reference = new OpenApiReference()
+ {
+ Id = "jwt_auth",
+ Type = ReferenceType.SecurityScheme
+ }
+ };
+
+ OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
+ {
+ {securityScheme, new string[] { }},
+ };
+
+ options.AddSecurityRequirement(securityRequirements);
});
builder.Services.AddScoped();
@@ -43,6 +94,7 @@ if (app.Environment.IsDevelopment())
}
}
+app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json
index 1a1f3fe..ff5949d 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json
+++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json
@@ -8,10 +8,5 @@
"Microsoft.AspNetCore": "Warning"
}
},
- "AllowedHosts": "*",
- "settings": {
- "endpoint1": "xxx",
- "endpoint2": "xxx",
- "endpoint3": "xxx"
- }
+ "AllowedHosts": "*"
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs
index cea800d..8de7678 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs
@@ -1,4 +1,5 @@
using DamageAssesment.Api.Locations.Interfaces;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -15,7 +16,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// Get all locations.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("locations")]
public async Task GetLocationsAsync()
{
@@ -31,7 +32,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// Get all locations based on locationdId.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("locations/{id}")]
public async Task GetLocationByIdAsync(int id)
{
@@ -47,7 +48,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// Update a Location.
///
-
+ [Authorize(Roles = "admin")]
[HttpPut("locations/{id}")]
public async Task UpdateLocation(int id, Models.Location Location)
{
@@ -65,7 +66,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// Save a new location.
///
-
+ [Authorize(Roles = "admin")]
[HttpPost("locations")]
public async Task CreateLocation(Models.Location Location)
{
@@ -83,7 +84,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// Delete an existing location.
///
-
+ [Authorize(Roles = "admin")]
[HttpDelete("locations/{id}")]
public async Task DeleteLocation(int id)
{
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs
index 172043c..d7fe03c 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs
@@ -1,4 +1,5 @@
using DamageAssesment.Api.Locations.Interfaces;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Locations.Controllers
@@ -15,7 +16,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// Get all regions.2
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("regions")]
public async Task GetRegionsAsync()
{
@@ -29,7 +30,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// GET request for retrieving a region by its ID.
///
-
+ [Authorize(Roles = "admin")]
[HttpGet("regions/{id}")]
public async Task GetRegionAsync(int id)
{
@@ -43,7 +44,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// POST request for creating a new region.
///
-
+ [Authorize(Roles = "admin")]
[HttpPost("regions")]
public async Task PostRegionAsync(Models.Region region)
{
@@ -57,7 +58,7 @@ namespace DamageAssesment.Api.Locations.Controllers
///
/// PUT request for updating an existing region.
///
-
+ [Authorize(Roles = "admin")]
[HttpPut("regions/{id}")]
public async Task PutRegionAsync(int id, Models.Region region)
{
@@ -75,7 +76,7 @@ namespace DamageAssesment.Api.Locations.Controllers
/// DELETE request for deleting a region based on ID.
///
-
+ [Authorize(Roles = "admin")]
[HttpDelete("regions/{id}")]
public async Task DeleteRegionAsync(int id)
{
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs
index 200e39b..6563a8b 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs
@@ -1,23 +1,73 @@
using DamageAssesment.Api.Locations.Db;
using DamageAssesment.Api.Locations.Interfaces;
using DamageAssesment.Api.Locations.Providers;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
+using Microsoft.IdentityModel.Tokens;
+using Microsoft.OpenApi.Models;
using System.Reflection;
+using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
-
+var authkey = builder.Configuration.GetValue("JwtSettings:securitykey");
+builder.Services.AddAuthentication(item =>
+{
+ item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+}).AddJwtBearer(item =>
+{
+ item.RequireHttpsMetadata = true;
+ item.SaveToken = true;
+ item.TokenValidationParameters = new TokenValidationParameters()
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
+ ValidateIssuer = false,
+ ValidateAudience = false,
+ ClockSkew = TimeSpan.Zero
+ };
+});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
-builder.Services.AddSwaggerGen(c =>
+builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
+ options.IncludeXmlComments(xmlPath);
+
+ OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
+ {
+ Name = "Bearer",
+ BearerFormat = "JWT",
+ Scheme = "bearer",
+ Description = "Specify the authorization token.",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.Http,
+ };
+
+ options.AddSecurityDefinition("jwt_auth", securityDefinition);
+
+ // Make sure swagger UI requires a Bearer token specified
+ OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
+ {
+ Reference = new OpenApiReference()
+ {
+ Id = "jwt_auth",
+ Type = ReferenceType.SecurityScheme
+ }
+ };
+
+ OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
+ {
+ {securityScheme, new string[] { }},
+ };
+
+ options.AddSecurityRequirement(securityRequirements);
});
builder.Services.AddScoped();
builder.Services.AddScoped();
@@ -26,7 +76,10 @@ builder.Services.AddDbContext(option =>
{
option.UseInMemoryDatabase("Locations");
});
+
+
var app = builder.Build();
+// Add services to the container.
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
@@ -44,6 +97,7 @@ if (app.Environment.IsDevelopment())
}
}
+app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs
index 7dec941..1171b0d 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs
@@ -1,4 +1,5 @@
using DamageAssesment.Api.Questions.Interfaces;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Questions.Controllers
@@ -10,16 +11,13 @@ namespace DamageAssesment.Api.Questions.Controllers
public QuestionsController(IQuestionsProvider questionsProvider)
{
-
this.questionsProvider = questionsProvider;
-
}
-
///
/// GET request for retrieving questions.
///
-
- // get all questions
+ //get all questions
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("questions")]
[Route("questions/{language:alpha}")]
[HttpGet]
@@ -37,6 +35,7 @@ namespace DamageAssesment.Api.Questions.Controllers
///
/// GET request for retrieving a question by ID.
///
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("questions/{id}/{language:alpha}")]
[Route("questions/{id:int}")]
[HttpGet]
@@ -55,6 +54,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// GET request for retrieving survey questions based on a survey ID.
/// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages
///
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("questions/bysurvey/{surveyId:int}")]
[Route("questions/bysurvey/{surveyId:int}/{language:alpha}")]
[HttpGet]
@@ -71,6 +71,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// PUT request for updating a question (multilingual).
///
+ [Authorize(Roles = "admin")]
[HttpPut("questions")]
public async Task UpdateQuestion(Models.Question question)
{
@@ -92,6 +93,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// POST request for creating a new question (multilingual).
///
+ [Authorize(Roles = "admin")]
[HttpPost("questions")]
public async Task CreateQuestion(Models.Question question)
{
@@ -110,6 +112,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// DELETE request for deleting a question based on ID.
///
+ [Authorize(Roles = "admin")]
[HttpDelete("questions/{id}")]
public async Task DeleteQuestion(int id)
{
@@ -125,6 +128,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// GET request for retrieving question categories.
///
+ [Authorize(Roles = "admin,user,report")]
[HttpGet("questions/categories")]
[HttpGet("questions/categories/{language:alpha}")]
public async Task GetQuestionCategoriesAsync(string? language)
@@ -139,7 +143,7 @@ namespace DamageAssesment.Api.Questions.Controllers
///
/// GET request for retrieving a question category by ID.
///
-
+ [Authorize(Roles = "admin,report")]
[HttpGet("questions/categories/{id:int}")]
[HttpGet("questions/categories/{id:int}/{language:alpha}")]
public async Task GetQuestionCategoryAsync(int id,string? language)
@@ -156,7 +160,7 @@ namespace DamageAssesment.Api.Questions.Controllers
///
/// PUT request for updating a question category.
///
-
+ [Authorize(Roles = "admin,survey,report")]
[HttpPut("questions/categories")]
public async Task UpdateQuestionCategory(Models.QuestionCategory questionCategory)
{
@@ -178,6 +182,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// POST request for creating a new question category.
///
+ [Authorize(Roles = "admin")]
[HttpPost("questions/categories")]
public async Task CreateQuestionCategory(Models.QuestionCategory questionCategory)
{
@@ -196,6 +201,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// DELETE request for deleting a question category based on ID.
///
+ [Authorize(Roles = "admin")]
[HttpDelete("questions/categories/{id}")]
public async Task DeleteQuestionCategory(int id)
{
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs
index b6c1668..f7fe7fb 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs
@@ -12,7 +12,7 @@
public bool IsRequired { get; set; }
public bool Comment { get; set; }
public bool Key { get; set; }
- public int? SurveyId { get; set; }
+ public int SurveyId { get; set; }
public int CategoryId { get; set; }
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs
index 073cb10..ac0eed7 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs
@@ -1,11 +1,33 @@
using DamageAssesment.Api.Questions.Db;
using DamageAssesment.Api.Questions.Interfaces;
using DamageAssesment.Api.Questions.Providers;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
+using Microsoft.IdentityModel.Tokens;
+using Microsoft.OpenApi.Models;
using System.Reflection;
+using System.Text;
var builder = WebApplication.CreateBuilder(args);
-
+// Add services to the container.
+var authkey = builder.Configuration.GetValue("JwtSettings:securitykey");
+builder.Services.AddAuthentication(item =>
+{
+ item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+}).AddJwtBearer(item =>
+{
+ item.RequireHttpsMetadata = true;
+ item.SaveToken = true;
+ item.TokenValidationParameters = new TokenValidationParameters()
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
+ ValidateIssuer = false,
+ ValidateAudience = false,
+ ClockSkew = TimeSpan.Zero
+ };
+});
// Add services to the container.
builder.Services.AddControllers();
@@ -17,13 +39,41 @@ builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
-builder.Services.AddSwaggerGen(c =>
+builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
+ options.IncludeXmlComments(xmlPath);
+
+ OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
+ {
+ Name = "Bearer",
+ BearerFormat = "JWT",
+ Scheme = "bearer",
+ Description = "Specify the authorization token.",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.Http,
+ };
+
+ options.AddSecurityDefinition("jwt_auth", securityDefinition);
+
+ // Make sure swagger UI requires a Bearer token specified
+ OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
+ {
+ Reference = new OpenApiReference()
+ {
+ Id = "jwt_auth",
+ Type = ReferenceType.SecurityScheme
+ }
+ };
+ OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
+ {
+ {securityScheme, new string[] { }},
+ };
+ options.AddSecurityRequirement(securityRequirements);
});
+
builder.Services.AddDbContext(option =>
{
option.UseInMemoryDatabase("Questions");
@@ -43,7 +93,7 @@ if (app.Environment.IsDevelopment())
questionProvider.SeedData();
}
}
-
+app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs
index 45f6ecf..4e94143 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs
@@ -19,7 +19,7 @@ namespace DamageAssesment.Api.Questions.Providers
this.questionDbContext = questionDbContext;
this.logger = logger;
this.mapper = mapper;
- // SeedData();
+ // SeedData();
}
public void SeedData()
@@ -31,8 +31,7 @@ namespace DamageAssesment.Api.Questions.Providers
questionDbContext.QuestionTypes.Add(new Db.QuestionType() { TypeText = "TextBox" });
questionDbContext.SaveChanges();
}
-
- if (!questionDbContext.QuestionCategories.Any())
+ if (!questionDbContext.QuestionsTranslations.Any())
{
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { IconName = "Flooding", IconLibrary = "https://example.com/images/img1.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { IconName = "Electrical", IconLibrary = "https://example.com/images/img2.png" });
@@ -70,7 +69,7 @@ namespace DamageAssesment.Api.Questions.Providers
var question4 = new Db.Question() { QuestionTypeId = 1, SurveyId = 2, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, CategoryId = 2 };
var question5 = new Db.Question() { QuestionTypeId = 1, SurveyId = 3, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = 1 };
var question6 = new Db.Question() { QuestionTypeId = 1, SurveyId = 3, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, CategoryId = 2 };
- var question7 = new Db.Question() { QuestionTypeId = 1, SurveyId = 3, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = 3};
+ var question7 = new Db.Question() { QuestionTypeId = 1, SurveyId = 3, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = 3 };
var question8 = new Db.Question() { QuestionTypeId = 1, SurveyId = 3, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, CategoryId = 4 };
var question9 = new Db.Question() { QuestionTypeId = 1, SurveyId = 3, QuestionNumber = 1, IsRequired = true, Comment = true, Key = true, CategoryId = 5 };
var question10 = new Db.Question() { QuestionTypeId = 1, SurveyId = 3, QuestionNumber = 2, IsRequired = false, Comment = false, Key = true, CategoryId = 1 };
@@ -275,7 +274,7 @@ namespace DamageAssesment.Api.Questions.Providers
if (question != null)
{
logger?.LogInformation($"{question} customer(s) found");
- var result = mapper.Map(question);
+ var result = mapper.Map(question);
result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(id, language));
return (true, result, null);
}
@@ -314,7 +313,7 @@ namespace DamageAssesment.Api.Questions.Providers
CategoryId = item.Id,
IconLibrary = item.IconLibrary,
IconName = item.IconName,
- CategoryNames= CreateCategoryMultiLanguageObject(GetCategoryTranslations(item.Id, language)),
+ CategoryNames = CreateCategoryMultiLanguageObject(GetCategoryTranslations(item.Id, language)),
QuestionsText = GetSurveyQuestion(mapper.Map, List>(questions.Where(a => a.CategoryId == item.Id).ToList()), language)
});
}
@@ -344,7 +343,7 @@ namespace DamageAssesment.Api.Questions.Providers
questionDbContext.SaveChanges();
Question.Id = dbquestion.Id;
var result = mapper.Map(dbquestion);
- result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id,""));
+ result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, ""));
return (true, result, null);
}
catch (Exception ex)
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses.Test/SurveyResponsesServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses.Test/SurveyResponsesServiceTest.cs
index 05b3e02..90a9a73 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses.Test/SurveyResponsesServiceTest.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses.Test/SurveyResponsesServiceTest.cs
@@ -25,17 +25,16 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse(mockRequestObject);
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesAsync(1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesAsync(1);
Assert.Equal(200, result.StatusCode);
}
-
[Fact(DisplayName = "Get Responses - BadRequest case")]
public async Task GetSurveyResponsesAsync_ShouldReturnStatusCode204()
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesAsync(1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (BadRequestObjectResult)await surveyResponseProvider.GetSurveyResponsesAsync(1);
Assert.Equal(400, result.StatusCode);
}
@@ -46,7 +45,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAsync(1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesAsync(1, 1);
Assert.Equal(200, result.StatusCode);
}
@@ -56,7 +55,7 @@ namespace DamageAssesment.SurveyResponses.Test
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAsync(1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesAsync(1, 1);
Assert.Equal(204, result.StatusCode);
}
@@ -70,7 +69,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1, 1);
Assert.Equal(200, result.StatusCode);
}
@@ -80,7 +79,7 @@ namespace DamageAssesment.SurveyResponses.Test
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1, 1);
Assert.Equal(204, result.StatusCode);
}
@@ -91,7 +90,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse();
mockSurveyResponseService.Setup(service => service.GetResponsesByAnswerAsync(1, 1, "Yes", 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesByAnswerAsyncAsync(1, 1, "Yes", 1);
Assert.Equal(200, result.StatusCode);
}
@@ -101,7 +100,7 @@ namespace DamageAssesment.SurveyResponses.Test
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.GetResponsesByAnswerAsync(1, 1, "Yes", 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesByAnswerAsyncAsync(1, 1, "Yes", 1);
Assert.Equal(204, result.StatusCode);
}
@@ -113,7 +112,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse();
mockSurveyResponseService.Setup(service => service.GetAnswersByRegionAsync(1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseProvider.GetAnswersByRegionAsync(1, 1);
Assert.Equal(200, result.StatusCode);
}
@@ -123,7 +122,7 @@ namespace DamageAssesment.SurveyResponses.Test
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.GetAnswersByRegionAsync(1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (NoContentResult)await surveyResponseProvider.GetAnswersByRegionAsync(1, 1);
Assert.Equal(204, result.StatusCode);
}
@@ -134,7 +133,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesByMaintenanceCenterAsync(1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseProvider.GetAnswersByMaintenaceCentersync(1, 1);
Assert.Equal(200, result.StatusCode);
}
@@ -144,7 +143,7 @@ namespace DamageAssesment.SurveyResponses.Test
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesByMaintenanceCenterAsync(1, 1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (NoContentResult)await surveyResponseProvider.GetAnswersByMaintenaceCentersync(1, 1);
Assert.Equal(204, result.StatusCode);
}
@@ -155,7 +154,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponseByIdAsync(1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponseByIdAsync(1);
Assert.Equal(200, result.StatusCode);
}
@@ -165,7 +164,7 @@ namespace DamageAssesment.SurveyResponses.Test
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.GetSurveyResponseByIdAsync(1)).ReturnsAsync(mockResponse);
- var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponseByIdAsync(1);
Assert.Equal(204, result.StatusCode);
}
@@ -177,7 +176,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse(mockRequestObject);
mockSurveyResponseService.Setup(service => service.PostSurveyResponseAsync(mockRequestObject)).ReturnsAsync(mockResponse);
- var surveyResponseController = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseController.PostSurveysAsync(mockRequestObject);
Assert.Equal(200, result.StatusCode);
}
@@ -188,7 +187,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.PostSurveyResponseAsync(mockRequestObject)).ReturnsAsync(mockResponse);
- var surveyResponseController = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (BadRequestObjectResult)await surveyResponseController.PostSurveysAsync(mockRequestObject);
Assert.Equal(400, result.StatusCode);
}
@@ -199,7 +198,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse(mockRequestObject);
mockSurveyResponseService.Setup(service => service.PutSurveyResponseAsync(1, mockRequestObject)).ReturnsAsync(mockResponse);
- var surveyResponseController = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseController.PutSurveyResponseAsync(1, mockRequestObject);
Assert.Equal(200, result.StatusCode);
}
@@ -210,7 +209,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.PutSurveyResponseAsync(1, mockRequestObject)).ReturnsAsync(mockResponse); ;
- var surveyResponseController = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (BadRequestObjectResult)await surveyResponseController.PutSurveyResponseAsync(1, mockRequestObject);
Assert.Equal(400, result.StatusCode);
}
@@ -221,7 +220,7 @@ namespace DamageAssesment.SurveyResponses.Test
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
var mockResponse = await MockData.getOkResponse(mockRequestObject);
mockSurveyResponseService.Setup(service => service.DeleteSurveyResponseAsync(1)).ReturnsAsync(mockResponse);
- var surveyResponseController = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (OkObjectResult)await surveyResponseController.DeleteSurveyResponseAsync(1);
Assert.Equal(200, result.StatusCode);
}
@@ -231,7 +230,7 @@ namespace DamageAssesment.SurveyResponses.Test
{
var mockResponse = await MockData.getResponse();
mockSurveyResponseService.Setup(service => service.DeleteSurveyResponseAsync(1)).ReturnsAsync(mockResponse); ;
- var surveyResponseController = new SurveyResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
+ var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object, mockExcelExportService.Object);
var result = (NotFoundResult)await surveyResponseController.DeleteSurveyResponseAsync(1);
Assert.Equal(404, result.StatusCode);
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Controllers/SurveyResponsesController.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Controllers/ResponsesController.cs
similarity index 91%
rename from DamageAssesmentApi/DamageAssesment.Api.Responses/Controllers/SurveyResponsesController.cs
rename to DamageAssesmentApi/DamageAssesment.Api.Responses/Controllers/ResponsesController.cs
index 871106c..85c38ea 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Controllers/SurveyResponsesController.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Controllers/ResponsesController.cs
@@ -1,16 +1,17 @@
using DamageAssesment.Api.Responses.Interfaces;
using DamageAssesment.Api.Responses.Models;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Responses.Controllers
{
[ApiController]
- public class SurveyResponsesController : ControllerBase
+ public class ResponsesController : ControllerBase
{
private readonly ISurveysResponse surveyResponseProvider;
private readonly IExcelExportService excelExportService;
- public SurveyResponsesController(ISurveysResponse surveyResponseProvider, IExcelExportService excelExportService)
+ public ResponsesController(ISurveysResponse surveyResponseProvider, IExcelExportService excelExportService)
{
this.surveyResponseProvider = surveyResponseProvider;
this.excelExportService = excelExportService;
@@ -19,6 +20,7 @@ namespace DamageAssesment.Api.Responses.Controllers
/// GET request for retrieving survey responses.
///
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/{employeeid:int}")]
[Route("responses")]
[HttpGet]
@@ -38,6 +40,7 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// GET request for retrieving survey responses by survey ID.
///
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/bysurvey/{surveyid:int}/{employeeid:int}")]
[Route("responses/bysurvey/{surveyid:int}")]
[HttpGet]
@@ -56,6 +59,7 @@ namespace DamageAssesment.Api.Responses.Controllers
/// The ID of the survey for which responses are to be retrieved.
/// The ID of the location for which responses are to be retrieved.
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/{surveyid:int}/{locationid:int}/{employeeid:int}")]
[Route("responses/{surveyid:int}/{locationid:int}")]
[HttpGet]
@@ -75,6 +79,7 @@ namespace DamageAssesment.Api.Responses.Controllers
/// The ID of the question for which responses are to be retrieved.
/// The answer for which responses are to be retrieved.
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/byanswer/{surveyid:int}/{questionid:int}/{answer:alpha}/{employeeid:int}")]
[Route("responses/byanswer/{surveyid:int}/{questionid:int}/{answer:alpha}")]
[HttpGet]
@@ -93,6 +98,7 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// The ID of the survey for which answers are to be retrieved.
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/byregion/{surveyid:int}")]
[Route("responses/byregion/{surveyid:int}/{employeeid}")]
[HttpGet]
@@ -109,6 +115,7 @@ namespace DamageAssesment.Api.Responses.Controllers
/// GET request for retrieving survey responses by survey ID and maintenance center.
///
/// The ID of the survey for which responses are to be retrieved.
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/bymaintenancecenter/{surveyid:int}/{employeeid:int}")]
[Route("responses/bymaintenancecenter/{surveyid:int}")]
[HttpGet]
@@ -126,6 +133,7 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// The ID of the survey response to be retrieved.
+ [Authorize(Roles = "admin,survey,user,report")]
[HttpGet("responses/{id}")]
public async Task GetSurveyResponseByIdAsync(int id)
{
@@ -142,6 +150,7 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// The survey response object to be created.
+ [Authorize(Roles = "admin,survey,user,report")]
[HttpPost("responses")]
public async Task PostSurveysAsync(Models.SurveyResponse surveyResponse)
{
@@ -158,6 +167,7 @@ namespace DamageAssesment.Api.Responses.Controllers
/// The ID of the survey response to be updated.
/// The updated survey response object.
+ [Authorize(Roles = "admin,survey,user,report")]
[HttpPut("responses/{id}")]
public async Task PutSurveyResponseAsync(int id, Models.SurveyResponse surveyResponse)
{
@@ -175,6 +185,7 @@ namespace DamageAssesment.Api.Responses.Controllers
/// DELETE request for deleting an existing survey response.
///
+ [Authorize(Roles = "admin,survey,user,report")]
[HttpDelete("responses/{id}")]
public async Task DeleteSurveyResponseAsync(int id)
{
@@ -190,6 +201,7 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// The answers to be submitted for the survey.
+ [Authorize(Roles = "admin,survey,user,report")]
[HttpPost("responses/answers")]
public async Task PostSurveyAnswersAsync(Request request)
{
@@ -203,6 +215,8 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// Get All active surveys .
///
+
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/surveys/active")]
[Route("responses/surveys/active/{language:alpha}")]
[Route("responses/surveys/active/{employeeid:int}")]
@@ -220,6 +234,7 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// Export all survey response data based on survey id.
///
+ [Authorize(Roles = "admin,survey,user,report")]
[HttpGet]
[Route("responses/surveys/export/{surveyid}")]
public async Task GetExcelSurveysAsync(int surveyid, string language, bool IsAdmin = false)
@@ -250,6 +265,7 @@ namespace DamageAssesment.Api.Responses.Controllers
///
/// Get all historical surveys .
///
+ [Authorize(Roles = "admin,survey,user,report")]
[Route("responses/surveys/historic")]
[Route("responses/surveys/historic/{language:alpha}")]
[Route("responses/surveys/historic/{employeeid:int}")]
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAnswerServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAnswerServiceProvider.cs
index 43ba9a1..7c23f55 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAnswerServiceProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAnswerServiceProvider.cs
@@ -4,9 +4,9 @@ namespace DamageAssesment.Api.Responses.Interfaces
{
public interface IAnswerServiceProvider
{
- Task> getAnswersAsync();
- Task> GetAnswersByResponseIdAsync(int responseId);
+ Task> getAnswersAsync(string token);
+ Task> GetAnswersByResponseIdAsync(int responseId, string token);
- Task PostAnswersAsync(Models.Answer answer);
+ Task PostAnswersAsync(Models.Answer answer, string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAttachmentServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAttachmentServiceProvider.cs
index 7350071..15f76a5 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAttachmentServiceProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IAttachmentServiceProvider.cs
@@ -4,7 +4,7 @@ namespace DamageAssesment.Api.Responses.Interfaces
{
public interface IAttachmentServiceProvider
{
- Task> getAttachmentsAsync();
- Task> PostAttachmentsAsync(Models.AttachmentInfo attachmentInfo);
+ Task> getAttachmentsAsync(string token);
+ Task> PostAttachmentsAsync(Models.AttachmentInfo attachmentInfo, string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IEmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IEmployeeServiceProvider.cs
index ef9eb00..de943d0 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IEmployeeServiceProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IEmployeeServiceProvider.cs
@@ -1,10 +1,10 @@
-using DamageAssesment.Api.Responses.Models;
+using DamageAssesment.Api.Responses.Models;
namespace DamageAssesment.Api.Responses.Interfaces
{
public interface IEmployeeServiceProvider
{
- Task> getEmployeesAsync();
- Task getEmployeeAsync(int employeeId);
+ Task> getEmployeesAsync(string token);
+ Task getEmployeeAsync(int employeeId, string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IHttpUtil.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IHttpUtil.cs
index a8578e0..ae5620f 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IHttpUtil.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IHttpUtil.cs
@@ -1,9 +1,9 @@
-using DamageAssesment.Api.Responses.Models;
+using DamageAssesment.Api.Responses.Models;
namespace DamageAssesment.Api.Responses.Interfaces
{
public interface IHttpUtil
{
- Task SendAsync(HttpMethod method, string url, string JsonInput);
+ Task SendAsync(HttpMethod method, string url, string JsonInput, string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ILocationServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ILocationServiceProvider.cs
index 75945cd..75ab80e 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ILocationServiceProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ILocationServiceProvider.cs
@@ -4,6 +4,6 @@ namespace DamageAssesment.Api.Responses.Interfaces
{
public interface ILocationServiceProvider
{
- Task> getLocationsAsync();
+ Task> getLocationsAsync(string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IQuestionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IQuestionServiceProvider.cs
index bbcec8b..eec0256 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IQuestionServiceProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IQuestionServiceProvider.cs
@@ -4,9 +4,9 @@ namespace DamageAssesment.Api.Responses.Interfaces
{
public interface IQuestionServiceProvider
{
- Task> getQuestionsAsync(string language);
- Task> getSurveyQuestionsAsync(int surveyId);
- Task getQuestionsAsync(int questionId);
- Task> GetQuestionCategoriesAsync(string? language);
+ Task> getQuestionsAsync(string language,string token);
+ Task> getSurveyQuestionsAsync(int surveyId, string token);
+ Task getQuestionsAsync(int questionId, string token);
+ Task> GetQuestionCategoriesAsync(string? language, string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IRegionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IRegionServiceProvider.cs
index be3b1c3..a97193e 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IRegionServiceProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/IRegionServiceProvider.cs
@@ -4,6 +4,6 @@ namespace DamageAssesment.Api.Responses.Interfaces
{
public interface IRegionServiceProvider
{
- Task> getRegionsAsync();
+ Task> getRegionsAsync(string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ISurveyServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ISurveyServiceProvider.cs
index 64252c9..8c66bda 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ISurveyServiceProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Interfaces/ISurveyServiceProvider.cs
@@ -4,7 +4,7 @@ namespace DamageAssesment.Api.Responses.Interfaces
{
public interface ISurveyServiceProvider
{
- Task> getSurveysAsync(string language);
- Task getSurveyAsync(int surveyId);
+ Task> getSurveysAsync(string language,string token);
+ Task getSurveyAsync(int surveyId,string token);
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Models/Employee.cs
index 72ceffc..3a84d81 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Models/Employee.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Models/Employee.cs
@@ -11,6 +11,6 @@ namespace DamageAssesment.Api.Responses.Models
public string OfficePhoneNumber { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
- public string? PreferredLanguage { get; set; }
+ public string PreferredLanguage { get; set; }
}
}
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Program.cs
index 91adc1c..ce0b901 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Program.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Program.cs
@@ -5,6 +5,10 @@ using DamageAssesment.Api.Responses.Providers;
using Microsoft.EntityFrameworkCore;
using Polly;
using System.Reflection;
+using Microsoft.OpenApi.Models;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.IdentityModel.Tokens;
+using System.Text;
var builder = WebApplication.CreateBuilder(args);
const int maxApiCallRetries = 3;
@@ -14,6 +18,24 @@ const int intervalForCircuitBraker = 5; //5 seconds
// Add services to the container.
+var authkey = builder.Configuration.GetValue("JwtSettings:securitykey");
+builder.Services.AddAuthentication(item =>
+{
+ item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+}).AddJwtBearer(item =>
+{
+ item.RequireHttpsMetadata = true;
+ item.SaveToken = true;
+ item.TokenValidationParameters = new TokenValidationParameters()
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
+ ValidateIssuer = false,
+ ValidateAudience = false,
+ ClockSkew = TimeSpan.Zero
+ };
+});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@@ -26,6 +48,7 @@ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped();
builder.Services.AddHttpClient().
@@ -36,12 +59,40 @@ builder.Services.AddHttpClient().
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
-builder.Services.AddSwaggerGen(c =>
+
+builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- c.IncludeXmlComments(xmlPath);
+ options.IncludeXmlComments(xmlPath);
+
+ OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
+ {
+ Name = "Bearer",
+ BearerFormat = "JWT",
+ Scheme = "bearer",
+ Description = "Specify the authorization token.",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.Http,
+ };
+
+ options.AddSecurityDefinition("jwt_auth", securityDefinition);
+
+ // Make sure swagger UI requires a Bearer token specified
+ OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
+ {
+ Reference = new OpenApiReference()
+ {
+ Id = "jwt_auth",
+ Type = ReferenceType.SecurityScheme
+ }
+ };
+ OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
+ {
+ {securityScheme, new string[] { }},
+ };
+ options.AddSecurityRequirement(securityRequirements);
});
builder.Services.AddDbContext(option =>
{
@@ -56,6 +107,7 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
+app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Properties/launchSettings.json b/DamageAssesmentApi/DamageAssesment.Api.Responses/Properties/launchSettings.json
index 0d51b15..f43ced8 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Properties/launchSettings.json
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Properties/launchSettings.json
@@ -9,7 +9,7 @@
}
},
"profiles": {
- "DamageAssesment.Api.SurveyResponses": {
+ "DamageAssesment.Api.Responses": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
diff --git a/DamageAssesmentApi/DamageAssesment.Api.Responses/Providers/SurveyResponsesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Responses/Providers/SurveyResponsesProvider.cs
index d52d153..816bc7a 100644
--- a/DamageAssesmentApi/DamageAssesment.Api.Responses/Providers/SurveyResponsesProvider.cs
+++ b/DamageAssesmentApi/DamageAssesment.Api.Responses/Providers/SurveyResponsesProvider.cs
@@ -2,6 +2,7 @@
using DamageAssesment.Api.Responses.Db;
using DamageAssesment.Api.Responses.Interfaces;
using DamageAssesment.Api.Responses.Models;
+using DamageAssesment.Api.Responses.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Reflection;
@@ -21,8 +22,10 @@ namespace DamageAssesment.Api.Responses.Providers
private readonly IQuestionServiceProvider questionServiceProvider;
private readonly ISurveyServiceProvider surveyServiceProvider;
private readonly IMapper mapper;
+ private readonly IHttpContextAccessor httpContextAccessor;
+ private string token;
- public SurveyResponsesProvider(SurveyResponseDbContext surveyResponseDbContext, ILogger logger, IAnswerServiceProvider answerServiceProvider, IRegionServiceProvider regionServiceProvider, ILocationServiceProvider locationServiceProvider, IEmployeeServiceProvider employeeServiceProvider, IAttachmentServiceProvider attachmentServiceProvider, IQuestionServiceProvider questionServiceProvider, ISurveyServiceProvider surveyServiceProvider, IMapper mapper)
+ public SurveyResponsesProvider(SurveyResponseDbContext surveyResponseDbContext, ILogger logger, IAnswerServiceProvider answerServiceProvider, IRegionServiceProvider regionServiceProvider, ILocationServiceProvider locationServiceProvider, IEmployeeServiceProvider employeeServiceProvider, IAttachmentServiceProvider attachmentServiceProvider, IQuestionServiceProvider questionServiceProvider, ISurveyServiceProvider surveyServiceProvider, IMapper mapper, IHttpContextAccessor httpContextAccessor)
{
this.surveyResponseDbContext = surveyResponseDbContext;
this.logger = logger;
@@ -33,8 +36,20 @@ namespace DamageAssesment.Api.Responses.Providers
this.attachmentServiceProvider = attachmentServiceProvider;
this.questionServiceProvider = questionServiceProvider;
this.surveyServiceProvider = surveyServiceProvider;
+ this.httpContextAccessor = httpContextAccessor;
this.mapper = mapper;
SeedData();
+
+ token = httpContextAccessor.HttpContext.Request.Headers.Authorization;
+ if (token != null)
+ {
+ token = token.Replace("Bearer ", string.Empty);
+ }
+ else
+ {
+ token = "";
+ }
+ // seedData();
}
public void SeedData()
@@ -120,7 +135,7 @@ namespace DamageAssesment.Api.Responses.Providers
{
logger?.LogInformation("Querying to get SurveyResponse object from DB");
//get all the survey that already taken by the employee
- var surveys = await surveyServiceProvider.getSurveysAsync(language);
+ var surveys = await surveyServiceProvider.getSurveysAsync(language,token);
surveys = surveys.Where(s => s.IsEnabled == true && s.Status == SurveyStatus.ACTIVE.ToString()).ToList();
if (employeeid == null || employeeid == 0)
return (true, surveys, null);
@@ -141,7 +156,7 @@ namespace DamageAssesment.Api.Responses.Providers
{
logger?.LogInformation("Querying to get SurveyResponse object from DB");
- var surveys = await surveyServiceProvider.getSurveysAsync(language);
+ var surveys = await surveyServiceProvider.getSurveysAsync(language, token);
// returning only historic data: end date is less than current date.
surveys = surveys.Where(s => s.Status == SurveyStatus.INACTIVE.ToString()).ToList();
if (employeeid == null || employeeid == 0)
@@ -166,7 +181,7 @@ namespace DamageAssesment.Api.Responses.Providers
try
{
logger?.LogInformation("Querying to get Survey object from microservice");
- var survey = await surveyServiceProvider.getSurveyAsync(surveyId);
+ var survey = await surveyServiceProvider.getSurveyAsync(surveyId, token);
if (survey != null)
{
@@ -197,7 +212,7 @@ namespace DamageAssesment.Api.Responses.Providers
try
{
logger?.LogInformation("Querying to get Survey object from microservice");
- var survey = await surveyServiceProvider.getSurveyAsync(surveyId);
+ var survey = await surveyServiceProvider.getSurveyAsync(surveyId, token);
if (survey != null)
{
@@ -228,7 +243,7 @@ namespace DamageAssesment.Api.Responses.Providers
try
{
logger?.LogInformation("Querying to get Survey object from microservice");
- var survey = await surveyServiceProvider.getSurveyAsync(surveyId);
+ var survey = await surveyServiceProvider.getSurveyAsync(surveyId, token);
if (survey != null)
{
@@ -259,8 +274,8 @@ namespace DamageAssesment.Api.Responses.Providers
try
{
logger?.LogInformation("Querying to get Survey object from microservice");
- var survey = await surveyServiceProvider.getSurveyAsync(surveyId);
- var question = await questionServiceProvider.getQuestionsAsync(questionId);
+ var survey = await surveyServiceProvider.getSurveyAsync(surveyId, token);
+ var question = await questionServiceProvider.getQuestionsAsync(questionId, token);
bool IsCorrectAnswer = answer.ToLower().Equals("yes") || answer.ToLower().Equals("no") ? true : false;
@@ -421,7 +436,7 @@ namespace DamageAssesment.Api.Responses.Providers
{
try
{
- var answersList = await answerServiceProvider.getAnswersAsync();
+ var answersList = await answerServiceProvider.getAnswersAsync(token);
if (answersList == null || !answersList.Any())
return null;
@@ -444,8 +459,8 @@ namespace DamageAssesment.Api.Responses.Providers
if (surveyAnswers == null || !surveyAnswers.Any())
return null;
- var regions = await regionServiceProvider.getRegionsAsync();
- var locations = await locationServiceProvider.getLocationsAsync();
+ var regions = await regionServiceProvider.getRegionsAsync(token);
+ var locations = await locationServiceProvider.getLocationsAsync(token);
if (regions == null || !regions.Any() || locations == null || !locations.Any())
return null;
@@ -507,11 +522,11 @@ namespace DamageAssesment.Api.Responses.Providers
{
try
{
- var employee = await employeeServiceProvider.getEmployeeAsync(surveyResponse.EmployeeId);
- var answers = await answerServiceProvider.GetAnswersByResponseIdAsync(surveyResponse.Id);
- var allQuestions = await questionServiceProvider.getQuestionsAsync(null);
+ var employee = await employeeServiceProvider.getEmployeeAsync(surveyResponse.EmployeeId, token);
+ var answers = await answerServiceProvider.GetAnswersByResponseIdAsync(surveyResponse.Id, token);
+ var allQuestions = await questionServiceProvider.getQuestionsAsync(null,token);
var questions = allQuestions.Where(s => s.SurveyId == surveyResponse.SurveyId);
- var attachments = await attachmentServiceProvider.getAttachmentsAsync();
+ var attachments = await attachmentServiceProvider.getAttachmentsAsync(token);
var result = new
{
@@ -556,85 +571,47 @@ namespace DamageAssesment.Api.Responses.Providers
if (employeeid == 0)
{
surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(x => x.SurveyId == surveyId).ToListAsync();
- employees = await employeeServiceProvider.getEmployeesAsync();
+ employees = await employeeServiceProvider.getEmployeesAsync(token);
}
else
{
surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(x => x.SurveyId == surveyId && x.EmployeeId == employeeid).ToListAsync();
- employee = await employeeServiceProvider.getEmployeeAsync(employeeid);
+ employee = await employeeServiceProvider.getEmployeeAsync(employeeid, token);
}
- var answers = await answerServiceProvider.getAnswersAsync();
- var questions = await questionServiceProvider.getQuestionsAsync(null);
+ var answers = await answerServiceProvider.getAnswersAsync(token);
+ var questions = await questionServiceProvider.getQuestionsAsync(null, token);
var surveyQuestions = from q in questions where q.SurveyId == surveyId select q;
//var surveyQuestions = await questionServiceProvider.getSurveyQuestionsAsync(surveyId);
- var attachments = await attachmentServiceProvider.getAttachmentsAsync();
+ var attachments = await attachmentServiceProvider.getAttachmentsAsync(token);
+ var result = from r in surveyResonses
+ select new
+ {
+ r.Id,
+ r.SurveyId,
+ r.LocationId,
+ r.EmployeeId,
+ r.ClientDevice,
+ r.KeyAnswerResult,
+ r.Longitute,
+ r.Latitude,
+ Employee = (from e in employees where e.Id == r.EmployeeId select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
+ answers = from ans in answers
+ where ans.SurveyResponseId == r.Id
+ select new
+ {
+ ans.Id,
+ ans.QuestionId,
+ ans.AnswerText,
+ ans.Comment,
+ Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(),
+ Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI }
- if (employeeid == 0)
- {
- var result = from r in surveyResonses
- select new
- {
- r.Id,
- r.SurveyId,
- r.LocationId,
- r.EmployeeId,
- r.ClientDevice,
- r.KeyAnswerResult,
- r.Longitute,
- r.Latitude,
- Employee = (from e in employees where e.Id == r.EmployeeId select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
- answers = from ans in answers
- where ans.SurveyResponseId == r.Id
- select new
- {
- ans.Id,
- ans.QuestionId,
- ans.AnswerText,
- ans.Comment,
- Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(),
- Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI }
-
- }
- };
- return result;
- }
- else
- {
- object _employee = new { };
- if (employee != null)
- {
- _employee = new { employee.Id, employee.Name, employee.BirthDate, employee.Email, employee.OfficePhoneNumber };
- }
- var result = from r in surveyResonses
- select new
- {
- r.Id,
- r.SurveyId,
- r.LocationId,
- r.EmployeeId,
- r.ClientDevice,
- r.KeyAnswerResult,
- r.Longitute,
- r.Latitude,
- Employee = _employee,
- answers = from ans in answers
- where ans.SurveyResponseId == r.Id
- select new
- {
- ans.Id,
- ans.QuestionId,
- ans.AnswerText,
- ans.Comment,
- Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(),
- Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI }
- }
- };
-
- return result;
- }
+ }
+ };
+ return result;
}
catch (Exception ex)
{
@@ -656,12 +633,12 @@ namespace DamageAssesment.Api.Responses.Providers
if (employeeid == 0)
{
surveyResonses = await surveyResponseDbContext.SurveyResponses.ToListAsync();
- employees = await employeeServiceProvider.getEmployeesAsync();
+ employees = await employeeServiceProvider.getEmployeesAsync(token);
}
else
{
surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(x => x.EmployeeId == employeeid).ToListAsync();
- employee = await employeeServiceProvider.getEmployeeAsync(employeeid);
+ employee = await employeeServiceProvider.getEmployeeAsync(employeeid, token);
if (employee != null)
{
@@ -670,9 +647,9 @@ namespace DamageAssesment.Api.Responses.Providers
}
- var answers = await answerServiceProvider.getAnswersAsync();
- var questions = await questionServiceProvider.getQuestionsAsync(null);
- var attachments = await attachmentServiceProvider.getAttachmentsAsync();
+ var answers = await answerServiceProvider.getAnswersAsync(token);
+ var questions = await questionServiceProvider.getQuestionsAsync(null,token);
+ var attachments = await attachmentServiceProvider.getAttachmentsAsync(token);
var result = from r in surveyResonses
select new
@@ -699,8 +676,6 @@ namespace DamageAssesment.Api.Responses.Providers
}
};
return result;
-
-
}
catch (Exception ex)
{
@@ -716,12 +691,12 @@ namespace DamageAssesment.Api.Responses.Providers
if (string.IsNullOrEmpty(language)) language = "en";
List surveyResonses;
surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(a => a.SurveyId == surveyId).ToListAsync();
- var answers = await answerServiceProvider.getAnswersAsync();
- var Locations = await locationServiceProvider.getLocationsAsync();
- var regions = await regionServiceProvider.getRegionsAsync();
- var questions = await questionServiceProvider.getQuestionsAsync(language);
- var categories = await questionServiceProvider.GetQuestionCategoriesAsync(language);
- var attachments = await attachmentServiceProvider.getAttachmentsAsync();
+ var answers = await answerServiceProvider.getAnswersAsync(token);
+ var Locations = await locationServiceProvider.getLocationsAsync(token);
+ var regions = await regionServiceProvider.getRegionsAsync(token);
+ var questions = await questionServiceProvider.getQuestionsAsync(language, token);
+ var categories = await questionServiceProvider.GetQuestionCategoriesAsync(language, token);
+ var attachments = await attachmentServiceProvider.getAttachmentsAsync(token);
List