diff --git a/FlaskAPI/.cert b/FlaskAPI/.cert new file mode 100644 index 0000000..e69de29 diff --git a/FlaskAPI/.gitignore b/FlaskAPI/.gitignore index b3cac3e..d03277b 100644 --- a/FlaskAPI/.gitignore +++ b/FlaskAPI/.gitignore @@ -1,3 +1,4 @@ .env venv/ -.idea/ \ No newline at end of file +.idea/ +.cert \ No newline at end of file diff --git a/FlaskAPI/__pycache__/__init__.cpython-37.pyc b/FlaskAPI/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000..6ec7abf Binary files /dev/null and b/FlaskAPI/__pycache__/__init__.cpython-37.pyc differ diff --git a/FlaskAPI/__pycache__/app.cpython-37.pyc b/FlaskAPI/__pycache__/app.cpython-37.pyc new file mode 100644 index 0000000..68fd050 Binary files /dev/null and b/FlaskAPI/__pycache__/app.cpython-37.pyc differ diff --git a/FlaskAPI/__pycache__/models.cpython-36.pyc b/FlaskAPI/__pycache__/models.cpython-36.pyc new file mode 100644 index 0000000..4e9ab10 Binary files /dev/null and b/FlaskAPI/__pycache__/models.cpython-36.pyc differ diff --git a/FlaskAPI/__pycache__/settings.cpython-36.pyc b/FlaskAPI/__pycache__/settings.cpython-36.pyc new file mode 100644 index 0000000..687b55c Binary files /dev/null and b/FlaskAPI/__pycache__/settings.cpython-36.pyc differ diff --git a/FlaskAPI/__pycache__/settings.cpython-37.pyc b/FlaskAPI/__pycache__/settings.cpython-37.pyc new file mode 100644 index 0000000..0dad0ea Binary files /dev/null and b/FlaskAPI/__pycache__/settings.cpython-37.pyc differ diff --git a/FlaskAPI/__pycache__/views.cpython-36.pyc b/FlaskAPI/__pycache__/views.cpython-36.pyc new file mode 100644 index 0000000..ac81534 Binary files /dev/null and b/FlaskAPI/__pycache__/views.cpython-36.pyc differ diff --git a/FlaskAPI/app.py b/FlaskAPI/app.py index 4b059ec..5d44e04 100644 --- a/FlaskAPI/app.py +++ b/FlaskAPI/app.py @@ -1,12 +1,57 @@ -from flask import Flask +from flask import Flask, request, render_template, jsonify +from flask_cors import CORS +from flask_jwt_extended import JWTManager, jwt_required, get_raw_jwt +from views import schema_blueprint +from views import db + +from settings import CERT + +import jwt as tokenizer +import os +import requests +from dotenv import load_dotenv app = Flask(__name__) +app.config.from_object('settings') + +cors = CORS(app, resources={r"/*": {"origins": "*"}}) +jwt = JWTManager(app) +app.config.update(JWT=jwt) + +app.register_blueprint(schema_blueprint) + +db.init_app(app) -@app.route('/') +@app.before_first_request +def create_database(): + db.create_all() + +@app.route('/ola') +@jwt_required def hello_world(): + token = request.headers["Authorization"].split()[1] # Split Bearer from token return 'Hello World!' +@app.route('/node/') +def node_info(nodeID): + if nodeID=='1': + r = requests.get('http://192.168.1.141:5000/testi') + if r.status_code != 200: + msg = {'msg': 'Erro 200'} + return msg + return jsonify(r.json()) + + if nodeID=='2': + r = requests.get('http://192.168.1.142:5000/testi') + if r.status_code != 200: + msg = {'msg': 'Erro 200'} + return msg + return jsonify(r.json()) + + if __name__ == '__main__': - app.run() + app.run(host=app.config['HOST'], + port=app.config['PORT'], + debug=app.config['DEBUG']) diff --git a/FlaskAPI/models.py b/FlaskAPI/models.py new file mode 100644 index 0000000..45a651a --- /dev/null +++ b/FlaskAPI/models.py @@ -0,0 +1,190 @@ +from flask_sqlalchemy import SQLAlchemy +from marshmallow import Schema + +db = SQLAlchemy() +session = None +class CRUD: + def add(self, resource): + db.session.add(resource) + return db.session.commit() + + def update(self): + return db.session.commit() + + def delete(self, resource): + db.session.delete(resource) + return db.session.commit() + + +class Role (db.Model, CRUD): + + __tablename__ = 'role' + id = db.Column(db.Integer, primary_key=True) + role_name = db.Column(db.String(20)) + + def __init__(self, role_name): + self.role_name = role_name + + @property + def serializable(self): + return { + 'id': self.id, + 'role_name': self.role_name, + } + + +class Profile(db.Model, CRUD): + + __tablename__ = 'profile' + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.String(80), nullable=False) + email = db.Column(db.String(200), nullable=False, unique=True) + num_test = db.Column(db.INTEGER, nullable=True) + register_date = db.Column(db.TIMESTAMP, nullable=False) + picture = db.Column(db.String(10485760), nullable=True) + last_login = db.Column(db.TIMESTAMP, nullable=True) + role = db.Column(db.Integer, db.ForeignKey('role.id')) + + def __init__(self, name, email, register_date, role, num_test=None, picture=None, last_login=None): + self.name = name + self.email = email + self.num_test = num_test + self.register_date = register_date + self.picture = picture + self.last_login = last_login + self.role = role + + def __repr__(self): + return '= date_start).filter( date_finish >= Experience.end_date) + + else: + if parse_data['begin_date']: + date = datetime.strptime(parse_data['begin_date'], "%Y-%m-%d").date() + experiences_query = experiences_query.filter(Experience.begin_date >= date) + if parse_data['end_date']: + date = datetime.strptime(parse_data['end_date'], "%Y-%m-%d").date() + experiences_query = experiences_query.filter(Experience.end_date <= date) + if parse_data['status']: + experiences_query = experiences_query.filter(Experience.status == parse_data['status']) + if parse_data['content']: + experiences_query = experiences_query.filter(Experience.name.contains(parse_data['content'])) + q = experiences_query.all() + response = [] + for experience, profile in q: + experience = experience.serializable + profile = profile.serializable + experience['author'] = profile['name'] + response.append(experience) + return jsonify(response) + + @jwt_required + def post(self): + jwt_data = get_raw_jwt() + email = jwt_data['email'] + user_id = get_user_by_email(email)['id'] + raw_data = request.get_json(force=True) + try: + message = raw_data + begin_date = datetime.strptime(message['begin_date'], "%Y-%m-%d %H:%M:%S") + template = db.session.query(Template).get(message['template']) + total_duration = message['num_test'] * (template.duration + 60) # 1 min for test setup + + experience = Experience(name=message['name'], + begin_date=begin_date, + num_test=message['num_test'], + end_date=begin_date + timedelta(0, total_duration), + status='SCHEDULED', + profile=user_id, + template=message['template'], + register_date=datetime.now()) + + experience.add(experience) + return experience.serializable, status.HTTP_201_CREATED + + except ValidationError as err: + resp = jsonify({"error": err.messages}) + resp.status_code = status.HTTP_403_FORBIDDEN + return resp + + except SQLAlchemyError as e: + db.session.rollback() + resp = jsonify({"error": str(e)}) + resp.status_code = status.HTTP_400_BAD_REQUEST + return resp + + +class ExperienceInfoView(Resource): + + @jwt_required + def get(self, id): + jwt_data = get_raw_jwt() + user_id = get_user_by_email(jwt_data['email'])['id'] + query = db.session.query(Experience, Template).filter(Experience.id==id).filter(Experience.template == Template.id).one() + experience = query[0].serializable + template = query[1].serializable + if not jwt_data['isAdmin'] and experience.profile != user_id: + results = jsonify() + results.status_code = status.HTTP_401_UNAUTHORIZED + results = make_response({"experience": experience, "template": template}) + results.status_code = status.HTTP_200_OK + return results + + +class ExperienceScheduleView(Resource): + def get(self): + + date_now = datetime.now() + experience_schedule_query = db.session.query(Experience, Profile)\ + .filter(Experience.end_date >= date_now)\ + .filter(Experience.profile == Profile.id)\ + .order_by(Experience.begin_date.asc())\ + .limit(2)\ + .all() + calendar = {'current_experience': None, 'next_experience': None} + + if len(experience_schedule_query) == 2: + if datetime.strptime(experience_schedule_query[0][0].serializable['begin_date'], + "%Y-%m-%d %H:%M:%S") < date_now: + calendar['current_experience'] = self.format_experience_calendar(experience_schedule_query[0]) + calendar['next_experience'] = self.format_experience_calendar(experience_schedule_query[1]) + else: + calendar['next_experience'] = self.format_experience_calendar(experience_schedule_query[0]) + + elif len(experience_schedule_query) == 1: + if datetime.strptime(experience_schedule_query[0][0].serializable['begin_date'], + "%Y-%m-%d %H:%M:%S") < date_now: + calendar['current_experience'] = self.format_experience_calendar(experience_schedule_query[0]) + else: + calendar['next_experience'] = self.format_experience_calendar(experience_schedule_query[0]) + return calendar + + @staticmethod + def format_experience_calendar(experince_calendar_fragment): + experience = experince_calendar_fragment[0].serializable + profile = experince_calendar_fragment[1].serializable + experience['author'] = profile['name'] + experience['email'] = profile['email'] + return experience + + +api.add_resource(UserView, '/user', '/user/') +api.add_resource(UserInfoView, '/user/', '/user//') +api.add_resource(RoleView, '/role', '/role/') +api.add_resource(ProfileView, '/profile', '/profile/') +api.add_resource(ExperienceView, '/experience', '/experience/') +api.add_resource(ExperienceInfoView, '/experience/', '/experience//') +api.add_resource(ExperienceScheduleView, '/experience/now', '/experience/now/')