コード例 #1
0
        public Operation <ReferralNode> AffixNewUser(string userId, string refereeCode)
        => _authorizer.AuthorizeAccess(UserContext.CurrentProcessPermissionProfile(), () =>
        {
            //lock because referal placement is not thread safe!
            lock (UniversalLock)
            {
                var referee   = _query.GetReferalNode(refereeCode).ThrowIfNull("invalid referee code");
                var downlines = _query.AllDownlines(referee);
                var user      = _query.GetUserById(userId);

                //affix to the referee if he has no downlines
                if (downlines.Count() == 0)
                {
                    var @ref = new ReferralNode
                    {
                        UplineCode    = refereeCode,
                        ReferrerCode  = refereeCode,
                        ReferenceCode = ReferralHelper.GenerateCode(userId),
                        User          = user
                    };

                    return(_pcommand.Add(@ref));
                }

                //generate a map for each downline referal node, with its reference code as key
                var hierarchyMap = GenerateHierarchyMap(downlines);

                //calculate and assign levels based on distance from the referee node in the hierarchy
                hierarchyMap.ForAll((cnt, duo) => duo.Value.Level = DistanceFromReferee(referee, duo.Key, hierarchyMap));

                //rearrange and order the downlines, then get the first incomplete duo, and place the new referal in the slot
                return(hierarchyMap
                       .Values
                       .OrderBy(_duo => _duo.Level)
                       .ThenBy(_duo => _duo.Count)
                       .FirstOrDefault(_duo => _duo.Count < 2)
                       .Pipe(_duo =>
                {
                    var @ref = new ReferralNode
                    {
                        UplineCode = _duo.UplineCode,
                        ReferrerCode = refereeCode,
                        ReferenceCode = ReferralHelper.GenerateCode(userId),
                        User = user
                    };

                    return _pcommand.Add(@ref);
                }));
            }
        });
コード例 #2
0
ファイル: PostService.cs プロジェクト: andyvauliln/BitDiamond
        public Operation <Post> CreateNewsPost(Post post)
        => _auth.AuthorizeAccess(this.PermissionProfile <IPostService>(UserContext.CurrentUser()), () =>
        {
            post.OwnerId = UserContext.CurrentUser().UserId;
            return(post.Validate()
                   .Then(opr =>
            {
                post.Id = 0;
                post.Status = PostStatus.Draft;
                post.OwnerId = UserContext.CurrentUser().UserId;
                post.Context = Constants.PostContext_News;

                return _pcommand.Add(post);
            }));
        });
コード例 #3
0
        public Operation <ContextVerification> CreateVerificationObject(string userId, string verificationContext, DateTime?expiryDate)
        => _authorizer.AuthorizeAccess(UserContext.CurrentProcessPermissionProfile(), () =>
        {
            var user         = _query.GetUserById(userId).ThrowIfNull("user not found");
            var _cv          = new ContextVerification();
            var cvexpiration = _settings.GetSetting(Constants.Settings_DefaultContextVerificationExpirationTime)
                               .Resolve()
                               .ParseData <TimeSpan>();
            _cv.Context           = verificationContext;
            _cv.ExpiresOn         = expiryDate ?? (DateTime.Now + cvexpiration);
            _cv.Target            = user;
            _cv.VerificationToken = GenerateToken();
            _cv.Verified          = false;

            return(_pcommand.Add(_cv));
        });
コード例 #4
0
        public Operation <User> RegisterUser(string targetUser, string referrer, Credential secretCredential)
        => _authorizer.AuthorizeAccess(UserContext.CurrentPPP(), () =>
        {
            var user = _query.GetUserById(targetUser);

            if (user != null)
            {
                throw new Exception($"{targetUser} already exists");
            }

            else if (secretCredential == null)
            {
                throw new Exception("user registration must contain a credential");
            }

            else
            {
                if (referrer == null)
                {
                    referrer = _query.GetRefNode(_query.GetUserById(Constants.SystemUsers_Apex)).ReferenceCode;
                }
                else if (_query.GetRefNode(referrer) == null)
                {
                    throw new Exception("invalid referer specified");
                }

                #region Create user
                user = new User
                {
                    UserId = targetUser,
                    Status = (int)AccountStatus.InActive
                };
                #endregion
                return(_pcommand

                       #region Add user
                       .Add(user) //add user
                       #endregion

                       #region Assign Credentials
                       .Then(opr =>
                {
                    #region Assign credentials (password)
                    //assign credentials
                    //load all credential expiration dates from settings
                    var passwordExpiration = _settingsManager.GetSetting(Constants.Settings_DefaultPasswordExpirationTime)
                                             .Resolve()
                                             .ParseData <TimeSpan>();

                    secretCredential.ExpiresIn = null;     //<-- never expires

                    return _credentialAuth.AssignCredential(targetUser, secretCredential);

                    #endregion
                })
                       #endregion

                       #region Assign role
                       .Then(opr =>
                {
                    return _authorizer.AssignRole(user, Constants.Roles_BitMemberRole);
                })
                       #endregion

                       #region Place the user in the referal hierarchy
                       .Then(opr =>
                {
                    return _refManager.AffixNewUser(user.UserId, referrer);
                })
                       #endregion

                       #region Request context verification
                       .Then(opr =>
                {
                    return RequestUserActivation(user.UserId);
                })
                       #endregion

                       #region Notify User
                       //welcome notification
                       .Then(opr => _notifier.NotifyUser(new Notification
                {
                    TargetId = user.UserId,
                    Title = "Welcome to the BitDiamond Family!",
                    Message = "Us here at BitDiamond warmly welcome you to our family of wealth growers and investors.",
                    Type = NotificationType.Info
                }))

                       //Add a Bitcoin Address
                       .Then(_opr => _notifier.NotifyUser(new Notification
                {
                    TargetId = user.UserId,
                    Type = NotificationType.Info,
                    Title = "Get a Bitcoin Address",
                    Message =
                        @"Already have a Bitcoin address? then go right ahead and add that address <a href='/bit-level/index#!/bitcoin-addresses'>Here</a><br/>
If you dont have one, you can create one with any of the popular Bitcoin Wallet services. 
"
                }))

                       //Add a Bitcoin Address
                       .Then(_opr => _notifier.NotifyUser(new Notification
                {
                    TargetId = user.UserId,
                    Type = NotificationType.Info,
                    Title = "Biodata request",
                    Message = @"Visit your <a href='/profile/index#!/home'>Profile Page</a> to supply your biodata information."
                }))
                       #endregion

                       .Then(opr => user));
            }
        });
コード例 #5
0
        /// <summary>
        /// Does both upgrading and recycling
        /// </summary>
        /// <returns></returns>
        public Operation <BitLevel> Upgrade()
        => _authorizer.AuthorizeAccess(UserContext.CurrentProcessPermissionProfile(), () =>
        {
            var maxLevelSettings = _settingsManager.GetSetting(Constants.Settings_MaxBitLevel).Resolve();
            var maxLevel         = (int)maxLevelSettings.ParseData <long>();
            var targetUser       = UserContext.CurrentUser();
            var currentLevel     = _query.CurrentBitLevel(targetUser);

            if (currentLevel != null)
            {
                ConfirmUpgradeDonation().Resolve();
            }

            else
            {
                currentLevel = new BitLevel
                {
                    Level    = maxLevel,
                    Cycle    = 0,
                    Donation = new BlockChainTransaction {
                        Status = BlockChainTransactionStatus.Verified
                    }
                }
            };


            if (currentLevel.Donation.Status == BlockChainTransactionStatus.Unverified)
            {
                throw new Exception("Current level donnation is still unverified");
            }

            var myAddress = _query.GetActiveBitcoinAddress(targetUser)
                            .ThrowIfNull("You do not have a valid block chain transaction address yet.");

            if (currentLevel.Cycle == int.MaxValue && currentLevel.Level == maxLevel)
            {
                throw new Exception("You cannot upgrade past the maximum cycle");
            }

            var nextLevel = (currentLevel.Level + 1) % (maxLevel + 1);
            var nextCycle = nextLevel == 0 ? currentLevel.Cycle + 1 : currentLevel.Cycle;

            var nextUpgradeBeneficiary = NextUpgradeBeneficiary(nextLevel == 0 ? targetUser : currentLevel.Donation.Receiver.Owner, nextLevel, nextCycle).ThrowIfNull("Could not find a valid beneficiary");
            var beneficiaryAddress     = _query.GetActiveBitcoinAddress(nextUpgradeBeneficiary);

            var bl = new BitLevel
            {
                Level         = nextLevel,
                Cycle         = nextCycle,
                DonationCount = 0,
                SkipCount     = 0,
                UserId        = targetUser.UserId
            };
            _pcommand.Add(bl).Resolve();

            var donation = new BlockChainTransaction
            {
                Amount      = nextLevel == maxLevel ? 0 : GetUpgradeAmount(nextLevel + 1),
                LedgerCount = nextLevel == maxLevel ? int.MaxValue : 0,
                CreatedOn   = DateTime.Now,
                Sender      = myAddress,
                Receiver    = beneficiaryAddress,
                ContextType = Constants.TransactionContext_UpgradeBitLevel,
                ContextId   = bl.Id.ToString(),
                Status      = nextLevel == maxLevel ?
                              BlockChainTransactionStatus.Verified :
                              BlockChainTransactionStatus.Unverified
            };
            _pcommand.Add(donation).Resolve();

            bl.DonationId = donation.Id;
            _pcommand.Update(bl);

            bl.Donation = donation;

            //notify user
            _notifier.NotifyUser(new Notification
            {
                Type     = NotificationType.Success,
                TargetId = targetUser.UserId,
                Title    = "Congratulations!",
                Message  = $"Well done, {targetUser.UserId}!! You are now <strong>proudly</strong> at Cycle-{nextCycle} / Level-{nextLevel}, no easy feat!<br/>" +
                           @"Now you can receive even more donations from your downlines. 
                  <p>Remember though, that this is a race to the <strong class='text-primary'>top</strong>, and as such
                  you may miss the donations of any of your downlines who upgrades to levels higher than yours. So dont waste much time here, Upgrade as soon as you can!</p>"
            })
            .Resolve();

            return(bl);
        });
コード例 #6
0
 public Operation <Notification> NotifyUser(Notification notification)
 => _auth.AuthorizeAccess(UserContext.CurrentPPP(), () =>
 {
     return(notification.Validate()
            .Then(opr => _pcommand.Add(notification)));
 });