using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using authorize.Models;
using Microsoft.EntityFrameworkCore;
namespace authorize.Controllers
{
public class AuthorizeController : Controller
{
private AuthorizeContext DB;
//private List<UserPassword> user_password_list;
public AuthorizeController(AuthorizeContext context)
{
DB = context;
}
// GET: Authorize
public async Task<IActionResult> Index()
{
await get_log_info();
return View(await DB.UserPassword.ToListAsync());
}
[HttpPost]
public async Task<IActionResult> Index(IFormCollection collection)
{
var login_id = Convert.ToInt32(collection["Id"]);
var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);
//if computer is registered, update login, otherwise register computer and login
if (existing_login_record != null)
{
existing_login_record.LoginId = login_id;
}
else
{
DB.Login.Add(new Login { Computer = machine, LoginId = login_id });
}
await DB.SaveChangesAsync();
return Content("successful");
}
public async Task<IActionResult> Login_out()
{
var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);
//clear login id
if (existing_login_record.LoginId != null)
{
existing_login_record.LoginId = null;
await DB.SaveChangesAsync();
}
return RedirectToAction("Index");
}
public async Task<JsonResult> webpage_open()
{
var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);
//open new webform count +1, else count =1
if (existing_login_record.OpenWindow != null)
{
existing_login_record.OpenWindow++;
}
else
{
existing_login_record.OpenWindow = 1;
}
await DB.SaveChangesAsync();
return Json(existing_login_record.OpenWindow);
}
public async Task<JsonResult> webpage_close()
{
var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);
//close webform count -1
existing_login_record.OpenWindow--;
await DB.SaveChangesAsync();
return Json(existing_login_record.OpenWindow);
}
public async Task<IActionResult> another_view()
{
await get_log_info();
return View();
}
public async Task get_log_info()
{
var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
ViewBag.computer_viewbag = machine;
var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);
//if is logged in, add user name to viewbag, otherwise add "log in" to viewbag
if (existing_login_record != null && existing_login_record.LoginId != null)
{
var user = await DB.UserPassword.FirstOrDefaultAsync(x => x.Id == existing_login_record.LoginId);
ViewBag.login_record_viewbag = user.Name;
}
else
{
ViewBag.login_record_viewbag = "log in";
}
}
}
}
----------------------------------------------------------------
//index.cshtml
@model IEnumerable<authorize.Models.UserPassword>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
var user_password_list = [];
var open_webpages = 0;
//webpage open event
$(document).ready(function () {
$.ajax({
url: '/Authorize/webpage_open',
type: "GET",
data: { },
success: function (result) {
open_webpages = result;
$('#log_lable').append(' open webpages = ' + open_webpages);
},
error: function () {
alert("Error");
}
});
//change navbar label log status text
var login_record = '@ViewBag.login_record_viewbag';
if (login_record == "log in") {
$('#log_navbar').text('log in');
}
else {
$('#log_navbar').text('log out ' + '@ViewBag.login_record_viewbag');
$('#log_lable').text('@ViewBag.login_record_viewbag' + ' logged in ' + '@ViewBag.computer_viewbag');
}
@foreach (var item in Model)
{
<text>
user_password_list.push(new user_password_class('@item.Id', '@item.Name', '@item.Password'));
</text>
}
});
//webpage close event
window.onbeforeunload = function () {
$.ajax({
type: "POST",
url: '/Authorize/webpage_close',
data: { },
success: function (result) {
//alert("success");
//all open webpages close
if (result == 0) {
//if (confirm("log out?")) {
//log out
$.post('/Authorize/Login_out', {});
}
},
error: function (xhr) {
alert("Error close web page");
}
});
}
function user_password_class(id, name, password) {
this.id = id;
this.name = name;
this.password = password;
}
function submit_onclick() {
var user_password_correct = false;
$.each(user_password_list, function (index, value) {
var name = value.name.replace(/\s/g, '');
var password = value.password.replace(/\s/g, '');
if (name == $('#ux_user').val() && password == $('#ux_password').val()) {
$('#log_navbar').text('log out ' + name);
$.ajax({
type: "POST",
url: '/Authorize/Index',
data: { Id: value.id },
success: function (result) {
//alert("success");
window.location.replace("/Authorize/another_view");
},
error: function (xhr) {
alert("Error button confirm Assign view");
}
});
user_password_correct = true;
return;
}
});
if (!user_password_correct) {
alert("user name & password not correct");
}
}
</script>
<div class="text-right">
<label id="log_lable"></label>
</div>
<h2>Enter User name, Password</h2>
<div class="row">
<div class="col-md-4">
<h4>user name</h4>
<input id="ux_user" type="text" class="form-control" />
</div>
<div class="col-md-4">
<h4>password</h4>
<input id="ux_password" type="text" class="form-control" />
</div>
<div class="col-md-4">
<h4>submit</h4>
<input type="button" value="Log in" class="form-control" onclick="submit_onclick()" />
</div>
</div>
<br />
<div>
<a href="/Authorize/another_view">another view</a>
</div>
-------------------------------------------------------------------------
//another_view.cshtml
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
var open_webpages = 0;
//webpage open event
$(document).ready(function () {
$.ajax({
url: '/Authorize/webpage_open',
type: "GET",
data: {},
success: function (result) {
open_webpages = result;
$('#log_lable').append(' open webpages = ' + open_webpages);
},
error: function () {
alert("Error");
}
});
var login_record = '@ViewBag.login_record_viewbag';
if (login_record == "log in") {
$('#log_navbar').text('log in');
}
else {
$('#log_navbar').text('log out ' + '@ViewBag.login_record_viewbag');
$('#log_lable').text('@ViewBag.login_record_viewbag' + ' logged in ' + '@ViewBag.computer_viewbag');
}
});
//webpage close event
window.onbeforeunload = function () {
$.ajax({
type: "POST",
url: '/Authorize/webpage_close',
data: {},
success: function (result) {
//alert("success");
//all open webpages close
if (result == 0) {
//if (confirm("log out?")) {
//log out
$.post('/Authorize/Login_out', {});
}
},
error: function (xhr) {
alert("Error close web page");
}
});
}
</script>
<h2>another view</h2>
<p>You are authorized to view this page</p>
<div class="text-right">
<label id="log_lable"></label>
</div>
-------------------------------------------------------------
//_logout.cshtml
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">authorize</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a id="log_navbar" href="/Authorize/Login_out">login</a>
</li>
</ul>
@*@await Html.PartialAsync("_LoginPartial")*@
----------------------------------------------------------------
//AuthorizeContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace authorize.Models
{
public partial class AuthorizeContext : DbContext
{
public virtual DbSet<Login> Login { get; set; }
public virtual DbSet<UserPassword> UserPassword { get; set; }
public AuthorizeContext(DbContextOptions<AuthorizeContext> options) : base(options){ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Login>(entity =>
{
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Computer)
.HasColumnName("computer")
.HasColumnType("nchar(50)");
entity.Property(e => e.LoginId).HasColumnName("login_id");
entity.Property(e => e.OpenWindow).HasColumnName("open_window");
entity.HasOne(d => d.LoginNavigation)
.WithMany(p => p.Login)
.HasForeignKey(d => d.LoginId)
.HasConstraintName("FK_Login_UserPassword");
});
modelBuilder.Entity<UserPassword>(entity =>
{
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Name)
.HasColumnName("name")
.HasColumnType("nchar(20)");
entity.Property(e => e.Password)
.HasColumnName("password")
.HasColumnType("nchar(20)");
});
}
}
}
---------------------------------------------------------
//userpassword.cs
using System;
using System.Collections.Generic;
namespace authorize.Models
{
public partial class UserPassword
{
public UserPassword()
{
Login = new HashSet<Login>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public virtual ICollection<Login> Login { get; set; }
}
}
------------------------------------------------------
//login.cs
using System;
using System.Collections.Generic;
namespace authorize.Models
{
public partial class Login
{
public int Id { get; set; }
public string Computer { get; set; }
public int? LoginId { get; set; }
public int? OpenWindow { get; set; }
public virtual UserPassword LoginNavigation { get; set; }
}
}
------------------------------------------------
reference:
http://stackoverflow.com/questions/3960701/javascript-to-remove-spaces-from-a-textbox-value
http://stackoverflow.com/questions/1816740/how-can-i-call-a-controller-action-directly-from-a-javascript-function
http://chuanshuoge1.blogspot.ca/search?q=.asp+final
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d4a58414-cc38-43ba-b7ef-1578767a823d/how-to-get-the-computer-name-using-c?forum=csharpgeneral
http://stackoverflow.com/questions/10389649/possible-to-access-mvc-viewbag-object-from-javascript-file
http://windowsitpro.com/powershell/files-powershell-cmdlets
Entity framework async
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/update-related-data
javascript async
https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript?gclid=CjwKEAjwtbPGBRDhoLaqn6HknWsSJABR-o5sv97LSSc7fgPD6C1qmnKX8Du83JUxGNXYXN68U5WJIBoCti3w_wcB
client side webpage onclose event
http://stackoverflow.com/questions/21227383/how-to-detect-browser-window-tab-close-event
No comments:
Post a Comment