Skip to content

Commit

Permalink
Add initial setup for DotnetAuth project
Browse files Browse the repository at this point in the history
- Added DotnetAuth.sln and DotnetAuth.csproj targeting .NET 8.0.
- Created appsettings.json and appsettings.Development.json for configuration.
- Implemented Program.cs to configure services, middleware, and HTTP pipeline.
- Added controllers for authentication (AuthController) and weather forecasts (WeatherForecastController).
- Created models and services for user management, JWT settings, and error handling.
- Set up Entity Framework Core with ApplicationDbContext and initial migration.
- Added HTTP request testing file (DotnetAuth.http) and launch settings.
- Implemented user service (UserServiceImpl) for registration, login, token management, and CRUD operations.
  • Loading branch information
Clifftech123 committed Dec 9, 2024
1 parent 22744ce commit 1083b75
Show file tree
Hide file tree
Showing 27 changed files with 1,999 additions and 0 deletions.
22 changes: 22 additions & 0 deletions DotnetAuth/DotnetAuth.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35506.116 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetAuth", "DotnetAuth\DotnetAuth.csproj", "{0E9423E7-5BC7-4050-A675-B2B9354A7123}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0E9423E7-5BC7-4050-A675-B2B9354A7123}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0E9423E7-5BC7-4050-A675-B2B9354A7123}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0E9423E7-5BC7-4050-A675-B2B9354A7123}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0E9423E7-5BC7-4050-A675-B2B9354A7123}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
119 changes: 119 additions & 0 deletions DotnetAuth/DotnetAuth/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using DotnetAuth.Domain.Contracts;
using DotnetAuth.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DotnetAuth.Controllers
{
/// <summary>
/// Controller for handling authentication-related operations.
/// </summary>
[Route("api/")]
public class AuthController : ControllerBase
{
private readonly IUserServices _userService;

/// <summary>
/// Initializes a new instance of the <see cref="AuthController"/> class.
/// </summary>
/// <param name="userService">The user service for managing user-related operations.</param>
public AuthController(IUserServices userService)
{
_userService = userService;
}

/// <summary>
/// Registers a new user.
/// </summary>
/// <param name="request">The user registration request.</param>
/// <returns>An <see cref="IActionResult"/> representing the result of the operation.</returns>
[HttpPost("register")]
[AllowAnonymous]
public async Task<IActionResult> Register([FromBody] UserRegisterRequest request)
{
var response = await _userService.RegisterAsync(request);
return Ok(response);
}

/// <summary>
/// Logs in a user.
/// </summary>
/// <param name="request">The user login request.</param>
/// <returns>An <see cref="IActionResult"/> representing the result of the operation.</returns>
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] UserLoginRequest request)
{
var response = await _userService.LoginAsync(request);
return Ok(response);
}

/// <summary>
/// Gets a user by ID.
/// </summary>
/// <param name="id">The ID of the user.</param>
/// <returns>An <see cref="IActionResult"/> representing the result of the operation.</returns>
[HttpGet("user/{id}")]
[Authorize]
public async Task<IActionResult> GetById(Guid id)
{
var response = await _userService.GetByIdAsync(id);
return Ok(response);
}

/// <summary>
/// Refreshes the access token using the refresh token.
/// </summary>
/// <param name="request">The refresh token request.</param>
/// <returns>An <see cref="IActionResult"/> representing the result of the operation.</returns>
[HttpPost("refresh-token")]
[Authorize]
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest request)
{
var response = await _userService.RefreshTokenAsync(request);
return Ok(response);
}

/// <summary>
/// Revokes the refresh token.
/// </summary>
/// <param name="request">The refresh token request to be revoked.</param>
/// <returns>An <see cref="IActionResult"/> representing the result of the operation.</returns>
[HttpPost("revoke-refresh-token")]
[Authorize]
public async Task<IActionResult> RevokeRefreshToken([FromBody] RefreshTokenRequest request)
{
var response = await _userService.RevokeRefreshToken(request);
if (response != null && response.Message == "Refresh token revoked successfully")
{
return Ok(response);
}
return BadRequest(response);
}

/// <summary>
/// Gets the current user.
/// </summary>
/// <returns>An <see cref="IActionResult"/> representing the result of the operation.</returns>
[HttpGet("current-user")]
[Authorize]
public async Task<IActionResult> GetCurrentUser()
{
var response = await _userService.GetCurrentUserAsync();
return Ok(response);
}

/// <summary>
/// Deletes a user.
/// </summary>
/// <param name="id">The ID of the user to be deleted.</param>
/// <returns>An <see cref="IActionResult"/> representing the result of the operation.</returns>
[HttpDelete("user/{id}")]
[Authorize]
public async Task<IActionResult> Delete(Guid id)
{
await _userService.DeleteAsync(id);
return Ok();
}
}
}
33 changes: 33 additions & 0 deletions DotnetAuth/DotnetAuth/Controllers/WeatherForecastController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;

namespace DotnetAuth.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
9 changes: 9 additions & 0 deletions DotnetAuth/DotnetAuth/Domain/Contracts/ErrorResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace DotnetAuth.Domain.Contracts
{
public class ErrorResponse
{
public string Titel { get; set; }
public int StatusCode { get; set; }
public string Message { get; set; }
}
}
10 changes: 10 additions & 0 deletions DotnetAuth/DotnetAuth/Domain/Contracts/JwtSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace DotnetAuth.Domain.Contracts
{
public class JwtSettings
{
public string? Key { get; set; }
public string ValidIssuer { get; set; }
public string ValidAudience { get; set; }
public double Expires { get; set; }
}
}
72 changes: 72 additions & 0 deletions DotnetAuth/DotnetAuth/Domain/Contracts/UserRequsetandResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
namespace DotnetAuth.Domain.Contracts
{

public class UserRegisterRequest
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Gender { get; set; }

}


public class UserResponse
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public DateTime CreateAt { get; set; }
public DateTime UpdateAt { get; set; }
public string? AccessToken { get; set; }
public string? RefreshToken { get; set; }


}

public class UserLoginRequest
{
public string Email { get; set; }
public string Password { get; set; }
}

public class CurrentUserResponse
{

public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public string AccessToken { get; set; }
public DateTime CreateAt { get; set; }
public DateTime UpdateAt { get; set; }

}


public class UpdateUserRequest
{
public string FirstName { get; set; }
public string LastName { get; set; }

public string Email { get; set; }
public string Password { get; set; }
public string Gender { get; set; }
}


public class RevokeRefreshTokenResponse
{
public string Message { get; set; }
}


public class RefreshTokenRequest
{
public string RefreshToken { get; set; }
}

}
15 changes: 15 additions & 0 deletions DotnetAuth/DotnetAuth/Domain/Entities/ApplicationUser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Identity;

namespace DotnetAuth.Domain.Entities
{
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string? RefreshToken { get; set; }
public DateTime? RefreshTokenExpiryTime { get; set; }
public DateTime CreateAt { get; set; }
public DateTime UpdateAt { get; set; }
}
}
25 changes: 25 additions & 0 deletions DotnetAuth/DotnetAuth/DotnetAuth.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions DotnetAuth/DotnetAuth/DotnetAuth.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@DotnetAuth_HostAddress = http://localhost:5130

GET {{DotnetAuth_HostAddress}}/weatherforecast/
Accept: application/json

###
43 changes: 43 additions & 0 deletions DotnetAuth/DotnetAuth/Exceptions/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using DotnetAuth.Domain.Contracts;
using Microsoft.AspNetCore.Diagnostics;
using System.Net;

namespace DotnetAuth.Exceptions
{
public class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;

public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}

public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
_logger.LogError(exception, exception.Message);
var response = new ErrorResponse
{
Message = exception.Message,
};

switch (exception)
{
case BadHttpRequestException:
response.StatusCode = (int)HttpStatusCode.BadRequest;
response.Titel = exception.GetType().Name;
break;

default:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
response.Titel = "Internal Server Error";
break;
}

httpContext.Response.StatusCode = response.StatusCode;
await httpContext.Response.WriteAsJsonAsync(response, cancellationToken);

return true;
}
}
}
Loading

0 comments on commit 1083b75

Please sign in to comment.