Oilshop / Controllers /AccountController.cs
almakhmri253-stack
Add self-registration page with fixed Employee permissions
af069e3
Raw History Blame Contribute Delete
6.73 kB
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using OilShopManagement.Authorization;
using OilShopManagement.Models;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
namespace OilShopManagement.Controllers;
public class AccountController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public AccountController(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
_signInManager = signInManager;
_userManager = userManager;
_roleManager = roleManager;
}
[AllowAnonymous]
public IActionResult Login(string? returnUrl = null)
{
if (User.Identity?.IsAuthenticated == true)
return RedirectToAction("Index", "Dashboard");
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string? returnUrl = null)
{
if (!ModelState.IsValid) return View(model);
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null || !user.IsActive)
{
ModelState.AddModelError("", "البريد الإلكتروني أو كلمة المرور غير صحيحة");
return View(model);
}
if (await _userManager.IsLockedOutAsync(user))
{
ModelState.AddModelError("", "تم تعطيل الحساب مؤقتاً بسبب محاولات دخول متكررة. حاول بعد 15 دقيقة.");
return View(model);
}
var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
user.LastLoginAt = DateTime.UtcNow;
await _userManager.UpdateAsync(user);
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
return RedirectToAction("Index", "Dashboard");
}
if (result.IsLockedOut)
{
ModelState.AddModelError("", "تم تعطيل الحساب مؤقتاً بسبب محاولات دخول متكررة. حاول بعد 15 دقيقة.");
return View(model);
}
ModelState.AddModelError("", "البريد الإلكتروني أو كلمة المرور غير صحيحة");
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction(nameof(Login));
}
[AllowAnonymous]
public IActionResult Register()
{
if (User.Identity?.IsAuthenticated == true)
return RedirectToAction("Index", "Dashboard");
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid) return View(model);
if (await _userManager.FindByEmailAsync(model.Email) != null)
{
ModelState.AddModelError("Email", "البريد الإلكتروني مستخدم بالفعل");
return View(model);
}
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FullName = model.FullName,
EmailConfirmed = true,
IsActive = true,
CreatedAt = DateTime.UtcNow
};
var result = await _userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
ModelState.AddModelError("", error.Description);
return View(model);
}
if (!await _roleManager.RoleExistsAsync("Employee"))
await _roleManager.CreateAsync(new IdentityRole("Employee"));
await _userManager.AddToRoleAsync(user, "Employee");
foreach (var perm in Permissions.EmployeeDefaults)
await _userManager.AddClaimAsync(user, new Claim("Permission", perm));
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Dashboard");
}
[AllowAnonymous]
public IActionResult SetLanguage(string culture, string returnUrl = "/")
{
Response.Cookies.Append(
"language",
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential = true }
);
return LocalRedirect(Url.IsLocalUrl(returnUrl) ? returnUrl : "/");
}
}
public class RegisterViewModel
{
[Required(ErrorMessage = "الاسم مطلوب")]
[StringLength(100)]
[Display(Name = "الاسم الكامل")]
public string FullName { get; set; } = string.Empty;
[Required(ErrorMessage = "البريد الإلكتروني مطلوب")]
[EmailAddress]
[Display(Name = "البريد الإلكتروني")]
public string Email { get; set; } = string.Empty;
[Required(ErrorMessage = "كلمة المرور مطلوبة")]
[DataType(DataType.Password)]
[StringLength(100, MinimumLength = 8, ErrorMessage = "كلمة المرور يجب أن تكون 8 أحرف على الأقل")]
[Display(Name = "كلمة المرور")]
public string Password { get; set; } = string.Empty;
[Required(ErrorMessage = "تأكيد كلمة المرور مطلوب")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "كلمتا المرور غير متطابقتين")]
[Display(Name = "تأكيد كلمة المرور")]
public string ConfirmPassword { get; set; } = string.Empty;
}
public class LoginViewModel
{
[Required(ErrorMessage = "البريد الإلكتروني مطلوب")]
[EmailAddress]
[Display(Name = "البريد الإلكتروني")]
public string Email { get; set; } = string.Empty;
[Required(ErrorMessage = "كلمة المرور مطلوبة")]
[DataType(DataType.Password)]
[Display(Name = "كلمة المرور")]
public string Password { get; set; } = string.Empty;
[Display(Name = "تذكرني")]
public bool RememberMe { get; set; }
}