Files
simapi-net/Attributes/SimApiAuthAttribute.cs
T

51 lines
1.3 KiB
C#
Raw Normal View History

2020-02-18 06:37:48 +08:00
using System;
using System.Linq;
2020-02-04 16:51:15 +08:00
using Microsoft.AspNetCore.Mvc.Filters;
2020-08-05 15:29:56 +08:00
using SimApi.Communications;
using SimApi.Exceptions;
2020-02-04 16:51:15 +08:00
2020-08-05 15:29:56 +08:00
namespace SimApi.Attributes
2020-02-04 16:51:15 +08:00
{
/// <summary>
/// 检测登录中间件
/// </summary>
2020-02-18 06:37:48 +08:00
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
2020-08-05 15:29:56 +08:00
public class SimApiAuthAttribute : ActionFilterAttribute
2020-02-04 16:51:15 +08:00
{
private string[] Types { get; }
//默认是user登录类型
2020-08-05 15:29:56 +08:00
public SimApiAuthAttribute()
2020-02-04 16:51:15 +08:00
{
Types = new[] { "user" };
}
//只检测一种用户类型的快捷方式
2020-08-05 15:29:56 +08:00
public SimApiAuthAttribute(string type)
2020-02-04 16:51:15 +08:00
{
Types = new[] { type };
}
//设定特定类型的检测
2020-08-05 15:29:56 +08:00
public SimApiAuthAttribute(string[] types)
2020-02-04 16:51:15 +08:00
{
Types = types;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
2020-08-05 15:29:56 +08:00
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"];
2020-02-04 16:51:15 +08:00
//检测是否登录
if (loginInfo == null)
{
2020-08-05 15:29:56 +08:00
throw new SimApiException(401);
2020-02-04 16:51:15 +08:00
}
//检测用户类型
2020-02-18 08:07:51 +08:00
if (Types.Intersect(loginInfo.Type).Count() == 0)
2020-02-04 16:51:15 +08:00
{
2020-08-05 15:29:56 +08:00
throw new SimApiException(403);
2020-02-04 16:51:15 +08:00
}
}
}
}