From 663b695da491a569f0d98993088ad0330e846b87 Mon Sep 17 00:00:00 2001 From: Giacomo Bertolazzi <20015159@studenti.uniupo.it> Date: Tue, 18 Dec 2018 18:03:05 +0100 Subject: [PATCH] Fixed login & auth --- .../Controllers/AccountController.cs | 72 +++---- SeniorAssistant/Controllers/HomeController.cs | 33 ++-- .../Controllers/Services/BaseController.cs | 10 +- SeniorAssistant/Models/Register.cs | 15 -- SeniorAssistant/Models/User.cs | 3 +- SeniorAssistant/Startup.cs | 54 ++++-- SeniorAssistant/Views/Home/Data.cshtml | 180 ++++++++++-------- SeniorAssistant/Views/Home/Index.cshtml | 12 +- SeniorAssistant/Views/Shared/Login.cshtml | 14 +- SeniorAssistant/Views/Shared/Profile.cshtml | 3 +- SeniorAssistant/Views/Shared/Register.cshtml | 32 ++-- .../Views/Shared/SidebarMenu.cshtml | 15 +- SeniorAssistant/Views/Shared/_Layout.cshtml | 2 +- SeniorAssistant/senior.db | Bin 86016 -> 118784 bytes 14 files changed, 235 insertions(+), 210 deletions(-) delete mode 100644 SeniorAssistant/Models/Register.cs diff --git a/SeniorAssistant/Controllers/AccountController.cs b/SeniorAssistant/Controllers/AccountController.cs index 34366d7..f7ebed2 100644 --- a/SeniorAssistant/Controllers/AccountController.cs +++ b/SeniorAssistant/Controllers/AccountController.cs @@ -4,44 +4,14 @@ using SeniorAssistant.Models; using SeniorAssistant.Controllers; using LinqToDB; using System.Linq; +using System.Collections.Generic; namespace IdentityDemo.Controllers { - [ApiExplorerSettings(IgnoreApi = true)] [Route("[controller]/[action]")] public class AccountController : BaseController { - /* - private readonly UserManager _userManager; - private readonly SignInManager _signInManager; - private readonly ILogger _logger; - - public AccountController( - UserManager userManager, - SignInManager signInManager, - ILogger logger) - { - _userManager = userManager; - _signInManager = signInManager; - _logger = logger; - } - /* - [TempData] - public string ErrorMessage { get; set; } - - [HttpGet] - [AllowAnonymous] - public async Task 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) { @@ -51,20 +21,22 @@ namespace IdentityDemo.Controllers Message = "Username or password is invalid." }; - var strunz = Db.GetTable().Where(user => user.Username.Equals(username) && user.Password.Equals(password)).ToListAsync().Result; + var result = Db.GetTable().Where(user => user.Username.Equals(username) && user.Password.Equals(password)).ToListAsync().Result; - if (strunz.Count == 1) + if (result.Count == 1) { - var loggedUser = HttpContext.Session.GetString("username"); + var loggedUser = HttpContext.Session.GetString(Username); if (loggedUser==null || !loggedUser.Equals(username)) { - HttpContext.Session.SetString("username", username); - HttpContext.Session.SetString("email", strunz.First().Email); - HttpContext.Session.SetString("name", strunz.First().Name); - HttpContext.Session.SetString("isdoc", strunz.First().Doctor?"true":"false"); - //HttpContext.Session.SetString("lastname", strunz.First().LastName); + User user = result.First(); + HttpContext.Session.SetString(Username, username); + HttpContext.Session.SetString("email", user.Email); + HttpContext.Session.SetString("name", user.Name); + HttpContext.Session.SetString("role", user.Role); + //HttpContext.Session.SetString("lastname", user.LastName); + response.Success = true; - response.Message = ""; + response.Message = Request.Query["ReturnUrl"]; } else { @@ -82,24 +54,32 @@ namespace IdentityDemo.Controllers } [HttpPost] - public ActionResult _register(Register register) + public ActionResult _register(User user) { + JsonResponse response = new JsonResponse() { Success = true }; + if(ModelState.IsValid) { - User user = new User() { Username = register.Username, Email = register.Email, Password = register.Password}; try { Db.Insert(user); + _login(user.Username, user.Password); } catch { - return Json(new JsonResponse() { Success = false, Message = "Username already exist" }); + response.Success = false; + response.Message = "Username already exists"; } - _login(user.Username, user.Password); - return Json(new JsonResponse() { Success = true }); } - return Json(new JsonResponse() { Success = false, Message = "Modello non valido" }); + else + { + response.Success = false; + response.Message = "Modello non valido"; + } + + return Json(response); } + internal class JsonResponse { public bool Success { get; internal set; } diff --git a/SeniorAssistant/Controllers/HomeController.cs b/SeniorAssistant/Controllers/HomeController.cs index 10faf56..f83ab7a 100644 --- a/SeniorAssistant/Controllers/HomeController.cs +++ b/SeniorAssistant/Controllers/HomeController.cs @@ -1,17 +1,12 @@ -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace SeniorAssistant.Controllers { [ApiExplorerSettings(IgnoreApi = true)] - public class HomeController : Controller + public class HomeController : BaseController { - private readonly ISession session; - public HomeController(IHttpContextAccessor httpContextAccessor) - { - this.session = httpContextAccessor.HttpContext.Session; - } - [Route("")] [Route("Home")] [Route("Index")] @@ -23,33 +18,41 @@ namespace SeniorAssistant.Controllers [Route("Heartbeat")] public IActionResult Heartbeat() { - return View(); + return CheckAuthorized("Heartbeat"); } [Route("Sleep")] public IActionResult Sleep() { - return View(); + return CheckAuthorized("Sleep"); } [Route("Step")] public IActionResult Step() { - return View(); + return CheckAuthorized("Step"); } [Route("Users")] public IActionResult Users() { - return View(); + return CheckAuthorized("Users"); } [Route("User/{User}")] public IActionResult SingleUser(string user) { - if(session.GetString("username") == null) - return RedirectToAction("Index"); - return View("data", user); + return CheckAuthorized("Data", user); + } + + private IActionResult CheckAuthorized(string view, object model = null) + { + if (HttpContext.Session.GetString("username") == null) + { + model = "/" + view; + view = "Index"; + } + return View(view, model); } } } \ No newline at end of file diff --git a/SeniorAssistant/Controllers/Services/BaseController.cs b/SeniorAssistant/Controllers/Services/BaseController.cs index 71be656..18bb5e4 100644 --- a/SeniorAssistant/Controllers/Services/BaseController.cs +++ b/SeniorAssistant/Controllers/Services/BaseController.cs @@ -1,10 +1,13 @@ -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using SeniorAssistant.Data; namespace SeniorAssistant.Controllers { public abstract class BaseController : Controller { + protected static readonly string Username = "username"; + IDataContextFactory dbFactory; SeniorDataContext db; @@ -20,5 +23,10 @@ namespace SeniorAssistant.Controllers base.Dispose(disposing); } + + protected bool IsLogged() + { + return HttpContext.Session.GetString(Username) != null; + } } } diff --git a/SeniorAssistant/Models/Register.cs b/SeniorAssistant/Models/Register.cs deleted file mode 100644 index 40bdbcf..0000000 --- a/SeniorAssistant/Models/Register.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace SeniorAssistant.Models -{ - public class Register - { - public string Username { get; set; } - public string Email { get; set; } - public string Password { get; set; } - public bool Doctor { get; set; } - } -} diff --git a/SeniorAssistant/Models/User.cs b/SeniorAssistant/Models/User.cs index 4f12d0b..911c80d 100644 --- a/SeniorAssistant/Models/User.cs +++ b/SeniorAssistant/Models/User.cs @@ -17,11 +17,10 @@ namespace SeniorAssistant.Models public string Password { get; set; } [NotNull] - public bool Doctor { get; set; } + public string Role { get; set; } public string Name { get; set; } public string LastName { get; set; } - } } diff --git a/SeniorAssistant/Startup.cs b/SeniorAssistant/Startup.cs index b2e605a..892d040 100644 --- a/SeniorAssistant/Startup.cs +++ b/SeniorAssistant/Startup.cs @@ -5,6 +5,7 @@ using LinqToDB.DataProvider.SQLite; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authorization; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -15,6 +16,10 @@ using SeniorAssistant.Extensions; using Swashbuckle.AspNetCore.Swagger; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.AspNetCore.Mvc; namespace SeniorAssistant { @@ -31,7 +36,15 @@ namespace SeniorAssistant // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { - services.AddMvc(); + services.AddMvc();// config => +// { +// var policy = new AuthorizationPolicyBuilder() +// .RequireAuthenticatedUser() +// .Build(); +// config.Filters.Add(new AuthorizeFilter(policy)); +// }) +// .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); + services.AddSession(); services.AddSwaggerGen(c => @@ -54,20 +67,30 @@ namespace SeniorAssistant services.Configure(Configuration.GetSection("kendo")); services.Configure(Configuration.GetSection("theme")); +// services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) +// .AddCookie(options => { +// options.LoginPath = "/"; +// options.AccessDeniedPath = "/"; +// }); + +// services.AddDefaultIdentity().AddRoles() +// .AddEntityFrameworkStores(); + services.TryAddSingleton(); - services.AddSingleton>(new IMenuItem[] + services.AddSingleton>(new List { - new SubMenu + new MenuItem("Index", "/"), + new SubMenu() { - Text = "Link veloci", + Text = "Raw Data", Items = new MenuItem[] { - new MenuItem("User", "/"), + new MenuItem("Users", "/users"), new MenuItem("Heartbeat", "/heartbeat"), new MenuItem("Sleep", "/sleep"), new MenuItem("Step", "/step") } - }, + } }); var dbFactory = new SeniorDataContextFactory( @@ -90,6 +113,7 @@ namespace SeniorAssistant app.UseSession(); app.UseStaticFiles(); +// app.UseAuthentication(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); @@ -126,19 +150,15 @@ namespace SeniorAssistant db.CreateTableIfNotExists(); db.CreateTableIfNotExists(); db.CreateTableIfNotExists(); - try + db.CreateTableIfNotExists(); + + int count = 0; + foreach (string user in names) { - db.CreateTable(); - int count = 0; - foreach (string user in names) - { - var username = baseUsername + count; - db.InsertOrReplace(new User { Name = user, Username = username, Password = username, Email = username + "@email.st" } ); - count++; - } + var username = baseUsername + count; + db.InsertOrReplace(new User { Role = "user", Name = user, Username = username, Password = username, Email = username + "@email.st" } ); + count++; } - catch - { } Random rnd = new Random(); DateTime now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); diff --git a/SeniorAssistant/Views/Home/Data.cshtml b/SeniorAssistant/Views/Home/Data.cshtml index c72a804..e4839cb 100644 --- a/SeniorAssistant/Views/Home/Data.cshtml +++ b/SeniorAssistant/Views/Home/Data.cshtml @@ -1,93 +1,107 @@ -@model string +@inject IHttpContextAccessor HttpContextAccessor +@model string + @{ ViewBag.Title = "Hello Razor"; + var session = HttpContextAccessor.HttpContext.Session; + + // Questa variabile serve a sapere se si e' autorizzati o meno. + // Per ora e' semplice ma magari si puo' peggiorare utilizzando il ruolo di Doc... etc + // (Utilizzare inject DbContext) + bool auth = session.GetString("username").Equals(Model); } -
+@if (!auth) +{ +

Non sei autorizzato a vedere i dati di @Model

+} +else +{ + // Aggiungere un qualcosa per scegliere le ore da vedere (Max 48?) +
+ \ No newline at end of file + }); + +} \ No newline at end of file diff --git a/SeniorAssistant/Views/Home/Index.cshtml b/SeniorAssistant/Views/Home/Index.cshtml index 76f15dd..575a7f8 100644 --- a/SeniorAssistant/Views/Home/Index.cshtml +++ b/SeniorAssistant/Views/Home/Index.cshtml @@ -5,23 +5,29 @@ logo sito disattivare l-aside e le opzioni se non loggato deve tornare qua --> +@model string @inject IHttpContextAccessor HttpContextAccessor @{ + ViewBag.Title = "Hello Razor"; string session = HttpContextAccessor.HttpContext.Session.GetString("username"); }
@if (session == null) { + @if (Model != null) + { +

Per poter accedere alla pagina [@Model] e' necessario essere loggati

+ } + - + } else { diff --git a/SeniorAssistant/Views/Shared/Login.cshtml b/SeniorAssistant/Views/Shared/Login.cshtml index bc96ed3..ec8c4d0 100644 --- a/SeniorAssistant/Views/Shared/Login.cshtml +++ b/SeniorAssistant/Views/Shared/Login.cshtml @@ -1,13 +1,9 @@ - - - - -
    +
    • - +
    • @@ -23,19 +19,17 @@ 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"); } + return false; }, error: function (xhr, status, error) { - alert(xhr.responseText) + alert(xhr.status+" "+xhr.responseText) } }) }); diff --git a/SeniorAssistant/Views/Shared/Profile.cshtml b/SeniorAssistant/Views/Shared/Profile.cshtml index 187bcc8..e3efdb8 100644 --- a/SeniorAssistant/Views/Shared/Profile.cshtml +++ b/SeniorAssistant/Views/Shared/Profile.cshtml @@ -1,5 +1,4 @@ -@model User -@inject IHttpContextAccessor HttpContextAccessor +@inject IHttpContextAccessor HttpContextAccessor @{ var session = HttpContextAccessor.HttpContext.Session; diff --git a/SeniorAssistant/Views/Shared/Register.cshtml b/SeniorAssistant/Views/Shared/Register.cshtml index 9cbe317..bbe41f9 100644 --- a/SeniorAssistant/Views/Shared/Register.cshtml +++ b/SeniorAssistant/Views/Shared/Register.cshtml @@ -1,8 +1,10 @@ 
      • - - - + + + + +
        @@ -13,20 +15,26 @@