)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Home » Code Library » IdentityController (Ia.Ftn.Wa.Controllers)

Public general use code classes and xml files that we've compiled and used over the years:

    1: using Ia.Ftn.Wa.Models.Application;
    2: using Microsoft.AspNetCore.Authorization;
    3: using Microsoft.AspNetCore.Identity;
    4: using Microsoft.AspNetCore.Mvc;
    5: using System.Diagnostics;
    6: using System.Net;
    7:  
    8: namespace Ia.Ftn.Wa.Controllers
    9: {
   10:     ////////////////////////////////////////////////////////////////////////////
   11:  
   12:     /// <summary publish="true">
   13:     ///
   14:     /// </summary>
   15:     /// 
   16:     /// <remarks> 
   17:     /// Copyright � 2006-2025 Jasem Y. Al-Shamlan (info@ia.com.kw), Integrated Applications - Kuwait. All Rights Reserved.
   18:     /// </remarks> 
   19:     [Authorize]
   20:     public class IdentityController : Controller
   21:     {
   22:         private static bool oneTimeCalled = false;
   23:         private readonly UserManager<Ia.Ftn.Cl.Models.StaffIdentityUser> userManager;
   24:         private readonly SignInManager<Ia.Ftn.Cl.Models.StaffIdentityUser> signInManager;
   25:         private readonly RoleManager<IdentityRole> roleManager;
   26:         private readonly ILogger logger;
   27:  
   28:         private static IdentityViewModel currentIdentityViewModel = new Ia.Ftn.Wa.Models.Application.IdentityViewModel();
   29:  
   30:         /////////////////////////////////////////////////////////////////////////////////
   31:  
   32:         /// <summary>
   33:         ///
   34:         /// </summary>
   35:         public IdentityController(UserManager<Ia.Ftn.Cl.Models.StaffIdentityUser> _userManager, SignInManager<Ia.Ftn.Cl.Models.StaffIdentityUser> _signInManager, RoleManager<IdentityRole> _roleManager, ILoggerFactory _loggerFactory)
   36:         {
   37:             userManager = _userManager;
   38:             signInManager = _signInManager;
   39:             roleManager = _roleManager;
   40:             logger = _loggerFactory.CreateLogger<IdentityController>();
   41:         }
   42:  
   43:         /////////////////////////////////////////////////////////////////////////////////
   44:  
   45:         /// <summary>
   46:         ///
   47:         /// </summary>
   48:         [Route("identity")]
   49:         public IActionResult Index()
   50:         {
   51:             return View();
   52:         }
   53:  
   54:         /////////////////////////////////////////////////////////////////////////////////
   55:  
   56:         /// <summary>
   57:         ///
   58:         /// </summary>
   59:         [HttpGet]
   60:         [AllowAnonymous]
   61:         [Route("identity/login")]
   62:         public IActionResult Login(string returnUrl = null)
   63:         {
   64:             ViewData["ReturnUrl"] = returnUrl;
   65:  
   66:             if (!oneTimeCalled)
   67:             {
   68:                 Ia.Ftn.Cl.Models.Data.Administration.CreateFrameworkIdentityRolesIfTheyDoNotExist(roleManager); // order important: role then user-role
   69:  
   70:                 Ia.Ftn.Cl.Models.Data.Administration.CreateApplicationUserAndStaffIfDoesNotExist(roleManager, userManager);
   71:  
   72:                 oneTimeCalled = true;
   73:             }
   74:  
   75:             return View();
   76:         }
   77:  
   78:         /////////////////////////////////////////////////////////////////////////////////
   79:  
   80:         /// <summary>
   81:         ///
   82:         /// </summary>
   83:         [HttpPost]
   84:         [AllowAnonymous]
   85:         [ValidateAntiForgeryToken]
   86:         [Route("identity/login")]
   87:         public async Task<IActionResult> Login(Ia.Ftn.Wa.Models.Identity.LoginViewModel loginViewModel, string returnUrl = null)
   88:         {
   89:             ViewData["ReturnUrl"] = returnUrl;
   90:  
   91:             if (ModelState.IsValid)
   92:             {
   93:                 // This doesn't count login failures towards account lockout
   94:                 // To enable password failures to trigger account lockout, set lockoutOnFailure: true
   95:                 var result = await signInManager.PasswordSignInAsync(loginViewModel.UserName, loginViewModel.Password, loginViewModel.RememberMe, lockoutOnFailure: false);
   96:                 if (result.Succeeded)
   97:                 {
   98:                     logger.LogInformation(1, "User logged in.");
   99:                     return RedirectToLocal(returnUrl);
  100:                 }
  101:                 /*
  102:                 if (result.RequiresTwoFactor)
  103:                 {
  104:                     return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  105:                 }*/
  106:                 if (result.IsLockedOut)
  107:                 {
  108:                     logger.LogWarning(2, "User account locked out.");
  109:                     return View("Lockout");
  110:                 }
  111:                 else
  112:                 {
  113:                     ModelState.AddModelError(string.Empty, "Invalid login attempt.");
  114:                     return View(loginViewModel);
  115:                 }
  116:             }
  117:  
  118:             // If we got this far, something failed, redisplay form
  119:             return View(loginViewModel);
  120:         }
  121:  
  122:         /////////////////////////////////////////////////////////////////////////////////
  123:  
  124:         /// <summary>
  125:         ///
  126:         /// </summary>
  127:         [HttpPost]
  128:         [ValidateAntiForgeryToken]
  129:         [Route("identity/logoff")]
  130:         public async Task<IActionResult> LogOff()
  131:         {
  132:             await signInManager.SignOutAsync();
  133:  
  134:             logger.LogInformation(4, "User logged out.");
  135:  
  136:             return RedirectToAction(nameof(HomeController.Index), "Home");
  137:         }
  138:  
  139:         /////////////////////////////////////////////////////////////////////////////////
  140:  
  141:         /// <summary>
  142:         ///
  143:         /// </summary>
  144:         [Route("identity/profile")]
  145:         public IActionResult Profile()
  146:         {
  147:             return View();
  148:         }
  149:  
  150:         /////////////////////////////////////////////////////////////////////////////////
  151:  
  152:         /// <summary>
  153:         ///
  154:         /// </summary>
  155:         [HttpGet]
  156:         [Route("identity/change-password")]
  157:         public IActionResult ChangePassword()
  158:         {
  159:             return View();
  160:         }
  161:  
  162:         /////////////////////////////////////////////////////////////////////////////////
  163:  
  164:         /// <summary>
  165:         ///
  166:         /// </summary>
  167:         [HttpPost]
  168:         [ValidateAntiForgeryToken]
  169:         [Route("identity/change-password")]
  170:         public async Task<IActionResult> ChangePassword(Ia.Ftn.Wa.Models.IdentityViewModels.ChangePasswordViewModel model)
  171:         {
  172:             if (!ModelState.IsValid)
  173:             {
  174:                 return View(model);
  175:             }
  176:             var user = await GetCurrentUserAsync();
  177:             if (user != null)
  178:             {
  179:                 var result = await userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
  180:                 if (result.Succeeded)
  181:                 {
  182:                     await signInManager.SignInAsync(user, isPersistent: false);
  183:                     logger.LogInformation(3, "User changed their password successfully.");
  184:                     return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
  185:                 }
  186:                 AddErrors(result);
  187:                 return View(model);
  188:             }
  189:             return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
  190:         }
  191:  
  192:         /////////////////////////////////////////////////////////////////////////////////
  193:  
  194:         /// <summary>
  195:         ///
  196:         /// </summary>
  197:         [HttpGet]
  198:         [AllowAnonymous]
  199:         [Route("identity/reset-password")]
  200:         public IActionResult ResetPassword(string code = null)
  201:         {
  202:             return code == null ? View("Error") : View();
  203:         }
  204:  
  205:         /////////////////////////////////////////////////////////////////////////////////
  206:  
  207:         /// <summary>
  208:         ///
  209:         /// </summary>
  210:         [HttpPost]
  211:         [AllowAnonymous]
  212:         [ValidateAntiForgeryToken]
  213:         [Route("identity/reset-password")]
  214:         public async Task<IActionResult> ResetPassword(Ia.Ftn.Wa.Models.IdentityViewModels.ResetPasswordViewModel model)
  215:         {
  216:             if (!ModelState.IsValid)
  217:             {
  218:                 return View(model);
  219:             }
  220:  
  221:             var user = await userManager.FindByEmailAsync(model.Email);
  222:  
  223:             if (user == null)
  224:             {
  225:                 // Don't reveal that the user does not exist
  226:                 return RedirectToAction(nameof(IdentityController.ResetPasswordConfirmation), "Identity");
  227:             }
  228:  
  229:             var result = await userManager.ResetPasswordAsync(user, model.Code, model.Password);
  230:  
  231:             if (result.Succeeded)
  232:             {
  233:                 return RedirectToAction(nameof(IdentityController.ResetPasswordConfirmation), "Identity");
  234:             }
  235:  
  236:             AddErrors(result);
  237:  
  238:             return View();
  239:         }
  240:  
  241:         /////////////////////////////////////////////////////////////////////////////////
  242:  
  243:         /// <summary>
  244:         ///
  245:         /// </summary>
  246:         [HttpGet]
  247:         [AllowAnonymous]
  248:         [Route("identity/reset-password-confirmation")]
  249:         public IActionResult ResetPasswordConfirmation()
  250:         {
  251:             return View();
  252:         }
  253:  
  254:         /////////////////////////////////////////////////////////////////////////////////
  255:         /////////////////////////////////////////////////////////////////////////////////
  256:  
  257:         /// <summary>
  258:         ///
  259:         /// </summary>
  260:         [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  261:         public IActionResult Error()
  262:         {
  263:             return View(new Ia.Ftn.Wa.Models.ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  264:         }
  265:  
  266:         /////////////////////////////////////////////////////////////////////////////////
  267:         /////////////////////////////////////////////////////////////////////////////////
  268:  
  269:         #region Helpers
  270:  
  271:         private void AddErrors(IdentityResult result)
  272:         {
  273:             foreach (var error in result.Errors)
  274:             {
  275:                 ModelState.AddModelError(string.Empty, error.Description);
  276:             }
  277:         }
  278:  
  279:         public enum ManageMessageId
  280:         {
  281:             AddPhoneSuccess,
  282:             AddLoginSuccess,
  283:             ChangePasswordSuccess,
  284:             SetTwoFactorSuccess,
  285:             SetPasswordSuccess,
  286:             RemoveLoginSuccess,
  287:             RemovePhoneSuccess,
  288:             Error
  289:         }
  290:  
  291:         private Task<Ia.Ftn.Cl.Models.StaffIdentityUser> GetCurrentUserAsync()
  292:         {
  293:             return userManager.GetUserAsync(HttpContext.User);
  294:         }
  295:  
  296:         private IActionResult RedirectToLocal(string returnUrl)
  297:         {
  298:             if (Url.IsLocalUrl(returnUrl))
  299:             {
  300:                 return Redirect(returnUrl);
  301:             }
  302:             else
  303:             {
  304:                 return RedirectToAction(nameof(HomeController.Index), "Home");
  305:             }
  306:         }
  307:  
  308:         #endregion
  309:  
  310:         /////////////////////////////////////////////////////////////////////////////////
  311:         /////////////////////////////////////////////////////////////////////////////////
  312:     }
  313: }