Hi,
I made a video on a great rest api course in Python. The oauth section of the course is outdated and uses a deprecated Oauth lib. The author has not yet had a chance to update the course.
The course:
https://www.udemy.com/course/advanced-rest-apis-flask-python/
I went ahead and make the changes using the newer library with Python 3.8. I made a video so you can see the changes that needed to be made.
In oa.py
import os
from flask import g
from authlib.integrations.flask_client import OAuth
oauth = OAuth()
oauth.register(
name='github',
client_id=os.getenv('GITHUB_CONSUMER_KEY', default=None),
client_secret=os.getenv('GITHUB_CONSUMER_SECRET', default=None),
access_token_url='https://github.com/login/oauth/access_token',
access_token_params=None,
authorize_url='https://github.com/login/oauth/authorize',
authorize_params=None,
api_base_url='https://api.github.com/',
client_kwargs={'scope': 'user:email'},
)
in github_login.py
from flask_restful import Resource, url_for
from flask import url_for, render_template
from flask_jwt_extended import create_access_token, create_refresh_token
from models.user import UserModel
from oa import oauth
import json
class GithubLogin(Resource):
@classmethod
def get(cls):
redirect_uri = url_for("github.authorize", _external = True)
return oauth.github.authorize_redirect(redirect_uri)
class GithubAuthorize(Resource):
# They already gave us authorization to get details, now we want the access token...
@classmethod
def get(cls):
token = oauth.github.authorize_access_token()
if token is None:
error_response = {
"error":"Error getting token",
"error_description": "Error getting token"
}
return error_response, 401
resp = oauth.github.get('user')
profile = json.loads(resp.text)
username = profile['login']
email = profile['email']
user = UserModel.find_by_username(username)
if not user:
user = UserModel(username=username, password=None)
user.save_to_db()
access_token = create_access_token(identity=user.id, fresh=True)
refresh_token = create_refresh_token(user.id)
return {"access_token":access_token, "refresh_token":refresh_token}, 200
In app.py
from authlib.integrations.flask_client import OAuth
....
from oa import oauth
...
if __name__ == "__main__":
db.init_app(app)
ma.init_app(app)
oauth.init_app(app)
print("Initialized OAuth ")
#print(f"{oauth.github.client_id} - {oauth.github.client_secret}")
app.run(port=5000)