Skip to content

Commit

Permalink
Logare + Inregistrare
Browse files Browse the repository at this point in the history
  • Loading branch information
Cipy34 committed Jan 31, 2025
1 parent e54d731 commit a15c702
Show file tree
Hide file tree
Showing 10 changed files with 2,335 additions and 211 deletions.
44 changes: 5 additions & 39 deletions backend-MT/Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
using backend_MT.Exceptions;
using backend_MT.Models;
using backend_MT.Models.DTOs.UserDTOs;
using backend_MT.Service.UserService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace backend_MT.Controllers
{
Expand All @@ -16,12 +12,9 @@ namespace backend_MT.Controllers
public class UserController : ControllerBase
{
private readonly IUserService _userService;
private readonly IConfiguration _configuration;

public UserController(IUserService userService, IConfiguration configuration)
public UserController(IUserService userService)
{
_userService = userService;
_configuration = configuration;
}

[HttpPost("register")]
Expand All @@ -45,27 +38,23 @@ public async Task<IActionResult> Register([FromBody] RegisterDTO user)
}
}


[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] LoginDTO user)
{
try
{
var result = await _userService.LoginAsync(user);
if (result != null)
var token = await _userService.LoginAsync(user);
if (!string.IsNullOrEmpty(token))
{
var token = GenerateJwtToken(user.username);

Response.Cookies.Append("jwt", token, new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.None,
Expires = DateTimeOffset.UtcNow.AddMinutes(30)
});

return Ok(new { Message = $"Autentificat ca {user.username}" });
return Ok(new { Message = $"Authenticated as {user.username}", Token = token });
}
else
{
Expand All @@ -85,28 +74,5 @@ public async Task<IActionResult> Login([FromBody] LoginDTO user)
return BadRequest(e.Message);
}
}

private string GenerateJwtToken(string username)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, username)
};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
issuer: _configuration["JWT:Issuer"],
audience: _configuration["JWT:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds
);

return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
30 changes: 30 additions & 0 deletions backend-MT/Data/SeedData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Microsoft.AspNetCore.Identity;

namespace backend_MT.Data
{
public static class Seed
{
public static async Task InitializeRoles(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole<int>>>();

string[] roleNames = { "Profesor", "Elev", "Administrator" };

foreach (var roleName in roleNames)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
var result = await roleManager.CreateAsync(new IdentityRole<int>(roleName));
if (!result.Succeeded)
{
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
throw new Exception($"Failed to create role '{roleName}': {errors}");
}
}
}
}
}
}
}
Loading

0 comments on commit a15c702

Please sign in to comment.