Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

111 improve registration2 #174

Merged
merged 5 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/deskstar-backend/Deskstar/Controllers/CompanyController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Program
*
* Version 1.0
*
* 2023-01-03
*
* MIT License
*/
using Deskstar.Core;
using Deskstar.Models;
using Deskstar.Usecases;
using Deskstar.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Deskstar.Controllers;

[ApiController]
[Route("/companies")]
[Produces("application/json")]
public class CompanyController : ControllerBase
{
private readonly ICompanyUsecases _companyUsecases;

private readonly ILogger<CompanyController> _logger;
private readonly IAutoMapperConfiguration _autoMapperConfiguration;

public CompanyController(ILogger<CompanyController> logger, ICompanyUsecases companyUsecases, IAutoMapperConfiguration autoMapperConfiguration)
{
_logger = logger;
_companyUsecases = companyUsecases;
_autoMapperConfiguration = autoMapperConfiguration;
}

/// <summary>
/// Get all companies
/// </summary>
/// <returns> A list of companies</returns>
/// <remarks>
/// Sample request: Get /companies
/// </remarks>
/// <response code="200">Returns a list of companies</response>
/// <response code="500">Internal Server Error</response>
[HttpGet]
[AllowAnonymous]
[ProducesResponseType(typeof(List<CompanyDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[Produces("application/json")]
public IActionResult GetCompanies()
{
List<CompanyDto> companies;
try
{
companies = _companyUsecases.GetCompanies();
return Ok(companies);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while getting companies");
return Problem(statusCode: 500);
}
}
}
21 changes: 21 additions & 0 deletions src/deskstar-backend/Deskstar/Models/CompanyDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
using AutoMapper;

namespace Deskstar.Models;

public class CompanyDto
{
public static void createMappings(IMapperConfigurationExpression cfg)
{
cfg.CreateMap<Entities.Company, CompanyDto>();
}
public CompanyDto()
{

}

[Required]
public string CompanyId { get; set; } = null!;
[Required]
public string CompanyName { get; set; } = null!;
}
47 changes: 24 additions & 23 deletions src/deskstar-backend/Deskstar/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,26 @@
// Add services to the container.
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = false,
ValidateIssuerSigningKey = true
};
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = false,
ValidateIssuerSigningKey = true
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy => policy.RequireClaim("IsCompanyAdmin"));
options.AddPolicy("Admin", policy => policy.RequireClaim("IsCompanyAdmin"));
});

builder.Services.AddControllers();
Expand All @@ -61,19 +61,19 @@
var dbPassword = builder.Configuration.GetValue<string>(Constants.CONFIG_DB_PASSWORD) ?? null;
if (dbHost == null || dbDatabase == null || dbUsername == null || dbPassword == null)
{
Console.Error.WriteLine($"missing db configuration. database configuration has host({dbHost != null})," +
$"database name({dbDatabase != null}), username({dbUsername != null}), password({dbPassword != null})");
return;
Console.Error.WriteLine($"missing db configuration. database configuration has host({dbHost != null})," +
$"database name({dbDatabase != null}), username({dbUsername != null}), password({dbPassword != null})");
return;
}
var emailPassword = builder.Configuration.GetValue<string>(Constants.CONFIG_EMAIL_PASSWORD) ?? null;
var emailHost = builder.Configuration.GetValue<string>(Constants.CONFIG_EMAIL_HOST) ?? null;
var emailPort = builder.Configuration.GetValue<int>(Constants.CONFIG_EMAIL_PORT);
var emailUsername = builder.Configuration.GetValue<string>(Constants.CONFIG_EMAIL_USERNAME) ?? null;
if (emailPassword == null || emailHost == null || emailPort == 0 || emailUsername == null)
{
Console.Error.WriteLine($"missing email configuration. email configuration has password({emailPassword != null})," +
$" host({emailHost != null}), port({emailPort != 0}), username({emailUsername != null})");
return;
Console.Error.WriteLine($"missing email configuration. email configuration has password({emailPassword != null})," +
$" host({emailHost != null}), port({emailPort != 0}), username({emailUsername != null})");
return;
}

builder.Services.AddDbContext<DataContext>(options => options.UseNpgsql($"Host={dbHost};Database={dbDatabase};Username={dbUsername};Password={dbPassword}"));
Expand All @@ -84,6 +84,7 @@

builder.Services.AddScoped<IAuthUsecases, AuthUsecases>();
builder.Services.AddScoped<IBookingUsecases, BookingUsecases>();
builder.Services.AddScoped<ICompanyUsecases, CompanyUsecases>();
builder.Services.AddScoped<IUserUsecases, UserUsecases>();
builder.Services.AddScoped<IAutoMapperConfiguration, AutoMapperConfiguration>();
builder.Services.AddScoped<IResourceUsecases, ResourceUsecases>();
Expand All @@ -98,8 +99,8 @@
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
Expand Down
38 changes: 38 additions & 0 deletions src/deskstar-backend/Deskstar/Usecases/CompanyUsecases.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Deskstar.DataAccess;
using Deskstar.Entities;
using Deskstar.Models;

namespace Deskstar.Usecases;

public interface ICompanyUsecases
{
public List<CompanyDto> GetCompanies();
}

public class CompanyUsecases : ICompanyUsecases
{
private readonly DataContext _context;

private readonly ILogger<CompanyUsecases> _logger;

public CompanyUsecases(DataContext context, ILogger<CompanyUsecases> logger)
{
_context = context;
_logger = logger;
}

public List<CompanyDto> GetCompanies()
{
var dbCompanies = _context.Companies.ToList();

if (dbCompanies.ToList().Count == 0) return new List<CompanyDto>();

var mapCompaniesToCompaniesDto = dbCompanies.Select((c) => new CompanyDto
{
CompanyId = c.CompanyId.ToString(),
CompanyName = c.CompanyName,
}).ToList();

return mapCompaniesToCompaniesDto;
}
}
48 changes: 48 additions & 0 deletions src/deskstar-backend/Teststar.Tests/Tests/CompanyUsecasesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Deskstar.Core.Exceptions;
using Deskstar.DataAccess;
using Deskstar.Entities;
using Deskstar.Usecases;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Moq;

namespace Teststar.Tests.Tests;

public class CompanyUsecasesTests
{
private void setupMockData(DataContext db, Guid companyID, String companyName)
{
var company = new Company
{
CompanyId = companyID,
CompanyName = companyName
};
db.Companies.Add(company);
db.SaveChanges();
}

private void GetCompanies_ShouldReturnAllCompanies()
{
// setup
using var db = new DataContext();
var companyID = Guid.NewGuid();
var companyName = "Test Company";
setupMockData(db, companyID, companyName);

// arrange
var logger = new Mock<ILogger<CompanyUsecases>>();
var companyUsecases = new CompanyUsecases(db, logger.Object);


// act
var companies = companyUsecases.GetCompanies();

// assert
Assert.That(1 == companies.Count());
Assert.That(companyID.ToString() == companies.First().CompanyId);
Assert.That(companyName == companies.First().CompanyName);

// cleanup
db.Database.EnsureDeleted();
}
}