Changeset 5b42c8d


Ignore:
Timestamp:
10/22/25 22:40:03 (11 months ago)
Author:
stefansaveski <stefansaveski19@…>
Branches:
master
Children:
41e4f9f
Parents:
d025ba3
Message:

Implement JWT Authentication and Update User Schema

Replaced repository interface with FinXaccesApi.Repositories in UsersControllers.cs. Updated database schema to use PasswordHash instead of Password. Added new migration files reflecting these changes. Updated service registration in Program.cs to include IAuthService and IUserRepository. Refactored UserRepository.cs and IUserRepository.cs with new methods and namespace changes. Commented out UserService.cs. Updated appsettings with new connection strings and JWT settings. Added BCrypt.Net-Next and System.IdentityModel.Tokens.Jwt packages. Introduced AuthController, UserDTO, AuthService, and IAuthService for handling authentication and user management.

Location:
iknow-api
Files:
4 added
10 edited
2 moved

Legend:

Unmodified
Added
Removed
  • iknow-api/Controllers/UsersControllers.cs

    rd025ba3 r5b42c8d  
    33using Microsoft.AspNetCore.Mvc;
    44using iknow_api.Core.Data;
    5 using iknow_api.Repository.Interfaces;
     5using FinXaccesApi.Repositories;
    66using iknow_api.Core.Interfaces;
    77
  • iknow-api/Migrations/20251022202014_InitialCreate.Designer.cs

    rd025ba3 r5b42c8d  
    1313{
    1414    [DbContext(typeof(AppDbContext))]
    15     [Migration("20251021141534_InitialCreate")]
     15    [Migration("20251022202014_InitialCreate")]
    1616    partial class InitialCreate
    1717    {
     
    4949                        .HasColumnType("text");
    5050
    51                     b.Property<string>("Password")
     51                    b.Property<string>("PasswordHash")
    5252                        .HasColumnType("text");
    5353
  • iknow-api/Migrations/20251022202014_InitialCreate.cs

    rd025ba3 r5b42c8d  
    2323                    Index = table.Column<string>(type: "text", nullable: true),
    2424                    Email = table.Column<string>(type: "text", nullable: true),
    25                     Password = table.Column<string>(type: "text", nullable: true),
     25                    PasswordHash = table.Column<string>(type: "text", nullable: true),
    2626                    Bday = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
    2727                    CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
  • iknow-api/Migrations/AppDbContextModelSnapshot.cs

    rd025ba3 r5b42c8d  
    4646                        .HasColumnType("text");
    4747
    48                     b.Property<string>("Password")
     48                    b.Property<string>("PasswordHash")
    4949                        .HasColumnType("text");
    5050
  • iknow-api/Models/User.cs

    rd025ba3 r5b42c8d  
    1717        public string? Index { get; set; }
    1818        public string? Email { get; set; }
    19         public string? Password { get; set; }
     19        public string? PasswordHash { get; set; }
    2020        public DateTime Bday { get; set; }
    2121        public DateTime CreatedAt { get; set; }
  • iknow-api/Program.cs

    rd025ba3 r5b42c8d  
    11using Microsoft.EntityFrameworkCore;
    22using iknow_api.Core.Data;
     3using FinXaccesApi.Services;
     4using FinXaccesApi.Repositories;
    35
    46var builder = WebApplication.CreateBuilder(args);
    57
    68// Add services to the container.
    7 
    89builder.Services.AddControllers();
    9 // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
    1010builder.Services.AddOpenApi();
    1111
    12 
     12// Register DbContext
    1313builder.Services.AddDbContext<AppDbContext>(options =>
    1414    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
    1515
    16 builder.Services.AddScoped<iknow_api.Repository.Interfaces.IUserRepository, iknow_api.Repository.UserRepository>();
     16// Register your services
     17builder.Services.AddScoped<IAuthService, AuthService>();
     18builder.Services.AddScoped<IUserRepository, UserRepository>(); // You'll need to add the UserRepository implementation
    1719
    1820var app = builder.Build();
     
    2426}
    2527
    26 builder.Services.AddDbContext<AppDbContext>(options =>
    27     options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
    28 
    29    
    3028app.UseHttpsRedirection();
    31 
    3229app.UseAuthorization();
    33 
    3430app.MapControllers();
    3531
  • iknow-api/Repository/Implementations/UserRepository.cs

    rd025ba3 r5b42c8d  
    1 using System.Threading;
    2 using System.Threading.Tasks;
     1using iknow_api.Core.Models;
     2using iknow_api.Core.Data;
     3using iknow_api.Core.Data;
     4using iknow_api.Core.Models;
    35using Microsoft.EntityFrameworkCore;
    4 using iknow_api.Core.Models;
    5 using iknow_api.Repository.Interfaces;
    6 using iknow_api.Core.Data;
    76
    8 namespace iknow_api.Repository
     7namespace FinXaccesApi.Repositories
    98{
    109    public class UserRepository : IUserRepository
     
    1716        }
    1817
    19         public Task<bool> EmailExistsAsync(string email, CancellationToken cancellationToken = default)
    20             => _context.User.AnyAsync(u => u.Email == email, cancellationToken);
    21 
    22         public async Task<User> AddUserAsync(User user, CancellationToken cancellationToken = default)
     18        public async Task<bool> UserExistsAsync(string username)
    2319        {
    24             await _context.User.AddAsync(user, cancellationToken);
    25             await _context.SaveChangesAsync(cancellationToken);
    26             return user;
     20            return await _context.User.AnyAsync(u => u.Email == username);
    2721        }
    2822
    29         public Task<User?> GetUserByIdAsync(int id, CancellationToken cancellationToken = default)
    30             => _context.User.FindAsync(new object[] { id }, cancellationToken).AsTask();
     23        public async Task<User?> GetUserByUsernameAsync(string username)
     24        {
     25            return await _context.User.FirstOrDefaultAsync(u => u.Email == username);
     26        }
     27
     28        public async Task AddUserAsync(User user)
     29        {
     30            _context.User.Add(user);
     31            await _context.SaveChangesAsync();
     32        }
     33
     34        public async Task<int> GetUsersCountAsync()
     35        {
     36            return await _context.User.CountAsync();
     37        }
    3138    }
    3239}
  • iknow-api/Repository/Interface/IUserRepository.cs

    rd025ba3 r5b42c8d  
    1 using System.Threading;
    2 using System.Threading.Tasks;
    31using iknow_api.Core.Models;
    4 
    5 namespace iknow_api.Repository.Interfaces
     2namespace FinXaccesApi.Repositories
    63{
    74    public interface IUserRepository
    85    {
    9         Task<bool> EmailExistsAsync(string email, CancellationToken cancellationToken = default);
    10         Task<User> AddUserAsync(User user, CancellationToken cancellationToken = default);
    11         Task<User?> GetUserByIdAsync(int id, CancellationToken cancellationToken = default);
     6        Task<bool> UserExistsAsync(string username);
     7        Task<User?> GetUserByUsernameAsync(string username);
     8        Task AddUserAsync(User user);
     9        Task<int> GetUsersCountAsync();
    1210    }
    1311}
  • iknow-api/Services/Implementations/UserService.cs

    rd025ba3 r5b42c8d  
    1 using Microsoft.EntityFrameworkCore;
    2 using iknow_api.Core.Models;
    3 using iknow_api.Repository.Interfaces;
    4 // ...existing code...
     1//using Microsoft.EntityFrameworkCore;
     2//using iknow_api.Core.Models;
     3//using iknow_api.Repository.Interfaces;
     4//// ...existing code...
    55
    6 namespace iknow_api.Core.Services
    7 {
    8     public class UserService
    9     {
    10         private readonly IUserRepository _users;
     6//namespace iknow_api.Core.Services
     7//{
     8//    public class UserService
     9//    {
     10//        private readonly IUserRepository _users;
    1111
    12         public UserService(IUserRepository users)
    13         {
    14             _users = users;
    15         }
     12//        public UserService(IUserRepository users)
     13//        {
     14//            _users = users;
     15//        }
    1616
    17         public async Task<User> AddUserAsync(User user, CancellationToken cancellationToken = default)
    18         {
    19             if (user == null) throw new ArgumentNullException(nameof(user));
     17//        public async Task<User> AddUserAsync(User user, CancellationToken cancellationToken = default)
     18//        {
     19//            if (user == null) throw new ArgumentNullException(nameof(user));
    2020
    21             if (!string.IsNullOrWhiteSpace(user.Email))
    22             {
    23                 user.Email = user.Email.Trim();
     21//            if (!string.IsNullOrWhiteSpace(user.Email))
     22//            {
     23//                user.Email = user.Email.Trim();
    2424
    25                 var exists = await _users.EmailExistsAsync(user.Email, cancellationToken);
    26                 if (exists)
    27                     throw new InvalidOperationException("A user with this email already exists.");
    28             }
     25//                var exists = await _users.EmailExistsAsync(user.Email, cancellationToken);
     26//                if (exists)
     27//                    throw new InvalidOperationException("A user with this email already exists.");
     28//            }
    2929
    30             return await _users.AddUserAsync(user, cancellationToken);
    31         }
    32     }
    33 }
     30//            return await _users.AddUserAsync(user, cancellationToken);
     31//        }
     32//    }
     33//}
  • iknow-api/appsettings.Development.json

    rd025ba3 r5b42c8d  
    66    }
    77  },
    8   "ConnectionStrings": {
    9     "DefaultConnection": "Host=localhost;Port=5432;Database=myappdb;Username=myuser;Password=kodrum2025"
    10   }
     8    "ConnectionStrings": {
     9        "DefaultConnection": "Host=localhost;Port=5432;Database=myappdb;Username=postgres;Password=newpassword"
     10    }
    1111}
  • iknow-api/appsettings.json

    rd025ba3 r5b42c8d  
    66    }
    77  },
    8     "ConnectionStrings": {
    9         "DefaultConnection": "Host=localhost;Port=3306;Database=myappdb;Username=root;Password=apipassword"
    10     }
     8  "ConnectionStrings": {
     9    "DefaultConnection": "Host=localhost;Port=55432;Database=myappdb;Username=postgres;Password=newpassword"
     10  },
     11  "Jwt": {
     12    "Key": "YourSecretKeyHereMustBeAtLeast32CharactersLongForHS256Algorithm"
     13  }
    1114}
  • iknow-api/iknow-api.csproj

    rd025ba3 r5b42c8d  
    99
    1010  <ItemGroup>
     11    <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
    1112    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.9" />
    1213    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.10">
     
    1516    </PackageReference>
    1617    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
     18    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.14.0" />
    1719  </ItemGroup>
    1820
Note: See TracChangeset for help on using the changeset viewer.