1
Fork 0
mirror of https://github.com/pds-nest/nest.git synced 2024-11-22 04:54:18 +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
<!-- TODO: Configurazione del database -->
Perchè il backend gestisca correttamente i cookie <!-- TODO: ma noi non usiamo cookies...? -->, è necessario che la
seguente variabile di ambiente sia settata a una stringa casuale:
### Configurazione del Database
Dopo aver installato Postgres, è necessario creare un database dedicato all'applicazione (ad esempio PdSTest).
Se si desidera, si può anche creare un utente dedicato (l'utente postgres di default va benissimo).
Per configurare l'URI del database che N.E.S.T. andrà a impiegare, è necessario eseguire
```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
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 .
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

View file

@ -5,7 +5,7 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/nest_backend" isTestSource="false" />
</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" />
</component>
</module>

View file

@ -22,7 +22,10 @@ else:
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)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost:5432/PdSDev'
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'
Base.app = app
Base.init_app(app)
jwt = JWTManager(app)
@ -44,4 +47,7 @@ if __name__ == "__main__":
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.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",
"msg": "Stop right there, criminal scum! Nobody accesses protected data under MY watch!"}), 403
return f(*args, **kwargs)
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")
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")
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()
if not condition:
condition = Condition(content=content, type=ConditionType.__getattr__(str(type)).value)
Base.session.add(condition)
repository = Repository.query.filter_by(request.json.get("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.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())
name = request.json.get("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)
Base.session.add(repository)
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:
repository.isActive = True
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").
"""
user = find_user(get_jwt_identity())
return {"result": "success", "content": {"owner": [r.to_json() for r in user.owner_of],
"spectator": [r.repository.to_json() for r in user.authorizations]}}
return json_success({"owner": [r.to_json() for r in user.owner_of],
"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>.
"""
if not request.json:
abort(400)
email = request.json.get("email", None)
password = request.json.get("password", None)
if authenticate(email, password):
access_token = create_access_token(identity=email)
user = find_user(email)
return jsonify({"result": "success", "access_token": access_token, 'user': user.to_json()}), 201
return jsonify({"result": "failure", "msg": "Bad username or password."}), 401
return json_success({"access_token": access_token, 'user': user.to_json()}), 201
return json_error("Bad username or password."), 401

View file

@ -23,4 +23,4 @@ def page_user_create():
username=request.json.get("username"))
Base.session.add(nUser)
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())
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'))
if not target:
return jsonify({"result": "failure", "msg": "User not found."}), 404
return json_error("User not found."), 404
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.commit()
return jsonify({"result": "success", "content":"The user has been deleted."})
return json_success("The user has been deleted.")

View file

@ -3,15 +3,18 @@ import json
auth_code = ""
def test_login():
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'})
j = json.loads(r.text)
assert j['result'] == "failure"
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)
assert j['result'] == "success"
auth_code = j['access_token']
auth_code = j['data']['access_token']
print("Login eseguito correttamente!")
print("Testing del login")
test_login()