Files
simapi-net/Attributes/SimApiAuthAttribute.cs
T

54 lines
1.4 KiB
C#
Raw Normal View History

2022-09-02 09:47:41 +08:00
using System;
2020-02-18 06:37:48 +08:00
using System.Linq;
2020-02-04 16:51:15 +08:00
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
2020-08-05 15:29:56 +08:00
using SimApi.Communications;
using SimApi.Exceptions;
using SimApi.Interfaces;
using static SimApi.Helpers.SimApiError;
2020-02-04 16:51:15 +08:00
2024-03-23 07:29:43 +08:00
namespace SimApi.Attributes;
/// <summary>
/// 检测登录中间件
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class SimApiAuthAttribute : ActionFilterAttribute
2020-02-04 16:51:15 +08:00
{
private string[]? Types { get; }
2024-03-23 07:29:43 +08:00
//默认是user登录类型
public SimApiAuthAttribute()
2020-02-04 16:51:15 +08:00
{
Types = null;
2024-03-23 07:29:43 +08:00
}
2020-02-04 16:51:15 +08:00
2024-03-23 07:29:43 +08:00
//只检测一种用户类型的快捷方式
public SimApiAuthAttribute(string type)
{
Types = type.Split(",");
}
2020-11-11 03:28:09 +08:00
2024-03-23 07:29:43 +08:00
//设定特定类型的检测
public SimApiAuthAttribute(string[] types)
{
Types = types;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
2024-07-26 08:11:21 +08:00
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
var token = (string)context.HttpContext.Items["LoginToken"]!;
ErrorWhenNull(loginInfo, 401);
var checkers = context.HttpContext.RequestServices.GetServices<ISimApiAuthChecker>();
foreach (var checker in checkers)
2020-02-04 16:51:15 +08:00
{
checker.Run(loginInfo, token);
2020-02-04 16:51:15 +08:00
}
if (Types == null) return;
2024-03-23 07:29:43 +08:00
//检测用户类型
ErrorWhenFalse(Types.Intersect(loginInfo.Type).Any(), 403);
2020-02-04 16:51:15 +08:00
}
2022-09-02 09:47:41 +08:00
}