Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

UserController

namespace FastFoodWeb.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Roles = SD.ManagerUser)]
public class UserController : Controller
{
private readonly ApplicationDbContext _db;
public UserController(ApplicationDbContext db)
{
_db = db;
}
//INDEX - GET
public async Task<IActionResult> Index()
{
var claimsIdentity = (ClaimsIdentity)this.User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
//var user = (from usuarios in _db.ApplicationUser
// join role in _db.UserRoles
// on usuarios.Id equals role.UserId
// join rol in _db.Roles
// on role.RoleId equals rol.Id
// where (usuarios.Id != claim.Value)
// select new { usuarios, role, rol }).ToList();
//ViewBag.User = user;
//return View(ViewBag.User);
return View(await _db.ApplicationUser.Where(u =>
u.Id != claim.Value).ToListAsync());
}
public async Task<IActionResult> Lock(string id)
{
if (id == null)
{
return NotFound();
}
var applicationUser = await _db.ApplicationUser.Where(m => m.Id == id).FirstOrDefaultAsync();
applicationUser.LockoutEnd = DateTime.Now.AddYears(100);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> UnLock(string id)
{
if (id == null)
{
return NotFound();
}
var applicationUser = await _db.ApplicationUser.Where(m => m.Id == id).FirstOrDefaultAsync();
applicationUser.LockoutEnd = DateTime.Now;
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}

}
}
Index.cshtml

@model IEnumerable<ApplicationUser>
@{
ViewData["Title"] = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
<br />
<br />
<div class="border backgroundWhite">
<div class="row">
<div class="col-6">
<h2 class="text-info">Employee List</h2>
</div>
<div class="col-6 text-right">
<a asp-area="Identity" asp-page="/Account/Register" class="btn btn-info">
<i class="fas fa-plus"></i>&nbsp;New Employee Registration
</a>
</div>
</div>
<br />
<div>
@if (Model.Count() > 0)
{
<table class="table table-striped border">
<tr class="table-secondary">
<th>
@Html.DisplayNameFor(m => m.Name)
</th>
<th>
@Html.DisplayNameFor(m => m.Email)
</th>
<th>
@Html.DisplayNameFor(m => m.PhoneNumber)
</th>
<th></th>
<th></th>

</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(m => item.Name)
</td>
<td>
@Html.DisplayFor(m => item.Email)
</td>
<td>
@Html.DisplayFor(m => item.PhoneNumber)
</td>
<td>
@if (item.LockoutEnd == null || item.LockoutEnd < DateTime.Now)
{
<a class="btn btn-success text-white" asp-action="Lock" asp-route-id="@item.Id">
<i class="fas fa-lock-open"></i>
</a>
}
else
{
<a class="btn btn-danger text-white" asp-action="UnLock" asp-route-id="@item.Id">
<i class="fas fa-lock"></i>
</a>
}
</td>
@*<td>
<a class="btn btn-danger text-white" asp-action="Edit" asp-route-id="@item.Id">
<i class="fas fa-edit"></i>
</a>
</td>
<td>
<a class="btn btn-danger text-white" asp-action="Details" asp-route-id="@item.Id">
<i class="fas fa-list-alt"></i>
</a>
</td>
<td>
<a class="btn btn-danger text-white" asp-action="Delete" asp-route-id="@item.Id">
<i class="fas fa-trash-alt"></i>
</a>
</td>*@

</tr>
}
</table>
}
else
{
<h3 style="color:red;">No Employee Exists...</h3>
}
</div>
</div>
}

Actualizar la vista razor Login.cshtml

@page
@model LoginModel

@{
ViewData["Title"] = "Log in";
}

<h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-4">
<section>
<form id="account" method="post">
<h4>Use a local account to log in.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label asp-for="Input.RememberMe">
<input asp-for="Input.RememberMe" />
@Html.DisplayNameFor(m => m.Input.RememberMe)
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Log in</button>
</div>
<div class="form-group">
<p>
<a id="forgot-password" asp-page="./ForgotPassword">Forgot your password?</a>
</p>
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
<p>
<a id="resend-confirmation" asp-page="./ResendEmailConfirmation">Resend email confirmation</a>
</p>
</div>
</form>
</section>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
<h4>Use another service to log in.</h4>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
There are no external authentication services configured. See <a
href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
for details on setting up this ASP.NET application to support logging in via external services.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin"
asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name"
title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div>

@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

Actualizar la vista razor Login.cshtml.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using FastFoodWeb.Data;
using Microsoft.EntityFrameworkCore;
using FastFoodWeb.Models;
using Microsoft.AspNetCore.Http;

namespace FastFoodWeb.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LoginModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
private readonly ApplicationDbContext _db;

public LoginModel(SignInManager<IdentityUser> signInManager,


ILogger<LoginModel> logger,
ApplicationDbContext db,
UserManager<IdentityUser> userManager)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_db = db;
}

[BindProperty]
public InputModel Input { get; set; }

public IList<AuthenticationScheme> ExternalLogins { get; set; }


public string ReturnUrl { get; set; }

[TempData]
public string ErrorMessage { get; set; }

public class InputModel


{
[Required]
[EmailAddress]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

[Display(Name = "Remember me?")]


public bool RememberMe { get; set; }
}

public async Task OnGetAsync(string returnUrl = null)


{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}

returnUrl ??= Url.Content("~/");

// Clear the existing external cookie to ensure a clean login process


await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

ReturnUrl = returnUrl;
}

public async Task<IActionResult> OnPostAsync(string returnUrl = null)


{
returnUrl ??= Url.Content("~/");

ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result =
await _signInManager.PasswordSignInAsync(Input.Email, Input.Password,
Input.RememberMe, lockoutOnFailure: false);

if (result.Succeeded)
{
var user = await _db.Users.Where(u => u.Email == Input.Email).FirstOrDefaultAsync();
List<ShoppingCart> lstShoppingCart = await _db.ShoppingCart.Where(u =>
u.ApplicationUserId == user.Id).ToListAsync();
HttpContext.Session.SetInt32("ssCartCount", lstShoppingCart.Count);

_logger.LogInformation("User logged in.");


return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}

// If we got this far, something failed, redisplay form


return Page();
}
}
}

Actualizar la vista razor Logout.cshtml

@page
@model LogoutModel
@{
ViewData["Title"] = "Log out";
}

<header>
<h1>@ViewData["Title"]</h1>
@{
if (User.Identity.IsAuthenticated)
{
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-
returnUrl="@Url.Page("/", new { area = "" })" method="post">
<button type="submit" class="nav-link btn btn-link text-dark">Click here to Logout</button>
</form>
}
else
{
<p>You have successfully logged out of the application.</p>
}
}
</header>

Actualizar la vista razor Login.cshtml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace FastFoodWeb.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LogoutModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LogoutModel> _logger;

public LogoutModel(SignInManager<IdentityUser> signInManager, ILogger<LogoutModel> logger)


{
_signInManager = signInManager;
_logger = logger;
}

public void OnGet()


{
}

public async Task<IActionResult> OnPost(string returnUrl = null)


{
await _signInManager.SignOutAsync();
HttpContext.Session.SetInt32("ssCartCount", 0);
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
return RedirectToPage();
}
}
}
}

Agregar la variable siguiente a SD.


public const string ssShoppingCartCount = "ssCartCount";

You might also like