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

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

    1: using Ia.Dn.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.Dn.Wa.Controllers
    9: {
   10:     ////////////////////////////////////////////////////////////////////////////
   11:  
   12:     /// <summary publish="true">
   13:     ///
   14:     /// </summary>
   15:     /// 
   16:     /// <remarks> 
   17:     /// Copyright � 2006-2026 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.Dn.Cl.Models.StaffIdentityUser> userManager;
   24:         private readonly SignInManager<Ia.Dn.Cl.Models.StaffIdentityUser> signInManager;
   25:         private readonly RoleManager<IdentityRole> roleManager;
   26:         private readonly ILogger logger;
   27:  
   28:         private static IdentityViewModel currentIdentityViewModel = new Ia.Dn.Wa.Models.Application.IdentityViewModel();
   29:  
   30:         /////////////////////////////////////////////////////////////////////////////////
   31:  
   32:         /// <summary>
   33:         ///
   34:         /// </summary>
   35:         public IdentityController(UserManager<Ia.Dn.Cl.Models.StaffIdentityUser> _userManager, SignInManager<Ia.Dn.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.Dn.Cl.Models.Data.Administration.CreateFrameworkIdentityRolesIfTheyDoNotExist(roleManager); // order important: role then user-role
   69:  
   70:                 Ia.Dn.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.Dn.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:         [AllowAnonymous]
  129:         [ValidateAntiForgeryToken]
  130:         [Route("identity/auto-login")]
  131:         public async Task<IActionResult> AutoLogin(string email)
  132:         {
  133:             var user = await userManager.FindByNameAsync(email);
  134:  
  135:             if (user != null)
  136:             {
  137:                 await signInManager.SignInAsync(user, isPersistent: false);
  138:  
  139:                 return RedirectToAction("Index", "Home");
  140:             }
  141:             else
  142:             {
  143:                 return NotFound("User not found.");
  144:             }
  145:         }
  146:         
  147:         /////////////////////////////////////////////////////////////////////////////////
  148:  
  149:         /// <summary>
  150:         ///
  151:         /// </summary>
  152:         [HttpPost]
  153:         [ValidateAntiForgeryToken]
  154:         [Route("identity/logoff")]
  155:         public async Task<IActionResult> LogOff()
  156:         {
  157:             await signInManager.SignOutAsync();
  158:  
  159:             logger.LogInformation(4, "User logged out.");
  160:  
  161:             return RedirectToAction(nameof(HomeController.Index), "Home");
  162:         }
  163:  
  164:         /////////////////////////////////////////////////////////////////////////////////
  165:  
  166:         /// <summary>
  167:         ///
  168:         /// </summary>
  169:         [Route("identity/profile")]
  170:         public IActionResult Profile()
  171:         {
  172:             return View();
  173:         }
  174:  
  175:         /////////////////////////////////////////////////////////////////////////////////
  176:  
  177:         /// <summary>
  178:         ///
  179:         /// </summary>
  180:         [HttpGet]
  181:         [Route("identity/change-password")]
  182:         public IActionResult ChangePassword()
  183:         {
  184:             return View();
  185:         }
  186:  
  187:         /////////////////////////////////////////////////////////////////////////////////
  188:  
  189:         /// <summary>
  190:         ///
  191:         /// </summary>
  192:         [HttpPost]
  193:         [ValidateAntiForgeryToken]
  194:         [Route("identity/change-password")]
  195:         public async Task<IActionResult> ChangePassword(Ia.Dn.Wa.Models.IdentityViewModels.ChangePasswordViewModel model)
  196:         {
  197:             if (!ModelState.IsValid)
  198:             {
  199:                 return View(model);
  200:             }
  201:             var user = await GetCurrentUserAsync();
  202:             if (user != null)
  203:             {
  204:                 var result = await userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
  205:                 if (result.Succeeded)
  206:                 {
  207:                     await signInManager.SignInAsync(user, isPersistent: false);
  208:                     logger.LogInformation(3, "User changed their password successfully.");
  209:                     return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
  210:                 }
  211:                 AddErrors(result);
  212:                 return View(model);
  213:             }
  214:             return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
  215:         }
  216:  
  217:         /////////////////////////////////////////////////////////////////////////////////
  218:  
  219:         /// <summary>
  220:         ///
  221:         /// </summary>
  222:         [HttpGet]
  223:         [AllowAnonymous]
  224:         [Route("identity/reset-password")]
  225:         public IActionResult ResetPassword(string code = null)
  226:         {
  227:             return code == null ? View("Error") : View();
  228:         }
  229:  
  230:         /////////////////////////////////////////////////////////////////////////////////
  231:  
  232:         /// <summary>
  233:         ///
  234:         /// </summary>
  235:         [HttpPost]
  236:         [AllowAnonymous]
  237:         [ValidateAntiForgeryToken]
  238:         [Route("identity/reset-password")]
  239:         public async Task<IActionResult> ResetPassword(Ia.Dn.Wa.Models.IdentityViewModels.ResetPasswordViewModel model)
  240:         {
  241:             if (!ModelState.IsValid)
  242:             {
  243:                 return View(model);
  244:             }
  245:  
  246:             var user = await userManager.FindByEmailAsync(model.Email);
  247:  
  248:             if (user == null)
  249:             {
  250:                 // Don't reveal that the user does not exist
  251:                 return RedirectToAction(nameof(IdentityController.ResetPasswordConfirmation), "Identity");
  252:             }
  253:  
  254:             var result = await userManager.ResetPasswordAsync(user, model.Code, model.Password);
  255:  
  256:             if (result.Succeeded)
  257:             {
  258:                 return RedirectToAction(nameof(IdentityController.ResetPasswordConfirmation), "Identity");
  259:             }
  260:  
  261:             AddErrors(result);
  262:  
  263:             return View();
  264:         }
  265:  
  266:         /////////////////////////////////////////////////////////////////////////////////
  267:  
  268:         /// <summary>
  269:         ///
  270:         /// </summary>
  271:         [HttpGet]
  272:         [AllowAnonymous]
  273:         [Route("identity/reset-password-confirmation")]
  274:         public IActionResult ResetPasswordConfirmation()
  275:         {
  276:             return View();
  277:         }
  278:  
  279:         /////////////////////////////////////////////////////////////////////////////////
  280:         /////////////////////////////////////////////////////////////////////////////////
  281:  
  282:         /// <summary>
  283:         ///
  284:         /// </summary>
  285:         [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  286:         public IActionResult Error()
  287:         {
  288:             return View(new Ia.Dn.Wa.Models.ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  289:         }
  290:  
  291:         /////////////////////////////////////////////////////////////////////////////////
  292:         /////////////////////////////////////////////////////////////////////////////////
  293:  
  294:         #region Helpers
  295:  
  296:         private void AddErrors(IdentityResult result)
  297:         {
  298:             foreach (var error in result.Errors)
  299:             {
  300:                 ModelState.AddModelError(string.Empty, error.Description);
  301:             }
  302:         }
  303:  
  304:         public enum ManageMessageId
  305:         {
  306:             AddPhoneSuccess,
  307:             AddLoginSuccess,
  308:             ChangePasswordSuccess,
  309:             SetTwoFactorSuccess,
  310:             SetPasswordSuccess,
  311:             RemoveLoginSuccess,
  312:             RemovePhoneSuccess,
  313:             Error
  314:         }
  315:  
  316:         private Task<Ia.Dn.Cl.Models.StaffIdentityUser> GetCurrentUserAsync()
  317:         {
  318:             return userManager.GetUserAsync(HttpContext.User);
  319:         }
  320:  
  321:         private IActionResult RedirectToLocal(string returnUrl)
  322:         {
  323:             if (Url.IsLocalUrl(returnUrl))
  324:             {
  325:                 return Redirect(returnUrl);
  326:             }
  327:             else
  328:             {
  329:                 return RedirectToAction(nameof(HomeController.Index), "Home");
  330:             }
  331:         }
  332:  
  333:         #endregion
  334:  
  335:         /////////////////////////////////////////////////////////////////////////////////
  336:         /////////////////////////////////////////////////////////////////////////////////
  337:     }
  338: }