Exemple #1
0
def main(url_to_check):
    data = scraper.get_item_info(url_to_check)

    if database.is_empty():  # writing first entry
        database.write_db(data)
        print("Item added.")
    else:
        if str(url_to_check) not in entries_in_db:  # if already in don't write
            database.write_db(data)
            print("Item added.")

        else:  # if item is already in db then check the price
            new_price = data['price']
            old_price = entries_in_db[str(url_to_check)]['price']
            print(f"Item already exists, checking {url_to_check}")
            # print("Price now: " + str(new_price))
            # print("Price before: " + str(old_price))
            try:
                if new_price < old_price:  # if new price < old
                    print("There is a sale!")
                    entries_in_db[str(url_to_check)]['sale'] = True
                    database.delete_db(data["url"])  # delete line with same url
                    database.write_db(data)         # add line back with new price
                elif new_price > old_price:  # if new price > old
                    database.delete_db(data["url"])
                    database.write_db(data)
            except TypeError:
                pass

            if entries_in_db[str(url_to_check)]['sale'] is True:
                print("Sending email...")
                send_email(new_price, old_price)
def create_test_app():
    deleter()
    initer()
    app = Flask(__name__)
    app.config.from_object('test_settings')
    ##------PAGE DEVIDING -----#
    app.register_blueprint(website)
    ##---SECRET KEY -----#
    app.secret_key = app.config.get('secret_key', 'secret')
    ##---MAIL SENDER --##
    app.sender = app.config.get('MAIL_USERNAME')
    app.mail = Mail(app)
    ##--SQL ALCHEMY CONFIGURAION--##
    app.db = SQLAlchemy(app)
    delete_db()
    init_db()
    # flask administration
    path = op.join(op.dirname(__file__), 'static')
    app.admin = Admin(app,
                      name="Casting Agency",
                      template_mode='bootstrap3',
                      index_view=MyAdminIndexView())
    app.admin.add_view(AdminView(Categories, app.db.session))
    app.admin.add_view(AdminView(User, app.db.session, category='User Ops'))
    app.admin.add_view(AdminView(Role, app.db.session, category='User Ops'))
    app.admin.add_view(
        AdminView(Agency, app.db.session, category='App Manager'))
    app.admin.add_view(
        AdminView(NormalContact, app.db.session, category='App Manager'))
    app.admin.add_view(AdminView(Setup, app.db.session,
                                 category='App Manager'))
    app.admin.add_view(
        AdminView(StaticNav, app.db.session, category='App Manager'))
    app.admin.add_view(AdminView(Actors, app.db.session, category='Actor Ops'))
    app.admin.add_view(
        AdminView(ActorBody, app.db.session, category='Actor Ops'))
    app.admin.add_view(
        AdminView(ActorSoul, app.db.session, category='Actor Ops'))
    app.admin.add_view(AdminView(Photos, app.db.session, category='Actor Ops'))
    app.admin.add_view(
        AdminView(TempActors, app.db.session, category='Coming Applies'))
    app.admin.add_view(
        AdminView(TempActorBody, app.db.session, category='Coming Applies'))
    app.admin.add_view(
        AdminView(TempActorSoul, app.db.session, category='Coming Applies'))
    app.admin.add_view(
        AdminView(TempPhotos, app.db.session, category='Coming Applies'))
    app.admin.add_view(MyFileView(path, '/static/', name='Static Files'))
    ##--FOR SESSIONS LIFETIME VALUE --##
    app.permanent_session_lifetime = timedelta(hours=10)
    ##-------SETUP FOR FLASK-SECURITY--------##
    app.user_datastore = SQLAlchemyUserDatastore(app.db, User, RolesUsers)
    app.security = Security(app, app.user_datastore)
    return app
Exemple #3
0
def verify_assertion():
    jsonData = request.get_json()
    AuthenticatorAttestationResponse = jsonData['AuthenticatorAttestationResponse']
    clientDataJSON = AuthenticatorAttestationResponse['clientDataJSON']
    clientDataJSON_padding = clientDataJSON.ljust((int)(math.ceil(len(clientDataJSON) / 4)) * 4, '=')
    clientDataJSON = base64.b64decode(clientDataJSON_padding).decode('utf8')
    clientDataJSONparsed = json.loads(clientDataJSON)
    retrievedChallenge = clientDataJSONparsed['challenge']
    try:
        data = database.query_db("select * from PublicKeyCredentialCreationOptions where challenge=?",[retrievedChallenge])[0]
    except:
        return jsonify({"Error:","Could not find challenge"}),500
    #DELETE from table
    database.delete_db("delete from PublicKeyCredentialCreationOptions where challenge=?",[retrievedChallenge])
    signature = AuthenticatorAttestationResponse['signature']
    assertion_response =  {'clientData':AuthenticatorAttestationResponse['clientDataJSON'],'authData':AuthenticatorAttestationResponse['authenticatorData'],'signature':signature,'userHandle':AuthenticatorAttestationResponse['userHandle']}

    credential_id = AuthenticatorAttestationResponse.get('id')
    user = database.query_db("select * from Users where credential_id=?",[credential_id])[0]
    if len(user)==0:
        return make_response(jsonify({'fail': 'User does not exist.'}), 401)
    webauthn_user = webauthn.WebAuthnUser(
        user[0], user[0], user[2], user[6],
        user[4], user[3], user[5], user[7])

    webauthn_assertion_response = webauthn.WebAuthnAssertionResponse(
        webauthn_user,
        assertion_response,
        retrievedChallenge,
        ORIGIN,
        uv_required=False)  # User Verification
    sign_count = webauthn_assertion_response.verify()
    try:
        sign_count = webauthn_assertion_response.verify()
    except Exception as e:
        print(e)
        return make_response(jsonify({'fail': 'Assertion failed'}),500)

    # Update counter.

    #Update database
    update = database.insert_db("update Users SET sign_count=? where username=?",[sign_count,user[1]])
    identityObj={'username':user[1],'id':user[0],'displayname':user[2]}
    expires = datetime.timedelta(hours=2)
    print(identityObj)
    jwt = create_access_token(identity=identityObj,expires_delta=expires)
    return jsonify({
        'success':
        'Successfully authenticated as {}'.format(user[1]),
        'jwt':jwt,
        'username': user[1]
    })
Exemple #4
0
def webauthn_end_activate():
    jsonData = request.get_json()
    AuthenticatorAttestationResponse = jsonData['AuthenticatorAttestationResponse']
    clientDataJSON = AuthenticatorAttestationResponse['clientDataJSON']
    clientDataJSON_padding = clientDataJSON.ljust((int)(math.ceil(len(clientDataJSON) / 4)) * 4, '=')
    clientDataJSON = base64.b64decode(clientDataJSON_padding).decode('utf8')
    clientDataJSONparsed = json.loads(clientDataJSON)
    retrievedChallenge = clientDataJSONparsed['challenge']
    try:
        data = database.query_db("select * from PublicKeyCredentialCreationOptions where challenge=?",[retrievedChallenge])[0]
    except:
        return jsonify({"Error:","Could not find challenge"}),500
    trusted_attestation_cert_required = True
    self_attestation_permitted = True
    none_attestation_permitted = True

    registration_response = {'clientData':AuthenticatorAttestationResponse['clientDataJSON'],'attObj':AuthenticatorAttestationResponse['attestationObject']}
    trust_anchor_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), TRUST_ANCHOR_DIR)
    webauthn_registration_response = webauthn.WebAuthnRegistrationResponse(
        RP_ID,
        ORIGIN,
        registration_response,
        data[5],
        trust_anchor_dir,
        trusted_attestation_cert_required,
        self_attestation_permitted,
        none_attestation_permitted,
        uv_required=False)  # User Verification

    try:
        webauthn_credential = webauthn_registration_response.verify()
    except (RuntimeError, TypeError, NameError):
        print(RuntimeError)
        return jsonify({'fail': 'Registration failed. Error: {}'.format(RuntimeError)})
    credential_id=webauthn_credential.credential_id.decode("utf-8")
    duplicatedId = database.query_db("select credential_id from Users where credential_id=?",[credential_id])
    if len(duplicatedId)!=0:
        return jsonify({"Error":"Error with register, try again"}),500

    existing_user = database.query_db("select user_id from Users where username=?",[data[4]])
    if len(existing_user)!=0:
        return jsonify({"Error":"Error with register, try again"}),500
    #Add user to database
    database.insert_db("insert into Users VALUES (?,?,?,?,?,?,?,?)",[data[2],data[4],data[3],webauthn_credential.public_key,credential_id,webauthn_credential.sign_count,'http://localhost',data[1]])
    #Remove from PublicKeyCredentialCreationOptions
    database.delete_db("delete from PublicKeyCredentialCreationOptions where challenge=?",[retrievedChallenge])
    return jsonify({'success': 'User successfully registered.'})
Exemple #5
0
def delete_book():
    del_input = input("Enter the book to remove:\n").capitalize().strip()
    print(database.delete_db(del_input))
Exemple #6
0
import database

file_name = "product_data.txt"
database.delete_db(input("Please enter the URL of the item you would like to stop tracking: "))
Exemple #7
0
 def tearDown(self):
     delete_db()
     self.app.db.drop_all()