If you need to get a quick admin panel on your knee, where the frontend will be react-admin , and the backend Flask-RESTful API , then below is the minimum code of several dozen lines to implement this.
Backend Flask-RESTful API
The code itself consists of a single main.py file:
from flask import Flask, request
from flask_restful import Resource, Api
from flask_jwt_extended import JWTManager
from flask_jwt_extended import create_access_token, jwt_required
from flask_cors import CORS
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'my_cool_secret'
jwt = JWTManager(app)
CORS(app)
api = Api(app)
class UserLogin(Resource):
def post(self):
username = request.get_json()['username']
password = request.get_json()['password']
if username == 'admin' and password == 'habr':
access_token = create_access_token(identity={
'role': 'admin',
}, expires_delta=False)
result = {'token': access_token}
return result
return {'error': 'Invalid username and password'}
class ProtectArea(Resource):
@jwt_required
def get(self):
return {'answer': 42}
api.add_resource(UserLogin, '/api/login/')
api.add_resource(ProtectArea, '/api/protect-area/')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Let's run through the code:
- All interaction with the outside world will be carried out by our backend only through the RESTful API, even authorization in the admin panel is also through it. Flask has a handy module for this: Flask-RESTful API
- The flask_jwt_extended module will serve us to protect those routes that can only be accessed after authorization. There is nothing sacred here, just a jwt token ( JSON Web Token ) will be added to the header (header) for each HTTP request, according to which our application will understand that the user is authorized.
In the code above, you can see that the @jwt_required decorator is used for this purpose. You can add it to those API routes that need to be protected. - Without flask_cors we will get the following error.
Access to XMLHttpRequest at 'http://localhost:5000/api/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Install all the necessary libraries and run the code with the command:
python main.pyAs you can see, I hardcoded the login and password for the admin panel: admin / habr.
Once flask is up and running, you can check if it works with curl:
curl -X POST -H "Content-Type: application/json" -d '{"username": "admin", "password": "habr"}' localhost:5000/api/login/
If this is the result:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIU...."
}So everything is correct and you can move to the front.
Comments
Post a Comment