Files
Web_SupplierManager_Prod/SupplierManager/Controllers/LoginController.cs
2025-11-20 09:14:00 +08:00

248 lines
8.3 KiB
C#

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using ViewModels;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using ViewModels.RequestData;
using ViewModels.ResponseData;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using NLog;
using SupplierManager.Extensions;
using SupplierManager.Models;
using ViewModels.Common;
using static IronPython.Modules._ast;
namespace WebAPIServer.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class LoginController : ControllerBase
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public IConfiguration? configuration { get; set; }
public LoginController(IConfiguration _configuration)
{
configuration = _configuration;
}
[Authorize()]
[HttpPost()]
public ReturnInfo TokenXuQi()
{
ReturnInfo r = new ReturnInfo();
r.isok = false;
try
{
var claims = HttpContext.AuthenticateAsync().Result?.Principal?.Claims;
if (claims != null && claims.Any())
{
var Name = claims.SingleOrDefault(A => A.Type == ClaimTypes.Name)?.Value;
var UUU = claims.SingleOrDefault(A => A.Type == ClaimTypes.Role)?.Value;
var TTT = claims.SingleOrDefault(A => A.Type == ClaimTypes.NameIdentifier)?.Value;
AasUser? HH = new AasUser();
int a = 0;
int.TryParse(TTT, out a);
HH.Id = a;
bool bl = false;
bool.TryParse(UUU, out bl);
HH.Username = Name;
string TokenStr = GetToken(HH);
r.isok = true;
r.response = TokenStr;
}
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
/// <summary>
/// 登录
/// </summary>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
/// <returns></returns>
[HttpPost]
public ReturnInfo Login([FromBody] LoginData data)
{
ReturnInfo res = new ReturnInfo();
try
{
string password = data.password;
string username = data.username;
AasUser? entity = null;
string TokenString = "";
using (var q = new AgentApprovalSystemContext())
{
entity = q.AasUsers.SingleOrDefault(A => A.Username.Equals(username)&&A.Isdelete==false);
if (entity != null)
{
bool vvv = Tools.VerifyHashedPassword(entity.Password, password);
if (vvv == false)
{
res.isok = false;
res.message = "密码错误";
}
else
{
TokenString = GetToken(entity);
res.isok = true;
ResLoginData r = new ResLoginData();
r.AccessToken = TokenString;
r.Id = entity.Id;
r.Username = entity.Username;
r.Realname = entity.Realname;
r.Position = entity.Position;
r.ComId = entity.ComId;
r.RoleId = entity.RoleId;
r.Avatar = entity.Avatar;
res.response = r;
}
}
else
{
res.isok = false;
res.message = "用户不存在";
}
}
}
catch (Exception ex)
{
res.message = ex.Message;
res.isok = false;
}
return res;
}
/// <summary>
/// wy登录验证
/// </summary>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
/// <returns></returns>
[HttpPost]
public ReturnInfo WeLogin([FromBody] LoginData data)
{
ReturnInfo res = new ReturnInfo();
try
{
string password = data.password;
string username = data.username;
AasUser? entity = null;
string TokenString = "";
using (var q = new AgentApprovalSystemContext())
{
entity = q.AasUsers.SingleOrDefault(A => A.Username.Equals(username)&&A.Isdelete==false);
if (entity != null)
{
bool vvv = Tools.VerifyHashedPassword(entity.Password, password);
if (vvv == false)
{
res.isok = false;
res.message = "密码错误";
}
else
{
TokenString = GetToken(entity);
res.isok = true;
JWTData r = new()
{
AccessToken = TokenString,
iss = "BLW-" + Guid.NewGuid().ToString(),
exp = Tools.ToUnixTimestampBySeconds(DateTime.Now.AddHours(12)),
iat = Tools.ToUnixTimestampBySeconds(DateTime.Now).ToString(),
jti = "AAS-" + Guid.NewGuid().ToString(),
};
res.response = r;
}
}
else
{
res.isok = false;
res.message = "用户不存在";
}
}
}
catch (Exception ex)
{
res.message = ex.Message;
res.isok = false;
}
return res;
}
private string GetToken(AasUser? entity)
{
string TokenString;
var claims = new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, entity.Id.ToString()),
new Claim(ClaimTypes.MobilePhone, entity.Mobile.ToString()),
new Claim(ClaimTypes.Name, entity.Username)
};
var secretByte = Encoding.UTF8.GetBytes(configuration["JwT:SecretKey"]);
var signingKey = new SymmetricSecurityKey(secretByte);
var a = SecurityAlgorithms.HmacSha256;
var signingCredentials = new SigningCredentials(signingKey, a);
var token = new JwtSecurityToken(
issuer: configuration["JwT:Issuer"],
audience: configuration["JwT:Audience"],//接收
claims: claims,//存放的用户信息
notBefore: DateTime.UtcNow,//发布时间
expires: DateTime.UtcNow.AddHours(12),
signingCredentials: signingCredentials
//有效期设置为1天signingCredentials //数字名
);
TokenString = new JwtSecurityTokenHandler().WriteToken(token);
return TokenString;
}
[HttpPost()]
[Authorize()]
public string Helloooo()
{
return "hello";
}
}
internal class TblUtsManageUser
{
public object Id { get; internal set; }
public bool IsAdmin { get; internal set; }
public string? UserName { get; internal set; }
}
}