AuthController (API)
Namespace: FL_Accounting_Suite.API.Controllers
Route: api/auth
Purpose: Handles user authentication, including login, registration, and JWT token generation.
Dependencies:
-
IUserRepository/_unitOfWork.Users— for user data access -
IUnitOfWork— for database transaction handling -
IConfiguration— for JWT secret key retrieval -
BCrypt.Net— for password hashing and verification
1. Login Endpoint
Route: POST api/auth/login
Purpose: Authenticates a user and returns a JWT token.
Request Body (LoginDto):
{"email": "admin@futurelogic.com",
"password": "Admin@123"}
Logic Flow:
- Validate request model.
- Fetch user by email using
_unitOfWork.Users.GetByEmailAsync(). - Check password with
BCrypt.Verify(). - Ensure account is not deleted.
- Generate JWT token using
GenerateJwtToken(). - Return
AuthResponseDtowith user info and token.
Response (AuthResponseDto):
{
"Token": "<JWT_TOKEN>",
"UserId": "guid",
"FullName": "John Doe",
"Email": "john@example.com",
"RoleName": "Admin",
"CompanyId": "guid"
}
Error Responses:
-
400 Bad Request— Invalid model. -
401 Unauthorized— Invalid email/password or deactivated account.
2. Register Endpoint
Route: POST api/auth/register
Purpose: Registers a new user and returns a JWT token.
Request Body (RegisterDto):
{
"FullName": "John Doe",
"Email": "john@example.com",
"Password": "userpassword",
"RoleId": "guid",
"CompanyId": "guid"
}
Logic Flow:
- Validate request model.
- Check for duplicate email.
- Create new
Userentity. - Hash password using
BCrypt.HashPassword(). - Save user via
_unitOfWork.Users.AddAsync(). - Generate JWT token.
- Return
AuthResponseDtowith user info and token.
Response (AuthResponseDto):
{
"Token": "<JWT_TOKEN>",
"UserId": "guid",
"FullName": "John Doe",
"Email": "john@example.com",
"RoleName": "User",
"CompanyId": "guid"
}
Error Responses:
-
400 Bad Request— Invalid model. -
409 Conflict— Email already exists.
3. JWT Token Generation
Method: GenerateJwtToken(User user)
Purpose: Creates a JWT token for the authenticated user.
Token Details:
- Expiration: 3 hours (
DateTime.UtcNow.AddHours(3)) -
Claims included:
-
NameIdentifier→user.Id -
Email→user.Email -
Name→user.FullName -
Role→user.Role?.Name -
CompanyId→user.CompanyId
-
Signing Algorithm:
HmacSha256Secret Key: Retrieved from
appsettings.json(Jwt:Key)
Return Value: JWT token string
4. Notes
- Passwords are never stored or transmitted in plain text.
- Uses
BCryptfor secure password hashing. - Accounts marked as
IsDeletedcannot log in. - JWT token contains all necessary user info for authentication & authorization.
If you want, I can also create a diagram showing the login & registration flow with JWT for easier understanding—it’s very handy for documentation.
Do you want me to create that?
Top comments (0)