Skip to content

Commit 7a5e35c

Browse files
committed
Master commit
1 parent 246786b commit 7a5e35c

File tree

69 files changed

+4746
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+4746
-0
lines changed

.gitignore

Lines changed: 477 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
using Asp.Versioning;
2+
using Project.API.Helpers;
3+
using Project.Core.Entities.Business;
4+
using Project.Core.Interfaces.IServices;
5+
using Microsoft.AspNetCore.Mvc;
6+
using Microsoft.IdentityModel.Tokens;
7+
using System.IdentityModel.Tokens.Jwt;
8+
using System.Security.Claims;
9+
using System.Text;
10+
11+
namespace Project.API.Controllers.V1
12+
{
13+
[ApiVersion("1.0")]
14+
[Route("api/v{version:apiVersion}/[controller]")]
15+
[ApiController]
16+
public class AuthController : ControllerBase
17+
{
18+
private readonly ILogger<AuthController> _logger;
19+
private readonly IAuthService _authService;
20+
private readonly IConfiguration _configuration;
21+
22+
public AuthController(
23+
ILogger<AuthController> logger,
24+
IAuthService authService,
25+
IConfiguration configuration)
26+
{
27+
_logger = logger;
28+
_authService = authService;
29+
_configuration = configuration;
30+
}
31+
32+
[HttpPost, Route("login")]
33+
public async Task<IActionResult> Login(LoginViewModel model)
34+
{
35+
if (ModelState.IsValid)
36+
{
37+
try
38+
{
39+
var result = await _authService.Login(model.UserName, model.Password);
40+
if (result.Success)
41+
{
42+
var token = GenerateJwtToken(result);
43+
return Ok(new ResponseViewModel<AuthResultViewModel>
44+
{
45+
Success = true,
46+
Data = token,
47+
Message = "Login successful"
48+
});
49+
}
50+
51+
return BadRequest(result);
52+
}
53+
catch (Exception ex)
54+
{
55+
_logger.LogError(ex, $"An error occurred while login");
56+
string message = $"An error occurred while login- " + ex.Message;
57+
58+
return StatusCode(StatusCodes.Status500InternalServerError, new ResponseViewModel
59+
{
60+
Success = false,
61+
Message = message,
62+
Error = new ErrorViewModel
63+
{
64+
Code = "LOGIN_ERROR",
65+
Message = message
66+
}
67+
});
68+
}
69+
70+
}
71+
72+
return BadRequest(new ResponseViewModel
73+
{
74+
Success = false,
75+
Message = "Invalid input",
76+
Error = new ErrorViewModel
77+
{
78+
Code = "INPUT_VALIDATION_ERROR",
79+
Message = ModelStateHelper.GetErrors(ModelState)
80+
}
81+
});
82+
}
83+
84+
[HttpPost, Route("logout")]
85+
public async Task<IActionResult> Logout()
86+
{
87+
await _authService.Logout();
88+
return Ok();
89+
}
90+
91+
private AuthResultViewModel GenerateJwtToken(ResponseViewModel<UserViewModel> auth)
92+
{
93+
var jwtTokenHandler = new JwtSecurityTokenHandler();
94+
var key = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]);
95+
96+
var claims = new List<Claim>
97+
{
98+
new Claim(JwtRegisteredClaimNames.Aud, _configuration["JwtConfig:ValidAudience"]),
99+
new Claim(JwtRegisteredClaimNames.Iss, _configuration["JwtConfig:ValidIssuer"]),
100+
new Claim(JwtRegisteredClaimNames.Sub, auth.Data.Id.ToString()),
101+
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
102+
};
103+
104+
var tokenDescriptor = new SecurityTokenDescriptor
105+
{
106+
Subject = new ClaimsIdentity(claims),
107+
Expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(_configuration["JwtConfig:TokenExpirationMinutes"])),
108+
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
109+
};
110+
111+
var token = jwtTokenHandler.CreateToken(tokenDescriptor);
112+
var jwtToken = jwtTokenHandler.WriteToken(token);
113+
114+
return new AuthResultViewModel()
115+
{
116+
AccessToken = jwtToken,
117+
Success = true,
118+
};
119+
}
120+
121+
}
122+
123+
}
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
using Asp.Versioning;
2+
using Project.Core.Entities.Business;
3+
using Project.Core.Interfaces.IServices;
4+
using Microsoft.AspNetCore.Authentication.JwtBearer;
5+
using Microsoft.AspNetCore.Authorization;
6+
using Microsoft.AspNetCore.Mvc;
7+
8+
namespace Project.API.Controllers.V1
9+
{
10+
[ApiVersion("1.0")]
11+
[Route("api/v{version:apiVersion}/[controller]")]
12+
[ApiController]
13+
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
14+
public class ProductController : ControllerBase
15+
{
16+
private readonly ILogger<ProductController> _logger;
17+
private readonly IProductService _productService;
18+
19+
public ProductController(ILogger<ProductController> logger, IProductService productService)
20+
{
21+
_logger = logger;
22+
_productService = productService;
23+
}
24+
25+
26+
[HttpGet("paginated")]
27+
[AllowAnonymous]
28+
public async Task<IActionResult> Get(int? pageNumber, int? pageSize, CancellationToken cancellationToken)
29+
{
30+
try
31+
{
32+
int pageSizeValue = pageSize ?? 10;
33+
int pageNumberValue = pageNumber ?? 1;
34+
35+
//Get peginated data
36+
var products = await _productService.GetPaginatedData(pageNumberValue, pageSizeValue, cancellationToken);
37+
38+
return Ok(products);
39+
}
40+
catch (Exception ex)
41+
{
42+
_logger.LogError(ex, "An error occurred while retrieving products");
43+
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
44+
}
45+
}
46+
47+
48+
[HttpGet]
49+
[AllowAnonymous]
50+
public async Task<IActionResult> Get(CancellationToken cancellationToken)
51+
{
52+
try
53+
{
54+
var products = await _productService.GetAll(cancellationToken);
55+
return Ok(products);
56+
}
57+
catch (Exception ex)
58+
{
59+
_logger.LogError(ex, "An error occurred while retrieving products");
60+
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
61+
}
62+
63+
}
64+
65+
66+
[HttpGet("{id}")]
67+
[AllowAnonymous]
68+
public async Task<IActionResult> Get(int id, CancellationToken cancellationToken)
69+
{
70+
try
71+
{
72+
var data = await _productService.GetById(id, cancellationToken);
73+
return Ok(data);
74+
}
75+
catch (Exception ex)
76+
{
77+
if (ex.Message == "No data found")
78+
{
79+
return StatusCode(StatusCodes.Status404NotFound, ex.Message);
80+
}
81+
_logger.LogError(ex, $"An error occurred while retrieving the product");
82+
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
83+
}
84+
}
85+
86+
87+
[HttpPost]
88+
public async Task<IActionResult> Create(ProductCreateViewModel model, CancellationToken cancellationToken)
89+
{
90+
if (ModelState.IsValid)
91+
{
92+
string message = "";
93+
if (await _productService.IsExists("Name", model.Name, cancellationToken))
94+
{
95+
message = $"The product name- '{model.Name}' already exists";
96+
return StatusCode(StatusCodes.Status400BadRequest, message);
97+
}
98+
99+
if (await _productService.IsExists("Code", model.Code, cancellationToken))
100+
{
101+
message = $"The product code- '{model.Code}' already exists";
102+
return StatusCode(StatusCodes.Status400BadRequest, message);
103+
}
104+
105+
try
106+
{
107+
var data = await _productService.Create(model, cancellationToken);
108+
return Ok(data);
109+
}
110+
catch (Exception ex)
111+
{
112+
_logger.LogError(ex, $"An error occurred while adding the product");
113+
message = $"An error occurred while adding the product- " + ex.Message;
114+
115+
return StatusCode(StatusCodes.Status500InternalServerError, message);
116+
}
117+
}
118+
return StatusCode(StatusCodes.Status400BadRequest, "Please input all required data");
119+
}
120+
121+
122+
[HttpPut]
123+
public async Task<IActionResult> Edit(ProductUpdateViewModel model, CancellationToken cancellationToken)
124+
{
125+
if (ModelState.IsValid)
126+
{
127+
string message = "";
128+
if (await _productService.IsExistsForUpdate(model.Id, "Name", model.Name, cancellationToken))
129+
{
130+
message = "The product name- '{model.Name}' already exists";
131+
return StatusCode(StatusCodes.Status400BadRequest, message);
132+
}
133+
134+
if (await _productService.IsExistsForUpdate(model.Id, "Code", model.Code, cancellationToken))
135+
{
136+
message = $"The product code- '{model.Code}' already exists";
137+
return StatusCode(StatusCodes.Status400BadRequest, message);
138+
}
139+
140+
try
141+
{
142+
await _productService.Update(model, cancellationToken);
143+
return Ok();
144+
}
145+
catch (Exception ex)
146+
{
147+
_logger.LogError(ex, $"An error occurred while updating the product");
148+
message = $"An error occurred while updating the product- " + ex.Message;
149+
150+
return StatusCode(StatusCodes.Status500InternalServerError, message);
151+
}
152+
}
153+
return StatusCode(StatusCodes.Status400BadRequest, "Please input all required data");
154+
}
155+
156+
157+
[HttpDelete("{id}")]
158+
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
159+
{
160+
try
161+
{
162+
await _productService.Delete(id, cancellationToken);
163+
return Ok();
164+
}
165+
catch (Exception ex)
166+
{
167+
_logger.LogError(ex, "An error occurred while deleting the product");
168+
return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while deleting the product- " + ex.Message);
169+
}
170+
}
171+
172+
[HttpGet("PriceCheck/{productId}")]
173+
[AllowAnonymous]
174+
public async Task<IActionResult> PriceCheck(int productId, CancellationToken cancellationToken)
175+
{
176+
try
177+
{
178+
var price = await _productService.PriceCheck(productId, cancellationToken);
179+
return Ok(price);
180+
}
181+
catch (Exception ex)
182+
{
183+
_logger.LogError(ex, "An error occurred while checking product price");
184+
return StatusCode(StatusCodes.Status500InternalServerError, $"An error occurred while checking product price- {ex.Message}");
185+
}
186+
}
187+
188+
}
189+
}

0 commit comments

Comments
 (0)