How can I connect front-end with back-end? - python

I have a web page (front-end) created with ASP.NET (visual studio) on one laptop and a server (back-end) for my web page on another laptop. In the first place, I have a login page and I want to take the username and the password from textBox-es (front-end) and somehow transfer the data to the other laptop to verify if it's correct and then receive if the data it's correct or not. The front-end is on Windows and the server is on Linux. My teammate is using python on back-end.
I'm working with HTML, CSS and a little bit of C# on the front-end and I don't know how to transfer that username and password to my teammate and how to receive an answer from him.
He has the database on his laptop and he's the one who will verify if the pair is correct or not and send me an answer, also he wants to code in python.
We think that we can do some magic connection between ASP.NET and Node.js.
How do I do this data transfer ?
It's my first time doing this so please be gentle because I really don't know what to do.

Your question is quite broad and while I am not that fluent in web applications I will share what advice I can. Because the question is broad, you cannot get an exact, short and concise, answer.
Some clarifications and feedback regarding your question.
I have a web page (front-end) created with ASP.NET ...
You actually have a web application here (that, in your case, includes one, or more, web pages). Give more attention to such little details, programming in itself is a form of grammar natzy-ism but it’s not grammar and you are not being corrected by a person, but by machines and life. A nice definition of web application: https://blog.stackpath.com/web-application/
We think that we can do some magic connection between ASP.NET and Node.js.
I am not specialized in web application but it appears to me that this line comes completely out of the blue, you have not indicated that you are using or intend to use Node.js in your back-end; you indicated that you were using Python, so I will ignore this statement. Oh and there is no magic, there are only race conditions.
Structurally speaking, I would split this question into several smaller ones. Some suggestions follow.
Because you are attempting a somewhat more complicated task you cannot escape de idea of a design pattern (especially because of using ASP.NET which is designed to be patterning friendly).
So your first question should be similar to
how to communicate with a web server asp.net
Two-way communication between ASP.NET Web App and C# Application
back-end is not python but read the answer, it gives you a valid indicator, that request-response pattern could help you
search for questions regarding how to implement that pattern in C#/ASP.NET
Another possible way of how to-ing would be
how to transmit data to server C#
a bit old but reading might give you an understanding of how the ecosystem works
C# server and client communication - send/receive data
maybe helps?
https://codingvision.net/networking/c-sending-data-using-get-or-post
https://www.csharp-examples.net/socket-send-receive/
From you explication I presume that you already have implemented the UI forms that will retrieve the input data so I will skip UI related questions.
Since you wish to send user SENSITIVE data over the internet then you MUST think about security. Further questions
how to store password in database securely
this question will actually lead you to examples of transmitting the password and maybe even receiving the content
https://www.meziantou.net/how-to-store-a-password-in-a-web-application.htm
How to store passwords in database securely?
There are 2 more issues I wish to discuss.
While searching the internet for tutorials you will probably see a
lot working with client and server applications on the same machine.
Those are still valid tutorials for you! Read them! I will explain
further down why it's (almost) the same for you even if your case is
a remote server.
You need to somehow be able to test your application.
Addressing #1
Why working with localhost (127.0.0.1) is for you the same as working with a real server (in your case).
Let's say you finish the application, the back-end is also made and you wish to communicate with one another. You read on the internet that you need to known the IP of the server so you ask your partner to for him to give his IP. You search the wild wild web and reach the conclusion that to find your IP you would try:
executing ipconfig.exe (or what tool you use depending on your platform) and getting the IPv4 Address. . . . . . . . . . . : 192.168.1.12 value.
you would presume that that is the IP you need to put in your application to connect to. This is FALSE.
reaching the conclusion that that does not work, you find that you can get your IP with online sites such as https://whatismyipaddress.com/
and use that IP for your server address. This (in 99% cases) is FALSE.
A bit of poetry
Consider IP as you address in the world and your local (private) IP as the exact place in your house. The IP address you see there is a local IP and it would indicate in which chair you are sitting in, let’s say the 12 from the already provided example. Anyone in the world (who has 12 chairs anyway) can sit in the 12th chair in their house. You cannot use this information to identify the address of someone.
How would you know that that IP is a local IP?
One way would be to look at the the full output of ipconfig.exe (or whatever tool you are using) where you see a Wireless LAN adapter Wi-Fi: above from where you got your IP, the LAN there (hxxps://en.wikipedia.org/wiki/Local_area_network) is an indicator of that.
The other (more straightforward) is by recognizing the IP range (or visual pattern, if IP range is not a clear concept for you just yet). If it starts with 198.168. then it's a local/private IP address. Please read here more: https://en.wikipedia.org/wiki/Private_network
IPs are a valuable commodity (I joke you not). As the world has evolved you cannot now simply plug your computer with an internet cable, and voila you have your own IP. This was (relatively) true when the internet first started decades ago but now the IPs are managed by big (huge) companies that they allocate them as they consider.
The IP address space is managed globally by the Internet Assigned Numbers Authority (IANA), and by five regional Internet registries (RIRs) responsible in their designated territories for assignment to local Internet registries, such as Internet service providers, and other end users.
Wiki quote: https://en.wikipedia.org/wiki/IP_address
I also highly (please do) recommend you read the following answer
hxxps://superuser.com/questions/323801/how-can-i-own-an-ip-address
If you ask your (real world) neighbors to look up https://whatismyipaddress.com/ (and they have the same ISP and monthly plan as you) there is a strong possibility that they will see the same IP as you see. To put it simply, the IP you see there, when accessing sites such as whatismyipaddress, is the IP that that your ISP has assigned to the network node you are in. It would be a waste of IPs to assign each user an IP (not to mention there actually aren’t mathematically that many IPs to do so).
Regarding your current predicament. I can see 3 options.
Option 1 - buy hosting
If your response is "I really really wanna have a separate IP" (or domain) then you will need to buy from a hosting service an IP (the good kind) that will point to a device the hosting company has. You usually buy domains that point to IPs, but let's not got there for now. You will connect to that machine/devices and install your code on the server there. Then, and only then, you could get the IP/domain of that machine and use it in your code and it will work (this is the 1% cases where sites like whatismyipaddress will actually help you).
Recommended searches: server hosting cheap :D (or something free for students if you are students)
Option 2 - work locally
If your project is used for academia and there is no actual need for a separate server then you and your partner will run the client/server applications while connected to the same wireless modem. Ask him to get his IP in this way (here you actually need the LAN IP), you hardcoded it in your code (preferably a separate config file, this way no extra compilation is required) and voila, it works.
Option 3 - LAN over the internet
Technically this would be hard to describe but the idea is you use programs that communicate over the internet, you each install it on your computer, somehow connect with each other (usually a name/password pair) and that software make is seem for the programs on your computer that you are actually in a LAN setup (Option 2). In my days I used hamachi so that we could play CS online :D.
hxxps://www.howtogeek.com/172762/how-to-play-old-lan-games-over-the-internet/
Regarding #2
Until your partner provides a server you will need to test your code. So you will need to somehow fake a server response so that you can actually continue development.
Quite simply, the operation of faking something, a return/a class, in your code, so that you can correctly develop and test your code is known as mocking
how to mock server response asp.net
hxxps://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/
For beginning programmers I think this is one of the most complicated parts. The concept of mocks and tests, while they do appear simple, are usually not engraved into the mind of young, innocent, previously untainted, future programmers. They are left stuck with printfs until graduations (even a dose of hate towards tests is sprinkled in the mix, what a pity).
As a courtesy, I wish to further extend that madness. Please, for all that is good and sacred in this world, do not use this code in production, burn it after you used it to understand some of the basics, BURN IT!
I modified the code from here Python 3.x BaseHTTPServer or http.server so that you could run a local HTTP server on your machine and test your application. You simply run it (python3) and test the sending of user name and password to the server using the following pagan syntax:
127.0.0.1:4242/?user=aba&password=Aba1 which would return I'al cohol you later
#!/usr/bin/python
from http.server import BaseHTTPRequestHandler,HTTPServer
from urllib.parse import urlparse, parse_qs
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT_NUMBER = 4242 # Port to listen on (non-privileged ports are > 1023)
# !!!!!!!!!!!!!!! THIS IS ONLY FOR DIDACTICAL PURPOSE< NEVER EVER DO SOMETHING LIKE THIS IN PRODUCTION!!!!!!!
# NEVER EVER STORE PASSWORDS LIKE THIS !!!!!!!
# LITERRLAY NEVER!!!!!!
data_base = [
{
'user': 'ionzapada',
'password': 'neaomat',
'data': b"I like pie!"
},
{
'user': 'aba',
'password': 'Aba1',
'data': b"I'al cohol you later"
}
]
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
query_components = parse_qs(urlparse(self.path).query)
# DO NOT USE THIS LOGIC ON ANY PRODUCTION PLATFORM!!!!
# NEVER SEND PASSWORDS THIS WAY!!!
# NEVER SEND PASSWORDS!!!!
# NEVER SEND HASHES WITHOUT SALT!!!!
# NEVER IMPLEMENT YOUR OWN TRICKY ALGORITHM!!!!
user_name = query_components.get("user",[None])[0]
password = query_components.get("password",[None])[0]
if user_name and password:
for data_base_entry in data_base:
if data_base_entry['user'] == user_name:
print('Found searched user: {}'.format(user_name))
if data_base_entry['password'] == password:
print('Valid password for user {} given; returning db data'.format(user_name))
self.wfile.write(data_base_entry['data'])
else:
self.wfile.write(b"Not supported!")
else:
self.wfile.write(b"Not supported!")
return
try:
server = HTTPServer((HOST, PORT_NUMBER), myHandler)
print('Started httpserver on port', PORT_NUMBER)
server.serve_forever()
except KeyboardInterrupt:
print('CTRL+C received, shutting down the web server')
server.socket.close()
I burned my finger writing that, do not ever send user names and passwords in this way!!! DO NOT EVEN SEND PASSWORDS FOR THE LOVE OF GOD!!!!!!!! search for standard and secure ways of doing this!!!!
Please also visit the links indicated by #amc they are an also good start.
P.S. I am not allowed to have more then 8 link in one post, on some links that I have posted change the hxxp to http for them to work.

Related

I am looking to run a django server on my personal PC that can be available through WAN

I am currently working on a developmental website and I need to be able to move it to a public domain, so I went and made the purchase of a domain and now i want to make the django app i have written publically available without purchasing a web hosting service quite yet or I might plan on investing in an actually windows server, if anyone knows how to go about doing this purely for developmental use and proff of concept practice, it would be great to see a video or a step by step guide.
This is a really broad question, so I will break it down for you in bits.
Your domain name has 'DNS records'. There are several types but the one you are looking for is the an A record. This type of DNS record points the 'domain.com' to an IP adress. The IP adress needs to be your external IP (can be found by going to api.ipify.org for example). This will make sure that when people on the internet will go to 'domain.com', the traffic is routed to you.
Then, on your own router, you will probably need to configure a NAT rule (e.g. all incoming traffic on port 80 needs to be routed to local IP:80 <ip_adress_of_your_computer>). Often this is called 'port forwarding' on your router, but that depends on the model you have.
After that, your web app is available through your domain name. Note that this is only very basic and does not take into account SSL (https).

How can there be differences in what my Computer sends and what my Router receives?

Since this is my first question, please excuse me if I did anything wrong, I'm happy to learn :)
I have tried to solve this for about 3 months but couldn't get it to work. I think the fault is mine, but the only thing clear to me is that something is wrong. However I've run out of ideas where this could be.
tl;dr:
I'm having trouble with my desktop and router appearing to capture different traffic, without anything between those two. I have rewritten my scripts several times but couldn't get it to work.
Here is my context:
In my bachelor thesis I'm interested in middlebox behaviour.
For this I have a setup in which I have one Ubuntu Server machine set up as a router using dnsmasq and the isc-dhcp-server and another machine running Ubuntu Desktop connected to the Server machines subnet over ethernet.
To test the middleboxes, I'm calling every on of the Alexa top sites (for testing purposes either the top 10 or top 100) using Firefox + Selenium with each middlebox and once without anything between the Desktop and Server(Router). At the same time I'm logging the requested domains using tcpdump on the desktop and on the server. However for my question, the middleboxes are not really important, they're only illustrating why I'm doing this.
To illustrate my setup I made this diagram(I'm not allowed to post images since I don't have enough reputation):
The Desktop is looping through the Alexa List, whereas the server is in an infinite loop, until it receives a quit message from the Desktop.
In the Desktops script there are timeouts (I've experimented with timeouts between 3s and 60s) between each step. It cycles through the Alexa List with websites.
Tcpdumps are named according to the current domain+middlebox/plain.
Afterwards another python script is loading the tcpdumps, cycles through dns packets and creates a dictionary with IP:Domain mapping. Then it creates a dictionary with each domain from the Alexa list as a key and the value containing a set of subsequently called domains. This is done for traffic captured on the server and traffic captured on the Desktop, however they both use the Desktops DNS Dictionary.
Finally I have a Script comparing the generated Dictionaries.
To verify the differences between Desktop and Server for middleboxes, I compare the Plain pages as well. However there are always differences between the domains captured on the desktop and on the server. Usually between 2 and 5 subcalls per alexa domain differing (Those are subcalls I would expect other Alexa Domains to call. For example wikipedia.org is probably not calling facebook.com, but facebook.com itself probably is. Facebook showing up as a subcall of wikipedia is what irritates me). From my understanding this shouldn't be the case. In the beginning I was using the Python Library PyShark, but because those problems were appearing I thought using tcpdump directly might do the trick.
I tried setting bigger timeouts, I tried capturing all traffic in a single file and I tried rewriting every line of code I thought could be erroneous.
There has to be an error somewhere, but I can't seem to find it. I know there is always some package loss, but especially when connected directly through ethernet I can't imagine it being this high.
I expect unexpected behavior from the combination between selenium/firefox and tcpdump. Latency in startup/closing down of those may be an issue, but I don't think this could be longer than 60s. I also expect the Ubuntu Desktop to send auto update requests and other system services while I'm running the test, but first I don't think they're doing that many requests and second I have my iptables set up to only allow tcp requests from the user that starts the python script.
Thank you so much for taking the time.
If you have any ideas/remarks where I could have gone wrong, I'd be grateful to hear it. If you have further questions, please don't hesitate to ask.
EDIT:(Clarification about what I'm trying to achieve)
My hypothesis is, that if I call a domain with my desktop computers browser and capture the network traffic on both the desktop and the router, both captures should contain the same packets.
If I have a middlebox which is blocking some of the domains and put it between the desktop computer and router, comparing the domains appearing in the captured traffic on the pc and on the router should yield exactly those domains, which the middlebox blocked.
My Problem:
Even without a middlebox, there is a difference in the captured traffic and I don't know where it is coming from.
Example (I made this one up, I'll post a real one once I'm back at uni):
Expected behavior:
wikipedia.org: {On PC but not on Router: [], On Router but not on PC: []}
facebook.com: {On PC but not on Router: [], On Router but not on PC: []}
Actual behavior:
wikipedia.org: {On PC but not on Router: [facebook.com], On Router but not on PC: []}
facebook.com: {On PC but not on Router: [], On Router but not on PC: []}

How do I get the client port number in a Django project?

I am using django to build my web server, other people connect to me as clients. Now I need to know the clients' port number to distinguish them. If their browser opens two 'Tabs' of the same link, i.e. two pages but the same link, I also have to distinguish them.
Although I know I can use request.META['REMOTE_ADDR'] to get the client's IP in my django view function, but this realy is not enough for me.
Then I studied some TCP/IP basics and then I know that in TCP/IP layer, every IP packet has an IP header which contains the client's port number. But how can I access it in django?
Additional info:
I'm using python 2.6 and django 1.4
I know every TAB of a browser will be allocated a random unique port to access my django web page port. -- see this link 'The web server opens port 80, but the browser has a different, randomly-assigned port.' I really need to distinguish them. So my intuitive thoughts is to use the port number in the IP packet. If you have any other suggestion, also welcome.
I have found the similar question here, but I am not using Apache now. And this may be hard for me to config so maybe causing other more complex questions. This might make this simple question complex.
while I debug the django , I find this
request.environ["wsgi.input"].raw._sock.getpeername()
maybe it can work
Yes, after days of struggling, I answer it, with a working, but ugly solution on 'how to get client port in Django'.
in your python26/Lib/SocketServer.py, find def process_request_thread,add
global gClientPort; gClientPort = client_address
use this global value in yout project. Its format is ('12.34.56.78',55437) for example. 55437 is the port number.
Your assumption about 'every user connection opens connection at unique port' is wrong. All users are using the same port to connect.
To distinguish users Django (and almost every other frameworks) is using sessions. Every user gets a cookie with his unique session ID, and this cookie is passed to a server on every connection, so the application can distinguish users.
Here is documentation on sessions:
https://docs.djangoproject.com/en/1.8/topics/http/sessions/

Python chat p2p system over internet

I want to build a peer to peer chat engine that runs over the Internet. So far my code works on a local network but not further. This is due to the fact that listening on sockets using python sockets does not make them available outside of the LAN.
It is acceptable for IPs to be shared knowledge, ie it is ok for the other person to need to know my IP address (and a port on which I am listening) to connect to me.
How does one tell the router to open a socket to the outside world? Presumably this can be done as p2p software such as BitTorrent must do it for communication between clients.
As you have mentioned you have to open a specific port on the router and use that port for communication. As there are many router manufacturers each with a variety of models I suggest you to check the manual for the router you want to use.
for the code, you may check if your code works on LAN and then see if the router let's you white-list some ports. you may find many simple examples online.
this is a code i played sometime ago:
http://www.mediafire.com/download/vef4q4prkr7be2e/python.socket.zip
if you don't want users to mess up with ports and router settings and such, first alternative i can think of is this:
you setup an REST API, in one interface one is able to retrieve the messages providing (chatRoomName, FromTimestamp, ToTimestamp[,optionally chatRoomPassWord]) but this has nothing to do with sockets, you have to use simple HTTP requests(urllib/urllib2). Of course there might exist some workaround for this such as an always-white-listed port(like 80 for browsers, 22 for SSH) but you have to search for such exceptions.
note that ports up to 1024 require special privileges(admin/sudo) to be used.
p.s. in traditional implementation other party(client) have to know your (ip, port) duo to be able to connect to the you(server).

Bitcoinrpc connection to remote server

Hey I was wondering if anyone knew how to connect to a bitcoin wallet located on another server with bitcoinrpc
I am running a web program made in django and using a python library called bitcoinrpc to make connections.
When testing locally, I can use bitcoinrpc.connect_to_local), or even bitcoinrpc.connect_to_remote('account','password') and this works as well as long as the account and password match the values specified in my 'bitcoin.conf' file. I can then use the connection object to get values and do some tasks in my django site.
The third parameter in connect_to_local is default localhost. I was wondering:
A) What to specify for this third parameter in order to connect from my webserver to the wallet stored on my home comp (is it my IP address?)
B) Because the wallet is on my PC and not some dedicated server, does that mean that my IP will change and I won't be able to access the wallet?
C) The connection string is in the django app - which is hosted on heroku. Heroku apps are launched by pushing with git but I believe it is to a private repository. Still, if anyone could see the first few lines of my 'view' they would have all they need to take my BTC (or, more accurately, mBTC). Anyone know how bad this is - or any ways to go about doing btc payments/movements in a more secure way.
Thanks a lot.
I'm currently doing something very similar (heroku using express/nodejs instead of django/python tho) so I will try to share my thoughts.
In spite of using other library and other language, all the wallet remote libraries should be primarily a wrapper around JSON RPC (remote procedure call) API, which is actually the same for most of the coins out there (i would say all, but that would be a wild guess).
Specifically to your questions:
A)
To access the wallet from outside, use your external ip (fastest way to find it is to query google for it). Depending on your ISP you hopefully have static external address. You must provide this address to bitcoin.conf file under rpcallowip= option to allow incomming connections.
Moreover you should forward the used port in your home router (usually under NAT settings) to your local machine so the incoming connection from the server is allowed and redirected to your wallet computer.
There is one important thing to consider (https://en.bitcoin.it/wiki/Running_Bitcoin):
By default, only RPC connections from localhost are allowed. Specify
as many rpcallowip= settings as you like to allow connections from
other hosts (and you may use * as a wildcard character).
NOTE: opening up the RPC port to hosts outside your local
trusted network is NOT RECOMMENDED, because the rpcpassword
is transmitted over the network unencrypted.
I am yet to look into it further, from this comment alone it seems totally unusable for monetary transactions.
B)
As I said before, it depends on your home ISP, type of connection and the service provided to you.
C)
If I understand correctly from a django point of view, as long as the login parameters (username/password) are inside a view (views.py of your app) and the debug mode is turned off, source code of the server should not be publicly accessible. But the security concern from A still applies.
You can use SSL with RPC to hide the password.
rpcssl=1

Categories