I have setup a loopback API, and I plan to use the login as such flask would make requests to loopback and loopback returns an accessToken
For example login to dashboard:
# Login route
@app.route("/login", methods=['GET', 'POST'])
def login():
status = ""
url_login = 'http://localhost:3000/api/Users/login'
try:
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
payload_login = {
"username": str(username),
"password":str(password)
}
print(payload_login)
r = requests.post(url_login, data=payload_login).text
access_token = json.loads(r)
# access_token = r['id']
# access_token = json.loads(access_token)
print("Access Token: " + str(access_token['id']))
return redirect('/') #CHANGE TO 404 PAGE
except Exception as e:
print(e)
return redirect('/') #CHANGE TO 404 PAGE
return render_template('login.html')
@app.route('/dashboard', methods=['GET', 'POST'])
def logged_in_dashboard():
return render_template('index.html')
How do I set it up so that login to dashboard requires accessToken from loopback? In the past I've used app.config['ACCESS_KEY'] ='key'
and have set that if it contains a token it would allow the user to login.
But I'm not sure if this is a good practice. Anything you would like to recommend that could handle lots of user logins?
Don't create requests to the API from within the API. To share functionality between endpoints, use functions. You need at least two functions here:
Authorization
header, for exampleCheck the approach that chans linked to for more implementation details: How do you implement token authentication in Flask?
Or the official tutorial for how to implement sessions: https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions
Which has something like this:
@app.route('/')
def index():
# this if is the login requirement
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Add logic for validating username and password here.
# If credentials are ok, set username to session.
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With