def wrapper(*args, **kwargs): # print('jwt is', get_jwt()) jwt_role = get_jwt()['role'] valid = jwt_role == 'admin' for role in valid_roles: if role == jwt_role: valid = True if not valid: raise APIException('Access denied', 403) user_id = get_jwt()['sub'] user = Users.query.get(user_id) if not user: raise APIException('User not found with id: ' + str(user_id), 404) invalid_status = ['suspended', 'invalid'] if user.status._value_ in invalid_status: raise APIException( f'The user account is "{user.status._value_}"', 403) kwargs = {**kwargs, 'user_id': user_id} return func(*args, **kwargs)
def swap_tracker(): id = int(get_jwt()['sub']) buyin = Buy_ins.query.filter_by(user_id=id).order_by( Buy_ins.id.desc()).first() if not buyin: raise APIException('Buy_in not found', 404) swaps = Swaps.query.filter_by(sender_id=id, tournament_id=buyin.flight.tournament_id) if not swaps: return jsonify( {'message': 'You have no live swaps in this tournament'}) now = datetime.utcnow() trnmt = (Tournaments.query.filter(Tournaments.start_at < now).filter( Tournaments.end_at > now)).first() if not trnmt: raise APIException('No current tournaments') return jsonify({ 'tournament': trnmt.serialize(), 'my_current_buy_in': buyin.serialize(), 'others_swaps': [x.serialize() for x in swaps] })
def post(self): jwt = get_jwt() user = jwt.get('sub', {}) email = user.get('email', '') if user.get('type', "") != 'user': return { "success": False, "message": "Only users can book an appointment" } exists = User.objects(email=email) if not exists: return {"success": False, "message": "No user exists"} parser = reqparse.RequestParser() parser.add_argument('hospital', type=str) parser.add_argument('date', type=str) body = parser.parse_args() if not (body.hospital and body.date): return {"success": False, "message": "Hospital or date missing"} else: creation_date = datetime.now() next_appointment = datetime.strptime(body.date, '%d/%m/%Y %H:%M') if next_appointment <= creation_date: return { "success": False, "message": "Appointment cannot be made to past" } appointment = Appointment(hospital=body.hospital, creationDate=creation_date, nextAppointment=next_appointment, patient=exists[0]) appointment.save() return {'success': True, 'appointment': appointment.format()}
def delete(self, appointment_id): print("Delete", appointment_id) try: user = self.get_user(get_jwt()) if not user[0]: return {"success": False, "message": user[1]} user_type, user = user appointment = self.get_appointment(appointment_id) if not appointment[0]: return {"success": False, "message": appointment[1]} appointment = appointment[1] if user_type == "user": if len(appointment.appointments) > 0: return {"success": False, "message": "Cannot be cancelled"} if appointment.patient.id != user.id: return {"success": False, "message": "Unauthorized"} appointment.closedDate = datetime.now() appointment.closed = True appointment.save() return {"success": True, "message": "Appointment Cancelled"} elif user_type == "hospital_admin": if str(appointment.hospital.id) != str(user.hospital.id): return {"success": False, "message": "Unauthorized"} appointment.closedDate = datetime.now() appointment.closed = True appointment.save() return {"success": True, "message": "Appointment Cancelled"} else: return {"success": False, "message": "Unauthorized"} except Exception as e: print(e) return {"success": False, "message": "Something went wrong"}
def reset_password(id): if id == 'me': id = str(get_jwt())['sub'] if not id.isnumeric(): raise APIException('Invalid id: ' + id, 400) if request.args.get('forgot') == 'true': return jsonify({ 'message': 'A link has been sent to your email to reset the password', 'link': os.environ.get('API_HOST') + '/users/reset_password/' + create_jwt({ 'id': id, 'role': 'password' }) }), 200 body = request.get_json() check_params(body, 'email', 'password', 'new_password') user = Users.query.filter_by(id=int(id), email=body['email'], password=sha256(body['password'])).first() if not user: raise APIException('Invalid parameters', 400) user.password = sha256(body['new_password']) db.session.commit() return jsonify({'message': 'Your password has been changed'}), 200
def get(self): res = self.get_doctor(get_jwt()) print(res) if not res[0]: return {"success": False, "message": res[1]} doctor = res[1] return {"success": True, "skills": doctor.skills}
def get_chat(): """Get dummy data returned from the server.""" jwt_data = get_jwt() params = request.get_json() myText = params.get('myText', None) print(myText) print(params) sentend = np.ones((300, ), dtype=np.float32) sent = nltk.word_tokenize(myText) sentvec = [mod[w] for w in sent if w in mod.vocab] sentvec[14:] = [] sentvec.append(sentend) if len(sentvec) < 15: for i in range(15 - len(sentvec)): sentvec.append(sentend) sentvec = np.array([sentvec]) predictions = model.predict(sentvec) outputlist = [ mod.most_similar([predictions[0][i]])[0][0] for i in range(5) ] output = ' '.join(outputlist) print(output) data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']} json_response = json.dumps(output) return Response(json_response, status=Status.HTTP_OK_BASIC, mimetype='application/json')
def test(): if not request.is_json: return 'request is not json' params = request.get_json() jwt_data = get_jwt() return jsonify({'exp': expired(jwt_data['exp'])})
def create_buy_in(): body = request.get_json() check_params(body, 'flight_id', 'chips', 'table', 'seat') id = int(get_jwt()['sub']) prof = Profiles.query.get(id) if not prof: raise APIException('User not found', 404) buyin = Buy_ins(user_id=id, flight_id=body['flight_id'], chips=body['chips'], table=body['table'], seat=body['seat']) db.session.add(buyin) db.session.commit() name = prof.nickname if prof.nickname else f'{prof.first_name} {prof.last_name}' # Get the latest entry by checking the created_at buyin = Buy_ins.query.filter_by(user_id=id, flight_id=body['flight_id'], chips=body['chips'], table=body['table'], seat=body['seat']).first() return jsonify({**buyin.serialize(), "name": name}), 200
def update_email(id): if id == 'me': id = str(get_jwt()['sub']) if not id.isnumeric(): raise APIException('Invalid id: ' + id, 400) body = request.get_json() check_params(body, 'email', 'password', 'new_email') user = Users.query.filter_by(id=int(id), email=body['email'], password=sha256(body['password'])).first() if not user: raise APIException('Invalid parameters', 400) user.valid = False user.email = body['new_email'] db.session.commit() return jsonify({ 'message': 'Please verify your new email', 'validation_link': validation_link(user.id) }), 200
def put(self, user_id): parser = reqparse.RequestParser() self.make_parser_args(parser) args = parser.parse_args() _userEmail = args['email'] _userName = args['name'] # _userPassword = args['password'] _userPhone = args['phone'] _userLocation = args['location'] user_jwt = get_jwt() if (user_jwt['id'] != int(user_id)): return {}, 404 try: stmt = select([data.users.c.id, data.users.c.name, data.users.c.email, data.users.c.phone, data.users.c.location])\ .select_from(data.users).where((data.users.c.id != user_id) & (data.users.c.email == _userEmail)) #checks if email has been used by another user res = data.conn.execute(stmt) res_dict = [dict(r) for r in res] if len(res_dict) > 0: return {}, 400 stmt = update(data.users).where(data.users.c.id == user_jwt['id']).\ values(email=_userEmail, name=_userName, phone=_userPhone, location=_userLocation) res = data.conn.execute(stmt) return {}, 200 except Exception as e: return {'error': str(e)}
def wrapper(*args, **kwargs): response = simple_jwt_required(fn)(*args, **kwargs) token = get_jwt() roles_in_token = current_app.config['JWT_ROLE_CLAIM'](token) if [role for role in roles_in_token if role in allowed_roles]: return response else: raise NoAuthorizationError('Does not have required role')
def get_swaps_actions(id): user_id = int(get_jwt()['sub']) prof = Profiles.query.get(user_id) if not prof: raise APIException('User not found', 404) return jsonify(prof.get_swaps_actions(id))
def get_data(): """Get dummy data returned from the server.""" jwt_data = get_jwt() data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']} json_response = json.dumps(data) return Response(json_response, status=Status.HTTP_OK_BASIC, mimetype='application/json')
def update_swap(): id = int(get_jwt()['sub']) # get sender user sender = Profiles.query.get(id) if not sender: raise APIException('User not found', 404) body = request.get_json() check_params(body, 'tournament_id', 'recipient_id') # get recipient user recipient = Profiles.query.get(body['recipient_id']) if not recipient: raise APIException('Recipient user not found', 404) # get swap swap = Swaps.query.get((id, recipient.id, body['tournament_id'])) counter_swap = Swaps.query.get((recipient.id, id, body['tournament_id'])) if not swap or not counter_swap: raise APIException('Swap not found', 404) if 'percentage' in body: percentage = abs(body['percentage']) counter = abs(body['counter_percentage'] ) if 'counter_percentage' in body else percentage sender_availability = sender.available_percentage( body['tournament_id']) if percentage > sender_availability: raise APIException(( 'Swap percentage too large. You can not exceed 50% per tournament. ' f'You have available: {sender_availability}%'), 400) recipient_availability = recipient.available_percentage( body['tournament_id']) if counter > recipient_availability: raise APIException( ('Swap percentage too large for recipient. ' f'He has available to swap: {recipient_availability}%'), 400) # So it can be updated correctly with the update_table funcion body['percentage'] = swap.percentage + percentage update_table(counter_swap, {'percentage': counter_swap.percentage + counter}) update_table( swap, body, ignore=['tournament_id', 'recipient_id', 'paid', 'counter_percentage']) db.session.commit() return jsonify(swap.serialize())
def wrapper(*args, **kwargs): jwt_role = get_jwt()['role'] valid = True if jwt_role == 'admin' else False for role in valid_roles: if role == jwt_role: valid = True if not valid: raise Exception('Access denied', 401) user_id = get_jwt()['sub'] if not Users.query.get(user_id): raise Exception('User not found', 404) kwargs = {**kwargs, 'user_id': user_id} return func(*args, **kwargs)
def wrapper(*args, **kwargs): response = simple_jwt_required(fn)(*args, **kwargs) token = get_jwt() try: if current_app.config['JWT_ROLE_CLAIM'](token) == role: return response else: raise NoAuthorizationError('Does not have required role') except KeyError: raise NoAuthorizationError('Does not have required role')
def validateJwtUser(user, site): try: jwt_data = json.loads(get_jwt()['sub']) ok = (user == jwt_data["userid"] and site == jwt_data["siteid"]) #log.info(repr(jwt_data)) ok = ok or (jwt_data["userid"] == '30405800' and jwt_data["siteid"] == '3') return ok except: return False
def get_data(): """Get dummy data returned from the server.""" jwt_data = get_jwt() print(request.headers) # print(jwt_data['roles'] ) # if jwt_data['roles'] != 'admin': # return jsonify(msg="Permission denied"), Status.HTTP_BAD_FORBIDDEN user = Session.query(User).filter_by(username='******').first() create_jwt(identity=user.email) identity = get_jwt_identity() print("identita %s" % identity) print("jwt %s" % get_jwt()) if not identity: return jsonify({"msg": "Token invalid"}), Status.HTTP_BAD_UNAUTHORIZED data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']} json_response = json.dumps(data) return Response(json_response, status=Status.HTTP_OK_BASIC, mimetype='application/json')
def post(self, appointment_id): try: user = self.get_user(get_jwt()) if not user[0]: return {"success": False, "message": user[1]} user_type, user = user if user_type != "doctor": return { "success": False, "message": "Only doctors can perform this action" } parser = reqparse.RequestParser() parser.add_argument('fees', type=float, default=0.0) parser.add_argument('unpaid', type=float, default=0.0) parser.add_argument('remarks', type=str, default=None) parser.add_argument('next_date', type=str) parser.add_argument('monitoring', type=dict, default={}) query_param = parser.parse_args() if query_param.remarks is None or query_param.next_date is None: return { "success": False, "message": "Remarks or Next Appointment date is missing" } next_appointment = datetime.strptime(query_param.next_date, '%d/%m/%Y %H:%M') if next_appointment < datetime.now(): return { "success": False, "message": "Next appointment cannot be in past" } appointment = self.get_appointment(appointment_id) if not appointment[0]: return {"success": False, "message": appointment[1]} appointment = appointment[1] if appointment.closed: return {"success": False, "message": "Appointment is closed"} if str(appointment.hospital.id) != str(user.hospital.id): return {"success": False, "message": "Unauthorized"} appointment.nextAppointment = next_appointment appointment_detail = AppointmentDetail( date=datetime.now(), doctor=str(user.email), fees=query_param.fees, unpaid=query_param.unpaid, remarks=query_param.remarks, monitoring=query_param.monitoring) appointment.appointments.append(appointment_detail) appointment.save() return {"success": True, "appointment": appointment.format()} except Exception as e: print(e) return {"success": False, "error": "Something went wrong"}
def validateJwtUser(user, site): try: jwt_info = get_jwt() #log.info("JWT " + repr(jwt_info)) jwt_data = json.loads(jwt_info['sub']) ok = (user == jwt_data["userid"] and site == jwt_data["siteid"]) #log.info("INFO " + repr(jwt_data)) ok = ok or (jwt_data["userid"] == '30405800' and jwt_data["siteid"] == '3') return ok except Exception as e: #log.info("ERROR " + str(e)) return False
def wrapper(*args, **kwargs): jwt_role = get_jwt()['role'] valid = True if jwt_role == 'admin' else False for role in valid_roles: if role == jwt_role: valid = True if not valid: raise APIException('Access denied', 401) return func(*args, **kwargs)
def put(self, post_id): parser = reqparse.RequestParser() self.make_parser_args(parser) args = parser.parse_args() _postTitle = args['title'] _postLastModified = args['last_modified'] _postDescription = args['description'] _postLocation = args['location'] _postLat = args['lat'] _postLon = args['lon'] user_jwt = get_jwt() jwt_user_id = user_jwt['id'] try: stmt = select([data.posts.c.id, data.posts.c.user_id, data.posts.c.title, data.posts.c.time, data.posts.c.expiry, data.posts.c.last_modified, data.posts.c.description, data.posts.c.location, data.posts.c.lat, data.posts.c.lon]) \ .select_from(data.posts).where(data.posts.c.id == post_id) res = data.conn.execute(stmt) res_dict = [dict(r) for r in res] print(res_dict) if jwt_user_id != res_dict[0]['user_id']: return {'message': 'Unauthorized'}, 403 if len(res_dict) == 0: return {'message': 'Post does not exist'}, 404 if _postTitle is None: _postTitle = res_dict[0]['title'] if _postLastModified is None: _postLastModified = res_dict[0]['last_modified'] if _postDescription is None: _postDescription = res_dict[0]['description'] if _postLocation is None: _postLocation = res_dict[0]['location'] if _postLat is None: _postLat = res_dict[0]['lat'] if _postLon is None: _postLon = res_dict[0]['lon'] stmt = update(data.posts).where(data.posts.c.id == post_id). \ values(title=_postTitle, last_modified=_postLastModified, description=_postDescription, location=_postLocation, lat=_postLat, lon=_postLon) res = data.conn.execute(stmt) return {}, 200 except Exception as e: return {'error': str(e)}
def get(self): jwt = get_jwt() user = jwt.get('sub', {}) email = user.get('email', '') user_type = user.get('type') if user_type not in ["user", 'hospital_admin']: return { "success": False, "message": "Only user or hospital admin can see this" } if user_type == 'user': user = User.objects(email=email) else: user = HospitalAdmin.objects(email=email) if not user: return {"success": False, "message": "No user exists"} user = user[0] parser = reqparse.RequestParser() parser.add_argument('page', type=int, default=1) parser.add_argument('closed', type=bool, default=False) params = parser.parse_args() page = params.page print(user.email, params.closed, user_type) if user_type == 'user': total_appointments = Appointment.objects( patient=user.email, closed=params.closed).count() appointments = Appointment.objects( patient=user.email, closed=params.closed).order_by('-nextAppointment')[(page - 1) * 10:page * 10] print(appointments) else: total_appointments = Appointment.objects( hospital=user.hospital.id, closed=params.closed).count() appointments = Appointment.objects( hospital=user.hospital.id, closed=params.closed).order_by('-nextAppointment')[(page - 1) * 10:page * 10] return { "success": True, "totalAppointments": total_appointments, "totalPages": ceil(total_appointments / 10), "page": page, "appointments": [appointment.format() for appointment in appointments] }
def run_seeds(user_id, **kwargs): print(get_jwt()) if get_jwt()['role'] != 'admin': raise APIException('Access denied', 403) print('running here') seeds.run() gabe = Profiles.query.filter_by(first_name='Gabriel').first() now = datetime.utcnow() # x['iat'] = now # x['nbf'] = now # x['sub'] = gabe.id # x['exp'] = now + timedelta(days=365) identity = { "id": gabe.id, "role": "admin", 'sub': gabe.id, "exp": now + timedelta(days=365), 'iat': now, 'nbf': now } xx = jwt.encode(identity, os.environ['JWT_SECRET_KEY'], algorithm='HS256') return jsonify( { "1 Gabe's id": gabe.id, "2 token_data": identity, "3 token": xx }, 200)
def get_data(): """Get dummy data returned from the server.""" jwt_data = get_jwt() if jwt_data['roles'] != 'admin': return jsonify(msg="Permission denied"), Status.HTTP_BAD_FORBIDDEN identity = get_jwt_identity() if not identity: return jsonify({"msg": "Token invalid"}), Status.HTTP_BAD_UNAUTHORIZED data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']} json_response = json.dumps(data) return Response(json_response, status=Status.HTTP_OK_BASIC, mimetype='application/json')
def get_Image(): """Get dummy data returned from the server.""" jwt_data = get_jwt() params = request.get_json() myText = params.get('myText', None) print(myText) print(params) img = cv2.imread(myText) img = cv2.resize(img, (100, 100)) img = img.transpose((2, 0, 1)) img = img.astype('float32') img = img / 255 img = np.expand_dims(img, axis=0) pred = Imagemodel.predict(img) y_pred = np.array( [1 if pred[0, i] >= 0.6 else 0 for i in range(pred.shape[1])]) finalOutput = [] for key, value in enumerate(y_pred): if key == 0 and value == 1: finalOutput.append("Good for lunch") if key == 1 and value == 1: finalOutput.append("Good for dinner") if key == 2 and value == 1: finalOutput.append("Takes reservation") if key == 3 and value == 1: finalOutput.append("Outdoor seating") if key == 4 and value == 1: finalOutput.append("Restaurent is expensive") if key == 5 and value == 1: finalOutput.append("Has alchohol") if key == 6 and value == 1: finalOutput.append("Has Table Service") if key == 7 and value == 1: finalOutput.append("Ambience is classy") if key == 8 and value == 1: finalOutput.append("Good for kids") print(finalOutput) data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']} json_response = json.dumps(finalOutput) return Response(json_response, status=Status.HTTP_OK_BASIC, mimetype='application/json')
def update_buy_in(id): body = request.get_json() check_params(body) user_id = int(get_jwt()['sub']) buyin = Buy_ins.query.get(id) update_table(buyin, body, ignore=['user_id', 'flight_id', 'receipt_img_url']) db.session.commit() return jsonify(Buy_ins.query.get(id).serialize())
def create_swap(): id = int(get_jwt()['sub']) # get sender user sender = Profiles.query.get(id) if not sender: raise APIException('User not found', 404) body = request.get_json() check_params(body, 'tournament_id', 'recipient_id', 'percentage') # get recipient user recipient = Profiles.query.get(body['recipient_id']) if not recipient: raise APIException('Recipient user not found', 404) if Swaps.query.get((id, body['recipient_id'], body['tournament_id'])): raise APIException('Swap already exists, can not duplicate', 400) sender_availability = sender.available_percentage(body['tournament_id']) if body['percentage'] > sender_availability: raise APIException(( 'Swap percentage too large. You can not exceed 50% per tournament. ' f'You have available: {sender_availability}%'), 400) recipient_availability = recipient.available_percentage( body['tournament_id']) if body['percentage'] > recipient_availability: raise APIException( ('Swap percentage too large for recipient. ' f'He has available to swap: {recipient_availability}%'), 400) db.session.add( Swaps(sender_id=id, tournament_id=body['tournament_id'], recipient_id=body['recipient_id'], percentage=body['percentage'])) db.session.add( Swaps(sender_id=body['recipient_id'], tournament_id=body['tournament_id'], recipient_id=id, percentage=body['percentage'])) db.session.commit() return jsonify({'message': 'ok'}), 200
def set_swap_paid(id): id = int(get_jwt()['sub']) # get sender user sender = Profiles.query.get(id) if not sender: raise APIException('User not found', 404) body = request.get_json() check_params(body, 'tournament_id', 'recipient_id') swap = Swaps.query.get(id, body['recipient_id'], body['tournament_id']) swap.paid = True db.session.commit() return jsonify({'message': 'Swap has been paid'})
def protected(): jwt_data = get_jwt() if jwt_data['roles'] != 'admin': return jsonify(msg="Permission denied"), 403 return jsonify(msg="Do not forget to drink your ovaltine")