Monday, March 28, 2016

How to Use Firebase with Braintree

My current Ionic / Angular / Firebase + a very simple Node server app has security issue when using Braintree to charge user credit card. The problem, according to @RaymondBerg is because client can post any customerId and create a braintree token and charge that customer. Since all my user authorization happened in Firebase / Angular - client side. So when user do a $HTTP.post from my AngularJS/Ionic to my Node server, I don't want to authorize them again (as I don't even know how to do that so I use Firebase).
So what is the strategy here to setup Firebase and my Node server to work with payment system like braintree?
One thing I can think off, is to first create a node in my firebase before http request and then pass in the client $id for request in client side (Ionic app):
$scope.getToken = function () {       var ref = new Firebase('[FirebaseURL]/braintreePaymentToken');       var tokenObj = $firebaseObject(ref.child(posterId));       tokenObj.tokenGenerated = true;        tokenObj.$save().then(function(){        $http({          method: 'POST',          url: 'http://localhost:3000/api/v1/token',          data: {            //user $id from Firebase            userId: snapshot.key(),          }        })}

In Firebase, I set up a security rule as:

"braintreePayment": {
      ".read": false,
      ".write": false,
    },
   "braintreePaymentToken": {
      "$uid": {
       ".read": "auth != null",
       ".write": "auth != null && auth.uid == $uid",
      }
    }, 

This way, the temp node braintreePaymentToken can ONLY be written by current login user in the app. Other login user (nefarious user) can not write on this node b/c their auth.uid will not equal to posterId, which posterId is the user who need to pay.
On server end, I use once to see if I can find the value:

var ref = new Firebase('[FirebaseURL]');
app.post('/api/v1/token', jsonParser, function (request, response) {
  var userId = request.body.userId;
  console.log (userId);
  //customerId from braintree is stored here so no one except the server can read it
  ref.child('braintreePayment').child(userId).once("value", function(snapshot){
    var exists = (snapshot.val() !== null);
    console.log (exists);
    if (exists) {
    console.log ("using exsiting customer!");
    //If braintreePaymentToken with userId child exsited, it mean this request is come from my Ionic client, not from anywhere else.
    ref.child('braintreePaymentToken').child(userId).once("value", function(snap) {
    if (snap.val()) {
      gateway.clientToken.generate({
        customerId: snapshot.val().customerId
      }, function (err, res) {
        if (err) throw err;
        response.json({
          "client_token": res.clientToken
        });
        //After I return the clientToken, I delete the braintreePaymentToken node. It is like using Firebase to send email with Zaiper. More secue I guess?
        ref.child('braintreePaymentToken').child(userId).remove();
      });
    else {
      response.json({
          "client_token": "Unauthorized Access!"
        });
    }
 } else {
    console.log ("using no customer!");
    gateway.clientToken.generate({}, function (err, res) {
      if (err) throw err;
      response.json({
        "client_token": res.clientToken
      });
    });
 }
 });
});

And when user hit pay button on my client(ionic app), I do the Firebase Once request again to see if the customerId already in my firebase/braintreePayment. If not, we save one with the return transaction customerId created by braintree.

app.post('/api/v1/process', jsonParser, function (request, response) {

  var transaction = request.body;
  ref.child('braintreePayment').child(transaction.userId).once("value",        function(snapshot){
 var exists = (snapshot.val() !== null);
 console.log (exists);
 if (exists) {
    console.log ("Return customer!");
    gateway.transaction.sale({
      amount: transaction.amount,
      paymentMethodNonce: transaction.payment_method_nonce,
      options: {
        submitForSettlement: true
      },

    }, function (err, result) {
      if (err) throw err;
      response.json(result);
    });
 } else {
    console.log ("First time customer!");
    gateway.transaction.sale({
      amount: transaction.amount,
      paymentMethodNonce: transaction.payment_method_nonce,

      options: {
        store_in_vault_on_success: true,
        submitForSettlement: true
      },

    }, function (err, result) {
      if (err) throw err;

      console.log ("Customer Id: " + result.transaction.customer.id);
      var customerId = result.transaction.customer.id;

           ref.child('braintreePayment').child(transaction.userId).update({customerId: customerId});

      response.json(result);
    });
    }
   });

  });

As you see, this is REALLY COMPLICATED. But I do not know a better, secue way to do this... Is this the best way to structure between Firebase, Node, and Braintree? Is this address the OWASP security concern? Is there way to improve this code to be better or there is a better way to do it?


Monday, May 14, 2012

Stop Auto Update for Windows server

For successful  and cleaner SharePoint environment ,  stopping auto updates will be a nicer option as it will prevent any environment changes . To do this please make this registry change.


HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU
NoAutoUpdate   1

Thursday, April 26, 2012

Get a file via ftp using VBA





' Edit these variables to match your specifications
ftp_address          = "hosted.datascope.reuters.com"
ftp_username         = "6666666"
ftp_password         = "xxxxxxxxx"
ftp_remote_directory = "reports" ' Leave blank if uploading to root directory
ftp_files_to_put     = "abcdefg.xml"     ' You can use wildcards here (e.g. *.txt)

'On Error Resume Next
Set oScript = CreateObject("WSCRIPT.SHELL")
Set oFileSys = CreateObject("Scripting.FileSystemObject")
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Build our ftp-commands file
Set objTextFile = objFSO.CreateTextFile("test.ftp")
objTextFile.WriteLine "lcd ."
objTextFile.WriteLine "open " & ftp_address
objTextFile.WriteLine ftp_username
objTextFile.WriteLine ftp_password

' Check to see if we need to issue a 'cd' command
If ftp_remote_directory <> "" Then
   objTextFile.WriteLine "cd " & ftp_remote_directory
End If

objTextFile.WriteLine "prompt"

' If the file(s) is/are binary (i.e. .jpg, .mdb, etc..), uncomment the following line' objTextFile.WriteLine "binary"
' If there are multiple files to put, we need to use the command 'mput', instead of 'put'
If Instr(1, ftp_files_to_put, "*",1) Then
   objTextFile.WriteLine "mput " & ftp_files_to_put
Else
   objTextFile.WriteLine "get " & ftp_files_to_put
End If
objTextFile.WriteLine "bye"
objTextFile.Close
Set objTextFile = Nothing
' Use cmd.exe to run ftp.exe, parsing our newly created command file
strCMD = "ftp.exe -s:test.ftp"

'strTempFile = "C:\" & oFileSys.GetTempName( )
strTempFile = oFileSys.GetTempName( )

' Pipe output from cmd.exe to a temporary file (Not :| Steve)
Call oScript.Run ("cmd.exe /c " & strCMD & " > " & strTempFile, 0, True)

Set oFile = oFileSys.OpenTextFile (strTempFile, 1, False, 0)

On Error Resume Next
' Grab output from temporary file
strCommandResult = oFile.ReadAll
oFile.Close
' Delete the temporary & ftp-command files
Call oFileSys.DeleteFile( strTempFile, True )
Call objFSO.DeleteFile("test.ftp", True )
Set oFileSys = Nothing
Set objFSO = Nothing
' Print result of FTP session to screen

C# Sort dictionary containing objects

Hi After searching a lot over internet how to sort dictionary containing objects e.g Dictionary<string,myclass> I end up writing this simple but effective method please have a look .



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, delta> mydict = new Dictionary<string, delta>();
            mydict.Add("a", new delta(true, 3,"ash1"));
            mydict.Add("d", new delta(false, 1,"bsh2"));
            mydict.Add("e", new delta(false, 1 , "ash3"));
            mydict.Add("b", new delta(true, 2 , "ash4"));
            IComparer<delta> myComparerorder = new compareorder() as IComparer<delta>;
            IComparer<delta> myComparerbool = new comparebool() as IComparer<delta>;
            IComparer<delta> myComparerstring = new comparestring() as IComparer<delta>;
            var sortedDict = mydict.OrderByDescending(x => (delta)x.Value, myComparerbool).ThenBy(x => (delta)x.Value, myComparerorder).ThenBy(x=>(delta)x.Value , myComparerstring);


            foreach (var key in sortedDict)
            {
                var _key = key.Key;
                var _delta = mydict[_key];
                Console.WriteLine(_delta.order + "---" + _delta.global + "----" + _delta.name);
            }
        }
    }
    public class delta
    {
        public bool global;
        public int order;
        public string name;
        public delta(bool _global,int _order,string _name)
        {


            global = _global;
            order = _order;
            name = _name;
        }
    }


    public class compareorder : IComparer<delta>
    {
        public int Compare(delta x, delta y)
        {
            if (x.order > y.order)
                return 1;
            if (x.order < y.order)
                return -1;
            else
                return 0;
        }
    }


    public class comparebool : IComparer<delta>
    {


        public int Compare(delta x, delta y)
        {
            return x.global.CompareTo(y.global);
        }
    }


    public class comparestring : IComparer<delta>
    {


        public int Compare(delta x, delta y)
        {
            return x.name.CompareTo(y.name);
        }
    }




}




The output of the above code will be:---


2---True----ash4
3---True----ash1
1---False----ash3
1---False----bsh2









Friday, March 23, 2007

Creating And Using Satellite Assembly!!!!

As a professional developer, your clients might ask you to develop a website in which users can choose the language they want the site to be in. Somehow, this scenario can be done by developing several pages with several languages. Finally, you can satisfy the clients' requirements. However, it takes you a very long time, and it also wastes your money. There is a faster way to accomplish the requirement. Let's enjoy!
Satellite Assemblies are the answer to this problem!!!!!
I'll tell you what i've experienced while creating a satellite assem
bly...let's try one windows application
1)now create one project naming windowsapplication1

2)now in the windows form add one lable and one dropdown
3)add item and there values in the drop down (english,en-GB) (Swiss German,de-CH) etc.
4)now go to add new resource files with names (any name you like) eg resource1.resx ,string.resx
5) now the way you have to create these resource file is very important here,for example you are choosing a file name as resource1.resx then the files youo will create will be as follows: resource1.resx,resource1.en-GB.resx,resource1.de-CH,resou
rce1.de-AT (I'm using resources for three languages here).
6)open each resource file and set some strings for each file.like the below one for each language and the default language also.













7)Now that you have specified all the resource now you have to build the code to generate all the dll's.
8)Now write the code to use these resource file in your windows form...I've give just a simple funtionality that whenever you change the selection from the dropdown then it will change the text of the lable according to the language selected.

so here is the code in C# for the windows form:
using System;
using System.Collections.Generic;

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Resources;
using System.Globalization;
using System.Threading;


namespace WindowsApplication1
{
public partial class Form1 : Form
{

private ResourceManager rm;
public Form1()
{
InitializeComponent();
}


private void Form1_Load(object sender, EventArgs e)
{

rm = new ResourceManager("WindowsApplication1.Resource1",typeof(Resource1).Assembly);
//string resource = rm.GetString("String1");


//MessageBox.Show(resource);


}

private void ultraComboEditor1_ValueChanged(object sender, EventArgs e)
{
string slang = ultraComboEditor1.Value.ToString();

Thread.CurrentThread.CurrentUICulture = new CultureInfo(slang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(slang);

label1.Text = rm.GetString("String1");

}
}

}
Now try changing the selection and you will see that the lable text will also change.
see the below scenario and you will get why these satellite assemblies are really important:



Thursday, March 15, 2007

Beginning .NET................

The .NET Framework 2.0................

The .NET Framework consists of two parts
1)Common Language Runtime(CLR).
2)Framework Class Library(FCL).

CLR provides the programming model That all application Types will use and FCL provides an object oriented API that all application model will use.CLR includes its own file loader ,memory manager etc. FCL includes type definitions for I/O,drawing shapes,comparing strings etc.



















What above figure shows is how CLR manages the integration of different programming language. By integration i mean that how that class written in C++ can be derivered or can reference a class written in C#.CLR manages this because it defines the Common Type System(CTS) that all the languages that target CLR must use.In order for other languages (any new one or the exsiting one ) to integrate with CLR these languages must use common language specification(CLS) so that they can be integrated with other languages that target CLR.















What above figure is specifying in lay man terms is that let's say you are creating one language and you want that your language can be integrated with CLR i.e. your programme written in your own language can be compiled by JIT('ll come to it later) than it should be using common language specifications in order to be understand by CLR and to be integrated with other CLR supported languages(If I'm wrong please correct me because this is the most common example i can find).You can refer this link to know more about CLS :http://blogs.msdn.com/brada/archive/2004/03/20/93341.aspx



















NOw the above figure is the real funda behind the .NET.Although unmanaged code('ll come to it later) is allowed but CLR is famous for creating managed modules or assembly. The main funda which one can get from the figure that what ever language you C#,visual basics ,your own language(if you can create one),java,perl etc. you should have a compiler(The work of the compiler if to check the syntax and analyze the source code) that can check the syntax and analyze the code and your end result will be a managed module(IL code and metadata[data of data]). managed module can be a portable executable file or a dynamic link library.
IL code is sometimes reffered to as managed code.Every compiler targeting the CLR is required to emit full metadata into every managed module.Metadata is a set of datatable that describe what is defined in the module,such as types and there members.In addition metadata also describe what this managed module references such as imported types and their members.

These assemblies can bemultifile assembly or single file assembly('ll come to it later).While creating a multifile assembly(Including many managed modules into one assembly) or a single file assembly CLR includes a Manifest which indicates the set of files in the assembly.If the manifest indicates that an assembly contains only one file this assembly will be a managed module in itself els if it indicates that group of files are there in an assembly than during build some extra work has to be done('ll come to it later).