| [dfe03b8] | 1 | using System.Threading.Tasks;
|
|---|
| 2 | using StockMaster.Data;
|
|---|
| 3 | using StockMaster.Models;
|
|---|
| 4 | using Microsoft.EntityFrameworkCore;
|
|---|
| 5 |
|
|---|
| 6 | namespace StockMaster.Services
|
|---|
| 7 | {
|
|---|
| 8 | public class AuthService : IAuthService
|
|---|
| 9 | {
|
|---|
| 10 | private readonly StockDbContext _context;
|
|---|
| 11 |
|
|---|
| 12 | public AuthService(StockDbContext context)
|
|---|
| 13 | {
|
|---|
| 14 | _context = context;
|
|---|
| 15 | }
|
|---|
| 16 |
|
|---|
| 17 | public async Task<User> AuthenticateAsync(string username, string password)
|
|---|
| 18 | {
|
|---|
| 19 | var user = await _context.Users
|
|---|
| 20 | .FirstOrDefaultAsync(u => u.Username == username && u.IsActive);
|
|---|
| 21 |
|
|---|
| 22 | if (user == null)
|
|---|
| 23 | return null;
|
|---|
| 24 |
|
|---|
| 25 | bool isHashed = user.Password.StartsWith("$2") && user.Password.Length == 60;
|
|---|
| 26 |
|
|---|
| 27 | if (isHashed)
|
|---|
| 28 | {
|
|---|
| 29 | if (BCrypt.Net.BCrypt.Verify(password, user.Password))
|
|---|
| 30 | return user;
|
|---|
| 31 | }
|
|---|
| 32 | else
|
|---|
| 33 | {
|
|---|
| 34 | if (user.Password == password)
|
|---|
| 35 | {
|
|---|
| 36 | user.Password = BCrypt.Net.BCrypt.HashPassword(password);
|
|---|
| 37 | await _context.SaveChangesAsync();
|
|---|
| 38 |
|
|---|
| 39 | return user;
|
|---|
| 40 | }
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | return null;
|
|---|
| 44 | }
|
|---|
| 45 |
|
|---|
| 46 |
|
|---|
| 47 | public async Task<User> GetUserByIdAsync(int userId)
|
|---|
| 48 | {
|
|---|
| 49 | return await _context.Users.FindAsync(userId);
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | public async Task<bool> CreateUserAsync(User user, string password)
|
|---|
| 53 | {
|
|---|
| 54 | using var transaction = await _context.Database.BeginTransactionAsync();
|
|---|
| 55 | try
|
|---|
| 56 | {
|
|---|
| 57 | user.Password = BCrypt.Net.BCrypt.HashPassword(password);
|
|---|
| 58 |
|
|---|
| 59 | _context.Users.Add(user);
|
|---|
| 60 | await _context.SaveChangesAsync();
|
|---|
| 61 |
|
|---|
| 62 | await transaction.CommitAsync();
|
|---|
| 63 | return true;
|
|---|
| 64 | }
|
|---|
| 65 | catch
|
|---|
| 66 | {
|
|---|
| 67 | await transaction.RollbackAsync();
|
|---|
| 68 | return false;
|
|---|
| 69 | }
|
|---|
| 70 | }
|
|---|
| 71 |
|
|---|
| 72 | }
|
|---|
| 73 | } |
|---|