using Bootstrap.Admin.Models;
using Bootstrap.DataAccess;
using Longbow.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Bootstrap.Admin.Controllers
{
///
/// Account controller.
///
[AllowAnonymous]
[AutoValidateAntiforgeryToken]
public class AccountController : Controller
{
///
///
///
///
[HttpGet]
public ActionResult Login()
{
return User.Identity.IsAuthenticated ? (ActionResult)Redirect("~/Home/Index") : View("Login", new ModelBase());
}
///
/// Login the specified userName, password and remember.
///
/// The login.
///
/// User name.
/// Password.
/// Remember.
[HttpPost]
public async Task Login([FromServices]IOnlineUsers onlineUserSvr, string userName, string password, string remember)
{
if (UserHelper.Authenticate(userName, password, loginUser => CreateLoginUser(onlineUserSvr, HttpContext, loginUser)))
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, userName));
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { ExpiresUtc = DateTimeOffset.Now.AddDays(DictHelper.RetrieveCookieExpiresPeriod()), IsPersistent = remember == "true" });
// redirect origin url
var originUrl = Request.Query[CookieAuthenticationDefaults.ReturnUrlParameter].FirstOrDefault() ?? "~/Home/Index";
return Redirect(originUrl);
}
return View("Login", new ModelBase());
}
///
///
///
///
///
///
internal static void CreateLoginUser(IOnlineUsers onlineUserSvr, HttpContext context, LoginUser loginUser)
{
var agent = new UserAgent(context.Request.Headers["User-Agent"]);
loginUser.Ip = (context.Connection.RemoteIpAddress ?? IPAddress.IPv6Loopback).ToString();
loginUser.City = onlineUserSvr.RetrieveLocaleByIp(loginUser.Ip);
loginUser.Browser = $"{agent.Browser.Name} {agent.Browser.Version}";
loginUser.OS = $"{agent.OS.Name} {agent.OS.Version}";
}
///
/// Logout this instance.
///
/// The logout.
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("~" + CookieAuthenticationDefaults.LoginPath);
}
///
/// Accesses the denied.
///
/// The denied.
[ResponseCache(Duration = 600)]
public ActionResult AccessDenied() => View("Error", ErrorModel.CreateById(403));
}
}