AccountController.cs
6.04 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
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using HHECS.DAQWebClient.ViewModel;
using HHECS.DAQWebClient.Models;
using HHECS.DAQWebClient.Dtos;
namespace HHECS.DAQWebClient.Controllers
{
public class AccountController : Controller
{
private readonly ILogger<AccountController> _logger;
private readonly IFreeSql _freeSql;
public AccountController(IFreeSql freeSql, ILogger<AccountController> logger)
{
_freeSql = freeSql;
_logger = logger;
}
public IActionResult Login()
{
var returnUrl = HttpContext.Request.Query.Where(x => x.Key == "ReturnUrl").Select(x => x.Value).FirstOrDefault();
return View(new LoginModel
{
ReturnUrl = returnUrl,
});
}
/// <summary>
/// 登录
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginAsync(LoginModel model)
{
try
{
var user = _freeSql.Queryable<User>().Where(x => x.Account == model.UserName).First();
if (user == null)
{
ModelState.AddModelError(nameof(model.UserName), $"用户“{model.UserName}”不存在!");
return View(model);
}
//实例化一个md5对像
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
byte[] bytes = MD5.HashData(Encoding.UTF8.GetBytes(model.Password));
var pwd = Convert.ToBase64String(bytes);
if (pwd != user.Password)
{
ModelState.AddModelError(nameof(model.Password), "密码错误");
return View(model);
}
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaims(new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.Role, user.Role.ToString()),
new Claim(ClaimTypes.System, "DataAcquisition")
});
var principal = new ClaimsPrincipal(identity);
// 登录
var properties = new AuthenticationProperties
{
IsPersistent = model.RememberMe,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30),
AllowRefresh = true
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
_logger.LogInformation($"用户{model.UserName}登录成功");
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return Redirect("/");
}
catch (Exception ex)
{
ModelState.AddModelError(nameof(model.UserName), $"程序异常:{ex.Message}");
return View(model);
}
}
/// <summary>
/// 退出登录
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Logout()
{
var userName = HttpContext.User.Identity?.Name;
await HttpContext.SignOutAsync();
_logger.LogInformation($"用户{userName}退出登录");
return Redirect("/");
}
[Authorize]
public async Task<IActionResult> UpdatePassword(SettingPasswordModel model)
{
try
{
if (model.NewPassword != model.ConfirmNewPassword)
{
return Ok(new ResultDto
{
Code = 500,
Msg = "“新密码”与“确认密码”不一致"
});
}
var account = HttpContext.User.Identity?.Name ?? string.Empty;
var user = await _freeSql.Queryable<User>().Where(x => x.Account == account).FirstAsync();
if (user == null)
{
return Ok(new ResultDto
{
Code = 500,
Msg = "获取用户信息失败"
});
}
byte[] bytes = MD5.HashData(Encoding.UTF8.GetBytes(model.CurrentPassword));
var pwd = Convert.ToBase64String(bytes);
if (user.Password != pwd)
{
return Ok(new ResultDto
{
Code = 500,
Msg = "原密码不正确"
});
}
byte[] bytes2 = MD5.HashData(Encoding.UTF8.GetBytes(model.NewPassword));
var newPwd = Convert.ToBase64String(bytes2);
await _freeSql.Update<User>(user.Id).Set(x => new User
{
Password = newPwd,
Updated = DateTime.Now,
UpdatedBy = user.Account
}).ExecuteAffrowsAsync();
var msg = "修改密码成功";
_logger.LogInformation(msg);
return Ok(new ResultDto
{
Code = 0,
Msg = msg
});
}
catch (Exception ex)
{
var msg = $"修改密码失败:{ex.Message}";
return Ok(new ResultDto
{
Code = 0,
Msg = msg
});
}
}
}
}