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

Update controllers #56

Merged
merged 9 commits into from
Apr 2, 2024
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
143 changes: 143 additions & 0 deletions Inflow.Api/Controllers/AuthenticationController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
using Inflow.Api.Constants;
using Inflow.Api.LoginModels;
using Inflow.Domain.Entities;
using Inflow.Domain.Intefaces.Services;
using Inflow.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Inflow.Api.Controllers
{

[Route("api/auth")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly InflowDbContext _context;
private readonly IEmailSender _emailSender;
public AuthenticationController(InflowDbContext context, IEmailSender emailSender)
{
_context = context;
_emailSender = emailSender;
}

[HttpPost("login")]
public ActionResult<string> Login(LoginRequest request)
{
var user = Authenticate(request.Login, request.Password);

if (user is null)
{
return Unauthorized();
}

if (!FindUser(request.Login, request.Password))
{
return Unauthorized();
}

var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("anvarSekretKalitSozMalades"));
var signingCredentials = new SigningCredentials(securityKey,
SecurityAlgorithms.HmacSha256);

var claimsForToken = new List<Claim>();
claimsForToken.Add(new Claim("sub", user.Phone));
claimsForToken.Add(new Claim("name", user.Name));

var jwtSecurityToken = new JwtSecurityToken(
"anvar-api",
"anvar-mobile",
claimsForToken,
DateTime.UtcNow,
DateTime.UtcNow.AddDays(5),
signingCredentials);

var token = new JwtSecurityTokenHandler()
.WriteToken(jwtSecurityToken);

return Ok(token);
}

[HttpPost("register")]
public ActionResult Register(RegisterRequest request)
{
var existingUser = FindUser(request.Login);
if (existingUser != null)
{
return Conflict("User with this login already exists.");
}

var user = new User
{
Login = request.Login,
Password = request.Password,
Name = request.FullName,
Phone = request.Phone
};

_context.Users.Add(user);

_context.SaveChanges();

_emailSender.SendEmail(request.Login, EmailConfigurations.Subject, EmailConfigurations.RegisterBody.Replace("{recipientName}", request.FullName));

var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("anvarSekretKalitSozMalades"));
var signingCredentials = new SigningCredentials(securityKey,
SecurityAlgorithms.HmacSha256);

var claimsForToken = new List<Claim>();
claimsForToken.Add(new Claim("sub", user.Phone));
claimsForToken.Add(new Claim("name", user.Name));

var jwtSecurityToken = new JwtSecurityToken(
"anvar-api",
"anvar-mobile",
claimsForToken,
DateTime.UtcNow,
DateTime.UtcNow.AddDays(30),
signingCredentials);

var token = new JwtSecurityTokenHandler()
.WriteToken(jwtSecurityToken);

return Ok(token);
}

private bool FindUser(string login, string password)
{
var user = _context.Users.FirstOrDefault(u => u.Login == login);

if (user is null || user.Password != password)
{
return false;
}

//Send email afte Login
_emailSender.SendEmail(user.Login, EmailConfigurations.Subject, EmailConfigurations.LoginBody.Replace("{recipientName}", user.Name));

return true;
}

private User FindUser(string login)
{
return _context.Users.FirstOrDefault(u => u.Login == login);
}

static User Authenticate(string login, string password)
{
return new User()
{
Login = login,
Password = password,
Name = "Anvar",
Phone = "124123"
};
}
}
}

121 changes: 84 additions & 37 deletions Inflow.Api/Controllers/CategoriesController.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
using Inflow.Domain.DTOs.Category;
using ClosedXML.Excel;
using Inflow.Domain.DTOs.Category;
using Inflow.Domain.DTOs.Product;
using Inflow.Domain.Interfaces.Services;
using Inflow.Domain.ResourceParameters;
using Inflow.ResourceParameters;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Grid;
using System.Data;

namespace Inflow.Controllers
{

[Route("api/categories")]
[ApiController]
//[Authorize]
Expand Down Expand Up @@ -38,34 +44,41 @@ public ActionResult<CategoryDto> Get(int id)
return Ok(category);
}

//[HttpGet("export")]
//public ActionResult ExportCustomers()
//{
// var category = _categoryService.GetAllCategories();
[HttpGet("export/xls")]
public ActionResult ExportCustomers()
{
var categories = _categoryService.GetAllCategories();
byte[] data = GenerateExcle(categories);

return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Categories.xlsx");
}

[HttpGet("export/pdf")]
public IActionResult CreatePDFDocument()
{
PdfDocument document = new PdfDocument();
PdfPage page = document.Pages.Add();

PdfGrid pdfGrid = new PdfGrid();

// using XLWorkbook wb = new XLWorkbook();
// var sheet1 = wb.AddWorksheet(GetCategoriesDataTable(category), "Categories");
var categories = _categoryService.GetAllCategories();
List<object> data = ConvertCategoriesToData(categories);

// sheet1.Column(1).Style.Font.FontColor = XLColor.Red;
pdfGrid.DataSource = data;

// sheet1.Columns(2, 4).Style.Font.FontColor = XLColor.Blue;
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);

// sheet1.Row(1).CellsUsed().Style.Fill.BackgroundColor = XLColor.Black;
// //sheet1.Row(1).Cells(1,3).Style.Fill.BackgroundColor = XLColor.Yellow;
// sheet1.Row(1).Style.Font.FontColor = XLColor.White;
pdfGrid.Draw(page, new PointF(10, 10));

// sheet1.Row(1).Style.Font.Bold = true;
// sheet1.Row(1).Style.Font.Shadow = true;
// sheet1.Row(1).Style.Font.Underline = XLFontUnderlineValues.Single;
// sheet1.Row(1).Style.Font.VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
// sheet1.Row(1).Style.Font.Italic = true;
MemoryStream stream = new MemoryStream();
document.Save(stream);
stream.Position = 0;

// sheet1.Rows(2, 3).Style.Font.FontColor = XLColor.AshGrey;
string contentType = "application/pdf";
string fileName = "categories.pdf";

// using MemoryStream ms = new MemoryStream();
// wb.SaveAs(ms);
// return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Categories.xlsx");
//}
return File(stream, contentType, fileName);
}

[HttpGet("{id}/products")]
public ActionResult<ProductDto> GetProductsByCategoryId(
Expand Down Expand Up @@ -106,21 +119,55 @@ public ActionResult Delete(int id)

return NoContent();
}
private static byte[] GenerateExcle(IEnumerable<CategoryDto> categoryDtos)
{
using XLWorkbook wb = new();
var sheet1 = wb.AddWorksheet(GetCategoriesDataTable(categoryDtos), "Categories");

sheet1.Columns(1, 3).Style.Font.FontColor = XLColor.Black;
sheet1.Row(1).CellsUsed().Style.Fill.BackgroundColor = XLColor.Black;
sheet1.Row(1).Style.Font.FontColor = XLColor.White;

sheet1.Column(1).Width = 5;
sheet1.Columns(2, 3).Width = 12;

sheet1.Row(1).Style.Font.FontSize = 15;
sheet1.Row(1).Style.Font.Bold = true;
sheet1.Row(1).Style.Font.Shadow = true;
sheet1.Row(1).Style.Font.VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
sheet1.Row(1).Style.Font.Italic = false;

using MemoryStream ms = new();
wb.SaveAs(ms);

return ms.ToArray();
}
private List<object> ConvertCategoriesToData(IEnumerable<CategoryDto> categories)
{
List<object> data = new List<object>();

foreach (var category in categories)
{
data.Add(new { ID = category.Id, category.Name, category.NumberOfProducts });
}

return data;
}
private static DataTable GetCategoriesDataTable(IEnumerable<CategoryDto> categories)
{
DataTable table = new DataTable();
table.TableName = "Categories Data";
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Number of Products", typeof(int));

foreach (var category in categories)
{
table.Rows.Add(category.Id, category.Name, category.NumberOfProducts);
}

return table;
}

//private DataTable GetCategoriesDataTable(IEnumerable<CategoryDto> categories)
//{
// DataTable table = new DataTable();
// table.TableName = "Categories Data";
// table.Columns.Add("Id", typeof(int));
// table.Columns.Add("Name", typeof(string));
// table.Columns.Add("NumberOfProducts", typeof(string));

// foreach (var category in categories)
// {
// table.Rows.Add(category.Id, category.Name);
// }

// return table;
//}
}
}
Loading
Loading