/
ilyakos
/
ChatWithAI
Обзор
Документация
Войти
/
ilyakos
/
ChatWithAI
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
ChatWithAI_Server/Services/AuthService.cs
82 строки
3 KB
Косоуров Илья Николаевич
заготовка сделана, есть авторизация и БД для работы с пользователями
15 май 2026, 23:16
15 май 2026, 23:16
d14fac3
Код
Авторство
О чём код?
using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using ChatWithAI.Database.Models; using ChatWithAI.Database.Repositories; using ChatWithAI_Server.DTOs; using Microsoft.IdentityModel.Tokens; namespace ChatWithAI_Server.Services; /// <summary> /// Сервис аутентификации: регистрация, вход и генерация JWT-токенов. /// </summary> public class AuthService(IUserRepository users, IConfiguration config) : IAuthService { /// <inheritdoc/> public async Task<AuthResponseDto> RegisterAsync(RegisterDto dto) { if (await users.GetByEmailAsync(dto.Email) is not null) throw new InvalidOperationException("Пользователь с таким email уже существует."); if (await users.GetByUsernameAsync(dto.Username) is not null) throw new InvalidOperationException("Имя пользователя уже занято."); var user = new User { Username = dto.Username, Email = dto.Email, PasswordHash = PasswordHasher.Hash(dto.Password) }; await users.AddAsync(user); await users.SaveChangesAsync(); return new AuthResponseDto(GenerateToken(user), user.Username, user.Email); } /// <inheritdoc/> public async Task<AuthResponseDto> LoginAsync(LoginDto dto) { var user = await users.GetByEmailAsync(dto.Email) ?? throw new UnauthorizedAccessException("Неверный email или пароль."); if (!PasswordHasher.Verify(dto.Password, user.PasswordHash)) throw new UnauthorizedAccessException("Неверный email или пароль."); return new AuthResponseDto(GenerateToken(user), user.Username, user.Email); } /// <summary> /// Генерирует подписанный JWT-токен для указанного пользователя. /// </summary> /// <param name="user">Пользователь, для которого создаётся токен.</param> /// <returns>Строка JWT-токена.</returns> private string GenerateToken(User user) { var key = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(config["Jwt:Key"]!)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.UtcNow.AddMinutes( double.Parse(config["Jwt:ExpiresInMinutes"]!)); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim(JwtRegisteredClaimNames.UniqueName, user.Username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken( issuer: config["Jwt:Issuer"], audience: config["Jwt:Audience"], claims: claims, expires: expires, signingCredentials: credentials); return new JwtSecurityTokenHandler().WriteToken(token); } }