inizio del login fatto
This commit is contained in:
207
SeniorAssistant/Controllers/AccountController.cs
Normal file
207
SeniorAssistant/Controllers/AccountController.cs
Normal file
@@ -0,0 +1,207 @@
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace IdentityDemo.Controllers
|
||||
{
|
||||
|
||||
[ApiExplorerSettings(IgnoreApi = true)]
|
||||
[Route("[controller]/[action]")]
|
||||
public class AccountController : Controller
|
||||
{
|
||||
/*
|
||||
private readonly UserManager<User> _userManager;
|
||||
private readonly SignInManager<User> _signInManager;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public AccountController(
|
||||
UserManager<User> userManager,
|
||||
SignInManager<User> signInManager,
|
||||
ILogger<AccountController> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
_logger = logger;
|
||||
}
|
||||
/*
|
||||
[TempData]
|
||||
public string ErrorMessage { get; set; }
|
||||
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> Login(string returnUrl = null)
|
||||
{
|
||||
// Clear the existing external cookie to ensure a clean login process
|
||||
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
|
||||
|
||||
ViewData["ReturnUrl"] = returnUrl;
|
||||
return View();
|
||||
}
|
||||
*/
|
||||
|
||||
[HttpPost]
|
||||
public ActionResult _login(string username, string password, bool rememberMe)
|
||||
{
|
||||
var result = username != null && password != null && username.Equals("acc1") && password.Equals("123"); //await _signInManager.PasswordSignInAsync(userName, password, rememberMe, lockoutOnFailure: false);
|
||||
JsonResponse response = new JsonResponse();
|
||||
response.Success = false;
|
||||
response.Message = "Username or password is invalid.";
|
||||
|
||||
if (result)
|
||||
{
|
||||
var loggedUser = HttpContext.Session.GetString("username");
|
||||
if (loggedUser==null || !loggedUser.Equals(username))
|
||||
{
|
||||
HttpContext.Session.SetString("username", username);
|
||||
response.Success = true;
|
||||
response.Message = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
response.Message = "User already logged";
|
||||
}
|
||||
}
|
||||
return Json(response);
|
||||
}
|
||||
|
||||
public ActionResult _logout()
|
||||
{
|
||||
HttpContext.Session.Clear();
|
||||
return Json(new JsonResponse());
|
||||
}
|
||||
|
||||
internal class JsonResponse
|
||||
{
|
||||
public bool Success { get; internal set; }
|
||||
public string Message { get; internal set; }
|
||||
}
|
||||
/*
|
||||
[HttpPost]
|
||||
[AllowAnonymous]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
|
||||
{
|
||||
ViewData["ReturnUrl"] = returnUrl;
|
||||
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(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
_logger.LogInformation("User logged in.");
|
||||
return RedirectToLocal(returnUrl);
|
||||
}
|
||||
if (result.IsLockedOut)
|
||||
{
|
||||
_logger.LogWarning("User account locked out.");
|
||||
return RedirectToAction(nameof(Lockout));
|
||||
}
|
||||
else
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
|
||||
return View(model);
|
||||
}
|
||||
}
|
||||
|
||||
// If we got this far, something failed, redisplay form
|
||||
return View(model);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Lockout()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Register(string returnUrl = null)
|
||||
{
|
||||
ViewData["ReturnUrl"] = returnUrl;
|
||||
return View();
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[AllowAnonymous]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
|
||||
{
|
||||
ViewData["ReturnUrl"] = returnUrl;
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
var user = new User { UserName = model.Email, Email = model.Email };
|
||||
var result = await _userManager.CreateAsync(user, model.Password);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
_logger.LogInformation("User created a new account with password.");
|
||||
return RedirectToLocal(returnUrl);
|
||||
}
|
||||
AddErrors(result);
|
||||
}
|
||||
|
||||
// If we got this far, something failed, redisplay form
|
||||
return View(model);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
await _signInManager.SignOutAsync();
|
||||
_logger.LogInformation("User logged out.");
|
||||
return RedirectToAction(nameof(HomeController.Index), "Home");
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> ConfirmEmail(string userId, string code)
|
||||
{
|
||||
if (userId == null || code == null)
|
||||
{
|
||||
return RedirectToAction(nameof(HomeController.Index), "Home");
|
||||
}
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
if (user == null)
|
||||
{
|
||||
throw new ApplicationException($"Unable to load user with ID '{userId}'.");
|
||||
}
|
||||
var result = await _userManager.ConfirmEmailAsync(user, code);
|
||||
return View(result.Succeeded ? "ConfirmEmail" : "Error");
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult AccessDenied()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
#region Helpers
|
||||
|
||||
private void AddErrors(IdentityResult result)
|
||||
{
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, error.Description);
|
||||
}
|
||||
}
|
||||
|
||||
private IActionResult RedirectToLocal(string returnUrl)
|
||||
{
|
||||
if (Url.IsLocalUrl(returnUrl))
|
||||
{
|
||||
return Redirect(returnUrl);
|
||||
}
|
||||
else
|
||||
{
|
||||
return RedirectToAction(nameof(HomeController.Index), "Home");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SeniorAssistant.Controllers
|
||||
{
|
||||
[ApiExplorerSettings(IgnoreApi = true)]
|
||||
public class HomeController : Controller
|
||||
{
|
||||
private readonly ISession session;
|
||||
public HomeController(IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
this.session = httpContextAccessor.HttpContext.Session;
|
||||
}
|
||||
|
||||
[Route("")]
|
||||
[Route("Home")]
|
||||
[Route("Index")]
|
||||
@@ -31,7 +38,7 @@ namespace SeniorAssistant.Controllers
|
||||
return View();
|
||||
}
|
||||
|
||||
[Route("{User}")]
|
||||
[Route("User/{User}")]
|
||||
public IActionResult SingleUser(string user)
|
||||
{
|
||||
return View("user", user);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using LinqToDB.Mapping;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace SeniorAssistant.Models
|
||||
{
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="linq2db" Version="2.3.0" />
|
||||
<PackageReference Include="linq2db" Version="2.5.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.App" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="2.1.0" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.0.1985401" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.4" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="3.0.0" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.1.1" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.6" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -13,6 +13,8 @@ using SeniorAssistant.Data;
|
||||
using SeniorAssistant.Models;
|
||||
using SeniorAssistant.Extensions;
|
||||
using Swashbuckle.AspNetCore.Swagger;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace SeniorAssistant
|
||||
{
|
||||
@@ -30,6 +32,7 @@ namespace SeniorAssistant
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc();
|
||||
services.AddSession();
|
||||
|
||||
services.AddSwaggerGen(c =>
|
||||
{
|
||||
@@ -51,6 +54,7 @@ namespace SeniorAssistant
|
||||
services.Configure<Kendo>(Configuration.GetSection("kendo"));
|
||||
services.Configure<Theme>(Configuration.GetSection("theme"));
|
||||
|
||||
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||||
services.AddSingleton<IEnumerable<IMenuItem>>(new IMenuItem[]
|
||||
{
|
||||
new SubMenu
|
||||
@@ -81,8 +85,10 @@ namespace SeniorAssistant
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseDatabaseErrorPage();
|
||||
}
|
||||
|
||||
|
||||
app.UseSession();
|
||||
app.UseStaticFiles();
|
||||
|
||||
// Enable middleware to serve generated Swagger as a JSON endpoint.
|
||||
|
||||
@@ -41,7 +41,8 @@
|
||||
editable: false,
|
||||
columns: [
|
||||
{ field: "username", title: "Username" },
|
||||
{ field: "name", title: "Name" } /*,
|
||||
{ field: "name", title: "Name" },
|
||||
{ field: "url", title: "",template:'<a href=/user/#=username#>Vedi Dati</a>'}/*,
|
||||
{ field: "time", title: "Date/Time", format: "{dd/MM/yyyy HH}" },
|
||||
{ field: "value", title: "Heartbeats" }
|
||||
*/
|
||||
|
||||
34
SeniorAssistant/Views/Shared/Login.cshtml
Normal file
34
SeniorAssistant/Views/Shared/Login.cshtml
Normal file
@@ -0,0 +1,34 @@
|
||||
<div class="">
|
||||
<input type="text" id="username" placeholder="username" />
|
||||
<input type="password" id="password" placeholder="password" />
|
||||
<button class="btn-default btn btn-flat" id="login-btn">Login</button>
|
||||
<p id="msg" class="login-box-msg"></p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
$("#login-btn").on("click", function () {
|
||||
var userName = $("#username").val();
|
||||
var password = $("#password").val();
|
||||
$.ajax({
|
||||
url: "/Account/_login",
|
||||
data: { UserName: userName, Password: password, RememberMe: false },
|
||||
dataType: "json",
|
||||
type: "POST",
|
||||
success: function (data) {
|
||||
console.log(data);
|
||||
var msg = $("#msg");
|
||||
if (data.success) {
|
||||
msg.hide();
|
||||
// app.navigate("");
|
||||
window.location.reload();
|
||||
} else {
|
||||
msg.html(data.message).show();
|
||||
$("#user-menu").addClass("open");
|
||||
}
|
||||
},
|
||||
error: function (xhr, status, error) {
|
||||
alert(xhr.responseText)
|
||||
}
|
||||
})
|
||||
});
|
||||
</script>
|
||||
19
SeniorAssistant/Views/Shared/Logout.cshtml
Normal file
19
SeniorAssistant/Views/Shared/Logout.cshtml
Normal file
@@ -0,0 +1,19 @@
|
||||
<div class="">
|
||||
<button class="btn-default btn btn-flat" id="logout-btn">Logout</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
$("#logout-btn").on("click", function () {
|
||||
$.ajax({
|
||||
url: "/Account/_logout",
|
||||
dataType: "json",
|
||||
type: "POST",
|
||||
success: function () {
|
||||
window.location.reload();
|
||||
},
|
||||
error: function (xhr, status, error) {
|
||||
alert(xhr.responseText)
|
||||
}
|
||||
})
|
||||
});
|
||||
</script>
|
||||
@@ -1,4 +1,10 @@
|
||||
<div class="navbar-custom-menu">
|
||||
@inject IHttpContextAccessor HttpContextAccessor
|
||||
|
||||
@{
|
||||
string session = HttpContextAccessor.HttpContext.Session.GetString("username");
|
||||
}
|
||||
|
||||
<div class="navbar-custom-menu">
|
||||
<ul class="nav navbar-nav">
|
||||
<!-- Messages: style can be found in dropdown.less-->
|
||||
<li class="dropdown messages-menu">
|
||||
@@ -99,16 +105,20 @@
|
||||
</ul>
|
||||
</li>
|
||||
<!-- User Account Menu -->
|
||||
<li class="dropdown user user-menu">
|
||||
<li id="user-menu" class="dropdown user user-menu">
|
||||
<!-- Menu Toggle Button -->
|
||||
|
||||
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
|
||||
<!-- The user image in the navbar-->
|
||||
<img src="~/AdminLTE-2.4.3/dist/img/user2-160x160.jpg" class="user-image" alt="User Image">
|
||||
<!-- hidden-xs hides the username on small devices so only the image appears. -->
|
||||
<span class="hidden-xs">Alexander Pierce</span>
|
||||
<span id="user-name" class="hidden-xs">@session</span>
|
||||
</a>
|
||||
<ul class="dropdown-menu">
|
||||
<!-- The user image in the menu -->
|
||||
<li class="user-body">
|
||||
@{ await Html.RenderPartialAsync(session == null?"Login":"Logout"); }
|
||||
</li>
|
||||
<li class="user-header">
|
||||
<img src="~/AdminLTE-2.4.3/dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
|
||||
<p>
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
@using SeniorAssistant.Models
|
||||
@using SeniorAssistant.Models
|
||||
@using Microsoft.AspNetCore.Mvc;
|
||||
@using Microsoft.AspNetCore.Http;
|
||||
Binary file not shown.
Reference in New Issue
Block a user