Esempio n. 1
0
def change_password():
    old_password = request.json['data']['old-password']
    new_password = request.json['data']['new-password']

    try:
        user = User.query.filter_by(id=current_user.id).one()
    except NoResultFound:
        return NotFoundError({'source': ''}, 'User Not Found').respond()
    else:
        if user.is_correct_password(old_password):
            if user.is_correct_password(new_password):
                return BadRequestError({'source': ''},
                                       'Old and New passwords must be different').respond()
            if len(new_password) < 8:
                return BadRequestError({'source': ''},
                                       'Password should have minimum 8 characters').respond()
            user.password = new_password
            save_to_db(user)
            send_email_with_action(user, PASSWORD_CHANGE,
                                   app_name=get_settings()['app_name'])
            send_notification_with_action(user, PASSWORD_CHANGE_NOTIF,
                                          app_name=get_settings()['app_name'])
        else:
            return BadRequestError({'source': ''}, 'Wrong Password. Please enter correct current password.').respond()

    return jsonify({
        "id": user.id,
        "email": user.email,
        "name": user.fullname if user.fullname else None,
        "password-changed": True
    })
Esempio n. 2
0
def join_stream(stream_id: int):
    stream = VideoStream.query.get_or_404(stream_id)
    if not stream.user_can_access:
        raise NotFoundError({'source': ''}, 'Video Stream Not Found')
    if not stream.channel or stream.channel.provider != 'bbb':
        raise BadRequestError(
            {'param': 'stream_id'},
            'Join action is not applicable on this stream provider',
        )

    options = stream.extra.get('bbb_options') or default_options

    params = dict(
        name=stream.name,
        meetingID=stream.extra['response']['meetingID'],
        moderatorPW=stream.extra['response']['moderatorPW'],
        attendeePW=stream.extra['response']['attendeePW'],
        **options,
    )

    channel = stream.channel
    bbb = BigBlueButton(channel.api_url, channel.api_key)
    result = bbb.request('create', params)

    if result.success and result.data:
        stream.extra = {**result.data, 'bbb_options': options}
        db.session.commit()
    elif (result.data and result.data.get('response', {}).get('messageKey')
          == 'idNotUnique'):
        # Meeting is already created
        pass
    else:
        logger.error('Error creating BBB Meeting: %s', result)
        raise BadRequestError('', 'Cannot create Meeting on BigBlueButton')

    join_url = bbb.build_url(
        'join',
        {
            'fullName':
            current_user.public_name or current_user.full_name
            or current_user.anonymous_name,
            'join_via_html5':
            'true',
            'meetingID':
            params['meetingID'],
            'password':
            params['moderatorPW' if stream.
                   user_is_moderator else 'attendeePW'],
        },
    )

    return jsonify(url=join_url)
Esempio n. 3
0
def create_source(order_identifier):
    """
    Create a source object for alipay payments.
    :param order_identifier:
    :return: The alipay redirection link.
    """
    try:
        order = safe_query(db, Order, 'identifier', order_identifier,
                           'identifier')
        source_object = AliPayPaymentsManager.create_source(
            amount=int(order.amount),
            currency='usd',
            redirect_return_uri=url_for(
                'alipay_blueprint.alipay_return_uri',
                order_identifier=order.identifier,
                _external=True,
            ),
        )
        order.order_notes = source_object.id
        save_to_db(order)
        return jsonify(link=source_object.redirect['url'])
    except TypeError:
        return BadRequestError({
            'source': ''
        }, 'Source creation error').respond()
    def test_exceptions(self):
        """Method to test all exceptions."""

        # Unprocessable Entity Exception
        with self.assertRaises(UnprocessableEntityError):
            raise UnprocessableEntityError(
                {'pointer': '/data/attributes/min-quantity'},
                "min-quantity should be less than max-quantity",
            )

        # Conflict Exception
        with self.assertRaises(ConflictError):
            raise ConflictError({'pointer': '/data/attributes/email'},
                                "Email already exists")

        # Forbidden Exception
        with self.assertRaises(ForbiddenError):
            raise ForbiddenError({'source': ''}, "Access Forbidden")

        # Not Found Error
        with self.assertRaises(NotFoundError):
            raise NotFoundError({'source': ''}, "Not Found")

        # Server Error
        with self.assertRaises(ServerError):
            raise ServerError({'source': ''}, "Internal Server Error")

        # Bad Request Error
        with self.assertRaises(BadRequestError):
            raise BadRequestError({'source': ''}, "Bad Request")

        # Method Not Allowed Exception
        with self.assertRaises(MethodNotAllowed):
            raise MethodNotAllowed({'source': ''}, "Method Not Allowed")
Esempio n. 5
0
def charge_paypal_payment_invoice(invoice_identifier):
    """
    Create a paypal payment.
    :return: The payment id of the created payment.
    """
    try:
        paypal_payment_id = request.json['data']['attributes'][
            'paypal_payment_id']
        paypal_payer_id = request.json['data']['attributes']['paypal_payer_id']
    except Exception as e:
        return BadRequestError({'source': e}, 'Bad Request Error').respond()
    event_invoice = safe_query(db, EventInvoice, 'identifier',
                               invoice_identifier, 'identifier')
    # save the paypal payment_id with the order
    event_invoice.paypal_token = paypal_payment_id
    save_to_db(event_invoice)

    # execute the invoice transaction.
    status, error = PayPalPaymentsManager.execute_payment(
        paypal_payer_id, paypal_payment_id)

    if status:
        # successful transaction hence update the order details.
        event_invoice.paid_via = 'paypal'
        event_invoice.status = 'paid'
        event_invoice.transaction_id = paypal_payment_id
        event_invoice.completed_at = datetime.datetime.now()
        save_to_db(event_invoice)

        return jsonify(status="Charge Successful",
                       payment_id=paypal_payment_id)
    else:
        # return the error message from Paypal
        return jsonify(status="Charge Unsuccessful", error=error)
Esempio n. 6
0
def reset_password_post():
    try:
        email = request.json['data']['email']
    except TypeError:
        return BadRequestError({'source': ''}, 'Bad Request Error').respond()

    try:
        user = User.query.filter_by(email=email).one()
    except NoResultFound:
        logger.info('Tried to reset password not existing email %s', email)
    else:
        link = make_frontend_url('/reset-password',
                                 {'token': user.reset_password})
        if user.was_registered_with_order:
            send_email_with_action(user,
                                   PASSWORD_RESET_AND_VERIFY,
                                   app_name=get_settings()['app_name'],
                                   link=link)
        else:
            send_email_with_action(user,
                                   PASSWORD_RESET,
                                   app_name=get_settings()['app_name'],
                                   link=link,
                                   token=user.reset_password)

    return make_response(
        jsonify(message="If your email was registered with us, you'll get an \
                         email with reset link shortly",
                email=email), 200)
Esempio n. 7
0
def resend_verification_email():
    try:
        email = request.json['data']['email']
    except TypeError:
        logging.error('Bad Request')
        raise BadRequestError({'source': ''}, 'Bad Request Error')

    try:
        user = User.query.filter_by(email=email).one()
    except NoResultFound:
        logging.info('User with email: ' + email + ' not found.')
        raise UnprocessableEntityError(
            {'source': ''}, 'User with email: ' + email + ' not found.'
        )
    else:
        serializer = get_serializer()
        hash_ = str(
            base64.b64encode(
                str(serializer.dumps([user.email, str_generator()])).encode()
            ),
            'utf-8',
        )
        link = make_frontend_url('/verify', {'token': hash_})
        send_email_confirmation(user.email, link)
        logging.info('Verification email resent')
        return make_response(jsonify(message="Verification email resent"), 200)
Esempio n. 8
0
    def after_update_object(self, stream, data, view_kwargs):
        if stream.channel and stream.channel.provider == 'bbb':
            bbb_options = stream.extra.get('bbb_options')
            if bbb_options and bbb_options.get('endCurrentMeeting'):
                params_isMeetingRunning = dict(
                    meetingID=stream.extra['response']['meetingID'], )

                channel = stream.channel
                bbb = BigBlueButton(channel.api_url, channel.api_key)
                result_isMeetingRunning = bbb.request('isMeetingRunning',
                                                      params_isMeetingRunning)

                if (result_isMeetingRunning.data.get(
                        'response', {}).get('running') == 'true'):
                    params_end_meeting = dict(
                        meetingID=stream.extra['response']['meetingID'],
                        password=stream.extra['response']['moderatorPW'],
                    )
                    result_end_meeting = bbb.request('end', params_end_meeting)

                    if not result_end_meeting.success:
                        logger.error(
                            'Error while ending current BBB Meeting: %s',
                            result_end_meeting,
                        )
                        raise BadRequestError(
                            '', 'Cannot end current Meeting on BigBlueButton')
Esempio n. 9
0
    def test_errors(self):
        """Method to test the status code of all errors"""

        with app.test_request_context():
            # Forbidden Error
            forbidden_error = ForbiddenError({'source': ''},
                                             'Super admin access is required')
            self.assertEqual(forbidden_error.status, 403)

            # Not Found Error
            not_found_error = NotFoundError({'source': ''},
                                            'Object not found.')
            self.assertEqual(not_found_error.status, 404)

            # Server Error
            server_error = ServerError({'source': ''}, 'Internal Server Error')
            self.assertEqual(server_error.status, 500)

            # UnprocessableEntity Error
            unprocessable_entity_error = UnprocessableEntityError(
                {'source': ''}, 'Entity cannot be processed')
            self.assertEqual(unprocessable_entity_error.status, 422)

            # Bad Request Error
            bad_request_error = BadRequestError({'source': ''},
                                                'Request cannot be served')
            self.assertEqual(bad_request_error.status, 400)
Esempio n. 10
0
def verify_email():
    token = base64.b64decode(request.json['data']['token'])
    s = get_serializer()

    try:
        data = s.loads(token)
    except Exception:
        return BadRequestError({'source': ''}, 'Invalid Token').respond()

    try:
        user = User.query.filter_by(email=data[0]).one()
    except Exception:
        return BadRequestError({'source': ''}, 'Invalid Token').respond()
    else:
        user.is_verified = True
        save_to_db(user)
        return make_response(jsonify(message="Email Verified"), 200)
Esempio n. 11
0
def verify_mobile_paypal_payment(order_identifier):
    """
    Verify paypal payment made on mobile client
    :return: The status of order verification
    """
    try:
        payment_id = request.json['data']['attributes']['payment-id']
    except TypeError:
        raise BadRequestError({'source': ''}, 'Bad Request Error')
    order = safe_query(Order, 'identifier', order_identifier, 'identifier')
    status, error = PayPalPaymentsManager.verify_payment(payment_id, order)
    return jsonify(status=status, error=error)
Esempio n. 12
0
def change_password():
    old_password = request.json['data']['old-password']
    new_password = request.json['data']['new-password']

    try:
        user = User.query.filter_by(id=current_user.id).one()
    except NoResultFound:
        logging.info('User Not Found')
        raise NotFoundError({'source': ''}, 'User Not Found')
    else:
        if user.is_correct_password(old_password):
            if user.is_correct_password(new_password):
                logging.error('Old and New passwords must be different')
                raise BadRequestError(
                    {'source': ''}, 'Old and New passwords must be different'
                )
            if len(new_password) < 8:
                logging.error('Password should have minimum 8 characters')
                raise BadRequestError(
                    {'source': ''}, 'Password should have minimum 8 characters'
                )
            user.password = new_password
            save_to_db(user)
            send_password_change_email(user)
        else:
            logging.error('Wrong Password. Please enter correct current password.')
            raise BadRequestError(
                {'source': ''}, 'Wrong Password. Please enter correct current password.'
            )

    return jsonify(
        {
            "id": user.id,
            "email": user.email,
            "name": user.fullname if user.fullname else None,
            "password-changed": True,
        }
    )
Esempio n. 13
0
def test_errors():
    """Method to test the status code of all errors"""
    forbidden_error = ForbiddenError({'source': ''},
                                     'Super admin access is required')
    assert forbidden_error.status == 403
    not_found_error = NotFoundError({'source': ''}, 'Object not found.')
    assert not_found_error.status == 404
    server_error = ServerError({'source': ''}, 'Internal Server Error')
    assert server_error.status == 500
    unprocessable_entity_error = UnprocessableEntityError(
        {'source': ''}, 'Entity cannot be processed')
    assert unprocessable_entity_error.status == 422
    bad_request_error = BadRequestError({'source': ''},
                                        'Request cannot be served')
    assert bad_request_error.status == 400
Esempio n. 14
0
def create_paypal_payment(order_identifier):
    """
    Create a paypal payment.
    :return: The payment id of the created payment.
    """
    try:
        return_url = request.json['data']['attributes']['return-url']
        cancel_url = request.json['data']['attributes']['cancel-url']
    except TypeError:
        raise BadRequestError({'source': ''}, 'Bad Request Error')

    order = safe_query(Order, 'identifier', order_identifier, 'identifier')
    status, response = PayPalPaymentsManager.create_payment(order, return_url, cancel_url)

    if status:
        return jsonify(status=True, payment_id=response)
    return jsonify(status=False, error=response)
Esempio n. 15
0
def reset_password_post():
    try:
        email = request.json['data']['email']
    except TypeError:
        return BadRequestError({'source': ''}, 'Bad Request Error').respond()

    try:
        user = User.query.filter_by(email=email).one()
    except NoResultFound:
        return NotFoundError({'source': ''}, 'User not found').respond()
    else:
        link = make_frontend_url('/reset-password', {'token': user.reset_password})
        if user.was_registered_with_order:
            send_email_with_action(user, PASSWORD_RESET_AND_VERIFY, app_name=get_settings()['app_name'], link=link)
        else:
            send_email_with_action(user, PASSWORD_RESET, app_name=get_settings()['app_name'], link=link)

    return make_response(jsonify(message="Email Sent"), 200)
Esempio n. 16
0
def create_paypal_payment_invoice(invoice_identifier):
    """
    Create a paypal payment.
    :return: The payment id of the created payment.
    """
    try:
        return_url = request.json['data']['attributes']['return-url']
        cancel_url = request.json['data']['attributes']['cancel-url']
    except TypeError:
        raise BadRequestError({'source': ''}, 'Bad Request Error')

    event_invoice = safe_query(EventInvoice, 'identifier', invoice_identifier,
                               'identifier')
    billing_email = get_settings()['admin_billing_paypal_email']
    status, response = PayPalPaymentsManager.create_payment(
        event_invoice, return_url, cancel_url, payee_email=billing_email)

    if status:
        return jsonify(status=True, payment_id=response)
    return jsonify(status=False, error=response)
Esempio n. 17
0
def create_paypal_payment_invoice(invoice_identifier):
    """
    Create a paypal payment.
    :return: The payment id of the created payment.
    """
    try:
        return_url = request.json['data']['attributes']['return-url']
        cancel_url = request.json['data']['attributes']['cancel-url']
    except TypeError:
        return BadRequestError({'source': ''}, 'Bad Request Error').respond()

    event_invoice = safe_query(db, EventInvoice, 'identifier',
                               invoice_identifier, 'identifier')
    status, response = PayPalPaymentsManager.create_payment(
        event_invoice, return_url, cancel_url)

    if status:
        return jsonify(status=True, payment_id=response)
    else:
        return jsonify(status=False, error=response)
Esempio n. 18
0
def reset_password_post():
    try:
        email = request.json['data']['email']
    except TypeError:
        logging.error('Bad Request Error')
        raise BadRequestError({'source': ''}, 'Bad Request Error')

    try:
        user = User.query.filter_by(email=email).one()
    except NoResultFound:
        logging.info('Tried to reset password not existing email %s', email)
    else:
        send_password_reset_email(user)

    return make_response(
        jsonify(
            message="If your email was registered with us, you'll get an email with reset link shortly",
            email=email,
        ),
        200,
    )