source: iknow-api/Controllers/AuthController.cs@ e49c3ed

Last change on this file since e49c3ed was e49c3ed, checked in by stefansaveski <stefansaveski19@…>, 11 months ago

Add JWT authentication and refactor namespaces

Introduced JWT-based authentication and authorization:

  • Configured JWT authentication in Program.cs with token validation.
  • Added [Authorize] attribute to a new getstring endpoint.

Refactored namespaces for consistency:

  • Updated namespaces from iknow_api.Core.* to iknow_api.*.

Enhanced middleware and dependency injection:

  • Registered IAuthService and IUserRepository.
  • Added app.UseAuthentication() and app.UseAuthorization().

Removed unused code and dependencies:

  • Deleted WeatherForecast class.
  • Cleaned up redundant imports.

Updated project dependencies to include JWT authentication library.

  • Property mode set to 100644
File size: 1.7 KB
Line 
1using iknow_api.DTOs;
2using iknow_api.Services;
3using Microsoft.AspNetCore.Authorization;
4using Microsoft.AspNetCore.Authentication.JwtBearer;
5using Microsoft.AspNetCore.Mvc;
6
7namespace iknow_api.Controllers
8{
9 [ApiController]
10 [Route("api/[controller]")]
11 public class AuthController : ControllerBase
12 {
13 private readonly IAuthService _authService;
14
15 public AuthController(IAuthService authService)
16 {
17 _authService = authService;
18 }
19
20 [HttpGet("testdb")]
21 public async Task<IActionResult> TestDb()
22 {
23 try
24 {
25 var count = await _authService.GetUsersCountAsync();
26 return Ok(new { message = "DB connection works!", usersCount = count });
27 }
28 catch (Exception ex)
29 {
30 return BadRequest(new { message = "DB connection failed", error = ex.Message });
31 }
32 }
33
34 [HttpPost("register")]
35 public async Task<IActionResult> Register([FromBody] RegisterDto request)
36 {
37 var result = await _authService.RegisterAsync(request);
38 if (!result) return BadRequest("User already exists");
39 return Ok("User registered successfully");
40 }
41
42 [HttpPost("login")]
43 public async Task<IActionResult> Login([FromBody] LoginDto request)
44 {
45 var token = await _authService.LoginAsync(request);
46 if (token == null) return Unauthorized("Invalid credentials");
47 return Ok(new { Token = token });
48 }
49
50 [Authorize]
51 [HttpGet("getstring")]
52 public async Task<IActionResult> getstring()
53 {
54 return Ok(new { message = "You are authorized!" });
55 }
56 }
57}
Note: See TracBrowser for help on using the repository browser.