Showing posts with label connection. Show all posts
Showing posts with label connection. Show all posts

Monday, November 6, 2017

Node msnodesqlv8 connection using trusted Connection

Leave a Comment
This summary is not available. Please click here to view the post.
Read More

Sunday, October 8, 2017

Connecting, authorizing and getting data for a web application using PHP

Leave a Comment

Any help/advice/direction would be greatly appreciated. Try bearing with me even if this question is not specific.

I am working on a web application which will connect to a pre-existing commercial cloud-based calendar which will have schedules for a certain event.

I will have a authorize button which will simply ask the users to enter their credentials for that cloud-based calendar. Once users enter their credentials successfully, I want my application to connect to the cloud-based application's database and fetch the necessary data.

The flow will be like

Users -> Click Authorize button -> Enter credentials -> Connect to the system -> Get the necessary data -> Update it in my web application.

I am on a point of drawing a blank because I don't find any useful resources on how to gain access to a separate application and fetching the data. I am aware I have to build an API of some sort to communicate with that system, but I don't know exactly HOW.

Sorry, if I am not making sense, but I really want some help here. Are there some libraries which provide a similar functionality? How should I even start? I am using PHP as a server-side language.

4 Answers

Answers 1

  1. Button On Click -> Redirect to Login Form

  2. Loging Form ->User Enters Credentials -> Submit Form

  3. In the respective action page ie. the page where you will post the data, you will have Username/Email and Password

  4. You have to authenticate. Now to authenticate you can't have the direct access to the other server database (cloud database directly) so you need to call the API of the respective cloud base database for which you want to authenticate. For this call, you can use CURL call with POST parameters or any necessary HTTP request like GET, POST, PUT, DELETE, PATCH. Make sure you use the TOKEN based API call. Even you can go for any respectively secured API calls as per the cloud database design for security.

BONUS: So what is token-based API call? Whenever you're requesting the API call to cross server ie. other servers make sure you can some random text sent along with the other parameters. The server on the other hand which received your request make sure to validate this token from its respective database table to make sure that you're the valid user and allows you to perform the necessary action like get customer details, get product details and so on.

  1. The authentication API returns the AUTHENTICATED data. Based on that you can continue to perform the actions.

  2. In case if the authentication fails, then you can flash the invalid credentials error message to the user.

  3. If its success then you will be granted the access and you can now perform an insertion data to your database.

  4. To read the data from the other database table, since you won't have the necessary permission you can't directly access it. Make the API call to the respective function to get all the necessary data, whether it may be GET, POST, PUT, DELETE, PATCH.

  5. As of now think that you want to get all the data of table CUSTOMER then you will have to make GET request to the API which returns the JSON data.

  6. Now its left to you what you want to do with this data. Whether you want to save this in your respective database table or play around with it on the fly.

To learn how to write the API's

Eg:

NOTE: I have not added any security check make sure you work out on the same

Think that your doing GET request to get the details of the customers then you can do like the following

API URL: http://127.0.0.1/project/getCustomers.php?token=2fdsd5f42314sfd85sds REQUEST METHOD: GET

getCustomers.php

<?php include_once 'dbConnect.php'; //I am having $link as database link //Only !isset will also work $errors = []; if(empty($_GET['token']) || !isset($_GET['token'])){     $errors[] = 'Token not found!'; }else{     $token = $_GET['token']; } //tokens table will have (id, user_id, token) coloumns $tokenQuery = mysqli_connect($link, "SELECT * FROM tokens WHERE token = '$token' LIMIT 1"); //If I get any result with the respective token if(mysqli_num_rows($tokenQuery) > 0){     $tokenDetails = mysqli_fetch_assoc($tokenQuery);     $userId = $tokenDetails['user_id'];     /* Now you can check whether the user has Authorization to access the particular module */     $isUserAuthorized = checkUserAuthorizationModule($userId); //Please help your self to do this all checks      if($isUserAuthorized === TRUE){         $customersQuery = mysqli_query($link, "SELECT * FROM customers");         $customersDetails = [];         if(mysqli_num_rows($customersQuery) > 0){             while($row = mysqli_fetch_assoc($customersQuery)){                 $customersDetails[] = $row;             }         }          return json_encode([             'customerDetails' => $customersDetails         ]);     } }else{     $errors[] = 'Token is not valid'; }  return json_encode([     'errors' => $errors ]); 

Answers 2

There's one way you could do it...

I'm gona get creative here:

  1. Hit an API endpoint on your server, deliver 'username' and 'password'.

  2. Store username and password to a .txt file on this server. The name of the txt file is the timestamp 'now'

  3. On this same server, launch a chain of USER INTERFACE commands, something like this (using a library like xdotool):

    • move the mouse to mozilla icon on the desktop,
    • double-click on mozilla,
    • move the mouse to the address bar,
    • go to the calendar website,
    • move mouse,
    • write username you got from user,
    • tab,
    • write password you got from user,
    • hit enter,
    • move mouse to place where you download calendar to csv (or you can select, and ctrl-c copy),
    • using mouse, save the file to a public html directory of server (name it the same you named the txt file up there).
  4. have the client webapp check constantly for that .txt file with the calendar info. Once the info is fetched, display it on your screen.

Voila.

Answers 3

Depends much on the resources available ate the platform. But if it has PHP, you can implement RESTFUL services that exchange data using JSON as Channaveer Hakari response, except that maybe you wouldn't take data from mySQL, but the flow and technologies and protocol are that (RESTFULL services, data delivered JSON type, because it can be consumed on a great variety of programming languages).

Answers 4

It really depends on how the cloud calendar likes to be interacted with.

Are you able to tell us what service it is?

For example, if it supports OAuth that may be a way to register your app with the service for that user, and then allow your app to update data to their account. This is how for example Facebook works when it asks your for a third party website to have permission to look at your contacts and make posts to your wall etc. This is almost the defacto standard of the Internet these days for your use case.

Alternatively it could be a case of like you said, grabbing their credentials and storing them, then connecting to the calendars REST API with those credentials and making updates. I would say this is a bad approach from a security point of view. No user should give their credentials to a third party and trust them. That is a bad idea. It's one of the reasons OAuth exists.

If you're building a small app for a small company for internal use only the second approach may be fine. I'll leave it up to you to decide.

Read More

Monday, February 27, 2017

Creating a connection to a subscription site in python

Leave a Comment

I am looking to open a connection with python to http://www.horseandcountry.tv which takes my login parameters via the POST method. I would like to open a connection to this website in order to scrape the site for all video links (this, I also don't know how to do yet but am using the project to learn).

My question is how do I pass my credentials to the individual pages of the website? For example if all I wanted to do was use python code to open a browser window pointing to http://play.horseandcountry.tv/live/ and have it open with me already logged in, how do I go about this?

3 Answers

Answers 1

As far as I know you have two options depending how you want to crawl and what you need to crawl:

1) Use urllib. You can do your POST request with the necessary login credentials. This is the low level solution, which means that this is fast, but doesn't handle high level stuff like javascript codes.

2) Use selenium. Whith that you can simulate a browser (Chrome, Firefox, other..), and run actions via your python code. Then it is much slower but works well with too "sophisticated" websites.

What I usually do: I try the first option and if a encounter a problem like a javascript security layer on the website, then go for option 2. Moreover, selenium can open a real web browser from your desktop and give you a visual of your scrapping.

In any case, just goolge "urllib/selenium login to website" and you'll find what you need.

Answers 2

If you want to avoid using Selenium (opening web browsers), you can go for requests, it can login the website and grab anything you need in the background.

Here is how you can login to that website with requests.

import requests from bs4 import BeautifulSoup  #Login Form Data payload = {      'account_email': 'your_email',     'account_password': 'your_passowrd',     'submit':   'Sign In' }  with requests.Session() as s:     #Login to the website.     response = s.post('https://play.horseandcountry.tv/login/', data=payload)      #Check if logged in successfully     soup = BeautifulSoup(response.text, 'lxml')     logged_in = soup.find('p', attrs={'class': 'navbar-text pull-right'})     print s.cookies     print response.status_code     if logged_in.text.startswith('Logged in as'):         print 'Logged In Successfully!' 

If you need explanations for this, you can check this answer, or requests documentation

Answers 3

You could also use the requests module. It is one the most popular. Here are some questions that relate to what you would like to do.

Log in to website using Python Requests module

logging in to website using requests

Read More

Wednesday, April 13, 2016

Android runtime exec with NetworkRequest

Leave a Comment

I am running a command line argument in my Android application like:

ProcessBuilder pb = new ProcessBuilder(cmds); Process process = pb.start(); process.waitFor(); 

Where cmds are a list of arguments to run. My commands probe a remote URL over a http connection. My device is connected to a WiFi network that does not have access to the internet, but does host the URL I want to probe. My device also has a cellular connection that does have access to the internet, but not the URL. My device is running Android 6.0 Marshmallow.

Normally in Lollipop or above, Android defaults to the network with a connection to the internet. To access WiFi networks without internet you need to use NetworkRequest, e.g: http://stackoverflow.com/a/27958106/1847734.

How can I pass an obtained Network to the above Process, so that the connection goes over my WiFi network, not my cellular network?

Do I instead need to use ConnectivityManager#bindProcessToNetwork? How do I join the process to set the network using this method? There doesn't seem to be an option to give the process.

1 Answers

Answers 1

Starting from Lollipop Network is Parcelable so you can write it to a byte array and then read back. Let's start from the writing part.

final Parcel parcel = Parcel.obtain(); try {   // Create a byte array from Network.   parcel.writeParcelable(network, 0);   final byte[] data = parcel.marshall();    // Start a process.   ProcessBuilder pb = new ProcessBuilder(cmds);   Process process = pb.start();    // Send serialized Network to the process.   final DataOutputStream out = new DataOutputStream(process.getOutputStream());   out.write(data.length);   out.write(data);    // Wait until the process terminates.   process.waitFor(); } finally {   parcel.recycle(); } 

And the reading part.

// Read data from the input stream. final DataInputStream in = new DataInputStream(System.in); final int length = in.readInt(); final byte[] data = new byte[length]; in.readFully(data);  final Parcel parcel = Parcel.obtain(); try {   // Restore Network from a byte array.   parcel.unmarshall(data, 0, data.length);   final Network network = parcel.readParcelable(null);    // Use the Network object to bind the process to it.   connectivityManager.bindProcessToNetwork(network); } finally {   parcel.recycle(); } 

This code will work on Android 6.0 only. If you want it to work on Lollipop you should use ConnectivityManager.setProcessDefaultNetwork(Network) instead of ConnectivityManager.bindProcessToNetwork(Network). And this code is not going to work on devices before Android 5.0.

Read More