Example #1
0
        public async Task <IActionResult> SignIn(
            [FromBody] SignRequestModel model,
            [FromServices] WorkshopDataContext context,
            [FromServices] ILogger <AuthController> logger)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await context.Users.FirstOrDefaultAsync(x => x.Email == model.Email);

            if (user == null)
            {
                logger.LogInformation($"User '{model.Email}' - Email not found");
                return(BadRequest(new ProblemDetails
                {
                    Status = 400,
                    Title = "You're not registered, please create an account"
                }));
            }

            if (PasswordHash.HashPassword(model.Password, user.PasswordSalt) != user.Password)
            {
                logger.LogInformation($"User '{user.Id}' - Password mismatch");
                return(BadRequest(new ProblemDetails
                {
                    Status = 400,
                    Title = "Invalid email or password"
                }));
            }

            return(Ok(JwtHelper.GenerateJwt(user)));
        }
        public override void DecodeBody(byte[] bytes)
        {
            MemoryStream ms = new MemoryStream(bytes);

            using (ms){
                SignRequestModel entity = Serializer.Deserialize <SignRequestModel>(ms);
                this.RoleId = entity.RoleId;
            }
        }
Example #3
0
        /// <exception cref="ErrorResponseException"/>
        /// <exception cref="UnknownResponseException"/>
        public async Task <SignedTransactionModel> SignTransactionAsync(SignRequestModel requestModel)
        {
            var request  = new SignTransactionRequest(requestModel.PublicAddresses?.ToList(), requestModel.TransactionHex);
            var response = await _api.SignTransactionAsync(request);

            SignTransactionResponse signTransactionResponse = ConvertToOrHandleErrorResponse <SignTransactionResponse>(response);

            return(new SignedTransactionModel(signTransactionResponse.SignedTransaction));
        }
        public override byte[] EncodeBody()
        {
            SignRequestModel entity = new SignRequestModel();

            entity.RoleId = this.RoleId;
            MemoryStream ms = new MemoryStream();

            using (ms){
                Serializer.Serialize(ms, entity);
                return(ms.ToArray());
            }
        }
        public async Task <IActionResult> SignRequest([FromBody] SignRequestModel model)
        {
            try
            {
                var merchant = await _payMerchantClient.Api.GetByIdAsync(model.LykkeMerchantId);

                if (model.ApiKey != merchant.ApiKey)
                {
                    throw new InvalidOperationException("Invalid api key for merchant.");
                }

                var rsa = model.RsaPrivateKey.CreateRsa();

                var signedBody = Convert.ToBase64String(
                    rsa.SignData(
                        Encoding.UTF8.GetBytes($"{model.ApiKey}{model.Body}"),
                        HashAlgorithmName.SHA256,
                        RSASignaturePadding.Pkcs1));

                // check signed body
                var verifyRequest = new VerifyRequest
                {
                    ClientId  = model.LykkeMerchantId,
                    SystemId  = SystemId,
                    Signature = signedBody,
                    Text      = model.Body
                };

                var verificationResponse = await _payAuthClient.VerifyAsync(verifyRequest);

                if (!verificationResponse.Description.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new InvalidOperationException($"Error in verification signed body with response: {verificationResponse.ToJson()}");
                }

                return(Ok(new SignRequestResultModel
                {
                    SignedBody = signedBody
                }));
            }
            catch (DefaultErrorResponseException ex)
            {
                _log.ErrorWithDetails(ex, model.Sanitize());

                return(BadRequest(ErrorResponse.Create(ex.Message)));
            }
            catch (Exception ex)
            {
                _log.ErrorWithDetails(ex, model.Sanitize());

                return(BadRequest(ErrorResponse.Create("Unable to sign with provided data.")));
            }
        }
Example #6
0
        public IActionResult DocuSign()
        {
            if (s_accountId == "")
            {
                ViewData["Message"] = "You need to sign in before signing documents.";
                return(View("Login"));
            }

            if (s_envelopeId == "")
            {
                ViewData["Message"] = "No Documents to sign";
                return(View("Index"));
            }

            DocuSignDemo.DocuSignDemo demo = new DocuSignDemo.DocuSignDemo();

            SignRequestModel signRequest = new SignRequestModel();

            signRequest.Username       = s_username;
            signRequest.Password       = s_password;
            signRequest.RecipientName  = s_recipientName;
            signRequest.RecipientEmail = s_recipientEmail;
            signRequest.EnvelopeId     = s_envelopeId;
            signRequest.AccountId      = s_accountId;


            ViewUrl recipientView = demo.SignDocument(ref signRequest);

            //Test Working Console Code
            //ViewUrl recipientView = demo.SignDocument(s_envelopeId);
            if (recipientView != null)
            {
                //return recipientView;
                return(Redirect(recipientView.Url));
                //return View();
            }
            else
            {
                ViewData["Message"] = signRequest.Message;
                return(View("Sign"));
            }
        }
Example #7
0
        //Method to embed a document signing in a new browser tab
        public ViewUrl SignDocument(ref SignRequestModel signRequest)
        {
            try
            {
                string Username      = signRequest.Username;          //[email]";
                string Password      = signRequest.Password;          //[password]";
                string IntegratorKey = GlobalVariables.integratorKey; //[INTEGRATOR_KEY]";

                // Enter recipient (signer) name and email address
                string recipientName  = signRequest.RecipientName;    //[SIGNER_NAME]";
                string recipientEmail = signRequest.RecipientEmail;   //[SIGNER_EMAIL]";

                // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
                string basePath = "https://demo.docusign.net/restapi";

                // instantiate a new api client
                ApiClient apiClient = new ApiClient(basePath);

                // set client in global config so we don't need to pass it to each API object
                Configuration.Default.ApiClient = apiClient;

                string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
                Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);

                // we will retrieve this from the login() results
                string accountId = null;

                // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
                AuthenticationApi authApi   = new AuthenticationApi();
                LoginInformation  loginInfo = authApi.Login();

                // user might be a member of multiple accounts
                accountId = loginInfo.LoginAccounts[0].AccountId;

                //// Use the EnvelopesApi to create and send the signature request
                EnvelopesApi envelopesApi = new EnvelopesApi();

                //Giving the recipient the view.

                RecipientViewRequest viewOptions = new RecipientViewRequest()
                {
                    ReturnUrl            = "https://www.docusign.com/devcenter",
                    ClientUserId         = "1234", // must match clientUserId set in step #2!
                    AuthenticationMethod = "email",
                    UserName             = recipientName,
                    Email = recipientEmail
                };

                // create the recipient view (aka signing URL)
                ViewUrl recipientView = envelopesApi.CreateRecipientView(signRequest.AccountId, signRequest.EnvelopeId, viewOptions);

                // print the JSON response
                //Console.WriteLine("ViewUrl:\n{0}", JsonConvert.SerializeObject(recipientView));

                // Start the embedded signing session!
                return(recipientView);
            }
            catch (Exception e)
            {
                signRequest.Message = e.Message;
                return(null);
            }
        }
        public async Task <IActionResult> SubmitRequest(SignRequestModel model)
        {
            SetHeaderWithApiToken(_httpClient);

            if (ModelState.IsValid)
            {
                bool isVertical;
                if (model.HeightInch > model.WidthInch)
                {
                    isVertical = true;
                }
                else
                {
                    isVertical = false;
                }

                // Get userID - TODO: REPLACE WITH A METHOD THAT WORKS
                var userinfoRequest  = new HttpRequestMessage(HttpMethod.Get, UserInfoRoute);
                var userinfoResponse = await _httpClient.SendAsync(userinfoRequest);

                if (userinfoResponse.IsSuccessStatusCode)
                {
                    var      userinfo    = userinfoResponse.Content.ReadAsStringAsync().Result;
                    UserInfo userInfo    = JsonConvert.DeserializeObject <UserInfo>(userinfo);
                    Guid     userId      = userInfo.Id;
                    var      accountName = model.AccountName.Trim();

                    var postRequest = JsonConvert.SerializeObject(new PostSignRequest
                    {
                        // NEED TO GET USER ID FUNCTION WORKING

                        UserId        = userId,
                        Account       = accountName,
                        Reason        = model.Reason,
                        NeededDate    = Convert.ToDateTime(model.NeededDate),
                        IsProofNeeded = model.IsProofNeeded,
                        MediaFK       = model.MediaFK,
                        Quantity      = model.Quantity,
                        IsVertical    = isVertical,
                        HeightInch    = model.HeightInch,
                        WidthInch     = model.WidthInch,
                        Template      = model.Template,
                        Information   = model.Information,
                        //DataFileUri = model.DataFileUri,
                        //ImageUri = model.ImageUri
                    });

                    var responseRequest = await _httpClient.PostAsync("https://signrequestexpressapi.azurewebsites.net/requests",
                                                                      new StringContent(postRequest, Encoding.UTF8, "application/json"));

                    if (responseRequest.IsSuccessStatusCode)
                    {
                        // Return to success page if request submitted successfully
                        return(RedirectToAction(nameof(SalesController.RequestSubmitted), "Sales"));
                    }
                }
            }
            // NOTE: When submitting the request, a POST needs to also occur to the
            //          Request_Account, User_Request

            // If we got this far, something failed, redisplay form
            return(View("Index", model)); // If there is an error the Account and Brand dropdowns are not filled
        }
Example #9
0
 public static SignRequestModel Sanitize(this SignRequestModel model)
 {
     model.RsaPrivateKey = null;
     return(model);
 }