How to keep an Object between calls without using sessions in Django? - python

I'm configuring MangoPay for my web application and it's now time for credit card registration. I'm using the python SDK that MangoPay recommends.
The workflow requires a CardRegistration to be created on the backend, which can be used to generate a form in the front end. On this form the user adds the credit card details, which are sent to a 3rd party tokenisation service and returned to the users front end. This token can be sent now to my backend and, added to the CardRegistration object, can be saved enabling the card for the user.
My issue is that I don't know how to store CardRegistration object between calls in the backend while I wait for the user to generate the token and return it.
Sessions can not be used, as the preregistration object contains sensitive data. To prove if it would have worked and I tried to use pickle but it raises a PicklingError, so serialization and storage doesn't look like an option either.
What should I look into? Is there some kind of design pattern I can use to store the object quickly for retrieval?

Related

How to check if user is signed in the frontend of swift App. Backend in python/django-rest-framework

Im trying to make an IOS app with a frontend coded in swift and the back in python using django's rest api.
I have a tab bar controller set up with two tabs, one ultimately connected to a HomeViewController. I have used firebaseAuth, in which I would normally use a firebase function that looked roughly like this
if firebase.Auth.currentUser != nil {
let vc = HomeViewController()
present(vc, animated:True)
}
However, to the best of my knowledge, django's rest api does not have a function of doing so, and so I have been stuck for a few hours now trying to figure this out.
Currently, I am planning on using the cached access token, retrieved on registration/login and sending a get request which returns the users information. (username and email). Then creating a function to decode the data which returns a boolean.
I plan on making a struct
struct AuthenticatedUser: Codable, Hashable {
let username: String
let email: String
}
If it does not confirm to the appropriate struct, the json decoder will fail. (This would be because the get request returned an error as the token was deleted. (In the process of logging out, i would delete the users tokens).
Finally, I will end up with something like this
if decodeData == false {
let vc = HomeViewController()
present(vc, animated:True)
}
Im sure this would work, but even as someone new to programming I can tell that this code seems longwinded, messy and most likely considered as bad code.
I was wondering if anyone had any improvement/new methods (preferably new methods) on combatting this problem.
Any help will be much appreciated!
Well, first your app does not strictly need to know a priori if the current user (which is some data stored persistently within the app) is signed-in in order to access protected user resources successfully (eventually).
The mechanism required in order to make this work, can be entirely embedded transparently into the "client network code", and your views and other parts of your app which perform "protected data access" do not need to know anything about the login scheme, or whether the user is registered or signed-in.
What is signed-in anyway?
What is registered?
What is a user?
Assuming you are using the more common login schemes (OpenID Connect or an custom scheme based in OAuth) which is based on user authentication, user consent and a bearer token, these questions can be answered as follows:
A user which is a struct containing some data about a real user is the identity which has been successfully authenticated. This information is available after user authentication and authorization which usually are the first two steps in the "register user" flow. This can happen on a third party identity provider, but can also be included in your domain server.
Once you have an authenticated user, the app registers this user in our domain database as part of the registration flow. That is, after this step, your user is registered, and that means, it can access the services provided by your domain server.
A user also can "unregister" and its private data and especially, the "user" record on the domain server will be deleted or marked "unregistered".
The processes running on the front end for this, can run on the device or anywhere, for example a web application or a desk top application.
Now, what should be immediately become clear is, that given a certain app on a certain device and just by querying local state, an app never can determine a priori if a user is registered or not, even if the app has a user info.
Now, suppose an app has a "current user" info, and that the user has been registered, but it is not yet "signed-in".
Signing in means, that the app receives a refresh token and an access token. The access token is the key to access protected user resources. When doing this, no user info is required, the access token is implicitly associated to this user.
The refresh token acts as a key to get a new access token, whose expiration time is much longer, possibly quite long, so that it literally never expires (not recommended).
The expiration duration of an access token is usually in the minutes. So, it is quite common that the access token expires all the time.
The access token will be required when accessing a protected resource, so it will be needed for every protected access.
When it is expired, the server sends a very specific unambiguous status code. So, your client code can act accordingly, which means:
push the request on a queue
use the refresh token and ask for a new access token on a certain refresh-token endpoint
Retry the request with the renewed access token
This mechanism is completely transparent to the higher level code and can be implemented quite deeply in the client network code.
Now, in the event that the refresh token is expired too, you again get an unambiguously status code from the refresh-token endpoint.
In this case, it is clear what to do:
Require the user to sign-in again
Step one returns a are refresh token and also access token
Retry the request.
It is clear, that this requires user interaction and will interrupt the current active flow. It should also be obvious, that an app can also not determine a priory if the refresh token has been expired.
Ideally, this "sign-in-again" flow can be pushed on top of any other flow which happens to access a protected resource. Alternatively, just let the refresh-token request fail without opening a sign-in flow, showing a clear error message hinting that the user needs to sign-in again.
The consequences of this is, that you have to try (or just can try!) to access a protected resource in order to find out whether a user is signed in or even registered.
This all has to be implemented in the client network code. Good luck! ;)

How to create a paypal payment with a custom amount?

I would like to integrate python's paypal sdk into my project so that users can pay however much they choose. The current method requires a fixed price, https://developer.paypal.com/docs/api/quickstart/create-process-order/
However I want the user to be able to choose how much they want to send.
You linked to a server integration document, which is also for a deprecated API.
Do you want to create the order on the server side, or not? If yes, sending the amount from the client to the server that executes the orders API call is work you will need to do.
Begin your integration with the current v2/checkout/orders API by making two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). When a capture response is successful, store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, the PayPal transaction ID) and perform any necessary business logic (such as sending confirmation emails or reserving product) before sending your return JSON.
Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server
Since your question was specific to setting a custom amount, you should probably add a JSON body to the createOrder's fetch call, to send the amount you want to your server.
For a simple client-side integration that uses no server-side API calls, see the documentation and
set the createOrder purchase units value: with some function or variable that gets the value you want. For instance:
value: document.getElementById(...).value
If you are not a programmer, you can even generate such a button for a custom amount via https://www.paypal.com/buttons/smart

How to generate an authentication token for limiting access to my server by external queries

I intend to realize a search engine in a niche area where the results must be searchable only from the front page of my website not through API or web scraping by third parties. It is not therefore any kind of token for users authentications, as the access to the website will be public at least in the beginning (no paywall or user accounts involved.)
My question is which method would be less computationally expensive to generate for each user/visit when someone initiates a search. I thought to use local storage of a random token generated at page loading (such as when some bot is scanning the page to not be able to create the token and therefore to not access the API for receiving search results) however in order to check that a token was issued legit (by my server) this means to grow a continuous database storage with all tokens issued earlier and consumed by users.
This not being a practical solutions for a huge number of users when the traffic will increase I want to know if someone used with success something similar or some better approach.
I don't want to use reCaptcha as a validation method [for human users] as this would offer a very poor user experience on the platform, degrading also the speed of using the system to run the searching queries.
The frontend will be made on React or Vue and backend on Python.
You could go with a set of pre-generated UUIDs in a database to pick-up and flag as used when consumed or compute a SHA3-512 hash from originating IP address + timestamp. On both cases, you can make the back-end process to inject a Set-Cookie containing the token into the response with the proper cookie policies, this key will be automatically provided by web-browsers afterwards but not by bots.

Designing API for internal and remote usage in the Django app

I am starting web project that should be very flexible and modular and definitely will grow much in the future. As we plan to provide an api to other developers I started thinking that maybe it is a good idea to implement all the methods as api and provide functionality to use them remotely and internally.
For instance, say we want to extract all registered Users. So we design method in api, like get_all_users,which maybe available via REST or internal invocation. The problem is I cannot figure out how to distinguish access from internal usage and remote usage, as I should take into consideration also speed of internal invocation,code reusage and checking of user permissions(secret keys for api access, etc). What are the best practices? How to organize such API?
So to build the API, Tastypie or Piston. These let you write 'resources' (which are basically API versions of the views) - instead of returning httpresponses you just return objects which piston/tastypie convert into json or xml or yaml or whatever your favorite data-language is.
Securing the access: Consider decorating any resources which contain confidential information with the #login_required or #staff_member_required decorator as appropriate.
You might even want to go a step further and write a decorator to check that the staff user is using https (whereas you might allow a normal user to use any connection type).
If you have not considered it yet I recommend to use Tastypie to set up an API with django.
In order to distinguish between your internal and remote usage maybe you can simply design a different URL scheme.

handling manual user creation with get_current_user() (GAE)

I am using GAE's Python environment and Janrain in order to provide multiple ways to login in my service.
Based on login information I receive from Janrain, I create a google.appengine.api.User object and store it to the datastore. Is there a way to handle this new object with the built-in get_current_user()? I need to be able to determine whether the requester is logged in or not and who the user is.
No, you cannot use your custom user objects with the native GAE Users API.
You could use a sessions library to track whether or not the request is coming from a logged in user (and who that user is). I recommend gae-sessions. The source includes a demo which shows how to integrate the sessions library with Janrain/RPX.
Disclaimer: I wrote gae-sessions, but for an informative comparison of it with alternatives, read this article.

Categories

Resources