Redirect User to original URL after Google login in Flask - google-oauth

I have implemented flask-dance and authlib Flask client for Google sign-in, one answer was unclear in all implementations were how to redirect a user to original user once they login. For example, a flow I wanted => clicks on /results checks if not logged in redirect to login makes them login and then again redirects back to results with logged in session.
I saw some answers using state and kwargs addition but didn't see any clear answer or a pseudo code implementation.
If you have implemented such a scenario please answer the question it will help a lot or you can also reference to your Github projects if implemented

The simple solution i discovered to my own problem was in any implementation for any such library use a session variable to record orignal url and then redirect user after login using that variable so in here i have used next param variable which stores it temp then once authorized sends user to orignal url what they asked for
see the code below
#app.route('/login')
def login():
google = oauth.create_client('google')
redirect_uri = url_for('authorize', _external=True)
return google.authorize_redirect(redirect_uri)
#app.route("/dashboard")
def protect():
if not session.get('profile'):
session['next']='/dashboard'
return redirect('/login')
if session['profile']:
#load dashboard
else:
return "forbidden"
#app.route('/authorize')
def authorize():
google = oauth.create_client('google')
token = google.authorize_access_token()
resp = google.get('userinfo')
user_info = resp.json()
user = oauth.google.userinfo()
session['profile'] = user_info
session.permanent = True
redirecti=session.get("next",None)
return redirect(redirecti)

Related

python requests login with redirect

I'd like to automate my log in to my bank to automatically fetch my transactions to stay up-to-date with spendings and earnings, but I am stuck.
The bank's login webpage is: https://login.bancochile.cl/bancochile-web/persona/login/index.html#/login
I am using python's request module with sessions:
urlLoginPage = 'https://login.bancochile.cl/bancochile-web/persona/login/index.html'
urlLoginSubmit = 'https://login.bancochile.cl/oam/server/auth_cred_submit'
username = '11.111.111-1' # this the format of a Chilean National ID ("RUT")
usernameFormatted = '111111111' # same id but formatted
pw = "password"
payload = [
("username2", usernameFormatted),
("username2", username),
("userpassword", pw),
("request_id", ''),
("ctx", "persona"),
("username", usernameFormatted),
("password", pw),
]
with requests.Session() as session:
login = session.get(urlLoginPage)
postLogin = session.post(
urlLoginSubmit,
data=payload,
allow_redirects=False,
)
redirectUrl = postLogin.headers["Location"]
First I find that the form data has duplicated keys, so I am using the payload as a list of tuples. From Chrome's inspect I find the form data to be like this:
username2=111111111&username2=11.111.111-1&userpassword=password&request_id=&ctx=persona&username=111111111&password=password
I've checked the page's source code to look for the use of a csrf token, but couldn't find any hint of it.
What happens is that the site does a redirect upon submitting the login data. I set allow_redirects=False to catch the redirect url of the post under the Location-header. However, here is the problem. Using the web-browser I know that the redirect url should be https://portalpersonas.bancochile.cl/mibancochile/rest/persona/perfilamiento/home, but I always end up on an error page when using the above method (https://login.bancochile.cl/bancochile-web/contingencia/error404.html). (I am using my own, correct login credentials to try this)
If I submit the payload in a wrong format (e.g. by dropping a key) I am redirected to the same error-page. This tells me that probably something with the payload is incorrect, but I don't know how to find out what may be wrong.
I am kind of stuck and don't know how I can figure out where/how to look for errors and possible solutions. Any suggestions on how to debug this and continue or ideas for other approaches would be very welcome!
Thanks!

Flask - How to require login only for post requests

I'm working in Flask and I want to allow users to enter information into a form without logging in but be required to login if they submit the form. After logging in, it should be as though a user just submitted the form (they shouldn't have to re-enter any information).
To store their information, I've used sessions like this. It works well:
if request.method == "POST":
if "arg1" not in session.keys() and "arg2" not in session.keys():
session["arg1"] = request.form.get('arg1')
session["arg2"] = request.form.get('arg2')
However, I'm having trouble with the login required part. I know I can use #login_required on the whole route but I just want #login_required to apply if the request is a post method. I've tried simply adding #login_required after checking if the method is a post request but it doesn't work.
My login route looks like this:
#app.route("/login", methods = ["POST", "GET"])
def login():
#log user in
return redirect(request.args.get("next") or url_for('index'))
It seems as though I need two things.
1: To apply #login_required solely to a post request.
2: To have request.args.get("next") call a post request, not get request
How could I go about doing these two things and achieve my goal?
Thank you!
Break out your routes. 1 for GET and 1 for POST
#app.route("/login", methods = ["GET"])
def get_login():
return stuff
#app.route("/login", methods = ["POST"])
#login_required
def post_login():
return stuff
There are a couple patterns that could be used here but this one is the most straight forward.

How to get the response content in selenium?

When I open the URL with driver.get(url), how can I get the response content of the page? Please refer to the image for more information.
In a separate post I saw this answer. As per it there is a ticket opened for Selenium.
I'm using Python and Django, but it's actually simple to get the response. I'm using a StaticLiveServerTestCase as my base test for the test. The .get() method on self.client actually returns the response itself. For example:
response = self.client.get(url)
However, it looks like what you're really trying to get is the cookie based on what you're pointing to in the picture. I use Django and the Django test suite to authenticate a user session to be used in the test.
def create_pre_authenticated_session(self, username, url="/"):
user = User.objects.create(username=username)
session = SessionStore()
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session[HASH_SESSION_KEY] = user.get_session_auth_hash()
session.save()
# to set a cookie we need to first visit the domain.
# 404 pages load the quickest!
self.browser.get(self.live_server_url + '/404_no_such_url/')
self.browser.add_cookie(dict(
name=settings.SESSION_COOKIE_NAME,
value=session.session_key,
secure=False,
path='/',
))
self.browser.get(self.live_server_url + url)
return user
This has some other stuff in it that I borrowed from Percival's Test-Driven Development with Python, but I hope that it can provide some guidance on what you're trying to accomplish.

How to get useID/Email of logged in user in Google Contacts API after OauTh Token

I developed a program which works well and I can import data from gmail but. I want to keep track how is the user given permission to manage contacts. But after a hard search I did not get any Idea about the loged in user. My code is as follows.
============================================
var parameters = new OAuth2Parameters
{
ClientId = ConfigurationManager.AppSettings["ClientID"].ToString(),
ClientSecret = ConfigurationManager.AppSettings["ClientSecret"].ToString(),
RedirectUri = ConfigurationManager.AppSettings["RedirectURL"].ToString(),
Scope ="https://www.googleapis.com/auth/userinfo.profile"
};
parameters.AccessCode = Request.QueryString["Code"].ToString();
OAuthUtil.GetAccessToken(parameters);
Session["Token"] = parameters.AccessToken;
==================================
But I dont how to get email of logged in user. Please let me that
Thanks in advance
Request an additionall scope of https://www.googleapis.com/auth/userinfo.email and then you can access the user info as well. There is also a userinfo.profile witch contains other info on the user like name, profile picture, language and so on.
Your code looks like C# but I only have a Python example of using multiple scopes and sharing tokens.
Code: https://code.google.com/p/google-api-oauth-demo/
Article: http://www.hackviking.com/2013/10/python-get-user-info-after-oauth/

Facebook OAuth login for iframe canvas apps displays a logo image and a Go to Facebook.com caption instead of logging in

I'm trying to set up my (iframe) Facebook application to use OAuth for authentication.
I used the python-sdk from Facebook, but I'm not really satisfied by the result, yet.
The problem is that when I redirect a user that never accessed my application to the login page, my iframe diplays an ugly intermediate page, such as the following one:
If the user clicks on "Go to Facebook.com" link, she is then redirected to the standard "Request for Permission" page.
Is there any way to avoid the first page and lead the user straight to the second one?
This problem happens on the first access for users that haven't granted any permission to my application yet.
The login code is based on the OAuth example in the Python SDK:
class LoginHandler(BaseHandler):
def get(self):
verification_code = self.request.get("code")
args = dict(client_id=FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
if self.request.get("code"):
args["client_secret"] = FACEBOOK_APP_SECRET
args["code"] = self.request.get("code")
raw_response = urllib.urlopen(
"https://graph.facebook.com/oauth/access_token?" +
urllib.urlencode(args)).read()
logging.debug("access_token raw response " + raw_response)
response = cgi.parse_qs(raw_response)
access_token = response["access_token"][-1]
# Download the user profile and cache a local instance of the
# basic profile info
graph = facebook.GraphAPI(access_token)
profile = graph.get_object("me")
user = User.get_by_key_name(profile["id"])
if not user:
user = User(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
firstname=profile["first_name"],
profile_url=profile["link"],
access_token=access_token)
user.put()
elif user.access_token != access_token:
# we already know this user, but we need to update
user.access_token = access_token
user.put()
set_cookie(self.response, "fb_user", str(profile["id"]),
expires=time.time() + 30 * 86400)
self.response.headers["P3P"] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"'
self.redirect("/")
else:
self.redirect(
"https://graph.facebook.com/oauth/authorize?" +
urllib.urlencode(args))
The issue is caused to the code Facebook uses to bust out of iframes. A bug has been filed on Facebook's bugzilla: http://bugs.developers.facebook.net/show_bug.cgi?id=11326
The only known solution to this problem is to do the first redirect to https://graph.facebook.com/oauth/authorize? from the client side (i.e. Via JavaScript), using
<script type='text/javascript'>
top.location.href="https://graph.facebook.com/oauth/authorize?.......
</script>
This can be triggered when the user clicks on some element (e.g. a login button) or whenever a specific page is visited (just include it in the HTML head).
yes, top.location.href should do the trick. If you get the problem that the app breaks out the iframe, make sure you use the canvas PAGE url in your redirect, in stead of canvas url (in your app settings)
This happens, apparently due to a bug in the Facebook side... I found this solution.
<script type="text/javascript">
top.location.href = '<?php echo $loginUrl ?>';
</script>
$loginUrl = your URL
Could work this way:
<script type="text/javascript">
top.location.href = 'http://www.yourappUrl.com';
</script>
always use this code in script tags...
The first page is an error. You absolutely can avoid that page. The problem is likely related to how you are doing the redirects to the login page in the first place. Without a code sample, that is really the best answer I can give.