1
Fork 0
mirror of https://github.com/pds-nest/nest.git synced 2024-11-25 22:44:19 +00:00

Uniformed json output

Warning: breaking changes ahead! All the data that gets returned by functions is now incapsulated within "data" (response['data']).
This commit is contained in:
Lorenzo Balugani 2021-04-26 16:26:25 +02:00
parent 335dce68f7
commit bbf7c1e360
12 changed files with 64 additions and 32 deletions

View file

@ -25,15 +25,31 @@ Questo creerà un nuovo venv nelle cartelle interne di Poetry e vi installerà a
## Configurazione ## Configurazione
<!-- TODO: Configurazione del database --> ### Configurazione del Database
Dopo aver installato Postgres, è necessario creare un database dedicato all'applicazione (ad esempio PdSTest).
Perchè il backend gestisca correttamente i cookie <!-- TODO: ma noi non usiamo cookies...? -->, è necessario che la Se si desidera, si può anche creare un utente dedicato (l'utente postgres di default va benissimo).
seguente variabile di ambiente sia settata a una stringa casuale: Per configurare l'URI del database che N.E.S.T. andrà a impiegare, è necessario eseguire
```bash ```bash
export COOKIE_SECRET=hippityhoppity export DATABASE_URI=postgresql://[postgresUser]:[postgresPassword]@localhost:[port, default 5432]/[DatabaseName]
``` ```
Ora il database è pronto per l'uso.
### Altre variabili d'ambiente
Questo ultimo passaggio è importante solo in un ambiente non-dev. La configurazione andrà a valore di default nel caso
in cui queste variabili non siano definite.
Per terminare la configurazione, eseguire:
```bash
export COOKIE_SECRET=[cookiepass]
export JWT_SECRET_KEY=[jwtsecret]
export DISABLE_DEBUG=[farts]
```
Queste due variabili d'ambiente conterranno le chiavi con cui i cookie e le key di autorizzazione JWT saranno
cifrate.
## Avvio ## Avvio
Per avviare il backend, è innanzitutto necessario attivare il venv contenente le dipendenze con il seguente comando: Per avviare il backend, è innanzitutto necessario attivare il venv contenente le dipendenze con il seguente comando:
@ -53,7 +69,7 @@ python -m nest_backend
Le pagine web del server sono disponibili a http://127.0.0.1:5000 . Le pagine web del server sono disponibili a http://127.0.0.1:5000 .
Mentre il development server è avviato, _buona parte_ delle modifiche saranno rilevate e applicate automaticamente Mentre il development server è avviato, _buona parte_ delle modifiche saranno rilevate e applicate automaticamente
senza dover riavviare il server. senza dover riavviare il server. Per testare la connettività, visitare http://127.0.0.1:5000/doa.
## Deployment ## Deployment

View file

@ -5,7 +5,7 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/nest_backend" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/nest_backend" isTestSource="false" />
</content> </content>
<orderEntry type="jdk" jdkName="Poetry (backend)" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="Poetry (g2-progetto) (2)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
</module> </module>

View file

@ -22,6 +22,9 @@ else:
app.config["JWT_SECRET_KEY"] = "testing" app.config["JWT_SECRET_KEY"] = "testing"
reverse_proxy_app = werkzeug.middleware.proxy_fix.ProxyFix(app=app, x_for=1, x_proto=0, x_host=1, x_port=0, x_prefix=0) reverse_proxy_app = werkzeug.middleware.proxy_fix.ProxyFix(app=app, x_for=1, x_proto=0, x_host=1, x_port=0, x_prefix=0)
if os.getenv("DATABASE_URI"):
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URI')
else:
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost:5432/PdSDev' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost:5432/PdSDev'
Base.app = app Base.app = app
Base.init_app(app) Base.init_app(app)
@ -44,4 +47,7 @@ if __name__ == "__main__":
if not User.query.filter_by(isAdmin=True).all(): if not User.query.filter_by(isAdmin=True).all():
Base.session.add(User(email="admin@admin.com", password=gen_password("password"), username="admin", isAdmin=True)) Base.session.add(User(email="admin@admin.com", password=gen_password("password"), username="admin", isAdmin=True))
Base.session.commit() Base.session.commit()
app.run(debug=True) debug = True
if os.getenv("DISABLE_DEBUG"):
debug = False
app.run(debug=debug)

View file

@ -78,4 +78,13 @@ def repository_auth(f):
return jsonify({"result": "failure", return jsonify({"result": "failure",
"msg": "Stop right there, criminal scum! Nobody accesses protected data under MY watch!"}), 403 "msg": "Stop right there, criminal scum! Nobody accesses protected data under MY watch!"}), 403
return f(*args, **kwargs) return f(*args, **kwargs)
return func return func
def json_error(msg):
return jsonify({"result": "failure", 'msg': msg})
def json_success(data):
return jsonify({"result": "success", "data": data})

View file

@ -18,17 +18,17 @@ def page_repository_add_condition():
""" """
type = request.json.get("type") type = request.json.get("type")
if not type or type not in dir(ConditionType): if not type or type not in dir(ConditionType):
return jsonify({"result": "failure", "msg": "Could not understand the type of the condition."}), 400 return json_error("Could not understand the type of the condition."), 400
content = request.json.get("content") content = request.json.get("content")
if not content: if not content:
return jsonify({"result": "failure", "msg": "Could not find the content"}), 400 return json_error("Could not find the content"), 400
condition = Condition.query.filter(Condition.content.ilike(str(content))).filter_by(type=ConditionType.__getattr__(str(type)).value).first() condition = Condition.query.filter(Condition.content.ilike(str(content))).filter_by(type=ConditionType.__getattr__(str(type)).value).first()
if not condition: if not condition:
condition = Condition(content=content, type=ConditionType.__getattr__(str(type)).value) condition = Condition(content=content, type=ConditionType.__getattr__(str(type)).value)
Base.session.add(condition) Base.session.add(condition)
repository = Repository.query.filter_by(request.json.get("id")) repository = Repository.query.filter_by(request.json.get("id"))
if Uses.query.filter_by(cid=condition.id, rid=repository.id): if Uses.query.filter_by(cid=condition.id, rid=repository.id):
return jsonify({"result": "failure", "msg": "This condition is already connected to the repository."}), 406 return json_error("This condition is already connected to the repository."), 406
Base.session.add(Uses(cid=condition.id, rid=repository.id)) Base.session.add(Uses(cid=condition.id, rid=repository.id))
Base.session.commit() Base.session.commit()
return jsonify({"result": "success", "content": "Condition added successfully."}), 200 return json_success("Operation done with success."), 200

View file

@ -18,8 +18,8 @@ def page_repository_create():
user = find_user(get_jwt_identity()) user = find_user(get_jwt_identity())
name = request.json.get("name") name = request.json.get("name")
if not name: if not name:
return jsonify({"result": "failure", "msg": "Missing one or more parameters"}), 400 return json_error("Missing one or more parameters"), 400
repository = Repository(name=name, owner_id=user.email) repository = Repository(name=name, owner_id=user.email)
Base.session.add(repository) Base.session.add(repository)
Base.session.commit() Base.session.commit()
return jsonify({"result": "success", "content": repository.to_json()}), 200 return json_success(repository.to_json()), 200

View file

@ -25,4 +25,4 @@ def page_repository_edit():
if 'open' in request.json and not repository.isActive and not repository.end: if 'open' in request.json and not repository.isActive and not repository.end:
repository.isActive = True repository.isActive = True
Base.session.commit() Base.session.commit()
return jsonify({"result": "success", "content":repository.to_json()}) return json_success(repository.to_json())

View file

@ -14,5 +14,5 @@ def page_repository_list():
the user ("owner") and a list of repositories that he can spectate ("spectator"). the user ("owner") and a list of repositories that he can spectate ("spectator").
""" """
user = find_user(get_jwt_identity()) user = find_user(get_jwt_identity())
return {"result": "success", "content": {"owner": [r.to_json() for r in user.owner_of], return json_success({"owner": [r.to_json() for r in user.owner_of],
"spectator": [r.repository.to_json() for r in user.authorizations]}} "spectator": [r.repository.to_json() for r in user.authorizations]})

View file

@ -15,12 +15,10 @@ def page_login():
The access_token must be included in the Authorization header, using the format Bearer <token>. The access_token must be included in the Authorization header, using the format Bearer <token>.
""" """
if not request.json:
abort(400)
email = request.json.get("email", None) email = request.json.get("email", None)
password = request.json.get("password", None) password = request.json.get("password", None)
if authenticate(email, password): if authenticate(email, password):
access_token = create_access_token(identity=email) access_token = create_access_token(identity=email)
user = find_user(email) user = find_user(email)
return jsonify({"result": "success", "access_token": access_token, 'user': user.to_json()}), 201 return json_success({"access_token": access_token, 'user': user.to_json()}), 201
return jsonify({"result": "failure", "msg": "Bad username or password."}), 401 return json_error("Bad username or password."), 401

View file

@ -23,4 +23,4 @@ def page_user_create():
username=request.json.get("username")) username=request.json.get("username"))
Base.session.add(nUser) Base.session.add(nUser)
Base.session.commit() Base.session.commit()
return jsonify({"result": "success", "content": user.to_json()}) return json_success(user.to_json())

View file

@ -16,12 +16,12 @@ def page_user_delete():
""" """
user = find_user(get_jwt_identity()) user = find_user(get_jwt_identity())
if not user.isAdmin: if not user.isAdmin:
return jsonify({"result": "failure", "msg": "User is not admin."}), 403 return json_error("User is not admin."), 403
target = find_user(request.json.get('email')) target = find_user(request.json.get('email'))
if not target: if not target:
return jsonify({"result": "failure", "msg": "User not found."}), 404 return json_error("User not found."), 404
if user == target: if user == target:
return jsonify({"result": "failure", "msg": "The user cant delete himself. Its a sin."}), 406 return json_error("The user cant delete himself. Its a sin."), 406
Base.session.remove(target) Base.session.remove(target)
Base.session.commit() Base.session.commit()
return jsonify({"result": "success", "content":"The user has been deleted."}) return json_success("The user has been deleted.")

View file

@ -3,6 +3,7 @@ import json
auth_code = "" auth_code = ""
def test_login(): def test_login():
global auth_code global auth_code
r = requests.post('http://localhost:5000/api/login', json={'email': 'admin@admin.com', 'password': 'amogus'}) r = requests.post('http://localhost:5000/api/login', json={'email': 'admin@admin.com', 'password': 'amogus'})
@ -11,7 +12,9 @@ def test_login():
r = requests.post('http://localhost:5000/api/login', json={'email': 'admin@admin.com', 'password': 'password'}) r = requests.post('http://localhost:5000/api/login', json={'email': 'admin@admin.com', 'password': 'password'})
j = json.loads(r.text) j = json.loads(r.text)
assert j['result'] == "success" assert j['result'] == "success"
auth_code = j['access_token'] auth_code = j['data']['access_token']
print("Login eseguito correttamente!")
print("Testing del login") print("Testing del login")
test_login() test_login()