Exemple #1
0
 public AuthenticationResponse GetUserDetail(string login, string password, out PlatformUser userDecorated)
 {
     userDecorated = null;
     using (var dbContext = DatabaseContext.Instance.Make())
     {
         try
         {
             var user = dbContext.PLATFORM_USER.FirstOrDefault(u => u.Login == login);
             if (user == null)
             {
                 return(AuthenticationResponse.InvalidAccount);
             }
             if (user.Password != password)
             {
                 return(AuthenticationResponse.WrongPassword);
             }
             userDecorated = LinqToEntity.DecoratePlatformUser(user);
             return(AuthenticationResponse.OK);
         }
         catch (Exception ex)
         {
             Logger.ErrorFormat("Ошибка в GetUserDetail({0}) : {1}", login, ex);
             return(AuthenticationResponse.ServerError);
         }
     }
 }
        public PaidServiceDetail GetPaidServiceDetail(int serviceId)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var service = ctx.SERVICE.First(s => s.ID == serviceId);
                    if (service == null)
                    {
                        return(null);
                    }

                    var srvDec = LinqToEntity.DecoratePaidService(service);
                    var detail = new PaidServiceDetail
                    {
                        Currency  = service.Currency,
                        DayFee    = service.FixedPrice,
                        MonthFee  = srvDec.FixedPriceMonth,
                        AccountId = service.AccountId
                    };

                    var signalOwner = LinqToEntity.DecoratePlatformUser(ctx.PLATFORM_USER.First(u => u.ID == service.User));
                    detail.UserName = signalOwner.MakeNameWithInitials();

                    if (srvDec.AccountId.HasValue)
                    {
                        var account = LinqToEntity.DecorateAccount(ctx.ACCOUNT.First(a => a.ID == srvDec.AccountId));
                        detail.AccountGroup = account.Group;
                    }

                    // информация по торговым сигналам
                    var userSignal =
                        ctx.SERVICE.FirstOrDefault(us => us.User == service.User);
                    if (userSignal == null)
                    {
                        return(detail);
                    }
                    detail.SignalTitle =
                        string.IsNullOrEmpty(userSignal.Comment) ? "Сигналы №" + userSignal.ID : userSignal.Comment;
                    var subsCount = ctx.SUBSCRIPTION.Count(us => us.Service == userSignal.ID);
                    detail.SubscribersCount = subsCount;

                    return(detail);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error in GetPaidServiceDetail()", ex);
                return(null);
            }
        }
Exemple #3
0
        private List <PaidService> GetServicesByUserOrId(int id, bool byUser, out PlatformUser serviceOwner)
        {
            serviceOwner = null;
            var srvList = new List <PaidService>();

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var query = byUser
                                    ? ctx.SERVICE.Where(s => s.User == id)
                                    : ctx.SERVICE.Where(s => s.ID == id);
                    foreach (var srv in query)
                    {
                        var paidServ = LinqToEntity.DecoratePaidService(srv);
                        var srvId    = srv.ID;
                        // добавить рейты
                        foreach (var rate in ctx.SERVICE_RATE.Where(r => r.Service == srvId))
                        {
                            paidServ.serviceRates.Add(new PaidServiceRate
                            {
                                Amount      = rate.Amount,
                                RateType    = (PaidServiceRate.ServiceRateType)rate.RateType,
                                UserBalance = rate.UserBalance
                            });
                        }
                        srvList.Add(paidServ);
                    }

                    if (byUser)
                    {
                        serviceOwner = LinqToEntity.DecoratePlatformUser(ctx.PLATFORM_USER.First(u => u.ID == id));
                    }
                    else
                    {
                        var srv = srvList.FirstOrDefault();
                        if (srv != null)
                        {
                            serviceOwner = LinqToEntity.DecoratePlatformUser(ctx.PLATFORM_USER.First(u => u.ID == srv.User));
                        }
                    }
                }
                return(srvList);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetServicesByUserOrId({0}, {1}) error: {2}", id, byUser, ex);
                return(srvList);
            }
        }
Exemple #4
0
        public WalletError GetTransferExtendedInfo(ProtectedOperationContext secCtx,
                                                   int transferId, out BalanceChange balanceChange, out PlatformUser user)
        {
            balanceChange = null;
            user          = null;

            if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false))
            {
                return(WalletError.InsufficientRights);
            }

            var error = WalletError.ServerError;

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var trans = ctx.TRANSFER.FirstOrDefault(t => t.ID == transferId);
                    if (trans == null)
                    {
                        return(WalletError.InvalidData);
                    }
                    if (trans.BalanceChange.HasValue)
                    {
                        balanceChange = LinqToEntity.DecorateBalanceChange(trans.BALANCE_CHANGE);
                        return(WalletError.OK);
                    }
                    if (trans.RefWallet.HasValue)
                    {
                        var us = ctx.PLATFORM_USER.FirstOrDefault(u => u.ID == trans.RefWallet.Value);
                        if (us != null)
                        {
                            user          = LinqToEntity.DecoratePlatformUser(us);
                            user.Password = string.Empty;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetTransferExtendedInfo({0}) error: {1}", transferId, ex);
                error = WalletError.ServerError;
            }
            return(error);
        }
        /// <summary>
        /// Получает пользователя - владельца указанного счёта
        /// </summary>
        /// <param name="id">уникальный идентификатор счёта</param>
        /// <returns>владелец указанного счёта</returns>
        public PlatformUser GetAccountOwner(int id)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var owner =
                        ctx.PLATFORM_USER_ACCOUNT.FirstOrDefault(x => x.Account == id && x.RightsMask == 0);
                    return(owner == null ? null : LinqToEntity.DecoratePlatformUser(owner.PLATFORM_USER));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetAccountOwner", ex);
            }

            return(null);
        }
        public SubscriptionListModel(int userId)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.Single(x => x.ID == userId);
                    CurrentUser = LinqToEntity.DecoratePlatformUser(user);

                    OwnerSignalList = new List <ServiceTradeSignalModel>();
                    OwnerSignalList = ctx.SERVICE.Where(x => x.User == userId).Select(s => new ServiceTradeSignalModel
                    {
                        Id              = s.ID,
                        User            = userId,
                        AccountId       = s.AccountId,
                        Comment         = s.Comment,
                        Currency        = s.Currency,
                        FixedPrice      = s.FixedPrice,
                        ServiceType     = (PaidServiceType)s.ServiceType,
                        UserLogin       = s.PLATFORM_USER.Login,
                        CountSubscriber = ctx.SUBSCRIPTION.Count(y => y.Service == s.ID)
                    }).ToList();



                    SubscriptionList = new List <SubscriptionModel>();
                    SubscriptionList = ctx.SUBSCRIPTION.Where(x => x.User == userId).Select(s => new SubscriptionModel
                    {
                        User             = s.User,
                        SignalOwnerId    = s.SERVICE1.PLATFORM_USER.ID,                 // Сигнальщик Id
                        SignalOwnerLogin = s.SERVICE1.PLATFORM_USER.Login,              // Сигнальщик Login
                        Service          = s.SERVICE1.ID,
                        ServiceType      = s.SERVICE1.ServiceType,
                        RenewAuto        = s.RenewAuto,
                        TimeEnd          = s.TimeEnd,
                        TimeStarted      = s.TimeStarted
                    }).ToList();
                }
            }
            catch (Exception ex)
            {
                Logger.Info("ServiceTradeSignalModel", ex);
            }
        }
Exemple #7
0
 public void MakeNewlyRegisteredAccountSignaller(TradeSharpConnection ctx,
                                                 PLATFORM_USER user, ACCOUNT account)
 {
     try
     {
         ctx.SERVICE.Add(new SERVICE
         {
             AccountId   = account.ID,
             ServiceType = (int)PaidServiceType.PAMM,
             Currency    = account.Currency,
             FixedPrice  = 1,
             Comment     = "Сигналы " + LinqToEntity.DecoratePlatformUser(user).NameWithInitials,
             User        = user.ID
         });
     }
     catch (Exception ex)
     {
         Logger.ErrorFormat("Ошибка в MakeNewlyRegisteredAccountSignaller(login={0}, account={1}): {2}",
                            user.Login, account.ID, ex);
     }
 }
Exemple #8
0
        private static List <PlatformUser> UserUpdateRoutine()
        {
            var users = new List <PlatformUser>();

            using (var ctx = DatabaseContext.Instance.Make())
            {
                try
                {
                    // ReSharper disable LoopCanBeConvertedToQuery
                    foreach (var usr in ctx.PLATFORM_USER)
                    // ReSharper restore LoopCanBeConvertedToQuery
                    {
                        users.Add(LinqToEntity.DecoratePlatformUser(usr));
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("DictionaryManager - ошибка в UserUpdateRoutine()", ex);
                }
            }
            return(users);
        }
 public PlatformUser GetUserFullInfo(string hash, string userLogin, long localTime, out List <Account> accounts)
 {
     using (var ctx = DatabaseContext.Instance.Make())
     {
         var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
         if (user == null)
         {
             accounts = null;
             return(null);
         }
         var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
         if (hash != userHash)
         {
             accounts = null;
             return(null);
         }
         accounts =
             (from pua in ctx.PLATFORM_USER_ACCOUNT where pua.PlatformUser == user.ID select pua.ACCOUNT1).ToList
                 ().Select(LinqToEntity.DecorateAccount).ToList();
         return(LinqToEntity.DecoratePlatformUser(user));
     }
 }
Exemple #10
0
        public bool RemindPassword(string email, string login)
        {
            if (string.IsNullOrEmpty(email))
            {
                email = "";
            }
            if (string.IsNullOrEmpty(login))
            {
                login = "";
            }

            using (var ctx = DatabaseContext.Instance.Make())
            {
                PLATFORM_USER user;
                try
                {
                    user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Email == email || u.Login == login);
                    if (user == null)
                    {
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("Ошибка в RemindPassword({0}) -  получение пользователя: {1}", email, ex);
                    return(false);
                }
                // отправить письмо
                try
                {
                    return(SendEmailOnNewAccount(LinqToEntity.DecoratePlatformUser(user), false));
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("Ошибка в RemindPassword({0}) - отправка письма: {1}", email, ex);
                    return(false);
                }
            }
        }
Exemple #11
0
        public RequestStatus QueryReadonlyUserForAccount(ProtectedOperationContext secCtx, int accountId,
                                                         out PlatformUser user)
        {
            user = null;

            if (UserOperationRightsStorage.IsProtectedOperation(UserOperation.GetAccountDetail))
            {
                if (
                    !UserSessionStorage.Instance.PermitUserOperation(secCtx,
                                                                     UserOperationRightsStorage.IsTradeOperation(
                                                                         UserOperation.GetAccountDetail), false))
                {
                    return(RequestStatus.Unauthorized);
                }
            }

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var existingUserRecord = ctx.PLATFORM_USER_ACCOUNT.FirstOrDefault(ua => ua.Account == accountId &&
                                                                                      ua.RightsMask ==
                                                                                      (int)AccountRights.Просмотр);
                    if (existingUserRecord != null)
                    {
                        user = LinqToEntity.DecoratePlatformUser(ctx.PLATFORM_USER.First(u => u.ID == existingUserRecord.PlatformUser));
                    }
                    return(RequestStatus.OK);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в QueryReadonlyUserForAccount()", ex);
                return(RequestStatus.CommonError);
            }
        }
        public static bool DeleteAccount(int accountId, out List <PlatformUser> newUsersWoAccount)
        {
            // пользователи, лишившиеся акаунта
            var emptyUserIds = new List <int>();

            newUsersWoAccount = new List <PlatformUser>();

            // удалить счет
            using (var ctx = DatabaseContext.Instance.Make())
            {
                // Проверка - является ли счёт управляющим для какого-нибудь портфеля кампании
                var portfolioSyst = ctx.TOP_PORTFOLIO.FirstOrDefault(p => p.ManagedAccount == accountId);
                if (portfolioSyst != null)
                {
                    throw new InvalidOperationException("Удаление счета " + accountId + " невозможно - счет выбран как управляющий для портфеля " +
                                                        portfolioSyst.Id + " (" + portfolioSyst.Name + " / " + portfolioSyst.ParticipantCount + ")");
                }

                // удалить все трансферы
                try
                {
                    var balanceChanges = ctx.BALANCE_CHANGE.Where(b => b.AccountID == accountId);
                    foreach (var bc in balanceChanges)
                    {
                        ctx.BALANCE_CHANGE.Remove(bc);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("DeleteAccount() - delete BALANCE_CHANGE", ex);
                    throw;
                }



                // удалить привязки пользователей
                try
                {
                    var acUsers = ctx.PLATFORM_USER_ACCOUNT.Where(b => b.Account == accountId);
                    foreach (var ac in acUsers)
                    {
                        emptyUserIds.Add(ac.PlatformUser);
                        ctx.PLATFORM_USER_ACCOUNT.Remove(ac);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("DeleteAccount() - delete PLATFORM_USER_ACCOUNT", ex);
                    throw;
                }

                // удалить открытые позы
                try
                {
                    var acPos = ctx.POSITION.Where(b => b.AccountID == accountId);
                    foreach (var ac in acPos)
                    {
                        ctx.POSITION.Remove(ac);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("DeleteAccount() - delete POSITION", ex);
                    throw;
                }

                // удалить отложенные ордера
                try
                {
                    var acPos = ctx.PENDING_ORDER.Where(b => b.AccountID == accountId);
                    foreach (var ac in acPos)
                    {
                        ctx.PENDING_ORDER.Remove(ac);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("DeleteAccount() - delete PENDING_ORDER", ex);
                    throw;
                }

                // удалить закрытые позы
                try
                {
                    var acPos = ctx.POSITION_CLOSED.Where(b => b.AccountID == accountId);
                    foreach (var ac in acPos)
                    {
                        ctx.POSITION_CLOSED.Remove(ac);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("DeleteAccount() - delete POSITION_CLOSED", ex);
                    throw;
                }

                // удалить сам счет
                try
                {
                    var account = ctx.ACCOUNT.First(a => a.ID == accountId);
                    ctx.ACCOUNT.Remove(account);
                }
                catch (Exception ex)
                {
                    Logger.Error("DeleteAccount() - delete ACCOUNT", ex);
                    throw;
                }

                // сохранить изменения
                try
                {
                    ctx.SaveChanges();
                }
                catch (Exception ex)
                {
                    Logger.Error("DeleteAccount() - saving changes", ex);
                    throw;
                }

                // найти пользователей, лишившихся счетов
                if (emptyUserIds.Count > 0)
                {
                    // проверить, есть ли еще счета?
                    for (var i = 0; i < emptyUserIds.Count; i++)
                    {
                        var id         = emptyUserIds[i];
                        var hasAccount = ctx.PLATFORM_USER_ACCOUNT.Any(a => a.PlatformUser == id);
                        if (!hasAccount)
                        {
                            continue;
                        }
                        emptyUserIds.RemoveAt(i);
                        i--;
                    }
                    foreach (var usId in emptyUserIds)
                    {
                        var userId = usId;
                        var user   = ctx.PLATFORM_USER.First(u => u.ID == userId);
                        newUsersWoAccount.Add(LinqToEntity.DecoratePlatformUser(user));
                    }
                }
            }

            return(true);
        }
Exemple #13
0
        public CreateReadonlyUserRequestStatus MakeOrDeleteReadonlyUser(ProtectedOperationContext secCtx,
                                                                        int accountId, bool makeNew, string pwrd, out PlatformUser user)
        {
            user = null;

            if (UserOperationRightsStorage.IsProtectedOperation(UserOperation.ChangeAccountSettings))
            {
                if (!UserSessionStorage.Instance.PermitUserOperation(secCtx,
                                                                     UserOperationRightsStorage.IsTradeOperation(UserOperation.ChangeAccountSettings), false))
                {
                    return(CreateReadonlyUserRequestStatus.NotPermitted);
                }
            }

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var existingUserRecord = ctx.PLATFORM_USER_ACCOUNT.FirstOrDefault(ua => ua.Account == accountId &&
                                                                                      ua.RightsMask ==
                                                                                      (int)AccountRights.Просмотр);
                    if (!makeNew)
                    {
                        // удалить
                        if (existingUserRecord == null)
                        {
                            return(CreateReadonlyUserRequestStatus.UserNotFound);
                        }
                        ctx.PLATFORM_USER_ACCOUNT.Remove(existingUserRecord);
                        // удалить самого пользователя платформы
                        var userRow = ctx.PLATFORM_USER.First(u => u.ID == existingUserRecord.PlatformUser);
                        ctx.PLATFORM_USER.Remove(userRow);
                        ctx.SaveChanges();
                        return(CreateReadonlyUserRequestStatus.Success);
                    }

                    // создать нового или редактировать старого
                    if (existingUserRecord != null)
                    {
                        var userRow = ctx.PLATFORM_USER.First(u => u.ID == existingUserRecord.PlatformUser);
                        user             = LinqToEntity.DecoratePlatformUser(userRow);
                        userRow.Password = pwrd;
                        ctx.SaveChanges();
                        return(CreateReadonlyUserRequestStatus.Success);
                    }

                    // таки создать нового
                    var newUser = new PLATFORM_USER
                    {
                        Title            = "Read" + accountId,
                        Login            = "******" + accountId,
                        Password         = pwrd,
                        RegistrationDate = DateTime.Now,
                        RoleMask         = (int)UserRole.Trader
                    };
                    user = LinqToEntity.DecoratePlatformUser(newUser);
                    var usr = ctx.PLATFORM_USER.Add(newUser);
                    ctx.SaveChanges();
                    ctx.PLATFORM_USER_ACCOUNT.Add(new PLATFORM_USER_ACCOUNT
                    {
                        Account      = accountId,
                        PlatformUser = usr.ID,
                        RightsMask   = (int)AccountRights.Просмотр
                    });
                    ctx.SaveChanges();
                    return(CreateReadonlyUserRequestStatus.Success);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в CreateReadonlyUserRequestStatus()", ex);
                return(CreateReadonlyUserRequestStatus.CommonError);
            }
        }