Ejemplo n.º 1
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context)
        {
            TelemetryClient telemetryClient = new TelemetryClient
            {
                InstrumentationKey = Settings.APPINSIGHTS_INSTRUMENTATIONKEY
            };

            telemetryClient.TrackTrace("Starting function: AddRecordVote");

            AddRecordVoteResponse result = new AddRecordVoteResponse
            {
                IsSucceded = true,
                ResultId   = (int)AddRecordVoteResultEnum.Success
            };

            try
            {
                string  requestBody = new StreamReader(req.Body).ReadToEnd();
                dynamic data        = JsonConvert.DeserializeObject(requestBody);
                string  token       = data?.token;
                string  username    = data?.username;
                string  hash        = data?.hash;
                bool    isApproval  = data?.isApproval;

                Dictionary <ParameterTypeEnum, object> parameters = new Dictionary <ParameterTypeEnum, object>
                {
                    { ParameterTypeEnum.Username, username },
                    { ParameterTypeEnum.Hash, hash },
                    { ParameterTypeEnum.IsApproval, isApproval },
                    { ParameterTypeEnum.MasterAddress, Settings.MASTER_ADDRESS },
                    { ParameterTypeEnum.MasterPrivateKey, Settings.MASTER_PRIVATEKEY },
                    { ParameterTypeEnum.ContractAddress, Settings.CONTRACT_ADDRESS },
                    { ParameterTypeEnum.ContractABI, Settings.CONTRACT_ABI }
                };

                telemetryClient.TrackTrace("Validating token");

                //validate token
                if (!string.IsNullOrEmpty(token))
                {
                    var      decrypted_token = SecurityHelper.Decrypt(token, Settings.SECURITY_SEED);
                    byte[]   token_bytes     = Convert.FromBase64String(decrypted_token);
                    DateTime when            = DateTime.FromBinary(BitConverter.ToInt64(token_bytes, 0));

                    if (when < DateTime.UtcNow.AddMinutes(-5))
                    {
                        result.IsSucceded = false;
                        result.ResultId   = (int)AddRecordVoteResultEnum.InvalidToken;
                    }
                    else
                    {
                        telemetryClient.TrackTrace("Calling helper");
                        AddRecordVoteHelper helper = new AddRecordVoteHelper(telemetryClient, Settings.STORAGE_ACCOUNT, Settings.RPC_CLIENT, Configurations.GetMongoDbConnectionInfo());
                        result = await helper.AddRecordVoteAsync(parameters);
                    }
                }
                else
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordVoteResultEnum.MissingToken;
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordVoteResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordVoteResultEnum.Failed;
            }

            //get message for result id
            string message = EnumDescription.GetEnumDescription((AddRecordVoteResultEnum)result.ResultId);

            //build json result object
            dynamic jsonresult = new JObject();

            jsonresult.message = message;

            telemetryClient.TrackTrace("Finishing function: AddRecordVote");

            //send ok result or bad request
            return((result.IsSucceded) ? (ActionResult) new OkObjectResult(jsonresult) : (ActionResult) new BadRequestObjectResult(jsonresult));
        }
Ejemplo n.º 2
0
        public async Task <AddRecordVoteResponse> AddRecordVoteAsync(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            AddRecordVoteResponse result = new AddRecordVoteResponse
            {
                IsSucceded = true,
                ResultId   = (int)AddRecordVoteResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.Username, out global::System.Object ousername);
                string username = ousername.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.Hash, out global::System.Object ohash);
                string hash = ohash.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.IsApproval, out global::System.Object oisApproval);
                bool isApproval = Convert.ToBoolean(oisApproval.ToString());

                parameters.TryGetValue(ParameterTypeEnum.MasterAddress, out global::System.Object omasterAddress);
                string masterAddress = omasterAddress.ToString();

                parameters.TryGetValue(ParameterTypeEnum.MasterPrivateKey, out global::System.Object omasterPrivateKey);
                string masterPrivateKey = omasterPrivateKey.ToString();

                parameters.TryGetValue(ParameterTypeEnum.ContractAddress, out global::System.Object ocontractAddress);
                string contractAddress = ocontractAddress.ToString();

                parameters.TryGetValue(ParameterTypeEnum.ContractABI, out global::System.Object ocontractABI);
                string contractABI = ocontractABI.ToString();

                //database helpers
                DBUserAccountHelper dbUserAccountHelper = new DBUserAccountHelper(DBCONNECTION_INFO);
                DBRecordItemHelper  dbRecordItemHelper  = new DBRecordItemHelper(DBCONNECTION_INFO);
                DBRecordVoteHelper  dbRecordVoteHelper  = new DBRecordVoteHelper(DBCONNECTION_INFO);

                //blockchain helper
                BlockchainHelper bh = new BlockchainHelper(telemetryClient, STORAGE_ACCOUNT, RPC_CLIENT, masterAddress, masterPrivateKey);

                telemetryClient.TrackTrace("Validating username length");

                //validate username length
                if (!RegexValidation.IsValidUsername(username))
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordVoteResultEnum.InvalidUsernameLength;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating username existance");

                //validate if account exists
                UserAccount userAccount = dbUserAccountHelper.GetUser(username);

                if (userAccount == null)
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordVoteResultEnum.UsernameNotExists;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating record item existance");

                //validate if record item exists for voting
                RecordItem recordItem = dbRecordItemHelper.GetRecordItem(hash);

                if (recordItem == null)
                {
                    //there is no record item linked with this vote
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordVoteResultEnum.NotExists;
                    return(result);
                }
                else
                {
                    telemetryClient.TrackTrace("Validating record vote existance");

                    //validate if user has voted submit a vote before
                    RecordVote vote = dbRecordVoteHelper.GetRecordVote(hash, username);

                    if (vote != null)
                    {
                        //the user already voted
                        result.IsSucceded = false;
                        result.ResultId   = (int)AddRecordVoteResultEnum.AlreadyVoted;
                        return(result);
                    }
                    else
                    {
                        telemetryClient.TrackTrace("Adding record vote to blockchain");

                        //sending to the blockchain
                        var res_IncreaseOperationAsync = string.Empty;
                        if ((bool)isApproval)
                        {
                            res_IncreaseOperationAsync = await bh.IncreaseApprovalsAsync(hash, contractAddress, contractABI);

                            System.Diagnostics.Trace.TraceInformation($"Add record for approval vote result: {res_IncreaseOperationAsync}");
                        }
                        else
                        {
                            res_IncreaseOperationAsync = await bh.IncreaseDisapprovalsAsync(hash, contractAddress, contractABI);

                            System.Diagnostics.Trace.TraceInformation($"Add record for disapproval vote result: {res_IncreaseOperationAsync }");
                        }

                        if (string.IsNullOrEmpty(res_IncreaseOperationAsync))
                        {
                            //there was an error voting the record in the blockchain
                            result.IsSucceded = false;
                            result.ResultId   = (int)AddRecordVoteResultEnum.BlockchainIssue;
                            return(result);
                        }

                        telemetryClient.TrackTrace("Adding record vote to database");

                        //save record in mongodb
                        vote = new RecordVote
                        {
                            username      = username,
                            hash          = hash,
                            isApproval    = isApproval,
                            transactionId = res_IncreaseOperationAsync,
                            createdDate   = Timezone.GetCustomTimeZone()
                        };

                        //perform insert in mongodb
                        await dbRecordVoteHelper.CreateRecordVote(vote);
                    }
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordVoteResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordVoteResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }