def get(self, id): try: item = Product.objects().get(id=id).to_json() except DoesNotExist: return {'error': 'Product ID not found'}, 404 else: if get_jwt_identity(): user_id=get_jwt_identity() if User.objects(id=user_id,recently_viewed=id): User.objects(id=user_id).update_one(pull__recently_viewed=id) User.objects(id=user_id).update_one(push__recently_viewed=id) # print(User.objects(id=user_id)[0].recently_viewed) return Response(item, mimetype="application/json", status=200)
def get(self): user_id = get_jwt_identity() user = User.objects.get(id=user_id) if not user.privilege: return {'error': 'Elevated privilege required'}, 403 out_stock = extract_basic_info(json.loads(Product.objects(stock=0).to_json()), True) return Response(json.dumps(out_stock), mimetype="application/json", status=200)
def get_paper_user_groups(paper: Paper) -> List[Collection]: if get_jwt_identity(): user = get_user_optional() return db.session.query(Collection.id).filter( Collection.users.any(id=user.id), Collection.papers.any(id=paper.id)).all() return []
def get(self): current_user = User.find_by_username(get_jwt_identity()) if not current_user: return { 'message': 'You are not logged in.' }, 401 return { 'data': user_schema.dump(current_user) }
def get(self): user_id = get_jwt_identity() user = User.objects.get(id=user_id) cart_items_with_quantity = [] invalid_item_index = [] cnt = 0 if user.cart: for item in user.cart: try: cart_item = json.loads( Product.objects.get(id=item['product_id']).to_json()) except DoesNotExist: invalid_item_index.append(cnt) else: cart_items_with_quantity.append({ 'product_summary': extract_basic_info(cart_item), 'quantity': item['quantity'] }) cnt += 1 if invalid_item_index: for x in reversed(invalid_item_index): user.cart.pop(x) user.save() return Response(json.dumps(cart_items_with_quantity), mimetype="application/json", status=200)
def get(self, message_id=None): user = get_jwt_identity() query_params = dict(request.args) if not query_params: return {"error": True, "message": "wrong params"}, 404 try: if 'all' in query_params and query_params['all'].lower() == "true": return jsonify([ message.json() for message in Message.get_message_by_id(id=user['id']) ]) elif 'unread' in query_params and query_params['unread'].lower( ) == "true": return jsonify([ message.json() for message in Message.get_unread_message_by_id( id=user['id']) ]) elif 'read' in query_params and query_params['read'].lower( ) == "true": return Message.read_message(id=user['id']).json() except AttributeError as e: return { "error": False, "message": "There is no messages for this query" }, 404 return {"error": True, "message": "wrong params"}, 401
def get(self, project_id, solution_id): project = Project.find_project_with_id(project_id) user_id = get_jwt_identity() if not project or not project.belongs_to_user(user_id): return self.project_does_not_exist_response() solution = Solution.find_solution_with_id(project.type, solution_id) if not solution or not solution.if_belongs_to(project.id): return self.solution_does_not_exist_response() analytics = Analytics(solution) status = analytics.get_status() main_stats, secondary_stats = status["main_status"], status["secondary_status"] parameters = status["hyperparameters"] if not solution.analytics_filled(): if analytics.solution_has_completed(main_stats): solution.update_analytics(analytics.get_solution_metrics()) return { "type": project.type, "status": main_stats, "secondary_status": secondary_stats, "parameters": parameters, "solution": solution.json() }
def post(self): args = blog_create_parser.parse_args() author_email = get_jwt_identity() author: UserModel = UserModel.query.filter_by(email=author_email).first() is_published = args["is_published"] if "is_published" in args else False thumbnail: FileStorage = args["thumbnail"] if is_allowed(thumbnail.filename): extension = get_extension(thumbnail.filename) filename = create_filename(author.id, args["title"], extension) filepath = f"thumbnails/{filename}" thumbnail.save("media/" + filepath) thumbnail_url = url_for("media.media", path=filepath, _external=True) blog = BlogModel( title=args["title"], content=args["content"], author=author.id, thumbnail=thumbnail_url, is_published=is_published) db.session.add(blog) db.session.commit() if current_app.testing: os.remove("media/" + filepath) return blog, 201 abort(400, message="File is not an image file")
def post(self): user_id = get_jwt_identity() user = User.objects.get(id=user_id) body = request.get_json() new_order = {} if user.cart: for product in user.cart: try: item = Product.objects.get(id=product['product_id']) except DoesNotExist: continue else: item.stock = max(item.stock - product['quantity'], 0) item.save() order_created = time.time() new_order['order_id'] = str(user_id) + str(order_created) new_order['status'] = 'pending' new_order['order_time'] = order_created new_order['delivery_time'] = None new_order['address'] = body.get('address') new_order['cart'] = user.cart new_order['payment_method'] = body.get('payment_method') user.orders.append(new_order) user.cart = None user.save() return {'msg': 'Success'}, 200 else: return {'error': 'User cart is empty'}, 404
def post(cls): """Changes the password for current user with new_password. Fails if old_password does not match the current user's stored password. Args: old_password (str): Body param indicating the old password for current user. new_password (str): Body param indicating the new password for current user. Returns: dict of (str, str): A confirmation message """ data = cls._user_parser.parse_args() username = get_jwt_identity() try: user = UserModel.find_by_username(username) except Exception as e: return {"error": str(e)}, 500 if not user: return {"message": "User not found"}, 404 if not check_password_hash(user.password, data["old_password"]): return {"message": "Incorrect password"}, 401 # Not authorized try: user.update_and_save(dict(password=data["new_password"])) except Exception as e: return {"error": str(e)}, 500 return {"message": "Password changed succesfully"}, 200
def getIntegration(type): integrations_collection = mongo.integrations.db.integrations user = get_jwt_identity() integration = integrations_collection.find({'user': user, 'type': type}) return jsonify(dumps(integration))
def getIntegrations(): integrations_collection = mongo.integrations.db.integrations user = get_jwt_identity() integrations = integrations_collection.find({'user': user}) return jsonify(dumps(integrations))
def retrieve_authenticated_user(*args, **kwargs): # type: ignore email = get_jwt_identity() user = find_user_by_email(email) if user is None or not user.isActive: logger.error("Authenticated user with email %s not found or inactive", email) raise ForbiddenError({"email": ["Utilisateur introuvable"]}) return route_function(user, *args, **kwargs)
def get(self): user_id = get_jwt_identity() user = User.objects.get(id=user_id) if not user.privilege: return {'error': 'Elevated privilege required'}, 403 users = User.objects(orders__0__exists=True).only( 'username', 'email', 'orders').to_json() return Response(users, mimetype="json/application", status=200)
def get(self): user_id = get_jwt_identity() items = [item.json() for item in ItemModel.find_all()] if user_id: return {'items': items}, 200 return { 'items': [item['name'] for item in items], 'message': 'More data available if you log in.' }, 200
def get(self): user_id = get_jwt_identity() items = [item.json() for item in ItemModel.find_all()] if user_id: return {"items": items} return { "items:": [item["name"] for item in items], "message": "More data avaiable if you login", }
def get(self, project_id): project = Project.find_project_with_id(project_id) user_id = get_jwt_identity() if not project or not project.belongs_to_user(user_id): return self.project_does_not_exist_response() return { "solution_ids": Solution.find_solutions_of_projects(project.type, project.id) }
def get(self): all_products = Product.objects() recently_viewed = extract_basic_info(json.loads(all_products[0:5].to_json())) new_arrivals = extract_basic_info(json.loads(all_products[5:10].to_json())) today_deals = extract_basic_info(json.loads(Product.objects(discount__gt=0)[:20].to_json())) pipeline=[{"$unwind": "$orders" },{"$unwind": "$orders.cart" },{"$group":{"_id":"$orders.cart.product_id", "quantity":{"$sum": "$orders.cart.quantity"}}}, {"$sort":{"quantity":-1}}] sales=[json.loads(Product.objects(id=i["_id"])[0].to_json()) for i in list(User.objects.aggregate(pipeline))[:10]] top_sells = extract_basic_info(sales) fresh_vegies = extract_basic_info(json.loads(Product.objects()[0:16].to_json())) data = {} data['slides'] = list(["https://via.placeholder.com/150", "https://via.placeholder.com/100", "https://via.placeholder.com/200"]) data['content'] = list([{'title': 'Today\'s Deals', 'content': today_deals}, \ {'title': 'New Arrivals', 'content': new_arrivals}, {'title': 'Top Sellers', 'content': top_sells}, \ {'title': 'Veggies', 'content': fresh_vegies}]) if get_jwt_identity(): # print([i for i in User.objects(id=get_jwt_identity())[0].recently_viewed]) recently_viewed=extract_basic_info(([json.loads(Product.objects(id=i)[0].to_json()) for i in User.objects(id=get_jwt_identity())[0].recently_viewed[:-11:-1]])) data['content'].append({'title': 'Recently Viewed', 'content': recently_viewed}) recently_viewed=User.objects(id=get_jwt_identity())[0].recently_viewed # recently_viewed= map(objectid.ObjectId,recently_viewed) recently_viewed=[objectid.ObjectId(i) for i in recently_viewed] pipeline=[ {"$match":{"_id":{"$in":recently_viewed}}}, {"$project": {"_id":0,"subcategory":1}}, ] s=[] for i in list(Product.objects().aggregate(pipeline)): s=s+i["subcategory"] s=list(set(s)) pipeline=[ {"$match":{"subcategory":{"$in":s}}}, {"$sample": {"size":20}}, ] data['content'].append({'title': 'Recommended Products', 'content': extract_basic_info((list(Product.objects().aggregate(pipeline))))[:100]}) return Response(json_util.dumps(data), mimetype="application/json", status=200)
def get(self, project_id): project = Project.find_project_with_id(project_id) user_id = get_jwt_identity() if not project or not project.belongs_to_user(user_id): return self.project_does_not_exist_response() project_data = Dataset.find_data_by_id(project.id) project_data_preview = self.get_data_preview(project_data) return {"project": project.json(), "data": project_data_preview}
def get(self): """ Get user's data --- security: - Bearer: [] """ user = User.get_by_email(get_jwt_identity()) return response(self.default_schema.dump(user), 200)
def delete(self, message_id=None): user = get_jwt_identity() if not message_id: return {"error": True, "message": "wrong params"}, 404 if Message.delete_message(id=user['id'], message_id=message_id): return { "error": False, "message": "Message deleted successfully" }, 200 return {"error": True, "message": "Could not delete message"}, 404
def createIntegration(): integrations_collection = mongo.integrations.db.integrations content = request.json user = get_jwt_identity() content['user'] = user integrations_collection.insert(content) return Response('Gathered ' + content['websiteURL'])
def delete_user(self, pk: int): current_user = self.repositorie.get_user( pk=get_jwt_identity() ) user_to_delete = self.repositorie.get_user(pk) if not user_to_delete: abort(400, code_error=400, error='User does not exists') if current_user.rol_id == 1 or current_user != user_to_delete: self.repositorie.delete_object(user_to_delete) return {'code': 200, 'message': 'deleted'}
def logout(self) -> dict: current_user = Users.query.filter_by(id=get_jwt_identity()).first() access_token = get_raw_jwt() token_blacklisted = { 'token': access_token['jti'], 'expires': BlacklistToken().transform_expires_to_date(access_token['exp']), 'user_id': access_token['identity'] } token = BlacklistToken(**token_blacklisted) token.add() return {'code': 200, 'message': f'Successfully logout user {current_user.email}'}
def post(self, message_id=None): current_user = get_jwt_identity() user_json = request.get_json() if user_json is None or 'receiver_id' not in user_json: return {"error": True, "message": "wrong params"}, 404 new_message = Message(sender_id=current_user['id'], receiver_id=user_json['receiver_id'], message=user_json['message'], subject=user_json['subject']) Message.create_message(new_message) return {"error": False, "message": "message created"}, 200
def refresh(): """Issue an authenticated user a new access token cookie.""" user = User.query.filter_by(email=get_jwt_identity()).first() if user is None: # There is no user email associated with that JWT identity raise Unauthorized("Unable to retrieve a new access token") response = jsonify(user_schema.dump(user)) set_access_cookies(response, create_access_token(user)) return response, HTTPStatus.OK
def post(self): """ Refresh Token """ current_user = get_jwt_identity() new_token = create_access_token(identity=current_user, fresh=False) new_refresh_token = create_refresh_token(identity=current_user) return { 'access_token': new_token, 'refresh_token': new_refresh_token },200
def refresh_expired_token(response): try: exp_timestamp = get_raw_jwt()['exp'] now = datetime.now(timezone.utc) target_timestam = datetime.timestamp(now + timedelta(minutes=30)) if target_timestam > exp_timestamp: access_token = create_access_token(identity=get_jwt_identity()) set_access_cookies(response=response, encoded_access_token=access_token) return response except: return response
def delete(self): body = request.get_json() user_id = get_jwt_identity() user = User.objects.get(id=user_id) if not user.privilege: return {'error': 'Elevated privilege required'}, 403 try: item = Product.objects.get(id=body.get('id')) except DoesNotExist: return {'error': 'Product not found'}, 404 item.delete() return {'msg': 'Success'}, 200
def get(self, blog_id): blog = BlogModel.query.get(blog_id) author_email = get_jwt_identity() if author_email is None and blog.is_published == False: abort(404) author = UserModel.query.filter_by(email=author_email).first() if blog.is_published == False and blog.author != author.id: abort(404) return blog