Skip to content

Commit

Permalink
#2 and #22 removed registration page and added geolocation package an…
Browse files Browse the repository at this point in the history
…d web api for logistic regression analysis
  • Loading branch information
dmnisson committed Nov 12, 2018
1 parent 955730b commit 731bcf5
Show file tree
Hide file tree
Showing 14 changed files with 348 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace DriverTracker.Areas.Identity.Data
namespace DriverTracker.Data
{
public class DriverTrackerIdentityDbContext : IdentityDbContext<IdentityUser>
{
Expand Down
21 changes: 19 additions & 2 deletions DriverTracker/Areas/Identity/IdentityHostingStartup.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System;
using DriverTracker.Areas.Identity.Data;
using DriverTracker.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity.UI.Services;

[assembly: HostingStartup(typeof(DriverTracker.Areas.Identity.IdentityHostingStartup))]
namespace DriverTracker.Areas.Identity
Expand All @@ -20,7 +22,22 @@ public void Configure(IWebHostBuilder builder)

services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<DriverTrackerIdentityDbContext>()
.AddDefaultUI().AddDefaultTokenProviders();
.AddDefaultTokenProviders();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Logout");
});

services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
});
}

Expand Down
102 changes: 102 additions & 0 deletions DriverTracker/Areas/Identity/Pages/Account/Login.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using System;
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;

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

public LoginModel(SignInManager<IdentityUser> signInManager, ILogger<LoginModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}

[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 = 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 = returnUrl ?? Url.Content("~/");

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: true);
if (result.Succeeded)
{
_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();
}
}
}
43 changes: 43 additions & 0 deletions DriverTracker/Areas/Identity/Pages/Account/Logout.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace DriverTracker.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();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
return Page();
}
}
}
}
81 changes: 81 additions & 0 deletions DriverTracker/Controllers/AnalysisApiController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Accord.Statistics.Models.Regression;

using DriverTracker.Models;
using DriverTracker.Domain;

namespace DriverTracker.Controllers
{
[Authorize(Roles = "Admin,Analyst")]
[Route("api/[controller]")]
public class AnalysisApiController : Controller
{
private readonly MvcDriverContext _context;
private readonly DriverStatistics _driverStatistics;

public AnalysisApiController(MvcDriverContext context) {
_context = context;
_driverStatistics = new DriverStatistics(context);
}

// GET: api/analysisapi
[HttpGet]
public IEnumerable<DriverStatisticResults> Get()
{
List<DriverStatisticResults> driverStatisticResults = new List<DriverStatisticResults>();

IEnumerable<Driver> drivers = _context.Drivers.AsEnumerable();


foreach (Driver driver in drivers) {
_driverStatistics.ComputeDriverStatistics(driver.DriverID);
driverStatisticResults.Add(_driverStatistics.GetDriverStatisticResults(driver.DriverID));
}

return driverStatisticResults;
}

// GET api/analysisapi/5
[HttpGet("{id}")]
public DriverStatisticResults Get(int id)
{
_driverStatistics.ComputeDriverStatistics(id);
return _driverStatistics.GetDriverStatisticResults(id);
}

// GET api/analysisapi/logistic/5
[HttpGet("logistic/{id}")]
public LogisticFarePredictionResult GetLogistic(int id)
{
FarePrediction farePrediction = new FarePrediction(_context, id);
DateTime fromDateTime = DateTime.Now.AddMonths(-12);
DateTime toDateTime = DateTime.Now;
farePrediction.LearnFromDates(fromDateTime, toDateTime);

LogisticFarePredictionResult result = new LogisticFarePredictionResult();
result.DriverID = id;
result.FromDateTime = fromDateTime;
result.ToDateTime = toDateTime;
result.RegressionResult = farePrediction.GetRegressionModel();

return result;
}

// GET api/analysisapi/multipickupprob/5/6/12/13.7/
[HttpGet("multipickupprob/{id}/{delay}/{duration}/{fare}/")]
public double[] GetMultiPickupProb(int id, double delay, double duration, double fare) {
FarePrediction farePrediction = new FarePrediction(_context, id);
DateTime fromDateTime = DateTime.Now.AddMonths(-12);
DateTime toDateTime = DateTime.Now;
farePrediction.LearnFromDates(fromDateTime, toDateTime);

LogisticRegression regression = farePrediction.GetRegressionModel();
return regression?.Probabilities(new double[] { delay, duration, fare });
}
}
}
2 changes: 1 addition & 1 deletion DriverTracker/Controllers/DriversApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace DriverTracker.Controllers
{
[Authorize]
[Authorize(Roles = "Admin, Analyst, Driver")]
[Route("api/[controller]")]
public class DriversApiController : ControllerBase
{
Expand Down
12 changes: 6 additions & 6 deletions DriverTracker/Controllers/DriversController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public DriversController(MvcDriverContext context)
}

// GET: Drivers
[Authorize]
[Authorize(Roles = "Admin,Driver")]
public async Task<IActionResult> Index()
{
_driverStatisticsService.ComputeCompanyStatistics();
Expand Down Expand Up @@ -61,7 +61,7 @@ public async Task<IActionResult> Index()
}

// GET: Drivers/Details/5
[Authorize]
[Authorize(Roles = "Admin,Driver")]
public async Task<IActionResult> Details(int? id)
{
_driverStatisticsService.ComputeDriverStatistics(id.Value);
Expand Down Expand Up @@ -104,7 +104,7 @@ public async Task<IActionResult> Details(int? id)
}

// GET: Drivers/Create
[Authorize]
[Authorize(Roles = "Admin,Driver")]
public IActionResult Create()
{
return View();
Expand All @@ -113,7 +113,7 @@ public IActionResult Create()
// POST: Drivers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[Authorize]
[Authorize(Roles = "Admin,Driver")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("DriverID,UserID,Name,LicenseNumber")] Driver driver)
Expand All @@ -128,7 +128,7 @@ public async Task<IActionResult> Create([Bind("DriverID,UserID,Name,LicenseNumbe
}

// GET: Drivers/Edit/5
[Authorize]
[Authorize(Roles = "Admin,Driver")]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
Expand All @@ -149,7 +149,7 @@ public async Task<IActionResult> Edit(int? id)
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
[Authorize(Roles = "Admin,Driver")]
public async Task<IActionResult> Edit(int id, [Bind("DriverID,UserID,Name,LicenseNumber")] Driver driver)
{
if (id != driver.DriverID)
Expand Down
5 changes: 5 additions & 0 deletions DriverTracker/Domain/DriverStatistics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,5 +139,10 @@ public decimal NetProfit {
return netProfit;
}
}

public DriverStatisticResults GetDriverStatisticResults(int id)
{
return driverStats[id];
}
}
}
Loading

0 comments on commit 731bcf5

Please sign in to comment.