BootstrapAdmin/Bootstrap.Admin/Controllers/AccountController.cs

76 lines
2.9 KiB
C#
Raw Normal View History

2018-06-07 00:45:47 +08:00
using Bootstrap.Admin.Models;
2018-10-19 23:09:52 +08:00
using Bootstrap.DataAccess;
using Longbow;
using Longbow.Configuration;
2018-06-07 00:45:47 +08:00
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
2018-06-07 00:45:47 +08:00
using System.Security.Claims;
using System.Threading.Tasks;
namespace Bootstrap.Admin.Controllers
{
/// <summary>
/// Account controller.
/// </summary>
[AllowAnonymous]
[AutoValidateAntiforgeryToken]
2018-06-07 00:45:47 +08:00
public class AccountController : Controller
{
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Login()
{
return User.Identity.IsAuthenticated ? (ActionResult)Redirect("~/Home/Index") : View("Login", new ModelBase());
}
2018-06-07 00:45:47 +08:00
/// <summary>
/// Login the specified userName, password and remember.
/// </summary>
/// <returns>The login.</returns>
/// <param name="userName">User name.</param>
/// <param name="password">Password.</param>
/// <param name="remember">Remember.</param>
[HttpPost]
2018-06-07 00:45:47 +08:00
public async Task<IActionResult> Login(string userName, string password, string remember)
{
2018-10-19 23:09:52 +08:00
if (UserHelper.Authenticate(userName, password))
2018-06-07 00:45:47 +08:00
{
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(LgbConvert.ReadValue(ConfigurationManager.AppSettings["CookieExpiresDays"], 7)), IsPersistent = remember == "true" });
2018-06-07 00:45:47 +08:00
}
// redirect origin url
var originUrl = Request.Query[CookieAuthenticationDefaults.ReturnUrlParameter].FirstOrDefault() ?? "~/Home/Index";
return Redirect(originUrl);
2018-06-07 00:45:47 +08:00
}
2018-06-07 00:45:47 +08:00
/// <summary>
/// Logout this instance.
/// </summary>
/// <returns>The logout.</returns>
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("~" + CookieAuthenticationDefaults.LoginPath);
}
2018-06-07 00:45:47 +08:00
/// <summary>
/// Accesses the denied.
/// </summary>
/// <returns>The denied.</returns>
[ResponseCache(Duration = 600)]
2018-06-07 00:45:47 +08:00
public ActionResult AccessDenied()
{
var returnUrl = Request.Query[CookieAuthenticationDefaults.ReturnUrlParameter].ToString();
ViewBag.ReturnUrl = string.IsNullOrEmpty(returnUrl) ? Url.Content("~/Home/Index") : returnUrl;
2018-06-07 00:45:47 +08:00
return View();
}
}
}