Example #1
0
def view_onboarded_users(user_id, session_token, offset=0, limit=20):
    if session_token:
        offset = int(offset)
        limit = int(limit)
        user_id = int(user_id)
        if offset < 0 or limit < 0:
            raise ValueError

        db = database.Database()
        db.logger = current_app.logger
        session_user_id = db.validate_session(session_token)
        if session_user_id == user_id:
            displayed_users = db.list_onboarded_users(session_user_id,
                                                      offset,
                                                      limit)
            user_count = len(displayed_users)
            augmented_user_data = []
            for each_user in displayed_users:
                new_obj = dict(each_user)
                new_obj["email"] = new_obj["email_address"]
                ledger = TransactionLedger(each_user['user_id'], db, current_app.logger)
                user_credits = Credits(each_user['user_id'], db, current_app.logger)
                new_obj['transactions'] = ledger.get_transaction_count()
                new_obj['credits_balance'] = user_credits.get_credit_balance()
                new_obj['owned_tokens'] = ledger.get_owned_token_count()
                augmented_user_data.append(new_obj)
            return render_template("admin/admin_users.jinja2",
                                   session_token=session_token,
                                   users=augmented_user_data,
                                   view_wallet=True,
                                   user_count=user_count,
                                   limit=limit,
                                   offset=offset)
        else:
            abort(403)
Example #2
0
def admin_tokens(session_token):
    if session_token:
        db = database.Database(logger=current_app.logger)
        user_id = db.validate_session(session_token)
        ctx = UserContext(user_id, db=db, logger=db.logger)
        can_launch_ico = ctx.check_acl("launch-ico")

        erc20_mined = Event("ERC20 Token Mined", db, logger=current_app.logger)
        mined_count = erc20_mined.get_event_count(user_id)
        mined_ids = []

        if mined_count:
            mined_erc20_events = erc20_mined.get_latest_events(mined_count, user_id)
            for each in mined_erc20_events:
                json_data = json.loads(each[0])
                token_id = json_data["token_id"]
                if token_id not in mined_ids:
                    mined_ids.append(token_id)

        if can_launch_ico or len(ctx.acl()["management"]) > 0:
            owned_tokens = []
            for key in ctx.acl()["management"].keys():
                token_id = ctx.acl()["management"][key]["token_id"]
                token_info = db.get_smart_contract_info(token_id)
                owned_tokens.append(token_info)
            owned_tokens.extend(get_owned_tokens(user_id, db, current_app.logger))
            if len(owned_tokens) == 0:
                owned_tokens = None
            email_address = ctx.user_info["email_address"]
            last_logged_in = ctx.user_info["last_logged_in"].isoformat()
            last_logged_in_ip = ctx.user_info["last_logged_in_ip"]
            credit_ctx = Credits(user_id, db, current_app.logger)
            credit_balance = credit_ctx.get_credit_balance()
            if owned_tokens:
                for each in owned_tokens:
                    if each["token_id"] in mined_ids:
                        if each["eth_address"] is None:
                            each["pending"] = True
                        else:
                            each["pending"] = False

            return render_template("admin/admin_tokens.jinja2",
                                   session_token=session_token,
                                   owned_tokens=owned_tokens,
                                   can_launch_ico=can_launch_ico,
                                   email_address=email_address,
                                   last_logged_in=last_logged_in,
                                   last_logged_in_ip=last_logged_in_ip,
                                   credit_balance=credit_balance)
    abort(403)
Example #3
0
def admin_main(session_token, transactions=False):
    db = database.Database(logger=current_app.logger)
    user_id = db.validate_session(session_token)
    if user_id:
        user_ctx = UserContext(user_id, db, current_app.logger)
        launch_ico = user_ctx.check_acl("launch-ico")
        onboard_users = user_ctx.check_acl("onboard-users")
        reset_passwords = user_ctx.check_acl("reset-passwords")
        ethereum_network = user_ctx.check_acl("ethereum-network")
        view_event_log = user_ctx.check_acl("view-event-log")
        issue_credits = user_ctx.check_acl("issue-credits")
        manager = len(user_ctx.acl()["administrator"]) > 0 or len(user_ctx.get_manager_tokens()) > 0
        if user_ctx.user_info["email_address"] == "admin":
            manager = True
        charting = Charting(db, logger=current_app.logger)
        eth_nodes = db.list_ethereum_nodes()

        epoch = datetime.datetime.now() - datetime.timedelta(hours=24)
        node_gas_prices = {}
        moving_average_gas_price_data = charting.get_gas_price_moving_average(start=epoch)
        for node in eth_nodes:
            node_gas_prices[node["node_identifier"]] = charting.get_gas_price_for_node_id(node["id"], start=epoch)

        graphing_metrics = {
            "moving_average": {"gas_price": json.dumps(moving_average_gas_price_data)},
        }

        for each in node_gas_prices.keys():
            graphing_metrics[each] = json.dumps(node_gas_prices[each])

        cr = Credits(user_id, db, current_app.logger)

        return render_template("admin/admin_main.jinja2",
                               full_name=user_ctx.user_info['full_name'],
                               email_address=user_ctx.user_info['email_address'],
                               last_logged_in=user_ctx.user_info['last_logged_in'],
                               credits=cr.get_credit_balance(),
                               session_token=session_token,
                               launch_ico=launch_ico,
                               onboard_users=onboard_users,
                               reset_passwords=reset_passwords,
                               ethereum_network=ethereum_network,
                               view_event_log=view_event_log,
                               issue_credits=issue_credits,
                               manager=manager,
                               metrics=graphing_metrics,
                               user_id=user_id)
    else:
        return render_template("admin/admin_login.jinja2", error="Invalid session.")
Example #4
0
def erc20_publish():
    session_token = request.form["session_token"]
    token_id_form_field = request.form["token_id"]
    confirmation = request.form["confirmation"]
    db = database.Database()
    user_id = db.validate_session(session_token)
    if user_id:
        token_id = int(token_id_form_field)
        if token_id < 1:
            raise ValueError
        sc = SmartContract(smart_token_id=token_id)
        if sc.smart_contract_id < 1:
            abort(404)
        if confirmation == "true":
            credits = Credits(user_id, db, current_app.logger)
            current_balance = credits.get_credit_balance()
            if current_balance < credits.erc20_publish_price:
                message = "Your credit balance of <span class=\"credit_balance\">"
                message += str(current_balance) + "</span> is less than the <span class=\"credit_price\">"
                message += str(credits.erc20_publish_price) + "</span> required to publish an ERC20 token."
                message += "<p>[ <a class=\"login_anchor\" href=\"/admin/credits/purchase/"
                message += session_token + "\">purchase credits</a> ]</p>"
                return render_template("admin/admin_confirmation.jinja2",
                                       title="Unable to publice ERC20 contract",
                                       session_token=session_token,
                                       confirmation_value=token_id,
                                       confirmation_title="Insufficient Credits",
                                       confirmation_type="insufficient_credits",
                                       confirmation_message=message,
                                       default_choice="Cancel")
            message = "Are you sure you want to publish <em>" + sc.token_name + "</em> permanently to the Ethereum "
            message += "blockchain, costing <span class=\"credit_price\">"
            message += str(credits.erc20_publish_price) + "</span> credits?"
            return render_template("admin/admin_confirmation.jinja2",
                                   title="Confirm",
                                   session_token=session_token,
                                   confirmation_value=token_id,
                                   confirmation_title="Publish ERC20 contract?",
                                   confirmation_message=message,
                                   confirmation_type="erc20_publish",
                                   choices=["Cancel"],
                                   default_choice="Publish")
Example #5
0
def view_users(session_token, offset=0, limit=20):
    if session_token:
        offset = int(offset)
        limit = int(limit)
        if offset < 0 or limit < 0:
            raise ValueError
        db = database.Database()
        db.logger = current_app.logger
        user_id = db.validate_session(session_token)
        if user_id:
            user_ctx = UserContext(user_id, db, current_app.logger)
            user_data = db.list_users(offset, limit)
            user_count = db.get_user_count()
            can_reset_password = user_ctx.check_acl("reset-passwords")
            can_change_permissions = user_ctx.check_acl("change-permissions")
            can_issue_credits = user_ctx.check_acl("issue-credits")
            can_view_wallet = user_ctx.check_acl("assign-tokens") or user_ctx.check_acl("remove-tokens")

            augmented_user_data = []
            for each_user in user_data:
                new_obj = dict(each_user)
                ledger = TransactionLedger(each_user['user_id'], db, current_app.logger)
                user_credits = Credits(each_user['user_id'], db, current_app.logger)
                new_obj['transactions'] = ledger.get_transaction_count()
                new_obj['credits_balance'] = user_credits.get_credit_balance()
                new_obj['owned_tokens'] = ledger.get_owned_token_count()
                augmented_user_data.append(new_obj)
            return render_template("admin/admin_users.jinja2",
                                   session_token=session_token,
                                   users=augmented_user_data,
                                   reset_password=can_reset_password,
                                   change_permissions=can_change_permissions,
                                   issue_credits=can_issue_credits,
                                   view_wallet=can_view_wallet,
                                   user_count=user_count,
                                   limit=limit,
                                   offset=offset)
Example #6
0
def admin_confirm():
    session_token = request.form["session_token"]
    confirmation_type = request.form["confirmation_type"]
    confirmation_val = request.form["confirmation_value"]
    choice = request.form["choice"]
    if confirmation_type == "recover_email":
        if choice == "Send E-mail":
            email_address = request.form['email_address']
            mailer = Mailer(email_address, request.access_route[-1], current_app.logger)
            mailer.recover_password()
            return render_template("admin/admin_login.jinja2", error="""
            If the e-mail address is in the database, instructions have been sent on how to recover 
            your password. Please check your spam/junk mail folder.
            """)
        return redirect(url_for('homepage'))
    elif confirmation_type == "no_erc20_tokens":
        return redirect(url_for('admin.admin_tokens', session_token=session_token))
    elif confirmation_type == "erc20_publish" and choice == "Cancel":
        return redirect(url_for('admin.admin_tokens', session_token=session_token))
    elif confirmation_type == "create_erc20_failed" and choice == "OK":
        return redirect(url_for('admin.admin_tokens', session_token=session_token))
    elif confirmation_type == "onboarded_new_user":
        if choice == "Administration":
            return redirect(url_for('admin.admin_main', session_token=session_token))
        else:
            return redirect(url_for('admin.create_user', session_token=session_token))
    elif confirmation_type == "reset-password":
        if choice == "Cancel":
            return redirect(url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
    elif confirmation_type == "acl_updated":
        if choice == "OK":
            return redirect(url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
    db = database.Database(logger=current_app.logger)
    user_id = db.validate_session(session_token)
    if user_id:
        user_ctx = UserContext(user_id, db, current_app.logger)
        if confirmation_type == "erc20_publish":
            token_id = int(confirmation_val)
            sc = SmartContract(smart_token_id=token_id)
            credits = Credits(user_id, db, logger=current_app.logger)
            if sc.smart_contract_id > 0:
                event_data = {"token_name": sc.token_name,
                              "token_symbol": sc.token_symbol,
                              "token_count": sc.tokens,
                              "token_id": sc.smart_contract_id,
                              "ip_address": request.access_route[-1]}
                if user_ctx.check_acl("launch-ico"):
                    credits_balance = credits.get_credit_balance()
                    if credits_balance >= credits.erc20_publish_price:
                        new_event = Event("ERC20 Token Mined", db, logger=current_app.logger)
                        event_id = new_event.log_event(user_id, event_data)
                        event_data["event_id"] = event_id
                        credits.debit(credits.erc20_publish_price, event_data)
                        command_id = db.post_command(json.dumps({"erc20_function":"publish",
                                                                 "token_name":sc.token_name,
                                                                 "token_symbol":sc.token_symbol,
                                                                 "token_count":sc.tokens,
                                                                 "token_id":sc.smart_contract_id}), 100)
                        if command_id:
                            return redirect(url_for("admin.admin_tokens", session_token=session_token))
                        else:
                            abort(500)
                    else:
                        credits.logger.error("Insufficient credits for ERC20 Publish: "
                                             + user_ctx.user_info["email_address"])
                abort(403)
        elif confirmation_type == "reset-password":
            user_id = int(confirmation_val)
            if request.form["password"] != request.form["repeat_password"]:
                return render_template("admin/admin_confirmation.jinja2",
                                       confirmation_type="reset-password",
                                       confirmation_value=user_id,
                                       title="Reset Password",
                                       confirmation_title="Reset Password",
                                       confirmation_message="Passwords must match both times.",
                                       new_password=True,
                                       choices=["Cancel"],
                                       default_choice="Reset Password",
                                       session_token=session_token)
            if db.reset_password(int(confirmation_val), request.form["password"]):
                return redirect(url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
        elif confirmation_type == "issue-credits":
            if choice == "Issue Credits" and user_ctx.check_acl("issue-credits"):
                user_credits = Credits(confirmation_val, db, current_app.logger)
                amount = int(request.form["credits"])
                # max issued credits 10,000
                if 0 < amount < 100000:
                    user_credits.issue_credits(amount, {"ip_addr": request.access_route[-1], "admin": user_id})
                    return redirect(
                        url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
                else:
                    raise ValueError

    abort(403)