chainetv_web/backend/chainetv/api.py
2019-05-08 18:06:44 +02:00

97 lines
2.8 KiB
Python

from flask import Blueprint, jsonify, request,make_response,redirect,url_for,render_template,current_app
from .Jsonfile import JSONfile
from . import emission
import jwt
from functools import wraps
from datetime import datetime, timedelta
from .user import User
data= JSONfile("chaine.json")
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
api = Blueprint("api", __name__)
@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'])
@token_required
def update_list(user):
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:
return jsonify(emission.parse_emmission(chaine))
#@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') })