LoginController.cs
6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using HHECS.Application.Enums;
using HHECS.Application.Service;
using HHECS.BllModel;
using HHECS.Model.ClassComparer;
using HHECS.Model.Entities;
using HHECS.Model.ViewEntity;
using HHECS.WebCommon.Config;
using HHECS.WebCommon.Port;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using HHECS.Infrastructure.Json;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Net;
using HHECS.Dal.Repository;
namespace HHECS.Web.Controllers
{
/// <summary>
/// 登录控制器
/// </summary>
[AllowAnonymous]
public class LoginController : Controller
{
private readonly PermissionService _permissionService;
private readonly LogService _logService;
public LoginController(PermissionService permissionService, LogService logService)
{
_permissionService = permissionService;
_logService = logService;
}
[HttpGet]
public IActionResult Index()
{
//var company = sysCompanyService.GetSysCompanyOne();
//var sysFile = sysCompanyService.GetSysFile(company.companyId);
//ViewBag.filePath = sysAppService.Download();
//ViewBag.ver = company.ver;
//ViewBag.Url = sysFile.FirstOrDefault(x => x.position == "home")?.url;
ViewBag.copyright = "Copyright © " + DateTime.Now.Year + "-" + new CompanyRepository().Where(t => true).ToOne()?.Name;
return View();
}
/// <summary>
/// 登入
/// </summary>
[HttpPost]
public string Login(string username, string password)
{
Stopwatch stopwatch = Stopwatch.StartNew();
var response = new Response();
try
{
var result = _permissionService.GetUserWithRoles(username, password);
if (!result.Success) return response.ResponseError(result.Msg).ToJson();
var user = result.Data;
var permissions = user.Roles.SelectMany(t => t.Permissions).Distinct(new PermissionComparer()).ToList();
var ips = ComputerHelp.GetAddressIP();
//写cookies
//https://www.cnblogs.com/land/archive/2009/04/10/1433074.html
var token = Guid.NewGuid().ToString("N");
response.Token = token;
Response.Cookies.Append("Token", token);
user.Token = token;
var bllResult = _permissionService.UserUpdate(user);
if (!bllResult.Success) return response.ResponseError(bllResult.Msg).ToJson();
var currentSession = new
{
Account = user.UserCode,
Name = user.UserName,
Sex = "",
Idcard = "",
Token = token,
Organizations = string.Join(",", permissions.Select(u => u.PermissionName).ToList()),
CreateTime = DateTime.Now,
};
response.Result = currentSession;
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); // 指定身份认证类型
identity.AddClaim(new Claim(ClaimTypes.Sid, result.Data.UserCode)); // 用户Id
identity.AddClaim(new Claim("Password", result.Data.Password)); // 用户名称
identity.AddClaim(new Claim(ClaimTypes.Name, result.Data.UserName));
//创建身份证这个证件的携带者:我们叫这个证件携带者为“证件当事人”
var principal = new ClaimsPrincipal(identity);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = false, AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(40) });
#region 记录登录日志
string url = $"{HttpContext.Request.Host}{HttpContext.Request.Path}{HttpContext.Request.QueryString}";
var actionArguments = JsonConvert.SerializeObject(username);
_logService.AddWebOperationLog(url,
"登录",
HttpContext.Request.Method.ToUpper(),
HttpContext.Request.Headers[HeaderNames.UserAgent].ToString(),
actionArguments,
response.ToJson(),
stopwatch.Elapsed.TotalSeconds,
user,
ips,
response.Status,
"登录日志");
#endregion
return response.ToJson();
}
catch (Exception ex)
{
return response.ResponseError(ex.Message).ToJson();
}
}
[HttpPost]
public async Task<BllResult> LoginIn(User user)
{
//写入Session
//HttpContext.Session.SetString("q", userName);
//登录Cookie
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); // 指定身份认证类型
identity.AddClaim(new Claim(ClaimTypes.Sid, user.UserCode)); // 用户Id
identity.AddClaim(new Claim("Password", user.Password)); // 用户名称
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
//创建身份证这个证件的携带者:我们叫这个证件携带者为“证件当事人”
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = false, AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(40) });
return BllResultFactory.Success();
}
[HttpGet]
public async Task<BllResult> LoginOut()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return BllResultFactory.Success();
}
/// <summary>
/// 退出
/// </summary>
[HttpGet]
public async Task<BllResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
Response.Cookies.Append("Token", "");
//return RedirectToAction("Index", "Login");
return BllResultFactory.Success();
}
}
}