Skip to content

Instantly share code, notes, and snippets.

@sharoonthomas
Created October 9, 2019 12:30
Show Gist options
  • Save sharoonthomas/a2037de1288d3aac9f7b749bab44a2a2 to your computer and use it in GitHub Desktop.
Save sharoonthomas/a2037de1288d3aac9f7b749bab44a2a2 to your computer and use it in GitHub Desktop.
Example of using fulfil authentication in a flask app
@blueprint.route('/login', methods=['GET', 'POST'])
def login():
"""
If there is no login, redirect the user to the authorization url
"""
oauth_session = get_oauth_session()
next = flask.request.args.get('next')
authorization_url, state = oauth_session.create_authorization_url(
redirect_uri=flask.url_for(
'.authorized',
next=next,
_external=True
),
scope=['stock.shipment.out:read']
)
flask.session['oauth_state'] = state
return flask.redirect(authorization_url)
@blueprint.route('/authorized')
def authorized():
"""
Callback function that fulfil will redirect the user to
after a login attempt.
"""
state = flask.request.args.get('state')
oauth_state = flask.session.pop('oauth_state', None)
if not oauth_state or oauth_state != state:
# Verify if state is there in session
flask.abort(401)
code = flask.request.args.get('code')
oauth_session = get_oauth_session()
try:
token = oauth_session.get_token(code=code)
except InvalidGrantError:
return flask.redirect(flask.url_for('public.home'))
if not token:
flask.abort(400)
user = User(
id=token['associated_user']['id'],
login=token['associated_user']['email'],
name=token['associated_user']['name'],
active=True
)
# this access token works as long as the session is active.
flask.session['FULFIL_ACCESS_TOKEN'] = token['access_token']
login_user(user)
next = flask.request.args.get('next')
return flask.redirect(next or flask.url_for('public.home'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment