1
Fork 0
mirror of https://github.com/pds-nest/nest.git synced 2024-11-23 21:44:19 +00:00
pds-2021-g2-nest/nest_backend/routes/users/users.py

82 lines
2.9 KiB
Python
Raw Normal View History

from flask import render_template, abort, jsonify, request
2021-05-05 20:21:04 +00:00
from nest_backend.database import *
2021-05-12 20:22:42 +00:00
from flask_jwt_extended import jwt_required, get_jwt_identity
2021-05-05 20:21:04 +00:00
from nest_backend.gestione import *
from flask_cors import cross_origin
import nest_backend.errors as errors
@cross_origin()
@jwt_required()
def page_users():
"""
2021-05-05 20:21:04 +00:00
---
get:
summary: Get a list of users.
security:
- jwt: []
2021-05-05 20:21:04 +00:00
responses:
'200':
description: A list of User schemas, incapsulated in Success.
'403':
description: The user is not authorized.
content:
application/json:
schema: Error
'401':
description: The user is not logged in.
content:
application/json:
schema: Error
tags:
- user-related
2021-05-05 20:21:04 +00:00
post:
summary: Creates a user.
security:
- jwt: []
2021-05-05 20:21:04 +00:00
requestBody:
required: true
content:
application/json:
schema: CreateUser
responses:
'201':
2021-05-05 20:21:04 +00:00
description: The user has been created successfully.
content:
application/json:
schema: User
'403':
description: The user is not authorized.
content:
application/json:
schema: Error
2021-05-12 15:32:37 +00:00
'406':
description: The user already exists.
content:
application/json:
schema: Error
2021-05-05 20:21:04 +00:00
'401':
description: The user is not logged in.
content:
application/json:
schema: Error
tags:
2021-05-12 15:35:41 +00:00
- admin-only
"""
user = find_user(get_jwt_identity())
if request.method == "GET":
users = User.query.all()
return json_success([user.to_json() for user in users]), 200
if request.method == "POST":
if not user.isAdmin:
return json_error("User is not admin. Thou art not authorized.", errors.USER_NOT_ADMIN), 403
2021-05-12 21:09:29 +00:00
if not request.json.get("email") or not request.json.get("password") or not request.json.get("username"):
return json_error("Missing required fields.", errors.GENERIC_MISSING_FIELDS), 400
2021-05-12 15:32:37 +00:00
if User.query.filter_by(email=request.json.get("email")).first():
return json_error("User already exists.", errors.GENERIC_ALREADY_EXISTS), 406
new_user = User(email=request.json.get("email"), password=gen_password(request.json.get("password")),
username=request.json.get("username"))
2021-05-07 17:46:14 +00:00
ext.session.add(new_user)
2021-05-12 21:09:29 +00:00
ext.session.commit()
return json_success(new_user.to_json()), 201