using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Core.Model.PowerBiModel;
using Core.Repository.RepositoryModel;
using Core.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Common;
using Core.Data.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
namespace PnWeb.Controllers.v1
{
using Common.Enum;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Log4Net.AspNetCore;
using Org.BouncyCastle.Crypto.Parameters;
using StackExchange.Redis;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Timers;
using System.Web;
[Authorize]
[Route("api")]
[ApiController]
public class ApiController : Controller
{
public readonly PnWebDbContext context;
public readonly GBDDataContext gBDDataContext;
//多线程
public readonly Func<GBDDataContext> gBDDataContextFactory;
private readonly ILogger<ApiController> logger;
private readonly IHttpContextAccessor httpContextAccessor;
private string userName
{
get
{
return GetUserName(httpContextAccessor.HttpContext.User.Identity.Name);
}
}
public IWebHostEnvironment HostingEnv { get; }
// PnWebDbContext dbContext
public ApiController(PnWebDbContext _context, ILogger<ApiController> _logger,
IHttpContextAccessor _httpContextAccessor, IWebHostEnvironment hostingEnv,
GBDDataContext _gBDDataContext, Func<GBDDataContext> _gBDDataContextFactory)
{
context = _context;
gBDDataContext = _gBDDataContext;
logger = _logger;
httpContextAccessor = _httpContextAccessor;
HostingEnv = hostingEnv;
gBDDataContextFactory = _gBDDataContextFactory;
}
/// <summary>
/// context为空的时候,初始化
/// </summary>
public void InitialDBContext()
{
//string connectionStr = AppSettings.app("ConnectionStrings", "GBDDataContext");
解密
//string encryptPwd = connectionStr.Split(";pwd=")[1].Split(";")[0];
//string decriptPwd = AESHelper.Decrypt(encryptPwd, "12345678876543211234567887654abc");
//connectionStr = connectionStr.Replace(encryptPwd, decriptPwd);
//var dbContextOptions = new DbContextOptionsBuilder<GBDDataContext>().UseSqlServer(connectionStr).Options;
//gBDDataContext = new GBDDataContext(dbContextOptions);
}
[HttpGet]
[Route("GetLoginName")]
public ActionResult GetLoginName()
{
UserDto result = new UserDto();
try
{
//文件夹报表权限存入缓存
RedisValue redisValue = RedisClient.db.StringGet("POWERBI:ISFIRST");
if (string.IsNullOrWhiteSpace((string)redisValue))
{
SaveFolderRightToRedis();
}
PnWebService pnWeb = new PnWebService();
//var userName = GetUserName(User.Identity.Name);
result.UserRole = 0;
RedisValue[] redisValuesUserName = RedisClient.db.SetMembers("POWERBI:FOLDERREPORTUSER:RIGHT:" + userName.ToUpper());
if (redisValuesUserName != null && redisValuesUserName.Any())
{
result.UserId = ((string)redisValuesUserName[0]).Split('#')[2];
result.UserName = userName.ToUpper();
}
//ApiResponse message = pnWeb.GetLoginName(userName);
//if (message.Success)
//{
// var svar = Newtonsoft.Json.Linq.JObject.Parse(message.Message);
// result.UserId = (string)svar["Id"];
// result.UserName = (string)svar["Username"];
//}
logger.Log(LogLevel.Information, "用户:" + userName + "登录了bi系统");
result.AesName = AESHelper.Encrypt(userName.Trim(), "12345678876543211234567887654abc");
//var IsRole = context.CustomAppInfo.Any(t => t.AuthUser == result.UserName);
var IsAdminRole = context.CustomAdminInfo.Any(t => (t.UserName) == result.UserName);
if (IsAdminRole)
{
result.UserRole = UserRole.SystemAdmin;
}
//不是系统管理员,默认为浏览者,内容管理员
else
{
result.UserRole = UserRole.Users;
}
RedisClient.db.StringSet("POWERBI:USERIDROLE" + userName.ToUpper(), result.UserId + "#" + (int)result.UserRole);
}
catch(Exception ex)
{
logger.Log(LogLevel.Error, "GetLoginName:" + ex.ToString());
}
return Json((result));
}
//定时,一个小时更新一次
private Timer redisTimer = new Timer(60 * 60000);
private static bool isFirstRun = false;
/// <summary>
/// 用户是否存在用户表中
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
[HttpGet]
[Route("UserExistInTable")]
public ActionResult UserExistInTable()
{
//设置定时器属性
redisTimer.Elapsed += RedisTimer_Elapsed;
redisTimer.AutoReset = true;
redisTimer.Enabled = true;
if (!isFirstRun)
{
isFirstRun = true;
foreach (Users item in context.Users)
{
RedisClient.db.StringSet(item.UserName.ToUpper(), item.UserType);
}
}
bool result = false;
string userType = RedisClient.db.StringGet(userName.ToUpper());
if (!string.IsNullOrWhiteSpace(userType))
{
result = true;
}
return Json(result);
}
/// <summary>
/// 参数是用户邮箱,分号分隔
/// </summary>
/// <param name="userNameList"></param>
/// <returns></returns>
[HttpPost]
[Route("CheckEmail")]
public ActionResult CheckEmail([FromForm]string userNameList)
{
string result = string.Empty;
try
{
string[] userNameArr = userNameList.Split(';');
if (userNameArr != null && userNameArr.Any())
{
foreach (string uName in userNameArr)
{
if(!uName.Contains("@"))
{
result += uName + "不存在;";
}
else
{
bool isContains = RedisClient.db.SetContains("POWERBI:SETALLUSERANDGROUPTOREDIS:GLOBAL", "POWERBI:SETALLUSERANDGROUPTOREDIS:" + uName.ToUpper());
if (!isContains)
{
result += uName + "不存在;";
}
}
}
}
}
catch (Exception ex)
{
}
return Json(result);
}
private void RedisTimer_Elapsed(object sender, ElapsedEventArgs e)
{
foreach (Users item in context.Users)
{
RedisClient.db.StringSet(item.UserName.ToUpper(), item.UserType);
}
}
private string GetUserName(string user)
{
if (!string.IsNullOrEmpty(user))
{
var index = user.LastIndexOf('\\');
var userName = user.Substring(index + 1, user.Length - index - 1);
return userName;
}
else
{
return "";
}
}
/// <summary>
/// 校验输入的UM
/// </summary>
/// <param name="Um"></param>
/// <returns></returns>
[HttpGet]
[Route("CheckUm")]
public ActionResult CheckUm([FromQuery] string Um)
{
if(string.IsNullOrWhiteSpace(Um))
{
Json(new ApiResponse { Success = false, Message = Um.ToUpper() + " is not found" });
}
bool isContains = RedisClient.db.SetContains("POWERBI:SETALLUSERANDGROUPTOREDIS:GLOBAL", "POWERBI:SETALLUSERANDGROUPTOREDIS:" + Um.ToUpper());
if (isContains)
{
return Json(new ApiResponse { Success = true, Message = Um.ToUpper() + " is Ok" });
}
return Json(new ApiResponse { Success = false, Message = Um.ToUpper() + " is not found" });
}
/// <summary>
/// 批量校验输入的um
/// </summary>
/// <param name="userNameList"></param>
/// <returns></returns>
[HttpPost]
[Route("CheckUmBatch")]
public ActionResult CheckUmBatch([FromForm] string userNameList)
{
string result = string.Empty;
bool isValid = true;
try
{
string[] userNameArr = userNameList.Split(';');
if (userNameArr != null && userNameArr.Any())
{
foreach(string uName in userNameArr)
{
if (uName.Contains("@"))
{
isValid = false;
result += uName + ";";
}
else
{
bool isContains = RedisClient.db.SetContains("POWERBI:SETALLUSERANDGROUPTOREDIS:GLOBAL", "POWERBI:SETALLUSERANDGROUPTOREDIS:" + uName.ToUpper().Trim());
if (!isContains)
{
isValid = false;
result += uName + ";";
}
}
}
if (!isValid)
{
result += "不存在";
}
}
}
catch (Exception ex)
{
logger.Log(LogLevel.Error, ex.ToString());
}
return Json(result);
}
/// <summary>
/// 添加AppName
/// </summary>
/// <param name="customApp"></param>
/// <returns></returns>
[HttpPost]
[Route("AddApp")]
public ActionResult AddApp([FromForm] CustomAppInfo customApp)
{
try
{
PnWebService pnWeb = new PnWebService();
string cataLogItem = "{\"@odata.type\":\"#Model.Folder\",\"Name\":\"" + customApp.AppName + "\",\"Path\":\"/" + customApp.AppName + "\"}";
var NewCatalogResJson = pnWeb.NewCatalogItem(cataLogItem, userName);
if (!NewCatalogResJson.Success)
{
return Json(new ApiResponse { Success = false, Message = NewCatalogResJson.Message });
}
var CataIDArray = NewCatalogResJson.Message.ToString().Split("\"Id\":");
string CataIdTmp = "";
CataIdTmp = CataIDArray[1].Split("\"")[1];
Guid CataId = Guid.Parse(CataIdTmp);
//添加缓存
List<PoliciesContext> result = CreateFolderAddRedis(true, CataIdTmp, pnWeb, cataLogItem, "2", customApp.AuthUser);
string appCode = "PB00001";
if (context.CustomAppInfo.Count() != 0)
{
string oldAppCode = context.CustomAppInfo.OrderByDescending(t => t.AppCode).ToList()[0].AppCode;
int count = int.Parse(oldAppCode.Substring(2)) + 1;
appCode = "PB" + count.ToString().PadLeft(5, '0');
}
CustomAppInfo appInfo = new CustomAppInfo();
appInfo.CreateDateTime = DateTime.Now;
appInfo.UpdateDateTime = DateTime.Now;
appInfo.AppCode = appCode;
appInfo.AppName = customApp.AppName;
appInfo.AuthUser = customApp.AuthUser;
appInfo.CataId = CataId;
appInfo.AppId = Guid.NewGuid();
appInfo.CreateUser = userName;
appInfo.UpdateUser = userName;
if (context.CustomAppInfo.Any(o => o.AppName == appInfo.AppName))
{
return Json(new ApiResponse { Success = false, Message = "AppName repetition" });
}
//if (context.CustomAppInfo.Any(o => o.AppCode == appCode))
//{
// return Json(new ApiResponse { Success = false, Message = "AppCode repetition" });
//}
if (context.CustomAppInfo.Any(o => o.CataId == appInfo.CataId))
{
return Json(new ApiResponse { Success = false, Message = "CataId repetition" });
}
context.CustomAppInfo.Add(appInfo);
context.SaveChanges();
}
catch (Exception ex)
{
logger.Log(LogLevel.Error, "AddApp exception:" + ex.ToString());
return Json(new ApiResponse { Success = false, Message = ex.Message });
}
return Json(new ApiResponse { Success = true, Message = "Success" });
}
/// <summary>
/// 删除AppName
/// </summary>
/// <param name="userGroups"></param>
/// <returns></returns>
[HttpPost]
[Route("DeleteApp")]
public ActionResult DeleteApp([FromForm] string[] userGroups)
{
var result = userGroups;
var DataPolicy = context.PolicyUserRole.ToList();
List<PolicyUserRole> policies = new List<PolicyUserRole>();
if (result.Count() > 0)
{
try
{
for (int i = 0; i < result.Length; i++)
{
if (CheckPurId(result[i]))
{
policies.AddRange(context.PolicyUserRole.Where(t => t.Id.ToString() == result[i]).ToList());
}
}
if (policies.Count < 0)
{
return Json(new ApiResponse { Success = false, Message = "请选择要删除的内容" });
}
context.PolicyUserRole.RemoveRange(policies);
context.SaveChanges();
}
catch (Exception ex)
{
logger.LogInformation(ex.Message);
throw;
}
return Json(new ApiResponse { Success = true, Message = "ok" });
}
else
{
return Json(new ApiResponse { Success = false, Message = "请选择要删除的AppName" });
}
}
private bool CheckPurId(string PurId)
{
if (string.IsNullOrEmpty(PurId))
{
return false;
}
else
{
var result = context.PolicyUserRole.Where(t => t.Id.ToString() == PurId).ToList();
if (result.Count > 0)
{
return true;
}
else
{
return false;
}
}
}
//[Obsolete]
//[HttpGet]
//[Route("GetRootFolder")]
//public JsonResult GetRootFolders()
//{
// PnWebService help = new PnWebService();
// var data = help.InitFolder(Administrator, password);
// var rootpath = help.Filter(data, null, Report.type.ParentFolderId);
// return Json(help.Filter(data, rootpath[0].Id, Report.type.ParentFolderId));
//}
/// <summary>
/// 获取一级目录
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("GetFoldersByUm")]
public ActionResult GetFoldersByUm()
{
PnWebService pnWebService = new PnWebService();
var result = pnWebService.InitsFolder(userName);
return Json(result);
}