chainetv_web/backend/chainetv/api.py

101 lines
2.9 KiB
Python
Raw Normal View History

2019-05-08 16:06:44 +00:00
from flask import Blueprint, jsonify, request,make_response,redirect,url_for,render_template,current_app
2019-05-08 12:14:55 +00:00
from .Jsonfile import JSONfile
2019-05-09 17:12:41 +00:00
from .emission import Emmission
2019-05-08 16:06:44 +00:00
import jwt
from functools import wraps
from datetime import datetime, timedelta
from .user import User
2019-05-09 17:12:41 +00:00
2019-04-29 14:23:24 +00:00
data= JSONfile("chaine.json")
2022-05-15 18:53:30 +00:00
data.parsechaine()
2019-05-09 17:12:41 +00:00
emmission= Emmission()
2019-04-29 14:23:24 +00:00
2019-05-08 16:06:44 +00:00
def token_required(f):
@wraps(f)
def _verify(*args, **kwargs):
auth_headers = request.headers.get('Authorization', '').split()
invalid_msg = {
'message': 'Invalid token. Registeration and / or authentication required',
'authenticated': False
}
expired_msg = {
'message': 'Expired token. Reauthentication required.',
'authenticated': False
}
if len(auth_headers) != 2:
return jsonify(invalid_msg), 401
try:
token = auth_headers[1]
data = jwt.decode(token,current_app.config['SECRET_KEY'])
user = User
if not user:
raise RuntimeError('User not found')
return f(user, *args, **kwargs)
except jwt.ExpiredSignatureError:
return jsonify(expired_msg), 401 # 401 is Unauthorized HTTP status code
except (jwt.InvalidTokenError) as e:
print(e)
return jsonify(invalid_msg), 401
return _verify
2019-04-29 14:23:24 +00:00
2019-04-29 14:36:29 +00:00
api = Blueprint("api", __name__)
2019-04-29 14:23:24 +00:00
@api.route('/ping', methods=['GET'])
def ping_pong():
return jsonify('pong!')
@api.route('/chaine/<num>', methods=['GET'])
def get_chaine(num):
chaine=data.get_chaine(num)
if (chaine == "numero de chaine inconnue"):
return make_response("",204)
else:
return jsonify(chaine)
@api.route('/chaine/', methods=['put'])
2019-05-08 16:06:44 +00:00
@token_required
def update_list(user):
2019-04-29 14:23:24 +00:00
status=data.parsechaine()
if(status=='ok'):
return jsonify("OK")
else:
return make_response('Error during Chaine Update',500)
@api.route('/chaine/<num>/emission', methods=['GET'])
def get_emmission(num):
chaine=data.get_chaine(num)
if (chaine == "numero de chaine inconnue"):
return make_response("",204)
else:
2019-05-09 17:12:41 +00:00
return jsonify(emmission.parse_emmission(chaine))
2019-05-08 16:06:44 +00:00
#@api.route('/register/', methods=('POST',))
#def register():
# data = request.get_json()
# user = User(**data)
# db.session.add(user)
# db.session.commit()
# return jsonify(user.to_dict()), 201
@api.route('/login/', methods=('POST',))
def login():
data = request.get_json()
user = User.authenticate(**data)
if not user:
return jsonify({ 'message': 'Invalid credentials', 'authenticated': False }), 401
token = jwt.encode({
'sub': user.name,
'iat':datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(minutes=30)},
current_app.config['SECRET_KEY'])
return jsonify({ 'token': token.decode('UTF-8') })