LoginController.cs
8.74 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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;
using Microsoft.AspNetCore.Http;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Localization;
using HHECS.Web.Resources;
namespace HHECS.Web.Controllers
{
/// <summary>
/// 登录控制器
/// </summary>
[AllowAnonymous]
public class LoginController : Controller
{
private readonly PermissionService _permissionService;
private readonly LogService _logService;
//公共多语言
//private readonly IHtmlLocalizer _sharedLocalizer;
// 视图本地化器
//private readonly IHtmlLocalizer _loginLocalizer;
public LoginController(PermissionService permissionService, LogService logService, IHtmlLocalizerFactory htmlLocalizerFactory)
{
_permissionService = permissionService;
_logService = logService;
// _sharedLocalizer = htmlLocalizerFactory.Create("SharedResource", Assembly.GetExecutingAssembly().GetName().Name);
// _loginLocalizer = htmlLocalizerFactory.Create("Views.Login.Index", Assembly.GetExecutingAssembly().GetName().Name);
}
[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 + "-" + @LangsWeb.company;
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();
}
[HttpPost]
public IActionResult SetCulture(string culture, string returnUrl)
{
try
{
// 确保文化代码为小写
culture = culture?.ToLowerInvariant();
// 只允许两种语言
if (culture != "zh-cn" && culture != "en-us")
{
culture = "en-us"; // 默认英文
}
// 设置语言 Cookie
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddYears(1),
Path = "/", // 确保在整个站点有效
IsEssential = true
}
);
// 返回成功响应
return Json(new { success = true, message =LangsWeb.登录成功 });
}
catch (Exception ex)
{
// 返回错误响应
return Json(new { success = false, message = LangsWeb.语言切换失败 + ex.Message });
}
}
}
}