Example #1
0
        public void ReviveChannel(ProtectedOperationContext ctx, ITradeSharpServerCallback callback,
                                  string address, string login, int accountId, string terminalVersion)
        {
            int    userId;
            string password;
            var    response = CheckCredentials(login, out password, out userId);

            if (response != AuthenticationResponse.OK)
            {
                return;
            }

            try
            {
                sessionLocker.AcquireWriterLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("ReviveChannel - unable to get writer lock to session storage");
                return;
            }
            try
            {
                UserSession session;
                sessions.TryGetValue(ctx.terminalId, out session);
                // сессия еще жива
                if (session != null)
                {
                    session.callback  = callback;
                    session.accountId = accountId;
                    return;
                }
                // создать новую сессию
                session = new UserSession
                {
                    ip = address,
                    lastRequestClientTime = ctx.clientLocalTime,
                    login           = login,
                    accountId       = accountId,
                    loginTime       = DateTime.Now,
                    sessionTag      = (int)(DateTime.Now.Ticks / 3),
                    terminalId      = ctx.terminalId,
                    callback        = callback,
                    enabledAccounts = GetUserAccounts(userId),
                    terminalVersion = terminalVersion
                };
                sessions.Add(ctx.terminalId, session);
            }
            catch (Exception ex)
            {
                Logger.Error("ReviveChannel - error", ex);
            }
            finally
            {
                sessionLocker.ReleaseWriterLock();
            }
        }
Example #2
0
        public TradeSharpServerTradeProxy(string endpointName, ITradeSharpServerCallback callback)
        {
            this.endpointName = endpointName;
            this.callback     = callback;
            RenewChannel();

            // сериализаторы
            SerializationWriter.TypeSurrogates.Add(new MarketOrderSerializer());
        }
        private static bool DeliverResponse(ITradeSharpServerCallback callback, TradeSharpClientResponse resp, out Exception exception)
        {
            exception = null;
            try
            {
                switch (resp.responseType)
                {
                case TradeSharpClientResponseType.NewOrder:
                    callback.NewOrderResponse((MarketOrder)resp.ticket, resp.status, resp.detailMessage);
                    break;

                case TradeSharpClientResponseType.NewPendingOrder:
                    callback.NewPendingOrderResponse((PendingOrder)resp.ticket, resp.status, resp.detailMessage);
                    break;

                case TradeSharpClientResponseType.CloseOrder:
                    callback.NewCloseOrderResponse((MarketOrder)resp.ticket, resp.status, resp.detailMessage);
                    break;

                case TradeSharpClientResponseType.EditOrder:
                    callback.EditOrderResponse((MarketOrder)resp.ticket, resp.status, resp.detailMessage);
                    break;

                case TradeSharpClientResponseType.EditPendingOrder:
                    callback.EditPendingOrderResponse((PendingOrder)resp.ticket, resp.status, resp.detailMessage);
                    break;

                //case TradeSharpClientResponseType.TradeSignalAction :
                //    callback.ProcessTradeSignalAction((TradeSignalAction)resp.ticket);
                //    break;
                default: break;
                }
            }
            catch (TimeoutException ex)
            {
                Logger.Error("ServiceManagerClientManagerProxy.DeliverResponse TimeoutException", ex);
                exception = ex;
                return(false);
            }
            catch (CommunicationObjectAbortedException ex)
            {
                Logger.Error("ServiceManagerClientManagerProxy.DeliverResponse CommunicationObjectAbortedException", ex);
                exception = ex;
                return(false);
            }
            catch (Exception ex)
            {
                Logger.Error("ServiceManagerClientManagerProxy.DeliverResponse exception: " + ex.Message);
                exception = ex;
                return(false);
            }
            return(true);
        }
Example #4
0
 public TradeSharpServerTrade(ITradeSharpServerCallback callback)
 {
     try
     {
         proxyWCF = new TradeSharpServerTradeProxy(BindingName, callback);
         proxy    = proxyWCF;
     }
     catch (Exception ex)
     {
         Logger.Error("TradeSharpServerTrade ctor", ex);
     }
 }
Example #5
0
 public UserSession(UserSession speciman)
 {
     login = speciman.login;
     ip = speciman.ip;
     terminalId = speciman.terminalId;
     loginTime = speciman.loginTime;
     sessionTag = speciman.sessionTag;
     lastRequestClientTime = speciman.lastRequestClientTime;
     callback = speciman.callback;
     accountId = speciman.accountId;
     enabledAccounts = speciman.enabledAccounts.ToList();
     terminalVersion = speciman.terminalVersion;
     userId = speciman.userId;
 }
Example #6
0
 public UserSession(UserSession speciman)
 {
     login                 = speciman.login;
     ip                    = speciman.ip;
     terminalId            = speciman.terminalId;
     loginTime             = speciman.loginTime;
     sessionTag            = speciman.sessionTag;
     lastRequestClientTime = speciman.lastRequestClientTime;
     callback              = speciman.callback;
     accountId             = speciman.accountId;
     enabledAccounts       = speciman.enabledAccounts.ToList();
     terminalVersion       = speciman.terminalVersion;
     userId                = speciman.userId;
 }
Example #7
0
 public TradeSharpServerTradeProxyNs(string endpointName, ITradeSharpServerCallback callback)
     : base(callback, endpointName)
 {
 }
        private static bool DeliverResponse(ITradeSharpServerCallback callback, TradeSharpClientResponse resp, out Exception exception)
        {
            exception = null;
            try
            {
                switch (resp.responseType)
                {
                    case TradeSharpClientResponseType.NewOrder:
                        callback.NewOrderResponse((MarketOrder)resp.ticket, resp.status, resp.detailMessage);
                        break;

                    case TradeSharpClientResponseType.NewPendingOrder:
                        callback.NewPendingOrderResponse((PendingOrder)resp.ticket, resp.status, resp.detailMessage);
                        break;

                    case TradeSharpClientResponseType.CloseOrder:
                        callback.NewCloseOrderResponse((MarketOrder)resp.ticket, resp.status, resp.detailMessage);
                        break;
                    case TradeSharpClientResponseType.EditOrder:
                        callback.EditOrderResponse((MarketOrder)resp.ticket, resp.status, resp.detailMessage);
                        break;
                    case TradeSharpClientResponseType.EditPendingOrder:
                        callback.EditPendingOrderResponse((PendingOrder)resp.ticket, resp.status, resp.detailMessage);
                        break;
                    //case TradeSharpClientResponseType.TradeSignalAction :
                    //    callback.ProcessTradeSignalAction((TradeSignalAction)resp.ticket);
                    //    break;
                    default: break;
                }
            }
            catch (TimeoutException ex)
            {
                Logger.Error("ServiceManagerClientManagerProxy.DeliverResponse TimeoutException", ex);
                exception = ex;
                return false;
            }
            catch (CommunicationObjectAbortedException ex)
            {
                Logger.Error("ServiceManagerClientManagerProxy.DeliverResponse CommunicationObjectAbortedException", ex);
                exception = ex;
                return false;
            }
            catch (Exception ex)
            {
                Logger.Error("ServiceManagerClientManagerProxy.DeliverResponse exception: " + ex.Message);
                exception = ex;
                return false;
            }
            return true;
        }
Example #9
0
        /// <summary>
        /// вернуть тег сессии клиента, передаваемый затем в последующих запросах
        /// </summary>
        public AuthenticationResponse Authenticate(string login, string hashString,
                                                   string terminalVersion,
                                                   long clientLocalTime, long terminalId, string address, ITradeSharpServerCallback callback,
                                                   out int sessionTag)
        {
            sessionTag = 0;

            // проверка параметров
            if (string.IsNullOrEmpty(login))
            {
                return(AuthenticationResponse.InvalidAccount);
            }
            if (string.IsNullOrEmpty(hashString))
            {
                return(AuthenticationResponse.WrongPassword);
            }
            if (terminalId == 0)
            {
                Logger.Info("AuthenticationResponse usr (" + login + "): terminal Id is 0");
                return(AuthenticationResponse.InvalidAccount);
            }
            if (clientLocalTime == 0)
            {
                Logger.Info("AuthenticationResponse usr (" + login + "): clientLocalTime is 0");
                return(AuthenticationResponse.InvalidAccount);
            }

            // получить пользователя и его роль по логину
            string password;
            int    userId;
            var    response = CheckCredentials(login, out password, out userId);

            if (response != AuthenticationResponse.OK)
            {
                return(response);
            }

            // проверить хеш из логина, пароля и локального времени клиента
            var userHash = CredentialsHash.MakeCredentialsHash(login, password, clientLocalTime);

            if (hashString != userHash)
            {
                return(AuthenticationResponse.WrongPassword);
            }

            // проверить наличие сессии
            try
            {
                sessionLocker.AcquireWriterLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("Authenticate - unable to get writer lock to session storage");
                return(AuthenticationResponse.ServerError);
            }
            try
            {
                UserSession session;
                sessions.TryGetValue(terminalId, out session);
                // сессия еще жива
                if (session != null)
                {
                    session.lastRequestClientTime = clientLocalTime;
                    session.callback        = callback;
                    sessionTag              = session.sessionTag;
                    session.enabledAccounts = GetUserAccounts(userId);
                    return(AuthenticationResponse.OK);
                }
                // создать новую сессию
                session = new UserSession
                {
                    ip = address,
                    lastRequestClientTime = clientLocalTime,
                    login           = login,
                    loginTime       = DateTime.Now,
                    sessionTag      = (int)(DateTime.Now.Ticks / 3),
                    terminalId      = terminalId,
                    callback        = callback,
                    enabledAccounts = GetUserAccounts(userId),
                    terminalVersion = terminalVersion,
                    userId          = userId
                };
                sessions.Add(terminalId, session);
                sessionTag = session.sessionTag;
                return(AuthenticationResponse.OK);
            }
            catch (Exception ex)
            {
                Logger.Error("UserSessionStorage - error in Authenticate", ex);
                return(AuthenticationResponse.ServerError);
            }
            finally
            {
                sessionLocker.ReleaseWriterLock();
            }
        }
Example #10
0
        /// <summary>
        /// сравнить переданные в запросе на торговую операцию параметры
        /// с переданным хэш-отпечатком, найти запись в хранилище сессий,
        /// обновить ее
        /// второй параметр опциональный
        /// </summary>
        public bool PermitUserOperation(ProtectedOperationContext ctx,
                                        ITradeSharpServerCallback callback, int?accountId, string login, bool isTradeOperation, bool checkAccountId)
        {
            // отправитель - сервер?
            if (ctx == null)
            {
                Logger.ErrorFormat("PermitUserOperation - login is \"{0}\" - no context", login);
                return(false);
            }
            if (ProtectedOperationContext.IsServerContext(ctx))
            {
                return(true);
            }

            var userHash = CredentialsHash.MakeOperationParamsHash(ctx.clientLocalTime, ctx.sessionTag, ctx.terminalId);

            if (ctx.hash != userHash)
            {
                Logger.InfoFormat("[{0: {1}] - hash is incorrect ({2}, correct hash: {3})",
                                  login, accountId, ctx, userHash);
                return(false);
            }
            // найти сессию
            try
            {
                sessionLocker.AcquireReaderLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("PermitUserOperation read timout");
                return(false);
            }
            try
            {
                UserSession session;
                sessions.TryGetValue(ctx.terminalId, out session);
                if (session == null)
                {
                    return(false);
                }
                if (!string.IsNullOrEmpty(login))
                {
                    if (login != session.login)
                    {
                        Logger.InfoFormat("Session #{0}: login ({1}) != session login ({2})",
                                          ctx.terminalId, login, session.login);
                        return(false);
                    }
                }

                // обновить сессию
                try
                {
                    sessionLocker.UpgradeToWriterLock(SessionLockTimeout);
                }
                catch (ApplicationException)
                {
                    Logger.Error("PermitUserOperation write timout");
                    return(false);
                }
                if (accountId.HasValue || checkAccountId)
                {
                    var targetAccount = accountId ?? session.accountId;
                    var accountRights = session.enabledAccounts.FirstOrNull(a => a.a == targetAccount);
                    // дополнительно проверяется, есть ли права на торговую (или иную защищенную) операцию
                    var hasRights = accountRights.HasValue && (accountRights.Value.b || !isTradeOperation);
                    if (!hasRights)
                    {
                        Logger.InfoFormat("User {0} #{1} has insufficient rights (trade op: {2}, session: {3} / {4})",
                                          login, targetAccount, isTradeOperation, ctx.terminalId,
                                          string.Join(",", session.enabledAccounts.Select(a => string.Format("{0}:{1}",
                                                                                                             a.a, a.b ? "en" : "dis"))));
                        //Logger.Error("PermitUserOperation: возврат false, session.enabledAccounts.Contains счет " +
                        //             session.accountId);
                        return(false);
                    }
                }
                // прописать счет для сессии
                if (accountId.HasValue)
                {
                    session.accountId = accountId.Value;
                    Logger.Info("PermitUserOperation: Успешная смена счета " + accountId.Value);
                }
                session.lastRequestClientTime = ctx.clientLocalTime;
                if (callback != null)
                {
                    session.callback = callback;
                }
                // доступ разрешен
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Error("PermitUserOperation error", ex);
                return(false);
            }
            finally
            {
                sessionLocker.ReleaseLock();
            }
        }
Example #11
0
 public bool PermitUserOperation(ProtectedOperationContext ctx, ITradeSharpServerCallback callback, bool isTradeOperation, bool checkAccountId)
 {
     return(PermitUserOperation(ctx, callback, null, null, isTradeOperation, checkAccountId));
 }
        /// <summary>
        /// вернуть тег сессии клиента, передаваемый затем в последующих запросах
        /// </summary>
        public AuthenticationResponse Authenticate(string login, string hashString, 
            string terminalVersion,
            long clientLocalTime, long terminalId, string address, ITradeSharpServerCallback callback,
            out int sessionTag)
        {
            sessionTag = 0;

            // проверка параметров
            if (string.IsNullOrEmpty(login)) return AuthenticationResponse.InvalidAccount;
            if (string.IsNullOrEmpty(hashString)) return AuthenticationResponse.WrongPassword;
            if (terminalId == 0)
            {
                Logger.Info("AuthenticationResponse usr (" + login + "): terminal Id is 0");
                return AuthenticationResponse.InvalidAccount;
            }
            if (clientLocalTime == 0)
            {
                Logger.Info("AuthenticationResponse usr (" + login + "): clientLocalTime is 0");
                return AuthenticationResponse.InvalidAccount;
            }

            // получить пользователя и его роль по логину
            string password;
            int userId;
            var response = CheckCredentials(login, out password, out userId);
            if (response != AuthenticationResponse.OK) return response;

            // проверить хеш из логина, пароля и локального времени клиента
            var userHash = CredentialsHash.MakeCredentialsHash(login, password, clientLocalTime);
            if (hashString != userHash) return AuthenticationResponse.WrongPassword;

            // проверить наличие сессии
            try
            {
                sessionLocker.AcquireWriterLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("Authenticate - unable to get writer lock to session storage");
                return AuthenticationResponse.ServerError;
            }
            try
            {
                UserSession session;
                sessions.TryGetValue(terminalId, out session);
                // сессия еще жива
                if (session != null)
                {
                    session.lastRequestClientTime = clientLocalTime;
                    session.callback = callback;
                    sessionTag = session.sessionTag;
                    session.enabledAccounts = GetUserAccounts(userId);
                    return AuthenticationResponse.OK;
                }
                // создать новую сессию
                session = new UserSession
                              {
                                  ip = address,
                                  lastRequestClientTime = clientLocalTime,
                                  login = login,
                                  loginTime = DateTime.Now,
                                  sessionTag = (int) (DateTime.Now.Ticks/3),
                                  terminalId = terminalId,
                                  callback = callback,
                                  enabledAccounts = GetUserAccounts(userId),
                                  terminalVersion = terminalVersion,
                                  userId = userId
                              };
                sessions.Add(terminalId, session);
                sessionTag = session.sessionTag;
                return AuthenticationResponse.OK;
            }
            catch (Exception ex)
            {
                Logger.Error("UserSessionStorage - error in Authenticate", ex);
                return AuthenticationResponse.ServerError;
            }
            finally
            {
                sessionLocker.ReleaseWriterLock();
            }
        }
        public void ReviveChannel(ProtectedOperationContext ctx, ITradeSharpServerCallback callback, 
            string address, string login, int accountId, string terminalVersion)
        {
            int userId;
            string password;
            var response = CheckCredentials(login, out password, out userId);
            if (response != AuthenticationResponse.OK)
            {
                return;
            }

            try
            {
                sessionLocker.AcquireWriterLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("ReviveChannel - unable to get writer lock to session storage");
                return;
            }
            try
            {
                UserSession session;
                sessions.TryGetValue(ctx.terminalId, out session);
                // сессия еще жива
                if (session != null)
                {
                    session.callback = callback;
                    session.accountId = accountId;
                    return;
                }
                // создать новую сессию
                session = new UserSession
                {
                    ip = address,
                    lastRequestClientTime = ctx.clientLocalTime,
                    login = login,
                    accountId = accountId,
                    loginTime = DateTime.Now,
                    sessionTag = (int)(DateTime.Now.Ticks / 3),
                    terminalId = ctx.terminalId,
                    callback = callback,
                    enabledAccounts = GetUserAccounts(userId),
                    terminalVersion = terminalVersion
                };
                sessions.Add(ctx.terminalId, session);
            }
            catch (Exception ex)
            {
                Logger.Error("ReviveChannel - error", ex);
            }
            finally
            {
                sessionLocker.ReleaseWriterLock();
            }
        }
        /// <summary>
        /// сравнить переданные в запросе на торговую операцию параметры
        /// с переданным хэш-отпечатком, найти запись в хранилище сессий,
        /// обновить ее
        /// второй параметр опциональный
        /// </summary>
        public bool PermitUserOperation(ProtectedOperationContext ctx, 
            ITradeSharpServerCallback callback, int? accountId, string login, bool isTradeOperation, bool checkAccountId)
        {
            // отправитель - сервер?
            if (ctx == null)
            {
                Logger.ErrorFormat("PermitUserOperation - login is \"{0}\" - no context", login);
                return false;
            }
            if (ProtectedOperationContext.IsServerContext(ctx)) return true;

            var userHash = CredentialsHash.MakeOperationParamsHash(ctx.clientLocalTime, ctx.sessionTag, ctx.terminalId);
            if (ctx.hash != userHash)
            {
                Logger.InfoFormat("[{0: {1}] - hash is incorrect ({2}, correct hash: {3})",
                    login, accountId, ctx, userHash);
                return false;
            }
            // найти сессию
            try
            {
                sessionLocker.AcquireReaderLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("PermitUserOperation read timout");
                return false;
            }
            try
            {
                UserSession session;
                sessions.TryGetValue(ctx.terminalId, out session);
                if (session == null) return false;
                if (!string.IsNullOrEmpty(login))
                    if (login != session.login)
                    {
                        Logger.InfoFormat("Session #{0}: login ({1}) != session login ({2})",
                            ctx.terminalId, login, session.login);
                        return false;
                    }

                // обновить сессию
                try
                {
                    sessionLocker.UpgradeToWriterLock(SessionLockTimeout);
                }
                catch (ApplicationException)
                {
                    Logger.Error("PermitUserOperation write timout");
                    return false;
                }
                if (accountId.HasValue || checkAccountId)
                {
                    var targetAccount = accountId ?? session.accountId;
                    var accountRights = session.enabledAccounts.FirstOrNull(a => a.a == targetAccount);
                    // дополнительно проверяется, есть ли права на торговую (или иную защищенную) операцию
                    var hasRights = accountRights.HasValue && (accountRights.Value.b || !isTradeOperation);
                    if (!hasRights)
                    {
                        Logger.InfoFormat("User {0} #{1} has insufficient rights (trade op: {2}, session: {3} / {4})",
                            login, targetAccount, isTradeOperation, ctx.terminalId,
                            string.Join(",", session.enabledAccounts.Select(a => string.Format("{0}:{1}",
                                a.a, a.b ? "en" : "dis"))));
                        //Logger.Error("PermitUserOperation: возврат false, session.enabledAccounts.Contains счет " +
                        //             session.accountId);
                        return false;
                    }
                }
                // прописать счет для сессии
                if (accountId.HasValue)
                {
                    session.accountId = accountId.Value;
                    Logger.Info("PermitUserOperation: Успешная смена счета " + accountId.Value);
                }
                session.lastRequestClientTime = ctx.clientLocalTime;
                if (callback != null) session.callback = callback;
                // доступ разрешен
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error("PermitUserOperation error", ex);
                return false;
            }
            finally
            {
                sessionLocker.ReleaseLock();
            }
        }
 public bool PermitUserOperation(ProtectedOperationContext ctx, ITradeSharpServerCallback callback, bool isTradeOperation, bool checkAccountId)
 {
     return PermitUserOperation(ctx, callback, null, null, isTradeOperation, checkAccountId);
 }