using AuditFieldSample.Models;
using Microsoft.AspNetCore.Authentication;//认证
using Microsoft.AspNetCore.Authorization; //授权
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;

namespace AuditFieldSample.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        public async Task<IActionResult> SignOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction(nameof(Login));
        }

        public IActionResult AccessDenied()
        {
            return Content("你没权限哦！");
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginModel model)
        {
            ClaimsPrincipal principal = null;

            if (!string.IsNullOrWhiteSpace(model.UserName) && model.UserName == model.Password)
            {
                Claim name = new Claim(ClaimTypes.Name, model.UserName);

                ClaimsIdentity claimsIdentity = new ClaimsIdentity(ClaimsIdentity.DefaultNameClaimType);
                claimsIdentity.AddClaim(name);

                principal = new ClaimsPrincipal(claimsIdentity);
            }

            if (principal == null)
            {
                ModelState.AddModelError("error", "无效的用户名或密码");
                return View(model);
            }

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

            return RedirectToAction(actionName: "Index", controllerName: "Post");
        }
    }
}