-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.cs
More file actions
112 lines (96 loc) · 3.59 KB
/
AuthController.cs
File metadata and controls
112 lines (96 loc) · 3.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using TryApi.ProductData;
using TryApi.Products;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using TryApi.Models;
using BCrypt.Net;
namespace TryApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly IConfiguration _configuration;
private readonly ILogger<AuthController> _logger;
public AuthController(ApplicationDbContext context, IConfiguration configuration, ILogger<AuthController> logger)
{
_context = context;
_configuration = configuration;
_logger = logger;
}
// Регистрация
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] UserRegisterDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
if (_context.Users.Any(u => u.Username == dto.Username))
return BadRequest("User already exists.");
var user = new User
{
Username = dto.Username,
Email = dto.Email // Добавьте это поле
};
user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
_context.Users.Add(user);
await _context.SaveChangesAsync();
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred during registration.");
return StatusCode(500, "Internal server error");
}
}
// Логин
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] UserLoginDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var user = await _context.Users.FirstOrDefaultAsync(u => u.Username == dto.Username);
if (user == null || !BCrypt.Net.BCrypt.Verify(dto.Password, user.PasswordHash))
return Unauthorized();
var token = GenerateJwtToken(user);
return Ok(new { Token = token });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred during login.");
return StatusCode(500, "Internal server error");
}
}
private string GenerateJwtToken(User user)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
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);
}
}
}