Beispiel #1
0
    def get(self):
        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()

        if current_user is None:
            return {'error': 'Header token is not good, please login again'}, 401

        all_users = User.objects(id__ne=user_id).to_json()
        all_users = json.loads(all_users)
        c = 0
        for u in all_users:
            u['already_follow'] = False

            for user in u['followers']:
                if user['$oid'] == user_id:
                    u['already_follow'] = True
                    break
            del u['password']
            del u['image_queue']
            del u['pictures']
            del u['followers']
            del u['following']
            del u['nb_followers']
            del u['nb_following']
            del u['dates']
            del u['nb_login']
            all_users[c] = u
            c += 1
        return Response(json.dumps(all_users), mimetype="application/json", status=200)
Beispiel #2
0
def delete_user(id):
    try:
        User.objects.get(user_id=id).delete()
        User.objects(parent=id).delete()
        return "User and associate childs are deleted", 200
    except:
        return {"error": "Could not delete user"}, 400
Beispiel #3
0
 def deposit_money(self, user_id, money, **kwargs):
     """Realiza un depósito de dinero en la cuenta del usuario solicitado."""
     if money >= 0:
         print('Cantidad depositada: ', money)
         User.objects(user_id=user_id).update_one(inc__balance=money)
     else:
         print('No es posible depositar valores negativos.')
Beispiel #4
0
def edit_conversiton():
    # get user data from the body as json.
    userData = request.json
    userId = userData['id']
    userName = userData['name']
    userAvatar = userData['avatar']

    try:
        User.objects(userId=userId).update(name=userName, avatar=userAvatar)
        return {"success": True, "msg": "User Updated.."}

    except Exception as e:
        return {"success": False, "msg": "Something Wron.."}
        print("update user info something wrong, ", e)
Beispiel #5
0
    def get(self):
        u = User.objects(role__nin=['user']).\
                exclude('private_key', 'public_key', 'password')

        if 'unapproved' in request.args:
            u = User.objects(Q(role=get_jwt_identity()['role']) & Q(approved=False)).\
                exclude('private_key', 'public_key', 'password')

        if 'excel' in request.args:
            return send_from_directory(directory=UPLOAD_FOLDER,
                                       filename=export_to_excel(
                                           u, get_user_id()))

        return Response(u.to_json(), mimetype="application/json", status=200)
 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)
Beispiel #7
0
    def post(self):
        try:
            body = request.get_json()
            username = body.get('username')
            role = body.get('role')
            password = body.get('password')
            authorized = False
            user = None
            for user in User.objects(role=role):
                if user.username == username:
                    authorized = user.check_password(password)
                    user = user
                    break

            if not authorized:
                return "", 401

            expires = datetime.timedelta(days=7)
            access_token = create_access_token(identity=str(user.id),
                                               expires_delta=expires)
            return f"Bearer {access_token}", 200
        except (UnauthorizedError, DoesNotExist):
            raise UnauthorizedError
        except Exception as e:
            raise InternalServerError
Beispiel #8
0
 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 reject(self, id, message=None):
        application = Application.objects(
            Q(id=id) & Q(assignedId=get_jwt_identity()['_id']['$oid'])).get()

        if message is not None:
            application.update(message=message)

        application.update(status=-1)

        user = User.objects(Q(id=application.creatorId)).get()
        send_email_async(
            get_user_email(),
            'notification',
            get_user_name(),
            notif=
            f"You have successfully rejected {application.name} created by {user.first_name}."
        )

        send_email_async(
            get_user_email(),
            'notification',
            get_user_name(),
            notif=
            f"{get_user_name()} has unfortunately rejected your application due to the following "
            f"reason: '{message}'. Please check E-Daftar portal for more updates."
        )

        return 'Success', 200
Beispiel #10
0
    def post(self):
        body = request.get_json()
        fields = ['picture_id']
        if not fields_are_in(body, fields):
            return {'error': 'Missing a field'}, 400
        if is_empy_or_none(body):
            return {'error': 'A field is empty or None'}, 400

        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()

        if current_user is None:
            return {
                'error': 'Header token is not good, please login again'
            }, 401

        picture = Picture.objects(id=body.get('picture_id')).first()

        if picture is None:
            return {'error': 'Picture id does not exist in database'}, 401

        if current_user.username in picture.liked_by:
            Picture.objects(id=body.get('picture_id')).update_one(
                pull__liked_by=current_user.username)
            Picture.objects(id=body.get('picture_id')).update_one(
                nb_likes=picture.nb_likes - 1)
            return {'message': 'Successfully disliked picture'}, 200

        Picture.objects(id=body.get('picture_id')).update_one(
            push__liked_by=current_user.username)
        Picture.objects(id=body.get('picture_id')).update_one(
            nb_likes=picture.nb_likes + 1)
        return {'message': 'Successfully liked picture'}, 200
Beispiel #11
0
    def post(self):
        body = request.get_json()
        fields = ['picture_id', 'message']
        if not fields_are_in(body, fields):
            return {'error': 'Missing a field'}, 400
        if is_empy_or_none(body):
            return {'error': 'A field is empty or None'}, 400

        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()

        if current_user is None:
            return {
                'error': 'Header token is not good, please login again'
            }, 401

        picture = Picture.objects(id=body.get('picture_id')).first()

        if picture is None:
            return {'error': 'Picture id does not exist in database'}, 401
        comment = {
            'user': current_user.username,
            'message': body.get('message')
        }

        comment = Comment(**comment)
        comment.save()

        Picture.objects(id=body.get('picture_id')).update_one(
            push__comments=comment)
        Picture.objects(id=body.get('picture_id')).update_one(
            nb_comments=picture.nb_comments + 1)

        return {'message': 'Comment successfully added to picture'}, 200
	def post(self):
		try:
			body		= request.get_json()
			username	= body.get('username').title()
			email		= body.get('email')
			password	= body.get('password')
			if username is None or password is None or email is None:
				raise ValidationError
			if password != body.get('password2'):
				return {'password': '******'}, 400
			if User.objects(Q(username__iexact=username) or Q(email__iexact=email)).count() > 0:
				raise NotUniqueError
			user = User(username=username, password=password, email=email)
			user.hash_password()
			user.save()

			expires		= timedelta(days=7)
			access_token= create_access_token(identity=str(user.id), expires_delta=expires)
			return  {'type': 'success', 'success': 'Login succesfull.', 'username': user.username, 'token': 'Bearer ' + access_token}, 200
		except (FieldDoesNotExist, ValidationError, ValueError) as e:
			return SchemaValidationError, 400
		except NotUniqueError:
			return EmailAlreadyExistsError, 400
		except Exception as e:
			print(e)
			return InternalServerError, 500
Beispiel #13
0
    def get(self, id):
        """Returns a user object with username matching id."""

        try:
            user = []
            for doc in User.objects(username=id):
                user.append({
                    "_id":
                    str(ObjectId(doc["id"])),
                    "username":
                    doc["username"],
                    "online":
                    doc["online"],
                    "snippets_created": [{
                        "snippet_title": k["title"],
                        "snippet_id": str(ObjectId(k["id"])),
                    } for k in doc["snippets_created"]],
                    "snippets_liked": [{
                        "snippet_title": k["title"],
                        "snippet_id": str(ObjectId(k["id"])),
                    } for k in doc["snippets_liked"]],
                    "collections": [{
                        "collection_name": k["name"],
                        "collection_id": str(ObjectId(k["id"])),
                    } for k in doc["collections"]],
                })
            return jsonify(user)

        except DoesNotExist:
            raise UserNotExistsError
        except Exception:
            raise InternalServerError
Beispiel #14
0
    def get(self):
        """Returns an array of all User objects."""

        users = []
        for doc in User.objects():
            users.append({
                "_id":
                str(doc["id"]),
                "username":
                doc["username"],
                "online":
                doc["online"],
                "snippets_created": [{
                    "snippet_title": k["title"],
                    "snippet_id": str(ObjectId(k["id"])),
                } for k in doc["snippets_created"]],
                "snippets_liked": [{
                    "snippet_title": k["title"],
                    "snippet_id": str(ObjectId(k["id"])),
                } for k in doc["snippets_liked"]],
                "collections": [{
                    "collection_name": k["name"],
                    "collection_id": str(ObjectId(k["id"])),
                } for k in doc["collections"]],
            })

        return jsonify(users)
    def sign(self, id):
        application = Application.objects(
            Q(id=id) & Q(assignedId=get_jwt_identity()['_id']['$oid'])).get()

        if application.to_hash() != application.hash:
            return 'Data Tampered', 403

        current_stage = int(application.stage)
        private_key = User.objects(
            Q(id=get_jwt_identity()['_id']['$oid'])).get().private_key

        signatures = application.signatures
        signatures[current_stage] = Ecdsa.sign(
            json.dumps(application.to_hash()),
            PrivateKey.fromPem(private_key)).toBase64()

        application.update(signatures=signatures)

        if application.stage == application.stages - 1:
            application.update(stage=current_stage + 1)
            application.update(status=1)
        else:
            workflow = Workflow.objects(id=application.workflowId).get()
            new_auth_id = workflow.stages[current_stage + 1]['authId']
            new_auth_name = workflow.stages[current_stage + 1]['authName']
            application.update(assignedId=new_auth_id)
            application.update(assignedName=new_auth_name)
            application.update(stage=current_stage + 1)

        user = User.objects(Q(id=application.creatorId)).get()
        send_email_async(
            get_user_email(),
            'notification',
            get_user_name(),
            notif=
            f"You have successfully signed {application.name} created by {user.first_name} with "
            f"your digital signatures")

        send_email_async(
            user.email,
            'notification',
            user.first_name,
            notif=
            f"{get_user_name()} has successfully signed your {application.name}. Please check "
            f"E-Daftar portal for more updates.")

        return signatures[current_stage], 200
Beispiel #16
0
 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)
Beispiel #17
0
def get_user_by_ids():
    body = request.get_json()
    if body is None:
        return jsonify({'message': 'Please provide ids'}), 400
    ids = body.get('ids', [])
    try:
        users = User.objects(id__in=ids)
    except ValidationError:
        return jsonify({'message': 'Invalid Ids'}), 400
    return jsonify(users), 200
Beispiel #18
0
    def get(self, username):
        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()

        if current_user is None:
            return {'error': 'Header token is not good, please login again'}, 401

        user_info = User.objects(username=username).first()

        if user_info is None:
            return {'error': 'User {} does not exist'.format(username)}, 401

        user_info = json.loads(user_info.to_json())

        del user_info['password']
        del user_info['image_queue']
        del user_info['_id']
        del user_info['nb_login']
        del user_info['dates']
        del user_info['following']

        user_info['already_follow'] = False

        for user in user_info['followers']:
            if user['$oid'] == user_id:
                user_info['already_follow'] = True
                break
        del user_info['followers']

        for pic in range(len(user_info['pictures'])):
            user_info['pictures'][pic] = json.loads(Picture.objects(id=user_info['pictures'][pic]['$oid']).first().to_json())
            user_info['pictures'][pic]['id'] = user_info['pictures'][pic]['_id']['$oid']
            del user_info['pictures'][pic]['_id']
            del user_info['pictures'][pic]['date']
            del user_info['pictures'][pic]['owner']
            for com in range(len(user_info['pictures'][pic]['comments'])):
                user_info['pictures'][pic]['comments'][com] = json.loads(Comment.objects(id=user_info['pictures'][pic]['comments'][com]['$oid']).first().to_json())
                del user_info['pictures'][pic]['comments'][com]['_id']
        user_info['pictures'] = user_info['pictures'][::-1]

        return Response(json.dumps(user_info), mimetype="application/json", status=200)
Beispiel #19
0
    def get_account_balance(self, user_id, **kwargs):
        """Calcula el saldo actual del usaurio solicitado."""
        user = User.objects(user_id=user_id).first()
        print('Saldo actual del usuario: ', float(user.balance))

        Execution(
            workflow=str(self.workflow.pk),
            name='account_balance',
            type=Execution.TYPE_STEP,
            result={'balance': float(user.balance)}
        ).save()
Beispiel #20
0
def get_conversationById(userId):
    print(userId)
    # conversation = Conversation.objects.get().filter().to_json()
    user = User.objects(userId=userId).first()
    print("\n\n\nuserConversations ", user)
    if user is None:
        return Response(json.dumps({"msg": "no user found.."}))
    userConversations = user.getUserConversation()
    return Response(json.dumps(userConversations),
                    mimetype="application/json",
                    status=200)
Beispiel #21
0
def rigs():
    if request.method == 'GET':
        username = current_user.username
        user = User.objects(username=username)[0]
        rigs = RigList.objects(user=user)
        return render_template('rigs.html', rigs=rigs, user=user)
    if request.method == 'POST':
        print(request.form)
        user = User.objects(username=request.form.get('username'))[0]
        body = {'name': request.form.get('name'), 'products': [], 'user': user}
        for product_id in request.form.getlist('product_id'):
            body['products'].append(Product.objects.get(id=product_id))
        print(body)
        try:
            riglist = RigList(**body).save()
        except NotUniqueError as e:
            raise Exception(e)

        id = riglist.id
        return {'id': str(id)}, 200
Beispiel #22
0
    def validate_account(self, step, user_id, pin):
        """Valída que la cuenta del usuario solicitado sea válida."""
        is_valid = User.objects(user_id=user_id, pin=pin).count() > 0
        print('Validación de cuenta de usuario: ', 'Válida' if is_valid else 'Inválida')

        Execution(
            workflow=str(self.workflow.pk),
            name=step['id'],
            type=Execution.TYPE_STEP,
            result={'is_valid': is_valid}
        ).save()
Beispiel #23
0
    def post(self):
        body = request.get_json()
        fields = ['link', 'message']
        if not fields_are_in(body, fields):
            return {'error': 'Missing a field'}, 400
        if is_empy_or_none(
                dict({
                    'link': body.get('link'),
                    'message': body.get('message')
                })):
            return {'error': 'A field is empty or None'}, 400

        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()

        if current_user is None:
            return {
                'error': 'Header token is not good, please login again'
            }, 401

        picture = {
            'user': current_user.username,
            'owner': current_user.username,
            'link': body.get('link'),
            'message': body.get('message'),
            'date': datetime.datetime.now(),
            'nb_likes': 0,
            'nb_comments': 0,
        }
        picture = Picture(**picture)
        picture.save()

        User.objects(id=user_id).update_one(push__image_queue=picture)
        User.objects(id=user_id).update_one(push__pictures=picture)
        User.objects(id=user_id).update_one(
            nb_pictures=current_user.nb_pictures + 1)

        User.objects(following__in=[current_user]).update_one(
            push__image_queue=picture)

        return {
            'message':
            'Picture successfully added to user {} '.format(
                current_user.username)
        }, 200
Beispiel #24
0
    def post(self): 
        body = json.loads(request.data)
        
        name = body.get("username", None)
        email = body.get("email", None)
        password = body.get("password", None)
        address = body.get("address", None)
        phone_number = body.get("phone_number", None)
        gender = body.get("gender", None)

        user_found = User.objects(username__in=[name]).first()
        email_found = User.objects(email__in=[email]).first()

        if user_found:
            return Response("There already is a user by that name", mimetype="application/json", status=400)
        if email_found:
            return Response("This email already exists in database", mimetype="application/json", status=400)
        else:
            user_input = User(username = name, email= email, password = generate_password_hash(password), address = address, phone_number = phone_number, gender = gender)            
            user_input.save()
            return Response("User created", mimetype="application/json", status=201)
Beispiel #25
0
    def test_deposit_money_negative(self):
        """Prueba que valída el método de depositar dinero en la cuenta de un usuario con valores negativos."""
        mock_workflow = Mock(pk=12345)
        user = User.objects().first()
        money = -100000

        bank = BankService(workflow=mock_workflow)
        bank.deposit_money(user_id=user.user_id, money=money)
        bank.get_account_balance(user_id=user.user_id)

        execution = Execution.objects(workflow=str(mock_workflow.pk)).first()
        self.assertEqual(execution.result['balance'], 0)
Beispiel #26
0
    def withdraw(self, user_id, money, **kwargs):
        """Realiza un retiro de dinero de la cuenta del usuario solicitado."""
        user = User.objects(user_id=user_id).first()

        if money > 0:
            if user.balance >= money:
                print('Cantidad retirada: ', money)
                user.balance = float(user.balance) - float(money)
                user.save()
            else:
                print('No hay fondos suficientes para realizar el retiro.')
        else:
            print('No es posible retirar valores negativos.')
Beispiel #27
0
    def post(self):
        body = request.get_json()
        # try:
        #User(name=body[])
        if len(body['firstName']) == 0 or len(body['lastName']) == 0 or len(
                body['emailID']) == 0 or len(body['password']) == 0 or len(
                    body['confirmPassword']) == 0:
            return make_response(
                jsonify({
                    "message": "all fields are required",
                    "statusCode": 500
                }))
            # raise FieldsEmpty

        existingUser = User.objects(emailID=body['emailID'])
        if (existingUser):
            return make_response(
                jsonify({
                    "message": "user already exists, try to login",
                    "statusCode": 500
                }))
            # raise UserAlreadyExist

        if len(body['password']) < 6:
            return make_response(
                jsonify({
                    "message": "password is less than 6 characters",
                    "statusCode": 500
                }))
            # raise PasswordIsShort

        if body['password'] != body['confirmPassword']:
            return make_response(
                jsonify({
                    "message": "passwords doesnt match,please check",
                    "statusCode": 500
                }))
            # raise UnAuthorized

        # print("body" + str(body))

    # except:
        print("entered")
        newUser = User(firstName=body['firstName'],
                       lastName=body['lastName'],
                       emailID=body['emailID'],
                       password=body['password'],
                       confirmPassword=body['confirmPassword'])
        newUser.hash_password()
        newUser.save()
        return make_response(jsonify(newUser['emailID'], {"statusCode": 200}))
Beispiel #28
0
    def test_withdraw_no_funds(self):
        """Prueba que valída el método de retirar dinero de la cuenta de un usuario sin fondos suficientes."""
        mock_workflow = Mock(pk=12345)
        user = User.objects().first()
        money = 200000
        withdraw = 300000

        bank = BankService(workflow=mock_workflow)
        bank.deposit_money(user_id=user.user_id, money=money)
        bank.withdraw(user_id=user.user_id, money=withdraw)
        bank.get_account_balance(user_id=user.user_id)

        execution = Execution.objects(workflow=str(mock_workflow.pk)).first()
        self.assertEqual(execution.result['balance'], money)
Beispiel #29
0
    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]
        }
Beispiel #30
0
    def test_withdraw_in_dollars_negative(self):
        """Prueba que valída el método de retirar dinero en dólares de la cuenta de un usuario con valores negativos.
        """
        mock_workflow = Mock(pk=12345)
        user = User.objects().first()
        money = 100000
        withdraw = -5

        bank = BankService(workflow=mock_workflow)
        bank.deposit_money(user_id=user.user_id, money=money)
        bank.withdraw_in_dollars(user_id=user.user_id, money=withdraw)
        bank.get_account_balance(user_id=user.user_id)

        execution = Execution.objects(workflow=str(mock_workflow.pk)).first()
        self.assertEqual(execution.result['balance'], money)