This commit is contained in:
ky_sunl
2021-04-01 06:47:58 +00:00
parent 687b79910e
commit cb7e07922f
41 changed files with 881 additions and 88 deletions

View File

@@ -0,0 +1,64 @@
using Dapper;
using DapperExtensions;
using Ewide.Core.Data;
using Ewide.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Common
{
public class ApiAuthorized
{
public static bool Authorized(string url, string userID = "")
{
using (var db = new DapperHelper())
{
// 将 /api/controller/action 形式转换成 api::controller::action
url = url.ToLower().Substring(1).Replace("/", "::");
var appliaction = db.Conn.GetList<EC_Appliaction>(new { Url = url }).FirstOrDefault();
// 默认没有配置的接口为开放接口
if (appliaction == null)
{
return true;
}
// 不需要验证权限和登录
if (appliaction.AuthorityType == (int)AuthorityType.)
{
return true;
}
// 只需要验证登录
if (appliaction.AuthorityType == (int)AuthorityType.)
{
return !String.IsNullOrEmpty(userID);
}
// 需要验证权限
if (!String.IsNullOrEmpty(userID))
{
var roles = db.Conn.GetList<EC_User_Role>(new { UserID = userID }).Select(p => p.RoleID).ToList();
var apps = db.Conn.ExecuteScalar<int>(@"SELECT COUNT(0) FROM ec_user_role UR
INNER JOIN ec_role_menu RM ON UR.roleID = RM.roleID
INNER JOIN ec_menu M ON RM.menuID = M.id AND M.enabled = 1
INNER JOIN ec_role_menu_appliaction RMA ON RM.ID = RMA.roleMenuID
INNER JOIN ec_menu_appliaction MA ON RMA.menuAppliactionID = MA.id AND MA.relationType = 2
WHERE UR.userID = @UserID AND MA.relationID = @RelationID", new
{
UserID = userID,
RelationID = appliaction.ID
});
return apps > 0;
}
}
return false;
}
}
}

View File

@@ -14,11 +14,9 @@ namespace Ewide.Core.Common
{
public class AuthorizedHelper : AuthorizedWhiteListHelper
{
private static readonly string JWT_Secret = System.Configuration.ConfigurationManager.ConnectionStrings["Token_JwtSecret"]?.ToString();
private static readonly string JWT_Secret = System.Configuration.ConfigurationManager.AppSettings["Token_JwtSecret"]?.ToString();
private static readonly string JWT_User = System.Configuration.ConfigurationManager.ConnectionStrings["Token_JwtUser"]?.ToString();
private static readonly string WhiteList_Key = System.Configuration.ConfigurationManager.ConnectionStrings["Token_WhiteList"]?.ToString();
private static readonly string JWT_User = System.Configuration.ConfigurationManager.AppSettings["Token_JwtUser"]?.ToString();
/// <summary>
/// 从Request中获取Token值。
@@ -69,6 +67,20 @@ namespace Ewide.Core.Common
}
}
public static string[] CurrentUserRoles
{
get
{
var userID = CurrentUserID;
if (String.IsNullOrEmpty(userID))
{
return null;
}
var roles = GetWhiteListUserRoles(userID);
return roles;
}
}
/// <summary>
/// 将字符串转成JwtToken类型并指示是否转换成功。
/// </summary>
@@ -207,7 +219,9 @@ namespace Ewide.Core.Common
{
var str = password.Trim().ToLower();
str = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(UTF8Encoding.Default.GetBytes(str))).Replace("-", "");
str = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(UTF8Encoding.Default.GetBytes(str)))
.Replace("-", "")
.ToLower();
return str;
}

View File

@@ -13,7 +13,7 @@ namespace Ewide.Core.Common
{
public class AuthorizedWhiteListHelper
{
private static readonly string WhiteList_Key = System.Configuration.ConfigurationManager.ConnectionStrings["Token_WhiteList"]?.ToString();
protected static readonly string WhiteList_Key = System.Configuration.ConfigurationManager.AppSettings["Token_WhiteList"]?.ToString();
private static readonly string CachePath = HttpContext.Current.Server.MapPath("\\" + Path.Combine("Cache", WhiteList_Key + ".bin"));
@@ -128,25 +128,29 @@ namespace Ewide.Core.Common
using (var db = new DapperHelper())
{
var user = db.Conn.Get<EC_User>(userID);
var roles = db.Conn.GetList<EC_User_Role>(new { UserID = userID }).Select(p => p.RoleID).ToArray();
var exp = DateTime.Now.AddDays(30);
if (list == null)
{
list = new List<WhiteListToken>
{
new WhiteListToken
{
UserID = userID,
User = user,
Token = token,
ExpDate = exp
}
};
new WhiteListToken
{
UserID = userID,
User = user,
Roles = roles,
Token = token,
ExpDate = exp
}
};
}
else
{
var item = list.FirstOrDefault(p => p.UserID.Equals(userID, StringComparison.CurrentCultureIgnoreCase));
if (item != null)
{
item.User = user;
item.Roles = roles;
item.Token = token;
item.ExpDate = exp;
}
@@ -156,6 +160,7 @@ namespace Ewide.Core.Common
{
UserID = userID,
User = user,
Roles = roles,
Token = token,
ExpDate = exp
});
@@ -218,6 +223,22 @@ namespace Ewide.Core.Common
WhiteList = list;
}
/// <summary>
/// 根据UserID获取白名单中的角色编号
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
protected static string[] GetWhiteListUserRoles(string userID)
{
var item = GetWhiteListByUserID(userID);
if (item == null)
{
return null;
}
return item.Roles;
}
/// <summary>
///
/// </summary>

View File

@@ -0,0 +1,58 @@
using Ewide.Core.Data;
using DapperExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ewide.Core.Model;
using Ewide.Core.DTO;
namespace Ewide.Core.Common
{
public class LoginHelper
{
public LoginRDTO Login(string account, string password, out string token, out string message)
{
token = String.Empty;
message = String.Empty;
using (var db = new DapperHelper())
{
var user = db.Conn.GetList<EC_User>(new { Account = account }).FirstOrDefault();
if (user == null)
{
message = "此用户不存在";
return null;
}
var passwordMD5 = AuthorizedHelper.GetPasswordMD5(password);
if (!passwordMD5.Equals(user.Password))
{
message = "密码错误";
return null;
}
if (!user.Enabled)
{
message = "当前用户已被禁止登录";
return null;
}
message = "登录成功";
token = AuthorizedHelper.AddToken(user);
return new LoginRDTO
{
Account = user.Account,
Name = user.Name,
Type = user.Type,
Sex = user.Sex,
Avatar = user.Avatar,
Code = user.Code,
Phone = user.Phone,
Desc = user.Desc
};
}
}
}
}

View File

@@ -11,6 +11,7 @@ namespace Ewide.Core.Common
{
public string UserID { get; set; }
public EC_User User { get; set; }
public string[] Roles { get; set; }
public string Token { get; set; }
public DateTime ExpDate { get; set; }
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Common
{
public enum AuthorityType
{
/// <summary>
/// 一般接口,需要验证权限
/// </summary>
= 1,
/// <summary>
/// 内部接口,只需要验证登录
/// </summary>
= 2,
/// <summary>
/// 开放接口,不需要验证权限和登录
/// </summary>
= 3,
}
}

View File

@@ -59,15 +59,18 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Authorized\ApiAuthorized.cs" />
<Compile Include="Authorized\AuthorizedHelper.cs" />
<Compile Include="Authorized\AuthorizedWhiteListHelper.cs" />
<Compile Include="Authorized\LoginHelper.cs" />
<Compile Include="Authorized\WhiteListToken.cs" />
<Compile Include="BaseDisplayJSON.cs" />
<Compile Include="EnumCode\AuthorityType.cs" />
<Compile Include="Menu\MenuHelper.cs" />
<Compile Include="Menu\MenuStructure.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="EnumCode\" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
@@ -77,6 +80,10 @@
<Project>{b5b46bad-81e3-4df0-83ef-75148236f7ce}</Project>
<Name>Ewide.Core.Data</Name>
</ProjectReference>
<ProjectReference Include="..\Ewide.Core.DTO\Ewide.Core.DTO.csproj">
<Project>{590704FF-28C5-4536-B587-AC213858CC42}</Project>
<Name>Ewide.Core.DTO</Name>
</ProjectReference>
<ProjectReference Include="..\Ewide.Core.Model\Ewide.Core.Model.csproj">
<Project>{31C3CA3D-14A1-453A-866D-76D4C74A9BDC}</Project>
<Name>Ewide.Core.Model</Name>

View File

@@ -0,0 +1,56 @@
using DapperExtensions;
using Ewide.Core.Data;
using Ewide.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Common
{
public class MenuHelper
{
public List<MenuStructure> GetMenu()
{
using (var db = new DapperHelper())
{
var roles = AuthorizedHelper.CurrentUserRoles;
var menuIDList = db.Conn.GetList<EC_Role_Menu>(new { RoleID = roles }).Select(p => p.MenuID).ToList();
var menuList = db.Conn.GetList<EC_Menu>(new { ID = menuIDList, Enabled = true })
.Select(p => new MenuStructure
{
ID = p.ID,
ParentID = p.ParentID,
Type = p.Type,
Name = p.Name,
Icon = p.Icon,
Color = p.Color,
Sort = p.Sort,
Children = null
})
.ToList();
return GetMenuStructure(menuList);
}
}
private List<MenuStructure> GetMenuStructure(List<MenuStructure> list, string parentID = "")
{
List<MenuStructure> menu;
if (String.IsNullOrEmpty(parentID))
{
menu = list.Where(p => String.IsNullOrEmpty(p.ParentID)).OrderBy(p => p.Sort).ToList();
}
else
{
menu = list.Where(p => parentID == p.ParentID).OrderBy(p => p.Sort).ToList();
}
foreach (var m in menu)
{
m.Children = GetMenuStructure(list, m.ID);
}
return menu;
}
}
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Common
{
public class MenuStructure
{
public string ID { get; set; }
public string ParentID { get; set; }
public int Type { get; set; }
public string Name { get; set; }
public string Component { get; set; }
public string Icon { get; set; }
public string Color { get; set; }
public int Sort { get; set; }
public List<MenuStructure> Children { get; set; }
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.DTO
{
public class CreateUserDTO
{
[DisplayName("登录帐号")]
[Required(AllowEmptyStrings = false, ErrorMessage = "登录帐号不可为空")]
public string Account { get; set; }
[DisplayName("登录密码")]
[Required(AllowEmptyStrings = false, ErrorMessage = "登录密码不可为空")]
public string Password { get; set; }
[DisplayName("用户名")]
[Required(AllowEmptyStrings = false, ErrorMessage = "用户名不可为空")]
public string Name { get; set; }
}
}

View File

@@ -42,7 +42,9 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CreateUserDTO.cs" />
<Compile Include="LoginDTO.cs" />
<Compile Include="LoginRDTO.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

View File

@@ -11,7 +11,6 @@ namespace Ewide.Core.DTO
public class LoginDTO
{
[DisplayName("登录帐号")]
[Phone(ErrorMessage = "a a")]
[Required(AllowEmptyStrings = false, ErrorMessage = "登录帐号不可为空")]
public string Account { get; set; }

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.DTO
{
public class LoginRDTO
{
public string Account { get; set; }
public string Name { get; set; }
public int Type { get; set; }
public int Sex { get; set; }
public string Avatar { get; set; }
public string Code { get; set; }
public string Phone { get; set; }
public string Desc { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Appliaction
{
public string ID { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public int AuthorityType { get; set; }
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Dictionary
{
public string ID { get; set; }
public string ParentID { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Value { get; set; }
public string Values { get; set; }
public string Desc { get; set; }
public bool IsSystem { get; set; }
public int Sort { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUserID { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Function
{
public string ID { get; set; }
public string MenuID { get; set; }
public string AppliactionID { get; set; }
public string Name { get; set; }
public string Text { get; set; }
public string Icon { get; set; }
public string Theme { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUserID { get; set; }
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Menu
{
public string ID { get; set; }
public string ParentID { get; set; }
public int Type { get; set; }
public string Name { get; set; }
public string Component { get; set; }
public string Icon { get; set; }
public string Color { get; set; }
public bool IsSystem { get; set; }
public bool Enabled { get; set; }
public int Sort { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUserID { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Menu_Appliaction
{
public string ID { get; set; }
public string MenuID { get; set; }
public int RelationType { get; set; }
public string RelationID { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Role
{
public string ID { get; set; }
public string Name { get; set; }
public string Desc { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUserID { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Role_Menu
{
public string ID { get; set; }
public string MenuID { get; set; }
public string ParentMenuID { get; set; }
public string RoleID { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUserID { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_Role_Menu_Appliaction
{
public string ID { get; set; }
public string RoleMenuID { get; set; }
public string MenuAppliactionID { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_System
{
public string ID { get; set; }
public int Status { get; set; }
public DateTime CreateTime { get; set; }
public string AdminID { get; set; }
}
}

View File

@@ -6,9 +6,21 @@ using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_User
{
public string ID { get; set; }
public string Account { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public int Type { get; set; }
public int Sex { get; set; }
public string Avatar { get; set; }
public string Code { get; set; }
public string Phone { get; set; }
public string Desc { get; set; }
public bool Enabled { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUserID { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Model
{
[Serializable]
public class EC_User_Role
{
public string ID { get; set; }
public string UserID { get; set; }
public string RoleID { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUserID { get; set; }
}
}

View File

@@ -54,7 +54,17 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="EC_Appliaction.cs" />
<Compile Include="EC_Dictionary.cs" />
<Compile Include="EC_Function.cs" />
<Compile Include="EC_Menu.cs" />
<Compile Include="EC_Menu_Appliaction.cs" />
<Compile Include="EC_Role.cs" />
<Compile Include="EC_Role_Menu.cs" />
<Compile Include="EC_Role_Menu_Appliaction.cs" />
<Compile Include="EC_System.cs" />
<Compile Include="EC_User.cs" />
<Compile Include="EC_User_Role.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ewide.Core.Service
{
public class BaseService
{
/// <summary>
/// 设置和读取异常信息。
/// </summary>
protected string _ErrorMessage = String.Empty;
/// <summary>
/// 读取异常信息。
/// </summary>
public string ErrorMessage
{
get
{
return _ErrorMessage;
}
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DapperExtensions;
using Ewide.Core.Model;
using Ewide.Core.Common;
namespace Ewide.Core.Service
{
public class GateService : BaseService
{
public void Login(string account, string password)
{
}
public string CreateAccount(string account, string password, string name)
{
using (var db = new Data.DapperTransactionHelper())
{
var user = new EC_User
{
ID = Guid.NewGuid().ToString(),
Account = account,
Password = AuthorizedHelper.GetPasswordMD5(password),
Name = name,
Type = 1,
Sex = 1,
Enabled = true,
CreateTime = DateTime.Now
};
db.Conn.Insert(user);
try
{
db.Complete();
return user.ID;
}
catch (Exception ex)
{
_ErrorMessage = ex.Message;
db.RollBack();
return null;
}
}
}
}
}

View File

@@ -42,6 +42,8 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Base\BaseService.cs" />
<Compile Include="Base\GateService.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 有关使用 web.config 转换的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
在下例中“SetAttributes”转换将更改
“connectionString”的值以仅在“Match”定位器
找到值为“MyDB”的特性“name”时使用“ReleaseSQLServer”。
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<!--
在下例中“Replace”转换将替换
web.config 文件的整个 <customErrors> 节。
请注意,由于
在 <system.web> 节点下仅有一个 customErrors 节因此不需要使用“xdt:Locator”特性。
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
</compilers>
</system.codedom>
</configuration>

View File

@@ -32,8 +32,16 @@ namespace Ewide.Core.WebApi
config.Services.Replace(typeof(IHttpActionInvoker), new HttpWebApiControllerActionInvoker(config));
#endregion
// 接口权限
config.Filters.Add(new ApiAuthorizeAttribute());
// 接口参数验证
config.Filters.Add(new ValidateArgumentsFilter());
#if DEBUG
// 允许跨域
config.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*"));
#endif
}
}
}

View File

@@ -1,38 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Ewide.Core.WebApi.Areas.Base.Controllers
{
[ValidateArgumentsFilter]
public class BetestController : BaseController
{
/// <summary>
/// 获取所有接口及其注释
/// </summary>
/// <returns></returns>
[Route("test22")]
[HttpPost]
public IHttpActionResult Test1()
{
var apis = Configuration.Services.GetApiExplorer().ApiDescriptions;
var result = apis
.Select(p => new
{
p.RelativePath,
p.Documentation
});
return DisplayJSON(result);
}
[HttpPost]
public IHttpActionResult Test2()
{
return DisplayJSON("");
}
}
}

View File

@@ -1,4 +1,6 @@
using Ewide.Core.DTO;
using Ewide.Core.Common;
using Ewide.Core.DTO;
using Ewide.Core.Service;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,11 +17,24 @@ namespace Ewide.Core.WebApi.Areas.Base.Controllers
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[ApiAuthorize(VerifyAuthorization = false)]
[AllowAnonymous]
[HttpPost]
public IHttpActionResult Login(LoginDTO dto)
{
return DisplayJSON(dto);
var info = new LoginHelper().Login(dto.Account, dto.Password, out string token, out string message);
if(info == null)
{
return DisplayErrorJSON(message);
}
else
{
return DisplaySuccessJSON(new
{
Token = token,
Message = message,
Info = info
});
}
}
[ValidateArgumentsFilter(AllowNull = true)]
@@ -28,5 +43,18 @@ namespace Ewide.Core.WebApi.Areas.Base.Controllers
{
return DisplayJSON(dto);
}
/// <summary>
/// 测试创建帐号
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public IHttpActionResult CreateAccount(CreateUserDTO dto)
{
var service = new GateService();
var result = service.CreateAccount(dto.Account, dto.Password, dto.Name);
return DisplayJSON(String.IsNullOrEmpty(service.ErrorMessage) ? result : service.ErrorMessage);
}
}
}

View File

@@ -0,0 +1,19 @@
using Ewide.Core.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Ewide.Core.WebApi.Areas.Base.Controllers
{
public class MenuController : BaseController
{
[HttpPost]
public IHttpActionResult Get()
{
return DisplaySuccessJSON(new MenuHelper().GetMenu());
}
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Ewide.Core.WebApi.Areas.Base.Controllers
{
public class SpareController : BaseController
{
/// <summary>
/// 获取所有接口及其注释
/// </summary>
/// <returns></returns>
[HttpPost]
public IHttpActionResult GetApis()
{
var apis = Configuration.Services.GetApiExplorer().ApiDescriptions;
var result = apis
.ToLookup(p => p.ActionDescriptor.ControllerDescriptor)
.Select(p => new
{
Group = p.Key.ControllerName.ToLower(),
Apis = p.Select(q => new
{
RelativePath = "/" + q.RelativePath.ToLower(),
q.Documentation
})
});
return DisplayJSON(result);
}
}
}

View File

@@ -13,26 +13,16 @@ namespace Ewide.Core.WebApi
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
/// <summary>
/// 是否验证权限
/// </summary>
public bool VerifyAuthorization { get; set; } = true;
public override void OnAuthorization(HttpActionContext actionContext)
{
if (!VerifyAuthorization)
{
base.IsAuthorized(actionContext);
return;
}
var path = actionContext.Request.RequestUri.AbsolutePath;
// 验证token
var authorization = actionContext.Request.Headers.Authorization;
if (authorization != null && !String.IsNullOrEmpty(authorization.Parameter))
{
var token = authorization.Parameter;
var userID = AuthorizedHelper.GetUserID(token);
if (!String.IsNullOrEmpty(userID))
if (ApiAuthorized.Authorized(path, userID))
{
base.IsAuthorized(actionContext);
return;
@@ -42,9 +32,10 @@ namespace Ewide.Core.WebApi
{
var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
if (isAnonymous)
if (isAnonymous || ApiAuthorized.Authorized(path))
{
base.OnAuthorization(actionContext);
base.IsAuthorized(actionContext);
return;
}
else
{

View File

@@ -58,13 +58,49 @@ namespace Ewide.Core.WebApi
return _DisplayJSON(BaseDisplayJSON.Ok(message));
}
protected IHttpActionResult DisplaySuccessJSON(object result)
{
return DisplayJSON(new
{
Success = true,
Data = result
});
}
protected IHttpActionResult DisplaySuccessJSON(string message)
{
return DisplayJSON(new
{
Success = true,
Message = message
});
}
protected IHttpActionResult DisplayErrorJSON(object result)
{
return DisplayJSON(new
{
Success = false,
Data = result
});
}
protected IHttpActionResult DisplayErrorJSON(string message)
{
return DisplayJSON(new
{
Success = false,
Message = message
});
}
protected IHttpActionResult DisplayDataJSON(object data, int total)
{
return _DisplayJSON(BaseDisplayJSON.Ok(new
return DisplayJSON(new
{
Data = data,
Total = total
}));
});
}
}
}

View File

@@ -52,6 +52,12 @@
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.7\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Web.Cors, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Cors.5.2.4\lib\net45\System.Web.Cors.dll</HintPath>
</Reference>
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
@@ -59,6 +65,12 @@
<Reference Include="System.Web" />
<Reference Include="System.Web.Abstractions" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Http, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.4\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.Cors, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Cors.5.2.4\lib\net45\System.Web.Http.Cors.dll</HintPath>
</Reference>
<Reference Include="System.Web.Routing" />
<Reference Include="System.Xml" />
<Reference Include="System.Configuration" />
@@ -72,18 +84,12 @@
</Reference>
<Reference Include="System.Net.Http">
</Reference>
<Reference Include="System.Net.Http.Formatting, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.4\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.WebRequest">
</Reference>
<Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.4\lib\net45\System.Web.Helpers.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.4\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.4\lib\net45\System.Web.Http.WebHost.dll</HintPath>
</Reference>
@@ -134,7 +140,8 @@
<Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Areas\Base\BaseAreaRegistration.cs" />
<Compile Include="Areas\Base\Controllers\BetestController.cs" />
<Compile Include="Areas\Base\Controllers\MenuController.cs" />
<Compile Include="Areas\Base\Controllers\SpareController.cs" />
<Compile Include="Areas\Base\Controllers\GateController.cs" />
<Compile Include="Areas\HelpPage\ApiDescriptionExtensions.cs" />
<Compile Include="Areas\HelpPage\App_Start\HelpPageConfig.cs" />
@@ -206,7 +213,9 @@
<Content Include="Areas\HelpPage\Views\Help\Api.cshtml" />
<Content Include="Scripts\jquery-3.3.1.js" />
<Content Include="Scripts\modernizr-2.8.3.js" />
<Content Include="Web.config" />
<Content Include="Web.config">
<SubType>Designer</SubType>
</Content>
<Content Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</Content>

View File

@@ -5,13 +5,17 @@
-->
<configuration>
<connectionStrings>
<add name="MySqlConnection" connectionString="server=localhost;user id=root;password=a45683926;database=ewide.core;persistsecurityinfo=True" />
<add name="MySqlConnection" connectionString="server=localhost;user id=root;password=a45683926;database=ewide_core;persistsecurityinfo=True" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="Token_JwtSecret" value="H@I9R^@vm!7loYnkG5xWC7frA6@IbBIPA!6NR1$hqBep2e4AC1OtdS^z!X0qT3ik" />
<add key="Token_JwtUser" value="ewide.core" />
<add key="Token_WhiteList" value="ewide.core.whitelist" />
</appSettings>
<!--
有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。
@@ -75,6 +79,10 @@
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>

View File

@@ -3,6 +3,7 @@
<package id="Antlr" version="3.5.0.2" targetFramework="net45" />
<package id="bootstrap" version="3.3.7" targetFramework="net45" />
<package id="jQuery" version="3.3.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Cors" version="5.2.4" targetFramework="net452" />
<package id="Microsoft.AspNet.Mvc" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc.zh-Hans" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="3.2.4" targetFramework="net45" />
@@ -10,10 +11,11 @@
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization.zh-Hans" version="1.1.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client.zh-Hans" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core.zh-Hans" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.7" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client.zh-Hans" version="5.2.7" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core.zh-Hans" version="5.2.4" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Cors" version="5.2.4" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.HelpPage" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.4" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost.zh-Hans" version="5.2.4" targetFramework="net45" />

View File

@@ -23,6 +23,28 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ewide.Core.Data", "Ewide.Co
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ewide.Core.DTO", "Ewide.Core.DTO\Ewide.Core.DTO.csproj", "{590704FF-28C5-4536-B587-AC213858CC42}"
EndProject
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "Ewide.Core.Web", "Ewide.Core.Web\", "{E36D9474-4C59-4E43-B9C7-7DFE1063AC9A}"
ProjectSection(WebsiteProperties) = preProject
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5.2"
Debug.AspNetCompiler.VirtualPath = "/localhost_54920"
Debug.AspNetCompiler.PhysicalPath = "Ewide.Core.Web\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_54920\"
Debug.AspNetCompiler.Updateable = "true"
Debug.AspNetCompiler.ForceOverwrite = "true"
Debug.AspNetCompiler.FixedNames = "false"
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.VirtualPath = "/localhost_54920"
Release.AspNetCompiler.PhysicalPath = "Ewide.Core.Web\"
Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_54920\"
Release.AspNetCompiler.Updateable = "true"
Release.AspNetCompiler.ForceOverwrite = "true"
Release.AspNetCompiler.FixedNames = "false"
Release.AspNetCompiler.Debug = "False"
VWDPort = "54920"
SlnRelativePath = "Ewide.Core.Web\"
DefaultWebSiteLanguage = "Visual C#"
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -57,6 +79,10 @@ Global
{590704FF-28C5-4536-B587-AC213858CC42}.Debug|Any CPU.Build.0 = Debug|Any CPU
{590704FF-28C5-4536-B587-AC213858CC42}.Release|Any CPU.ActiveCfg = Release|Any CPU
{590704FF-28C5-4536-B587-AC213858CC42}.Release|Any CPU.Build.0 = Release|Any CPU
{E36D9474-4C59-4E43-B9C7-7DFE1063AC9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E36D9474-4C59-4E43-B9C7-7DFE1063AC9A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E36D9474-4C59-4E43-B9C7-7DFE1063AC9A}.Release|Any CPU.ActiveCfg = Debug|Any CPU
{E36D9474-4C59-4E43-B9C7-7DFE1063AC9A}.Release|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE