def create_booth(): """ Create a new booth using the request's ACCESS_LEVEL parameter. Returns the booth ID of the newly created booth. """ req = request.get_json() access_level = req['access_level'] user = User.objects.get(username=get_jwt_identity()) bid = booth_registry.add_booth(user.username, access_level) user.update(creator_status=bid) # Use BID as req param for JOIN_BOOTH view return join_booth(bid)
def crud_donantes(donante_id): """ GET: devolver el detalle de un donante específico PATCH: actualizar datos del donante específico, guardar en base de datos y devolver el detalle DELETE: eliminar el donante específico y devolver 204 """ usuario_id_jwt = get_jwt_identity() usuario = Donante.query.get(usuario_id_jwt) # crear una variable y asignar el donante específico donante = Donante.query.get(donante_id) # verificar si el donante con id donante_id existe if isinstance(donante, Donante): if request.method == "GET": # devolver el donante serializado y jsonificado. Y 200 # return jsonify(donante.serializar()), 200 return jsonify({ "resultado": f"ajá, esto fue {usuario.nombre_completo} fastidiando la paciencia..." }) elif request.method == "PATCH": # recuperar diccionario con insumos del body del request diccionario = request.get_json() # actualizar propiedades que vengan en el diccionario donante.actualizar_donante(diccionario) # guardar en base de datos, hacer commit try: db.session.commit() # devolver el donante serializado y jsonificado. Y 200 return jsonify(donante.serializar()), 200 except Exception as error: db.session.rollback() print(f"{error.args} {type(error)}") return jsonify({ "resultado": f"{error.args}" }), 500 else: # remover el donante específico de la sesión de base de datos db.session.delete(donante) # hacer commit y devolver 204 try: db.session.commit() return jsonify({}), 204 except Exception as error: db.session.rollback() print(f"{error.args} {type(error)}") return jsonify({ "resultado": f"{error.args}" }), 500 else: # el donante no existe! return jsonify({ "resultado": "el donante no existe..." }), 404
def decorated_function(*args, **kwargs): user = jwt.get_jwt_identity() db_user = User.query.options( joinedload('roles')).filter_by(username=user).first() if db_user is None: raise UnauthorizedUse('Permission denied', 403) # make user object available to routes on flask.g g.user = db_user for role in db_user.roles: if role.name in allowed_roles: return f(*args, **kwargs) raise UnauthorizedUse('Permission denied', 403)
def create_task(): data = request.get_json() print(data) task = data['task'] category = 'new' status = 'open' list = 'inbox' due = datetime.datetime.utcnow() new_task = Task(task, get_jwt_identity(), category, due, status, list) new_task.save_to_mongo() return jsonify({"msg": "task created"}), 201
def newOrder(): specific_user_id = get_jwt_identity() user = User.query.get(specific_user_id) input_data = request.json new_order= Order( data = input_data, user_id = specific_user_id, working_id=0 ) db.session.add(new_order) db.session.commit() return jsonify(new_order.id),200
def favorite_song(): """ Adds the clicked on song to the user's favorite songs list. """ # TODO: test favorite_song endpoint req = request.get_json() song = req['song'] user = User.objects.get(username=get_jwt_identity()) user.modify(push__favorite_songs_list=json.dumps(song)) return json.dumps( {'errors': {}} ) # dont need to return favorite songs list because this endpoint is only hit from inside a booth
def post(self, note_id): user_id = get_jwt_identity()['id'] note = Note().where([['id', '=', note_id], ['user_id', '=', user_id]]).first() if note.exists(): note.delete() return response({ 'message': 'Note deleted successfully' }, 202) return response({ 'message': 'Note does not exist or it is not yours to delete' }, 404)
def add_post(): in_json = request.json if not in_json: return make_resp(jsonify({"message": "Empty request"}), 400) elif not check_keys(request.json, ('category', 'type', 'title')): return make_resp(jsonify({"message": "Bad request"}), 400) post = Post(**in_json) post.author = User(**get_jwt_identity()) post = app.post_repo.request_create(post) return make_resp(jsonify(post), 200)
def protected(): # Access the identity of the current user with get_jwt_identity specific_user_id = get_jwt_identity() specific_user = User.query.filter_by(id=specific_user_id).one_or_none() #specific_user = User.query.get(specific_user_id) if specific_user is None: return jsonify({'msg': "user not found"}), 404 else: return jsonify({ 'msg': "Yay! You sent your token correctly so I know who you are", "user_data": specific_user.serialize() }), 200
def update_pokemon(name): trainer1=get_jwt_identity() pokemon=request.json["pokemon"] trainerdb = User.query.filter(User.email==trainer1).first() pokemondb = Pokemon.query.filter(Pokemon.name == name).first() #trainer=User.query.filter(User.trainer == trainerdb.id).first() if "sprite" in pokemon: pokemondb.sprite=pokemon["sprite"] if "description" in pokemon: pokemondb.description=pokemon["description"] db.session.commit() if "tagList" in pokemon: for tag in tags: pokemon_id=pokemon.id lists=Taglist(pokemon_id,tag) db.session.add(lists) db.session.commit() tag_data = Taglist.query.filter(pokemondb.id==Taglist.pokemon_id).all() pokemon_tag=[] for tag_data in tag_data: pokemon_tag.append(tag_data.tag) updated_pokemon={ "Pokemon":{ "id": pokemondb.id, "name": pokemondb.name, "sprite": pokemondb.sprite, "description": pokemondb.description, "tagList": pokemon_tag, "createdAt": str(pokemondb.createdAt), "updatedAt": str(pokemondb.updatedAt), "favorited": pokemondb.favorited, "favoritesCount": Favorite.query.filter(Favorite.user_id==pokemondb.id).count(), "trainer": { "username": trainerdb.username, "bio": trainerdb.bio, "image": trainerdb.image, "following": Follower.query.filter(Follower.user_id == trainerdb.id and Follower.follow_id==pokemondb.trainer).count()>0 } } } return jsonify(updated_pokemon)
def post(self): hostname = get_jwt_identity() timestamp = datetime.now(get_localzone()).isoformat() try: record = self.record_schema.load(request.get_json()) except ValidationError as e: abort(422, str(e)) self.influx_db.connection.write_points( self._transform_datapoints(hostname, timestamp, record)) return jsonify(record), 201
def post(self, dist_id): #args = parser.parse_args() user_id = get_jwt_identity()['id'] grade_distribution = GradeDistribution().where( [['id', '=', dist_id], ['user_id', '=', user_id]]).first() if grade_distribution.exists() is True: grade_distribution.delete() return response( {'message': 'Grade Distribution has deleted successfully'}, 202) return response({'errors': ['Grade distribution could not found']}, 404)
def save_candidate(candidate_id): params = request.get_json(silent=True) action = params.get('action', None) rewritten_intent = params.get('rewerittenIntent', '') assert action in action2decision decision = action2decision[action] email = get_jwt_identity() annotations = get_annotations(email) (question_id, answer_id, rank), _ = annotations[candidate_id] annotations[candidate_id] = (question_id, answer_id, rank), (decision, rewritten_intent) mark_task_result(question_id, answer_id, rank, decision) response = {'count': len(annotations)} return jsonify(response), 200
def post(self, lecturer_id): args = parser.parse_args() user_id = get_jwt_identity()['id'] lecturer = Lecturer().where([['id', '=', lecturer_id], ['user_id', '=', user_id]]).first() if lecturer.exists() is True: lecturer.update({ 'name': args['name'], 'email': args['email'], 'slug': lecturer.generateSlug(name=args['name']) }) return response({'lecturer': lecturer.data()}) return response({'errors': ['Lecturer could not found']}, 404)
def post_service(title): """ Get one service for the role needed; Test with curl -H "Authorization: Bearer YOUR_JWT_ID_TOKEN" -X POST http://localhost:7654/api/services/:title """ roles = get_jwt_identity() if 'Nuxeo' not in roles: return {'result': ''}, 403 formData = request.data output, outputStatus = ServicesDirectoryFactory.get().launchService(title, formData) return {'result': output}, outputStatus
def user_get(): email=get_jwt_identity() userdb = User.query.filter(User.email == email).first() cur_user={ "user":{ "username":userdb.username, "token":create_jwt(identity=userdb.email), "email":userdb.email, "bio":userdb.bio, "image":userdb.image } } return jsonify(cur_user)
def put_user(): try: utils.flask_validate_request_is_json(request) now = datetime.datetime.now() in_user = utils.get_args(received=request.json, defaultable={ 'created_at': now, 'updated_at': now, 'payload': {} }) filters = {'id': get_jwt_identity()} user = db_api.update_row(User, filters, in_user) return utils.flask_return_success(user.json_dict) except Exception as e: return utils.flask_handle_exception(e)
def save_booking(): try: print('Adding new service...') user = guests.find_guest(get_jwt_identity()) print(user) if not user: raise Exception("Employees are not allowed to book rooms!") json = request.json json['guestId'] = user['_id'] bookings.save_booking(json) return 'Success', 200 except Exception as e: print(str(e)) return 'Failed to create room: ' + str(e), 400
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_record(): filters = utils.get_args( received=request.args, constant={'user_id': get_jwt_identity()}, optional={ 'id': str, 'event_id': str, 'type_id': int }, ) try: rows = db_api.get_rows(Record, filters) return utils.flask_return_success([row.json_dict for row in rows]) except Exception as e: return utils.flask_handle_exception(e)
def call(*args, **kwargs): playerid = get_jwt_identity() player = Player.query.get(playerid) if player: ctx_stack.top.current_player_object = player return f(*args, **kwargs) else: # this really is a server error, since causing this error by the user should be caused by a forged request, # which should not be possible because of the jwt current_app.logger.warning("A valid JWT token received but the Player ID is invalid!") return abort(500, "Player ID invalid")
def get_profile(username): userdb = User.query.filter(User.username == username).first() cur_user=get_jwt_identity() cur_userdb=User.query.filter(User.email == cur_user).first() ret={ "profile":{ "username":userdb.username, "bio":userdb.bio, "image":userdb.image, "following":Follower.query.filter(Follower.user_id == cur_userdb.id and Follower.follow_id==userdb.id).count()>0 } } return json.dumps(ret)
def menuItems(item_id=None): # Get All Menu Items specific_vendor_id = get_jwt_identity() if request.method == 'GET': if item_id is None: vendor_items = Product.query.filter_by( vendor_id=specific_vendor_id).all() serialized_items = [] for item in vendor_items: serialized_items.append(item.serialize()) return jsonify(serialized_items), 200 else: specific_item = Product.query.filter_by(id=item_id).one_or_none() return jsonify(specific_item.serialize()), 200 elif request.method == 'POST': body = request.get_json() item = Product(name=body['name'], category=body['category'], vendor_id=specific_vendor_id, price=body['price'], description=body['description']) db.session.add(item) db.session.commit() print(item) return jsonify(item.serialize()), 201 elif request.method == 'PUT': body = request.get_json() item = Product.query.get(item_id) if item is None: raise APIException('Menu item not found', status_code=404) if 'name' in body: item.name = body['name'] if 'price' in body: item.price = body['price'] if 'description' in body: item.description = body['description'] if 'category' in body: item.category = body['category'] db.session.commit() return jsonify(item.serialize()), 200 elif request.method == 'DELETE': item = Product.query.get(item_id) if item is None: raise APIException('Item not found', status_code=404) db.session.delete(item) db.session.commit() return jsonify({}), 204
def signup_visit(): request_body = request.get_json() print(request_body) visit1 = Visit( temperature=request_body["temperature"], business_id=get_jwt_identity(), visitor_id=request_body["visitor_id"], entry_date=datetime.strptime(request_body["entry_date"], "%a, %d %b %Y %H:%M:%S %Z"), has_fever=request_body["has_fever"], has_covid=request_body["has_covid"], ) db.session.add(visit1) db.session.commit() return jsonify(visit1.serialize()), 200
def delegate(): """ This endpoint gives a vote for the given bill to the given delegate. """ req = request.get_json() bill_id = req['bill_id'] delegate_id = req['delegate'] user = User.objects.get(email=get_jwt_identity()) delegate = User.objects.get(id=delegate_id) bill = Bill.objects.get(id=bill_id) delegated_vote = DelegatedVote( delegator=user.id, delegate=delegate_id, cast_vote=CastVote(bill_id=bill_id)) for d in user.delegated_votes: if d.delegate == delegate.id \ and d.cast_vote.bill_id == bill.id: return jsonify(msg='Already delegated this vote.') elif d.cast_vote.bill_id == bill.id: user.delegated_votes.remove(d) old_delegate = User.objects.get(id=d.delegate) for d_1 in old_delegate.received_votes: if d_1.cast_vote.bill_id == bill.id \ and d_1.delegator == user.id: old_delegate.received_votes.remove(d_1) old_delegate.save() break user.delegated_votes.append(delegated_vote) delegate.received_votes.append(delegated_vote) reformatted = '_'.join([word.lower() for word in bill.category.split()]) vector_dict = user.interest_vector.to_mongo() vector_dict[reformatted] -= 1 min_val = vector_dict[min(vector_dict, key=vector_dict.get)] for k in vector_dict.keys(): vector_dict[k] -= min_val user.interest_vector = InterestVector(**vector_dict.to_dict()) user.save() delegate.save() return jsonify(msg='success')
def remove_friend(): """ Remove user FID from user's friends. """ errors = {} friend = request.get_json()['username'] user = User.objects.get(username=get_jwt_identity()) if friend in user.friends_list: user.modify(pull__friends_list=friend) friends = [User.objects.get(username=f) for f in user.friends_list] friends = [(f['username'], f['email'], f['creator_status']) for f in friends] return json.dumps({'errors': errors, 'data': friends})
def find_users(): """ Returns the list of users in the User model whose username or email match the search string. """ # TODO: only() doesn't work search_string = request.get_json()['query'] regex = re.compile('.*{}.*'.format(search_string)) user = User.objects.get(username=get_jwt_identity()) users = User.objects((Q(email=regex) | Q(username=regex)) & Q(username__ne=user.username) & Q(username__nin=user.friends_list)).only( 'username', 'email') return json.dumps( {'data': [(u['username'], u['profile_pic']) for u in users]})
def post(self, type_id, comment_id): args = parser.parse_args() commentText = args['comment'] user_id = get_jwt_identity()['id'] comment = Comment().where([['id', '=', comment_id], ['user_id', '=', user_id]]).first() if comment.exists() is False or comment.validate() is False: return response( { 'message': 'That comment does not exist or it does not belong to you' }, 401) comment.update({ 'comment': commentText, }) return response({'message': 'Comment successfully updated!'}, 200)
def edit_review(resId, revId): restaurant = Restaurant.query.filter(Restaurant.id == resId).first() if (restaurant): review = Review.query.filter(Review.id == revId).first() if (review): email = get_jwt_identity() user = User.query.filter(User.email == email).first() if (user.id == review.reviewerId and restaurant.id == review.restaurantId): if request.method == 'PATCH': data = request.get_json() review.review = data['review']['review'] review.updatedAt = datetime.now() db.session.commit() data = Review.query.filter(Review.id == revId).first() reviewdata = { "review": { "id": data.id, "restaurantId": data.restaurantId, "reviewerId": data.reviewerId, "review": data.review, "createdAt": data.createdAt, "updatedAt": data.updatedAt } } return jsonify(reviewdata), 201 elif request.method == 'DELETE': db.session.delete(review) db.session.commit() reviewdata = { "review": { "id": review.id, "restaurantId": review.restaurantId, "reviewerId": review.reviewerId, "review": review.review, "createdAt": review.createdAt, "updatedAt": review.updatedAt } } return jsonify(reviewdata), 200 else: return ('You cannot Edit/Delete this Review'), 403 else: return ('No Review found with that ID'), 404 else: return ('No Restaurant found with that ID'), 404
def add_friend(): """ Add user FID to user's friends. """ errors = {} friend = request.get_json()['username'] user = User.objects.get(username=get_jwt_identity()) if friend not in user.friends_list: user.modify(push__friends_list=(friend)) friends = [User.objects.get(username=f) for f in user.friends_list] friends = [(f['username'], f['email'], f['creator_status'], f['profile_pic']) for f in friends] return json.dumps({'errors': errors, 'data': friends})