prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  User should be redirected to his original destination after login with Google OAuth
  If the user tried to open a page before being logged in, he should be redirected to this page after successful login.
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `redash/google_oauth.py`
  Content:
  ```
  1 import logging
  2 from flask.ext.login import login_user
  3 import requests
  4 from flask import redirect, url_for, Blueprint, flash
  5 from flask_oauth import OAuth
  6 from redash import models, settings
  7 
  8 logger = logging.getLogger('google_oauth')
  9 oauth = OAuth()
  10 
  11 
  12 if not settings.GOOGLE_APPS_DOMAIN:
  13     logger.warning("No Google Apps domain defined, all Google accounts allowed.")
  14 
  15 google = oauth.remote_app('google',
  16                           base_url='https://www.google.com/accounts/',
  17                           authorize_url='https://accounts.google.com/o/oauth2/auth',
  18                           request_token_url=None,
  19                           request_token_params={
  20                               'scope': 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
  21                               'response_type': 'code'
  22                           },
  23                           access_token_url='https://accounts.google.com/o/oauth2/token',
  24                           access_token_method='POST',
  25                           access_token_params={'grant_type': 'authorization_code'},
  26                           consumer_key=settings.GOOGLE_CLIENT_ID,
  27                           consumer_secret=settings.GOOGLE_CLIENT_SECRET)
  28 
  29 
  30 blueprint = Blueprint('google_oauth', __name__)
  31 
  32 
  33 def get_user_profile(access_token):
  34     headers = {'Authorization': 'OAuth {}'.format(access_token)}
  35     response = requests.get('https://www.googleapis.com/oauth2/v1/userinfo', headers=headers)
  36 
  37     if response.status_code == 401:
  38         logger.warning("Failed getting user profile (response code 401).")
  39         return None
  40 
  41     return response.json()
  42 
  43 
  44 def verify_profile(profile):
  45     if not settings.GOOGLE_APPS_DOMAIN:
  46         return True
  47 
  48     domain = profile['email'].split('@')[-1]
  49     return domain in settings.GOOGLE_APPS_DOMAIN
  50 
  51 
  52 def create_and_login_user(name, email):
  53     try:
  54         user_object = models.User.get_by_email(email)
  55         if user_object.name != name:
  56             logger.debug("Updating user name (%r -> %r)", user_object.name, name)
  57             user_object.name = name
  58             user_object.save()
  59     except models.User.DoesNotExist:
  60         logger.debug("Creating user object (%r)", name)
  61         user_object = models.User.create(name=name, email=email, groups=models.User.DEFAULT_GROUPS)
  62 
  63     login_user(user_object, remember=True)
  64 
  65 
  66 @blueprint.route('/oauth/google', endpoint="authorize")
  67 def login():
  68     # TODO, suport next
  69     callback=url_for('.callback', _external=True)
  70     logger.debug("Callback url: %s", callback)
  71     return google.authorize(callback=callback)
  72 
  73 
  74 @blueprint.route('/oauth/google_callback', endpoint="callback")
  75 @google.authorized_handler
  76 def authorized(resp):
  77     access_token = resp['access_token']
  78 
  79     if access_token is None:
  80         logger.warning("Access token missing in call back request.")
  81         flash("Validation error. Please retry.")
  82         return redirect(url_for('login'))
  83 
  84     profile = get_user_profile(access_token)
  85     if profile is None:
  86         flash("Validation error. Please retry.")
  87         return redirect(url_for('login'))
  88 
  89     if not verify_profile(profile):
  90         logger.warning("User tried to login with unauthorized domain name: %s", profile['email'])
  91         flash("Your Google Apps domain name isn't allowed.")
  92         return redirect(url_for('login'))
  93 
  94     create_and_login_user(profile['name'], profile['email'])
  95 
  96     return redirect(url_for('index'))
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/redash/google_oauth.py b/redash/google_oauth.py
  --- a/redash/google_oauth.py
  +++ b/redash/google_oauth.py
  @@ -1,8 +1,8 @@
   import logging
   from flask.ext.login import login_user
   import requests
  -from flask import redirect, url_for, Blueprint, flash
  -from flask_oauth import OAuth
  +from flask import redirect, url_for, Blueprint, flash, request
  +from flask_oauthlib.client import OAuth
   from redash import models, settings
   
   logger = logging.getLogger('google_oauth')
  @@ -18,11 +18,9 @@
                             request_token_url=None,
                             request_token_params={
                                 'scope': 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
  -                              'response_type': 'code'
                             },
                             access_token_url='https://accounts.google.com/o/oauth2/token',
                             access_token_method='POST',
  -                          access_token_params={'grant_type': 'authorization_code'},
                             consumer_key=settings.GOOGLE_CLIENT_ID,
                             consumer_secret=settings.GOOGLE_CLIENT_SECRET)
   
  @@ -65,10 +63,10 @@
   
   @blueprint.route('/oauth/google', endpoint="authorize")
   def login():
  -    # TODO, suport next
  +    next = request.args.get('next','/')
       callback=url_for('.callback', _external=True)
       logger.debug("Callback url: %s", callback)
  -    return google.authorize(callback=callback)
  +    return google.authorize(callback=callback, state=next)
   
   
   @blueprint.route('/oauth/google_callback', endpoint="callback")
  @@ -93,4 +91,6 @@
   
       create_and_login_user(profile['name'], profile['email'])
   
  -    return redirect(url_for('index'))
  \ No newline at end of file
  +    next = request.args.get('state','/')
  +
  +    return redirect(next)
  
verification_info: {"golden_diff": "diff --git a/redash/google_oauth.py b/redash/google_oauth.py\n--- a/redash/google_oauth.py\n+++ b/redash/google_oauth.py\n@@ -1,8 +1,8 @@\n import logging\n from flask.ext.login import login_user\n import requests\n-from flask import redirect, url_for, Blueprint, flash\n-from flask_oauth import OAuth\n+from flask import redirect, url_for, Blueprint, flash, request\n+from flask_oauthlib.client import OAuth\n from redash import models, settings\n \n logger = logging.getLogger('google_oauth')\n@@ -18,11 +18,9 @@\n                           request_token_url=None,\n                           request_token_params={\n                               'scope': 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',\n-                              'response_type': 'code'\n                           },\n                           access_token_url='https://accounts.google.com/o/oauth2/token',\n                           access_token_method='POST',\n-                          access_token_params={'grant_type': 'authorization_code'},\n                           consumer_key=settings.GOOGLE_CLIENT_ID,\n                           consumer_secret=settings.GOOGLE_CLIENT_SECRET)\n \n@@ -65,10 +63,10 @@\n \n @blueprint.route('/oauth/google', endpoint=\"authorize\")\n def login():\n-    # TODO, suport next\n+    next = request.args.get('next','/')\n     callback=url_for('.callback', _external=True)\n     logger.debug(\"Callback url: %s\", callback)\n-    return google.authorize(callback=callback)\n+    return google.authorize(callback=callback, state=next)\n \n \n @blueprint.route('/oauth/google_callback', endpoint=\"callback\")\n@@ -93,4 +91,6 @@\n \n     create_and_login_user(profile['name'], profile['email'])\n \n-    return redirect(url_for('index'))\n\\ No newline at end of file\n+    next = request.args.get('state','/')\n+\n+    return redirect(next)\n", "issue": "User should be redirected to his original destination after login with Google OAuth\nIf the user tried to open a page before being logged in, he should be redirected to this page after successful login.\n\n", "before_files": [{"content": "import logging\nfrom flask.ext.login import login_user\nimport requests\nfrom flask import redirect, url_for, Blueprint, flash\nfrom flask_oauth import OAuth\nfrom redash import models, settings\n\nlogger = logging.getLogger('google_oauth')\noauth = OAuth()\n\n\nif not settings.GOOGLE_APPS_DOMAIN:\n    logger.warning(\"No Google Apps domain defined, all Google accounts allowed.\")\n\ngoogle = oauth.remote_app('google',\n                          base_url='https://www.google.com/accounts/',\n                          authorize_url='https://accounts.google.com/o/oauth2/auth',\n                          request_token_url=None,\n                          request_token_params={\n                              'scope': 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',\n                              'response_type': 'code'\n                          },\n                          access_token_url='https://accounts.google.com/o/oauth2/token',\n                          access_token_method='POST',\n                          access_token_params={'grant_type': 'authorization_code'},\n                          consumer_key=settings.GOOGLE_CLIENT_ID,\n                          consumer_secret=settings.GOOGLE_CLIENT_SECRET)\n\n\nblueprint = Blueprint('google_oauth', __name__)\n\n\ndef get_user_profile(access_token):\n    headers = {'Authorization': 'OAuth {}'.format(access_token)}\n    response = requests.get('https://www.googleapis.com/oauth2/v1/userinfo', headers=headers)\n\n    if response.status_code == 401:\n        logger.warning(\"Failed getting user profile (response code 401).\")\n        return None\n\n    return response.json()\n\n\ndef verify_profile(profile):\n    if not settings.GOOGLE_APPS_DOMAIN:\n        return True\n\n    domain = profile['email'].split('@')[-1]\n    return domain in settings.GOOGLE_APPS_DOMAIN\n\n\ndef create_and_login_user(name, email):\n    try:\n        user_object = models.User.get_by_email(email)\n        if user_object.name != name:\n            logger.debug(\"Updating user name (%r -> %r)\", user_object.name, name)\n            user_object.name = name\n            user_object.save()\n    except models.User.DoesNotExist:\n        logger.debug(\"Creating user object (%r)\", name)\n        user_object = models.User.create(name=name, email=email, groups=models.User.DEFAULT_GROUPS)\n\n    login_user(user_object, remember=True)\n\n\n@blueprint.route('/oauth/google', endpoint=\"authorize\")\ndef login():\n    # TODO, suport next\n    callback=url_for('.callback', _external=True)\n    logger.debug(\"Callback url: %s\", callback)\n    return google.authorize(callback=callback)\n\n\n@blueprint.route('/oauth/google_callback', endpoint=\"callback\")\n@google.authorized_handler\ndef authorized(resp):\n    access_token = resp['access_token']\n\n    if access_token is None:\n        logger.warning(\"Access token missing in call back request.\")\n        flash(\"Validation error. Please retry.\")\n        return redirect(url_for('login'))\n\n    profile = get_user_profile(access_token)\n    if profile is None:\n        flash(\"Validation error. Please retry.\")\n        return redirect(url_for('login'))\n\n    if not verify_profile(profile):\n        logger.warning(\"User tried to login with unauthorized domain name: %s\", profile['email'])\n        flash(\"Your Google Apps domain name isn't allowed.\")\n        return redirect(url_for('login'))\n\n    create_and_login_user(profile['name'], profile['email'])\n\n    return redirect(url_for('index'))", "path": "redash/google_oauth.py"}], "after_files": [{"content": "import logging\nfrom flask.ext.login import login_user\nimport requests\nfrom flask import redirect, url_for, Blueprint, flash, request\nfrom flask_oauthlib.client import OAuth\nfrom redash import models, settings\n\nlogger = logging.getLogger('google_oauth')\noauth = OAuth()\n\n\nif not settings.GOOGLE_APPS_DOMAIN:\n    logger.warning(\"No Google Apps domain defined, all Google accounts allowed.\")\n\ngoogle = oauth.remote_app('google',\n                          base_url='https://www.google.com/accounts/',\n                          authorize_url='https://accounts.google.com/o/oauth2/auth',\n                          request_token_url=None,\n                          request_token_params={\n                              'scope': 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',\n                          },\n                          access_token_url='https://accounts.google.com/o/oauth2/token',\n                          access_token_method='POST',\n                          consumer_key=settings.GOOGLE_CLIENT_ID,\n                          consumer_secret=settings.GOOGLE_CLIENT_SECRET)\n\n\nblueprint = Blueprint('google_oauth', __name__)\n\n\ndef get_user_profile(access_token):\n    headers = {'Authorization': 'OAuth {}'.format(access_token)}\n    response = requests.get('https://www.googleapis.com/oauth2/v1/userinfo', headers=headers)\n\n    if response.status_code == 401:\n        logger.warning(\"Failed getting user profile (response code 401).\")\n        return None\n\n    return response.json()\n\n\ndef verify_profile(profile):\n    if not settings.GOOGLE_APPS_DOMAIN:\n        return True\n\n    domain = profile['email'].split('@')[-1]\n    return domain in settings.GOOGLE_APPS_DOMAIN\n\n\ndef create_and_login_user(name, email):\n    try:\n        user_object = models.User.get_by_email(email)\n        if user_object.name != name:\n            logger.debug(\"Updating user name (%r -> %r)\", user_object.name, name)\n            user_object.name = name\n            user_object.save()\n    except models.User.DoesNotExist:\n        logger.debug(\"Creating user object (%r)\", name)\n        user_object = models.User.create(name=name, email=email, groups=models.User.DEFAULT_GROUPS)\n\n    login_user(user_object, remember=True)\n\n\n@blueprint.route('/oauth/google', endpoint=\"authorize\")\ndef login():\n    next = request.args.get('next','/')\n    callback=url_for('.callback', _external=True)\n    logger.debug(\"Callback url: %s\", callback)\n    return google.authorize(callback=callback, state=next)\n\n\n@blueprint.route('/oauth/google_callback', endpoint=\"callback\")\n@google.authorized_handler\ndef authorized(resp):\n    access_token = resp['access_token']\n\n    if access_token is None:\n        logger.warning(\"Access token missing in call back request.\")\n        flash(\"Validation error. Please retry.\")\n        return redirect(url_for('login'))\n\n    profile = get_user_profile(access_token)\n    if profile is None:\n        flash(\"Validation error. Please retry.\")\n        return redirect(url_for('login'))\n\n    if not verify_profile(profile):\n        logger.warning(\"User tried to login with unauthorized domain name: %s\", profile['email'])\n        flash(\"Your Google Apps domain name isn't allowed.\")\n        return redirect(url_for('login'))\n\n    create_and_login_user(profile['name'], profile['email'])\n\n    next = request.args.get('state','/')\n\n    return redirect(next)\n", "path": "redash/google_oauth.py"}]}