bugmenot123
bugmenot123

Reputation: 1146

Using Python Social Auth with Flask-Login

https://python-social-auth.readthedocs.io/en/latest/configuration/flask.html says "The application works quite well with Flask-Login" however it does not specify what exactly is needed to be implemented and setup.

I used the code snippets from https://github.com/maxcountryman/flask-login to create a tiny PoC of Flask-Login. The user database is a simple dictionary here. It works fine.

# https://github.com/maxcountryman/flask-login
import flask
import flask_login

app = flask.Flask(__name__)
app.secret_key = 'throwaway97b1d9abffce3c5dbf1d3d79079166eede16ca098550'
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
users = {'[email protected]': {'password': 'secret'}}

class User(flask_login.UserMixin):
    pass

@login_manager.user_loader
def user_loader(email):
    if email not in users:
        return

    user = User()
    user.id = email
    return user

@login_manager.request_loader
def request_loader(request):
    email = request.form.get('email')
    if email not in users:
        return

    user = User()
    user.id = email
    return user

@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'GET':
        return '''
<form action='login' method='POST'>
<input type='text' name='email' id='email' placeholder='email'/>
<input type='password' name='password' id='password' placeholder='password'/>
<input type='submit' name='submit'/>
</form>
'''
    email = flask.request.form['email']
    if email in users and flask.request.form['password'] == users[email]['password']:
        user = User()
        user.id = email
        flask_login.login_user(user)
        return flask.redirect(flask.url_for('protected'))

    return 'Bad login'

@app.route('/protected')
@flask_login.login_required
def protected():
    return 'Logged in as: ' + flask_login.current_user.id

@app.route('/logout')
def logout():
    flask_login.logout_user()
    return 'Logged out'

@login_manager.unauthorized_handler
def unauthorized_handler():
    return 'Unauthorized', 401

What do I need to change and add to be able to login to that Flask-Login using a authentication method from Python Social Auth, e. g. a properly set up Discourse forum? The goal would be accessing /protected and seeing information that was received from the serviced used via PSA to login.

Upvotes: 1

Views: 178

Answers (0)

Related Questions