Beispiel #1
0
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <returns></returns>
        public int Delete()
        {
            IEnumerable <KeyValuePair <string, PropertyInfo> > keys = this.Keys();

            string sql = $"DELETE {this.GetTableName()} WHERE 1=1 {BuildCondition(keys)}";

            return(TwinkleContext.GetRequiredService <DatabaseManager>().ExecuteNonQuery(sql, BuildDataParameter(keys)));
        }
        public BaseController()
        {
            Db            = TwinkleContext.GetRequiredService <DatabaseManager>();
            Auth          = TwinkleContext.GetService <TokenAuthManager>().GetUser(TwinkleContext.UserToken) ?? new AuthUser();
            Auth.TenantId = "0000000000";// 暂时没有多租户模块 给予一个默认租户编码

            Logger = GetLogger((dynamic)this);
        }
Beispiel #3
0
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            string token    = this.Context.GetHttpContext().Request.Cookies["access-token"];
            object userData = TwinkleContext.GetService <TokenAuthManager>().GetUser(token);

            if (userData != null)
            {
                RemoveClient((dynamic)this, JToken.Parse(userData.ToString()).Value <string>("uid"));
            }
            await base.OnDisconnectedAsync(exception);
        }
        private IOnlineClient CreateClientForCurrentConnection(string token)
        {
            AuthUser user = TwinkleContext.GetService <TokenAuthManager>().GetUser(token);

            return(new OnlineClient
            {
                ConnectionId = Context.ConnectionId,
                TenantId = user.TenantId,
                UserId = user.UserId
            });
        }
Beispiel #5
0
        public void SendNotify()
        {
            IRealTimeNotifier rtf = TwinkleContext.GetService <IRealTimeNotifier>();

            rtf.SendNotificationsAsync(new UserNotification[] {
                new UserNotification {
                    UserId = "admin", Data = new NotifyData {
                        Channel = "test", Data = new { key = "key", num = 2 }
                    }
                }
            });
        }
Beispiel #6
0
        /// <summary>
        /// 根据非主键信息创建赋值字符串
        /// </summary>
        /// <param name="generals">非主键集合</param>
        /// <returns></returns>
        private int Update(IEnumerable <KeyValuePair <string, PropertyInfo> > keys, IEnumerable <KeyValuePair <string, PropertyInfo> > generals)
        {
            if (keys.Count() == 0)
            {
                throw new KeyNotFoundException("无主键信息");
            }
            if (generals.Count() == 0)
            {
                throw new KeyNotFoundException("无字段信息");
            }


            string update = string.Empty;

            foreach (KeyValuePair <string, PropertyInfo> item in generals)
            {
                ModelPropertyAttribute mpa = item.Value.GetCustomAttribute <ModelPropertyAttribute>(false);
                if (mpa != null && (mpa.Identity || mpa.OnlyInsert))
                {
                    continue;
                }
                update += $", {item.Key}=@{item.Key}";
            }
            update = $"UPDATE {GetTableName()} SET {update.TrimStart(',')} WHERE 1=1 {BuildCondition(keys)}";

            //拼接主键和普通属性,并移除非Key的Identity属性
            IEnumerable <KeyValuePair <string, PropertyInfo> > allKeys = keys.Union(generals).Where(item =>
            {
                ModelPropertyAttribute mpa = item.Value.GetCustomAttribute <ModelPropertyAttribute>(false);
                if (mpa == null)
                {
                    return(true);
                }
                else
                {
                    if (mpa.Identity && !mpa.Key)
                    {
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                }
            });

            return(TwinkleContext.GetRequiredService <DatabaseManager>().ExecuteNonQuery(update, BuildDataParameter(allKeys)));
        }
Beispiel #7
0
        /// <summary>
        /// 执行插入操作
        /// </summary>
        /// <param name="keys">主键集合</param>
        /// <param name="generals">非主键集合</param>
        /// <returns></returns>
        private int Insert(IEnumerable <KeyValuePair <string, PropertyInfo> > keys, IEnumerable <KeyValuePair <string, PropertyInfo> > generals)
        {
            PropertyInfo identityKey = null;
            //拼接主键和普通属性,并移除Identity属性
            IEnumerable <KeyValuePair <string, PropertyInfo> > allKey = keys.Union(generals).Where(item =>
            {
                ModelPropertyAttribute mpa = item.Value.GetCustomAttribute <ModelPropertyAttribute>(false);
                if (mpa == null)
                {
                    return(true);
                }
                else if (mpa.Identity)
                {
                    identityKey = item.Value;
                    return(false);
                }
                else
                {
                    return(true);
                }
            });

            if (allKey.Count() == 0)
            {
                throw new KeyNotFoundException("无字段信息");
            }

            string insert       = string.Empty;
            string insertValues = string.Empty;

            foreach (KeyValuePair <string, PropertyInfo> item in allKey)
            {
                insert       += $",{item.Key}";
                insertValues += $",@{item.Key}";
            }

            insert  = $"INSERT INTO {GetTableName()}({insert.TrimStart(',')}) VALUES({insertValues.TrimStart(',')});";
            insert += "SELECT @@Identity";//获取自增长列的值
            int result = TwinkleContext.GetRequiredService <DatabaseManager>().ExecuteInteger(insert, BuildDataParameter(allKey));

            if (identityKey != null)
            {
                identityKey.SetValue(this, Convert.ChangeType(result.ToString(), (Nullable.GetUnderlyingType(identityKey.PropertyType) == null ? identityKey.PropertyType : Nullable.GetUnderlyingType(identityKey.PropertyType))));
            }
            return(result);
        }
Beispiel #8
0
        /// <summary>
        /// 检测实体在数据库中是否存在(根据主键判断)
        /// </summary>
        /// <returns></returns>
        public bool Exists()
        {
            IEnumerable <KeyValuePair <string, PropertyInfo> > keys = this.Keys();

            if (keys.Count() == 0)
            {
                throw new KeyNotFoundException("未找到主键信息,无法操作");
            }

            string sql = $"SELECT COUNT(1) FROM {this.GetTableName()} WHERE 1=1 {BuildCondition(keys)}";

            if (TwinkleContext.GetRequiredService <DatabaseManager>().ExecuteInteger(sql, BuildDataParameter(keys)) > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #9
0
 public override async Task OnConnectedAsync()
 {
     if (this.Context.GetHttpContext().Request.Cookies.ContainsKey("accessToken"))
     {
         string token = this.Context.GetHttpContext().Request.Cookies["accessToken"];
         User   user  = TwinkleContext.GetService <TokenAuthManager>().GetUser(token);
         if (user != null && TwinkleContext.GetService <TokenAuthManager>().IsValid(token))
         {
             HubClient client = new HubClient
             {
                 ConnectionId = this.Context.ConnectionId,
                 AccountId    = user.UserId
             };
             AddClient((dynamic)this, client);
         }
     }
     else
     {
         throw new Exception("授权无效,或已过期");
     }
     await base.OnConnectedAsync();
 }
Beispiel #10
0
        private void SendToClient(ReportArgs args, int status = 0)
        {
            string token = TwinkleContext.UserToken;

            AuthUser user = TwinkleContext.GetService <TokenAuthManager>().GetUser(token);

            IRealTimeNotifier rtf = TwinkleContext.GetService <IRealTimeNotifier>();

            rtf.SendNotificationsAsync(new UserNotification[] {
                new UserNotification {
                    TenantId = user.TenantId,
                    UserId   = user.UserId,
                    Data     = new NotifyData {
                        Channel = "signalr.reveive",
                        Data    = new {
                            uploadId = TwinkleContext.HttpContext.Request.Form["uploadId"].ToString(),//有待测试验证
                            message  = args.Message,
                            status   = args.Status
                        }
                    }
                }
            });
        }
        public void OnException(ExceptionContext context)
        {
            var             logger = TwinkleContext.GetService <ILogger <ExceptionFilter> >();
            DatabaseManager Db     = TwinkleContext.GetRequiredService <DatabaseManager>();

            if (context.ExceptionHandled == false)
            {
                string msg = context.Exception.Message;

                if (Db.Transaction != null)
                {
                    Db.Rollback();
                }

                logger.LogError($"{string.Join("/", context.RouteData.Values.Values)} - {msg}");

                context.Result = new JsonResult(new { status = 1, msg })
                {
                    StatusCode  = StatusCodes.Status200OK,
                    ContentType = "text/html;charset=utf-8"
                };
            }
            context.ExceptionHandled = true; // 标记已经被处理 不再冒泡
        }
Beispiel #12
0
        public JsonResult Login(ClientModel client)
        {
            string UserId   = client.GetString("UserId");
            string Password = client.GetString("Password");

            string tenantId = this.Auth.TenantId;// 后期 tenantId 一般会是从登陆界面带过来

            Sys_User user = Db.ExecuteEntity <Sys_User>("SELECT * FROM Sys_User WHERE UserId=@UserId and TenantId=@TenantId", new { UserId, TenantId = tenantId });

            if (user == null)
            {
                return(Json(new
                {
                    status = 1,
                    msg = "账号不存在."
                }));
            }

            user.cLoginIP = this.Request.HttpContext.Connection.RemoteIpAddress.ToString().Replace("::1", "127.0.0.1");


            if (user.cPassword != DataCipher.MD5Encrypt(user.UserId + user.cNonceStr + Password))
            {
                if (user.dUnlockDate > DateTime.Now)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "账户已经被锁定,请稍后再试或联系管理员."
                    }));
                }

                if ((DateTime.Now - (user.dLoginDate ?? DateTime.MinValue)).TotalMinutes > 30)
                {
                    user.nFailedCount = 0;
                }

                user.nFailedCount = (user.nFailedCount ?? 0) + 1;

                if (user.nFailedCount == 5)
                {
                    user.dUnlockDate = DateTime.Now.AddMinutes(20);
                }
                else
                {
                    user.dUnlockDate = null;
                }

                Db.ExecuteNonQuery("UPDATE Sys_User SET cLoginIP = @cLoginIP,dLoginDate = GETDATE(),nFailedCount =@nFailedCount,dUnlockDate=@dUnlockDate WHERE UserId=@UserId AND TenantId=@TenantId", user);

                if (user.nFailedCount == 5)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "由于多次密码错误,账号已经被锁定,请20分钟后重试."
                    }));
                }
                else
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = $"账号或密码错误,无法登陆,还可尝试 {5 - user.nFailedCount} 次."
                    }));
                }
            }
            else
            {
                if (user.dUnlockDate > DateTime.Now)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "账户已经被锁定,请稍后再试或联系管理员."
                    }));
                }

                if (user.iStatus == 0)
                {
                    return(Json(new
                    {
                        status = 1,
                        msg = "账户已经被停用,请联系管理员."
                    }));
                }

                user.nFailedCount = 0;
                user.dUnlockDate  = null;

                Db.ExecuteNonQuery("UPDATE Sys_User SET cLoginIP = @cLoginIP,dLoginDate = GETDATE(),nFailedCount =@nFailedCount WHERE UserId=@UserId AND TenantId=@TenantId", user);

                TwinkleContext.Login(new AuthUser {
                    UserId = UserId, TenantId = tenantId
                });
                return(Json(new
                {
                    status = 0,
                    userId = UserId,
                    tenantId,
                }));
            }
        }
Beispiel #13
0
 public JsonResult Logout()
 {
     TwinkleContext.Logout();
     return(Json(new { status = 0 }));
 }
 private ILogger GetLogger <T>(T controller)
 {
     return(TwinkleContext.GetService <ILogger <T> >());
 }
Beispiel #15
0
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var       items     = context.HttpContext.Items;
            long?     duration  = null;
            Stopwatch stopWatch = items[keyDur] as Stopwatch;

            stopWatch?.Stop();
            duration = stopWatch?.ElapsedMilliseconds;

            DateTime start = (DateTime)items[keyStart];

            string paramJson = string.Empty;

            IDictionary <string, object> parameters = items[keyParam] as IDictionary <string, object>;

            if (parameters != null)
            {
                if (parameters.Count == 1)
                {
                    ClientModel cm = parameters.FirstOrDefault().Value as ClientModel;
                    if (cm != null)
                    {
                        paramJson = cm.GetClientParams().ToString();
                    }
                    else
                    {
                        paramJson = JToken.FromObject(parameters).ToString();
                    }
                }
                else if (parameters.Count > 1)
                {
                    paramJson = JToken.FromObject(parameters).ToString();
                }
            }


            var user = TwinkleContext.User;

            DatabaseManager db = TwinkleContext.GetService <DatabaseManager>();

            db.ExecuteNonQuery(@"INSERT INTO OperationLogs
              (
                TenantId
               ,UserId
               ,Area
               ,Controller
               ,[Action]
               ,[Parameters]
               ,ExecutionTime
               ,ExecutionDuration
               ,ClientIpAddress
               ,ClientName
               ,BrowserInfo
               ,Exception
              )
            VALUES
              (
                @TenantId
               ,@UserId
               ,@Area
               ,@Controller
               ,@Action
               ,@Parameters
               ,@ExecutionTime
               ,@ExecutionDuration
               ,@ClientIpAddress
               ,@ClientName
               ,@BrowserInfo
               ,@Exception
              )", new
            {
                user?.TenantId,
                user?.UserId,
                Area              = context.RouteData.Values["area"]?.ToString(),
                Controller        = context.RouteData.Values["controller"]?.ToString(),
                Action            = context.RouteData.Values["action"]?.ToString(),
                Parameters        = paramJson,
                ExecutionTime     = start,
                ExecutionDuration = duration,
                ClientIpAddress   = context.HttpContext.Connection.RemoteIpAddress.ToString().Replace("::1", "127.0.0.1"),
                ClientName        = "",
                BrowserInfo       = context.HttpContext.Request.Headers["User-Agent"],
                Exception         = context.Exception?.Message
            });
        }