GaeUtilities: Session Problem - google-app-engine

I'm programming an application with google app engine, with django 1.1 (no django pacth or others), well as you know is impossible use django login and session features so I download
Gae utility and use Session Object (http://gaeutilities.appspot.com/) but some time this object create 2 sessions instead 1 session ... here's code
def index(request):
aSWrap = SWrap(SWrap.createSession())
....
def login(request):
aSWrap = SWrap(SWrap.createSession())
....
class SWrap(object):
#classmethod
def createSession():
return Session(cookie_name='my_cookie',session_expire_time=7200)
and for setting session no expiration or really long expiration...enter code here
Thanks

Judging by the code, you're calling createsession twice within the same request. That will cause problems with David's library as well.
Also, gaeutilties session included a config file where you can modify all the default values as you like.
https://github.com/joerussbowman/gaeutilities/blob/master/appengine_utilities/settings_default.py
gaeutilities session also has security features lacking in gae-sessions. I'm afraid David didn't attempt to answer you question, rather just suggested you use his library which under your current implementation would have the exact same problem. You need to be sure you only initiate the session once per http request no matter what session library you're using.
I'm moving gaeutilities session to a decorator in order to address this issue as well and provide better performance. You can watch the master branch on Github for updates. https://github.com/joerussbowman/gaeutilities

I suggest using a different sessions library. Check out this comparison of the available sessions libraries for GAE.
I'd recommend gae-sessions - it presents an API almost identical to the library you are currently using, but it is much faster and shouldn't give you headaches like the bug you've encountered above.
Disclaimer: I wrote gae-sessions, but I'm not the only one who would recommend it. Here is a recent thread discussing sessions on the google group for GAE python.

What are you trying to do with SWrap(SWrap.createSession())? It looks like the result of SWrap.createSession() is passed to the SWrap() constructor. Have you omitted part of the definition of SWrap?
Perhaps this is more what you are wanting:
def index(request):
mysession = SWrap.createSession()
....
def login(request):
mysession = SWrap.createSession()
....
class SWrap(object):
#staticmethod
def createSession():
return Session(cookie_name='my_cookie',session_expire_time=7200)

Related

How to protect web client ID in GCP source code

My GAE app publishes some APIs in GCP and uses the following structure:
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '????????????.apps.googleusercontent.com'
ALLOWED_CLIENT_IDS = [WEB_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID]
SCOPES = [endpoints.EMAIL_SCOPE]
#endpoints.api(name=API_NAME,
version=API_VERSION,
description='An API to manage languages',
allowed_client_ids=ALLOWED_CLIENT_IDS,
scopes=SCOPES)
My doubt is if someone picks this source code from my machine or GitHub project. He or she can access the APIs using the discovered web client id.
What’s the best practice in this case?
I acknowledge that the client can expose the ID and someone have access to it. But I believe that is another matter.
There are many ways you can do this. One way is to always check in a default value for the client ID, so that when people check out your code, they have to modify it to deploy it. You can also move the client ID to its own module and not check it in at all, and make the expectation that they create their own module with their own client ID. This avoids having a modified state for a checked in file all of the time.
The client ID itself is not sufficient information to generate a valid token. The cryptography involved will prevent such a person from accessing your API.

Downsides using front-end frameworks for API handling? Performance and security

So, while practising all the new tech. Angular 2, AngularJS, Firebase, Loopback, NodeJS etc .. I'm kind of confused on some topics that people don't really talk about. It might go into too much detail, but I'll try to split it as much as I can.
Part 1 -- Performance
I like the approach of: MyApp (Web, Mobile, ..) --> API <-- Database
Okay, we perform API requests to the same server over HTTP which is slower, but for small projects this should be a non issue right? Or are there any other solutions for this matter?
I know they often just do: MyApp --> Framework <-- Database and add an API interface which calls the correct actions to get the necessary logic/data out to eg. a mobile app
-- End Part 1
Part 2 -- Security
So, assume we have an API up and running either with Lumen, LoopBack or anything else like a realtime Firebase database (not really an API). Then we can connect with it over HTTP requests via Angular, jQuery... If a user inspects our source code, they can easily see how we handle data in the backend. How can this be secured in a way that only the necessary applications have control over the API (OAuth2 ?) and also that we limit the insight of users into our API.
-- End Part 2
Thanks.
Okay, I thought, it's a "too broad" question, but actually, it has a short answer.
Performance
Irrelevant. If you gotta fetch data, you gotta fetch data. Be it API call or some custom action in your laravel code (or something). Same HTTP stuff.
Security
... where a user can check the source code of the API calls.
Security through obscurity doesn't work. Always consider that your client is compromised. Use proper authentication/authorization methods (OAuth and the like). So even if a malicious user knows (which he will) your api endpoint signatures (or whatever you were trying to hide), he can't abuse them.

user / session variables appengine with python

I'm new to app engine, python an web development in general. I have an issue that i don't know how to solve. I want to maintain in the server an tuple with values that the user select. I pass this values to the server in the parameters of the page.
But the problem is that this tuple is modified by all the users and I want that each user can have his own values. The users aren't identified.
I've been looking for how to solve it, and I found some answers here in stackoverflow, but major part of them are more than 2 years old, and I think that I need to use the library gaeutilities, but not sure about it, and If Google have an “official” solution to maintain session variables with python in app engine.
I defined the var “categoria” as a class variable,
class returnElements(webapp2.RequestHandler):
categoria = []
def get(self):
…...
cat = str(self.request.get("cat"))
self.categoria.append(cat)
…...
app = webapp2.WSGIApplication([
('/returnElements', returnElements),
…....
and here the url
http://localhost:13080/returnElements?cat=Sudaderas
It works fine, but just with one user at time :-(
By the way Im new to stackoverflow, sorry in advance if the question isn't accurate or solved in another thread.
In any web app, you must never store user-specific data in module or class-level variables as they will be shared by all users.
If you need to persist data for a user, save it in the datastore! That's what it's for. There are various implementations of user-specific sessions, such as the gaeutilities library which you link to. That library has full documentation which you should read.

What are ResourceContainers and how to use them for Cloud Endpoints?

Since Google AppEngine 1.8.5 there is a new warning in the development environment:
WARNING 2013-09-27 10:10:53,035 api_config.py:1768] Method specifies path
parameters but you are not using a ResourceContainer. This will fail in future
releases; please switch to using ResourceContainer as soon as possible.
What are ResourceContainers and how to use them?
They recently updated the docs to explain this change here: Google App Engine Docs
Basically what you want to do is to separate the request body and the query/path parameters.
The request body will be a normal messages.Message class and you define any additional parameters in the ResourceContainer.
YOUR_RESOURCE_CONTAINER = endpoints.ResourceContainer(
MyRequestBodyMessagesClass,
parameter1=messages.IntegerField(2, required=True)
parameter2=messages.StringField(3))
This change should help to minimize the amount of necessary Message classes because you can mostly reuse the RequestBody-Message for Response-Messages as well.
Note: if you are using the endpoints-proto-datastore there's an open issue about this.

How do I get an instance Id of app engine front server?

And is there a way to send a request directly to that server?
Actually there is a way and it can be useful for pushing new data out to all instances of an application.
from google.appengine.api import modules
instance_id = modules.get_current_instance_id()
ref: GAE Modules Docs
For what purpose?
If you want to test different versions, you can use traffic splitting https://developers.google.com/appengine/docs/adminconsole/trafficsplitting
That is different versions though, and not a specific instance.
No there isn't.
Usually when someone asks something like this, they're headed in the wrong direction on app engine. Frontend servers get started and shutdown all the time. If you are designing anything that relies on a particular instance, you're doing it wrong. You need to design requests that work no matter what instance they hit.
Consider using backends if you must do that.
I use Python and a datetime stamp to identify an instance. This instance id is set by appengine_config.py. To signal other instances I use a flag in memcache, which is checked by the __init__ of my webapp2 request handler.
I use signals to other instances to flush the jinja environment and reload dynamic python code, because I could not find another way.
Here is an example of a memcache flag; signalling to reload all dynamic modules, which had been set by instance id: '2012-12-26 16:39:50.072000'
{ u'_all': { u'dyn_reloads_dt': datetime.datetime(2012, 12, 26, 16, 39, 59, 120000),
u'setter_instance': '2012-12-26 16:39:50.072000'}}
And I starred the feature request from : Ibrahim Arief
With the advent of Modules, you can get the current instance id in a more elegant way:
ModulesServiceFactory.getModulesService().getCurrentInstanceId()
Also, according to this doc, you can route requests specifically to a particular instance by using a URL like
http://instance.version.module.app-id.appspot.com
Note that you need to replace the dot with -dot- to suppress the SSL certificate warning your web client may be complaining about:
http://instance-dot-version-dot-module-dot-app-id.appspot.com

Resources