92 lines
2.4 KiB
C#
92 lines
2.4 KiB
C#
namespace WebApi.Controllers;
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Mysqlx;
|
|
using Newtonsoft.Json.Linq;
|
|
using NuGet.Common;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using Parking_space_WebAPI.Authorization;
|
|
using Parking_space_WebAPI.Models;
|
|
using Parking_space_WebAPI.Services;
|
|
|
|
[ApiController]
|
|
[Authorize]
|
|
[Route("[controller]")]
|
|
public class UsersController : ControllerBase
|
|
{
|
|
private IUserService _userService;
|
|
private readonly SqlContext _context;
|
|
|
|
public UsersController(IUserService userService, SqlContext context)
|
|
{
|
|
_userService = userService;
|
|
_context = context;
|
|
}
|
|
|
|
|
|
[AllowAnonymous]
|
|
[HttpPost("authenticate")]
|
|
public IActionResult Authenticate(AuthenticateRequest model)
|
|
{
|
|
var response = _userService.Authenticate(model);
|
|
|
|
if (response == null)
|
|
return BadRequest(new { message = "Username or password is incorrect" });
|
|
|
|
// 将令牌添加到响应头中
|
|
Response.Headers.Add("Authorization", "Bearer " + response.Token);
|
|
|
|
// 将令牌保存在Cookie或其他适当的位置
|
|
Response.Cookies.Append("token", response.Token);
|
|
return Ok(response);
|
|
// 重定向到另一个页面
|
|
//return RedirectToAction("/Park_spaces/Parking_spaces_total_table");
|
|
//return RedirectToAction("Parking_spaces_total_table", "Park_spaces");
|
|
}
|
|
|
|
[HttpGet]
|
|
public IActionResult GetAll()
|
|
{
|
|
var users = _userService.GetAll();
|
|
return Ok(users);
|
|
}
|
|
|
|
[HttpGet("token_check")]
|
|
public IActionResult Token()
|
|
{
|
|
|
|
return Ok();
|
|
}
|
|
|
|
[HttpGet("token-{id}")]
|
|
public IActionResult get_user_data(string id)
|
|
{
|
|
// Your token string
|
|
string tokenString = id;
|
|
|
|
// Decode the token
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var token = tokenHandler.ReadJwtToken(tokenString);
|
|
|
|
// Access the payload
|
|
var payload = token.Payload;
|
|
|
|
// Retrieve data from the payload
|
|
string user_id = payload["id"].ToString(); // Assuming 'sub' is the key for the user ID
|
|
|
|
|
|
// You can access other claims as needed
|
|
//var users = _userService.GetAll();
|
|
return Ok(user_id);
|
|
}
|
|
|
|
[HttpGet("user_id-{id}")]
|
|
public IActionResult user_id(int id)
|
|
{
|
|
var user_data = _context.parking_spaces_user.FindAsync(id);
|
|
return Ok(user_data);
|
|
}
|
|
|
|
}
|