def login_to_firebase(self):
        config = {
            "apiKey": "AIzaSyDKNDAFLkSqwzr1BTjQq6ZZV8Xqb-WH4lA",
            "authDomain": "hasadna-attendance.firebaseapp.com",
            "databaseURL": "https://hasadna-attendance.firebaseio.com",
            "storageBucket": "hasadna-attendance.appspot.com",
            "serviceAccount": "c:/hasadna-attendance-firebase-adminsdk-efpir-b8a5ce26b1.json"
        }

        firebase = pyrebase.initialize_app(config)

        # Get a reference to the auth service
        auth = firebase.auth()

        ColorEngine.print("--- Authentication Process ---", ColorEngine.BLUE)
        print("Enter your email address: ")
        email = input()
        print("Enter your password: "******"Login failed, error: {0}".format(e))

        # at this point database can be used.

        return self.connection
Exemple #2
0
def write2fb(logger):

  firebase_config = {
    'apiKey': "AIzaSyCv6jE0O5QjsAMK_WzUG2pDvEsIlTZCduY",
    'authDomain': "libtech-app.firebaseapp.com",
    'databaseURL': "https://libtech-app.firebaseio.com",
    'storageBucket': "libtech-app.appspot.com"
    }
  
  firebase = pyrebase.initialize_app(firebase_config)
  db = firebase.database()

  all_panchayats = db.child("panchayats").get()
  for panchayat in all_panchayats.each():
    print(panchayat.key()) # Morty
    print(panchayat.val()) # {name": "Mortimer 'Morty' Smith"}

  print(' ********* DONE ********** ')

  data = { 'users' : '' }
  db.update(data);

  '''
  all_users = db.child("users").get()
  for user in all_users.each():
    print(user.key()) # Morty
    print(user.val()) # {name": "Mortimer 'Morty' Smith"}

  print(' ********* DONE ********** ')
  '''
  
  return 'SUCCESS'
def main(noemail):
	"""
	IMPORTANT: Pleas don't add the configfile.py and the json credential
	files to gitHub
	"""
	firebase = pyrebase.initialize_app(configfile.config)

	print ("Getting credentials...")
	credentials = get_credentials()
	print("Done")
	print ("Reading user data from spread sheet...")
	userData = readFromSheet(credentials)
	print ("Done")
	if not noemail:
		print ("Register user and send email...")
		registeredUsers = registerUser(userData, firebase, False)
	else:
		print ("Register user and do not send email...")
		registeredUsers = registerUser(userData, firebase, True)
	if registeredUsers:
		print ("Adding user infomation to the database...")
		count = updateDatabase(registeredUsers, firebase)
		print ("Finished! Successfully added %s users to the database" % (str(count)))
	else:
		print ("No new user added")
    def pyrebase_init(self, email, password):

        # Fetch the service account key JSON file contents

        # As an admin, the app has access to read and write all data, regardless of Security Rules
        config = {
            "apiKey": "AIzaSyDt-RK1Njxn_aqMOcl0ngKv9mTp886Ebh4",
            "authDomain": "intelligent-medicine-box.firebaseapp.com",
            "databaseURL": "https://intelligent-medicine-box.firebaseio.com",
            "storageBucket": "intelligent-medicine-box.appspot.com"
        }
        firebase = pyrebase.initialize_app(config)
        auth = firebase.auth()
        self._db = firebase.database()

        # authenticate a user
        if email is None or password is None:
            print('email or password is None in notifier')
            assert(False)
        # login the user.
        try:
            self._user = auth.sign_in_with_email_and_password(email, password)
        except Exception:
            print("Wrong login or password.")
            return False
        # print(user)

        self._patient_id = self._user['localId']
        # print(self._ref.get())

        print("Login successful.")
        return True
Exemple #5
0
def run():
    firebase = pyrebase.initialize_app(config)
    auth =firebase.auth()
    user = auth.sign_in_with_email_and_password("*****@*****.**", "test123")
    db = firebase.database()
    #data = db.child("auto-update").get(user['idToken'])
    data = db.child("uuid").get(user['idToken'])
    
    return data
Exemple #6
0
    def connectToFirebase(self):
        self.firebase = pyrebase.initialize_app(self.config['Firebase'])

        try:
            self.refreshAuthToken()
        except:
            logger.error('Failed to login to Firebase: {}'.format(e))

        self.firebase_db = self.firebase.database()
Exemple #7
0
    def __init__(self):
        config = {
            "apiKey": "AIzaSyBch97dQuSayarcFVa3tsG3MxrcLke8LV0",
            "authDomain": "asti-2d7bd.firebaseapp.com",
            "databaseURL": "https://asti-2d7bd.firebaseio.com",
            "storageBucket": "asti-2d7bd.appspot.com",
            "serviceAccount": "firebase/Asti-72defd5ee1a9.json"

        }
        
        self.firebase = pyrebase.initialize_app(config)
        auth = self.firebase.auth()
        self.user = auth.sign_in_with_email_and_password(username, password)
Exemple #8
0
def json2fb(logger):
  with open(filename, 'r') as infile:
    logger.info('Reading from file[%s]' % filename)
    data = json.load(infile)
    logger.info(data)

  firebase = pyrebase.initialize_app(config)
  db = firebase.database()

  all_users = db.child("9099").get()
  for user in all_users.each():
    print(user.key()) # Morty
    print(user.val()) # {name": "Mortimer 'Morty' Smith"}
    
  return 'SUCCESS'
def main(args):
    email = args.email
    password = args.password
    firebase = pyrebase.initialize_app(config)
    auth = firebase.auth()
    _user = auth.sign_in_with_email_and_password(email, password)
    db = firebase.database()
    all_users = db.child('users').get()
    #loop through users, acess child works
    for user in all_users.each():
        use_key = user.key()
        works = db.child('users').child(use_key).child('Works').get()
        try:
            for work in works.each():
                db.child('users').child(use_key).child('Works').child(work.key()).update({"sold":"false"},
                                                                                         _user['idToken'])
        except:
            tb = traceback.format_exc()
            print(tb)
Exemple #10
0
def main():
    firebase = pyrebase.initialize_app(firebase_config)
    auth = firebase.auth()
    db = firebase.database()

    dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
    load_dotenv(dotenv_path)

    email = os.environ.get('EMAIL')
    password = os.environ.get('PASSWORD')
    user = auth.sign_in_with_email_and_password(email, password)

    page_id = db.child('continuation').get(user['idToken']).val()
    if not page_id:
        db.child('continuation').set(1, user['idToken'])
        page_id = 1

    while True:
        user = auth.sign_in_with_email_and_password(email, password)

        print('#' * 50)
        print('page_id == {}'.format(page_id))
        print('#' * 50)
        ranking_html = pq(
            url='https://beta.atcoder.jp/ranking?page={}'.format(page_id))
        table = ranking_html.find('.table > tbody').children()

        if not table:
            print('#' * 50)
            print('Table is empty. Back to page 1.')
            print('#' * 50)
            page_id = 1
            db.child('continuation').set(page_id, user['idToken'])
            continue

        for tr in table:
            rank = int(pq(tr).children().eq(0).text())
            country = pq(tr).children().eq(1).children().eq(0).attr(
                'href').split('=')[1]
            if country in country_names:
                formal_country_name = country_names[country]
            else:
                formal_country_name = None
            crown = pq(tr).children().eq(1).children('img').attr('src')
            crown = crown.split('/assets/icon/')[1].split(
                '.gif')[0] if crown else None
            username = pq(tr).children().eq(1).children('.username').text()
            user_color_elem = pq(tr).children().eq(1).children(
                '.username').children()
            user_color = user_color_elem.attr('class').replace('user-', '') if user_color_elem.attr('class') \
                else user_color_elem.attr('style').replace('color:', '').replace(';', '')
            affiliation = pq(tr).children().eq(1).children().eq(
                -1).children().text()
            affiliation = affiliation if affiliation else None
            birth_year = pq(tr).children().eq(2).text()
            birth_year = int(birth_year) if birth_year else None
            rating = int(pq(tr).children().eq(3).text())
            highest_rating = int(pq(tr).children().eq(4).text())
            competitions = int(pq(tr).children().eq(5).text())
            wins = int(pq(tr).children().eq(6).text())

            twitter_id = None
            userpage_html = pq(
                'https://beta.atcoder.jp/users/{}'.format(username))
            user_info = userpage_html.find('.dl-table').find(
                'tr')  # 環境によってtbodyがあったり無かったり?
            for el in user_info:
                if pq(el).children().eq(0).text() == 'twitter ID':
                    twitter_id = pq(el).find('a').text()[1:]
                    # 空文字やめて
                    if not twitter_id:
                        twitter_id = None
                        break
                    # @から始まるものを救済
                    if twitter_id[0] == '@':
                        twitter_id = twitter_id[1:]
                    # invalidなIDは弾く
                    if re.search(r'[^a-zA-Z0-9_]', twitter_id):
                        twitter_id = None
                        break
                    # @だった場合救済措置で空文字になる
                    if twitter_id == '':
                        twitter_id = None
                        break

            updated = str(datetime.datetime.today())

            data_by_username = {
                'rank': rank,
                'country': country,
                'formal_country_name': formal_country_name,
                'crown': crown,
                'user_color': user_color,
                'affiliation': affiliation,
                'birth_year': birth_year,
                'rating': rating,
                'highest_rating': highest_rating,
                'competitions': competitions,
                'wins': wins,
                'twitter_id': twitter_id,
                'updated': updated,
            }
            data_by_twitter_id = {
                'rank': rank,
                'country': country,
                'formal_country_name': formal_country_name,
                'crown': crown,
                'username': username,
                'user_color': user_color,
                'affiliation': affiliation,
                'birth_year': birth_year,
                'rating': rating,
                'highest_rating': highest_rating,
                'competitions': competitions,
                'wins': wins,
                'updated': updated,
            }

            db.child('by_username').child(username).set(
                data_by_username, user['idToken'])
            if twitter_id:
                db.child('by_twitter_id').child(twitter_id).set(
                    data_by_twitter_id, user['idToken'])

            print(username)

            if do_not_scrape(datetime.datetime.today()):
                print('I\'m sleeping...')
                while True:
                    print('zzz...')
                    sleep(10 * 60)
                    if not do_not_scrape(datetime.datetime.today()):
                        print('Good morning! Let\'s work!')
                        user = auth.sign_in_with_email_and_password(
                            email, password)
                        break

            sleep(interval)

        page_id += 1
        db.child('continuation').set(page_id, user['idToken'])
import pyrebase

firebaseConfig = {
    "apiKey": "AIzaSyDFp_lhvJuvJE_or0ODMyqbI4jsiBS6Wlc",
    "authDomain": "sd-biblioteca-3a528.firebaseapp.com",
    "databaseURL": "https://sd-biblioteca-3a528.firebaseio.com",
    "projectId": "sd-biblioteca-3a528",
    "storageBucket": "",
    "messagingSenderId": "967381443181",
    "appId": "1:967381443181:web:b96e03b085893a38"
  };



firebase = pyrebase.initialize_app(firebaseConfig)
auth = firebase.auth() 
#authenticar um usuário 

#email = input("Enter the email : ")
#password = input("Enter the pass : "******"*****@*****.**", "joao1996")

db=firebase.database()
#cliar
#livros = {"titulo": None, "autor": None, "paginas": None, "ano": None}


#db.child("biblioteca").child("livros").set(livros, usu['idToken'])
Exemple #12
0
def configure_db():
    '''return db ref'''
    firebase = pyrebase.initialize_app(config)
    db = firebase.database()
    return db
Exemple #13
0
##########################################################################################
# Program Name :     Discord Bot
# Author       :     DMCTruong
# Last Updated :     August 31, 2017
# License      :     MIT
# Description  :     A general purpose bot written for Discord
##########################################################################################

import discord
from discord.ext import commands
import asyncio
import configurations
import pyrebase

bot = commands.Bot(configurations.PREFIX)
firebase = pyrebase.initialize_app(configurations.FIREBASE_INFO)
db = firebase.database()
storage = firebase.storage()


class Database:
    def __init__(self, bot):
        self.bot = bot

    @bot.command(aliases=["db, DB, allDB, , showdb, showDB"])
    async def alldb(self):
        """Give list of all databases saved"""

        getAlldb = db.child("Discord").shallow().get()
        allDatabases = "The databases that are available are:\n - {}".format(
            "\n - ".join(getAlldb.val()))
Exemple #14
0
#                   avail = book['Availability'], book_id = book['Book_ID'],
#                   book_upc = book['UPC_Code'], img_url = book['img_url'])

# def Scrapping():
from bs4 import BeautifulSoup
import requests
import pyrebase

# connectivity to the fire base
config = {
    'apiKey': "AIzaSyBdpemUwtU64fJNVVhTubjQSUyCybtOc5w",
    'authDomain': "college-connectivity.firebaseapp.com",
    'databaseURL': "https://college-connectivity.firebaseio.com",
    'storageBucket': "college-connectivity.appspot.com",
}
connection = pyrebase.initialize_app(config)

db = connection.database()

## create a global list, that contains all the books dictionaries
all_books_details = []

# To write Into firebase
def entry(name, price, avail, book_id, img_url, book_upc):
    # Book_Id = 100+c

    record = {
        "Book-name":  name, "Book-price": price, "Book-avail": avail,"Book-image": img_url,
        "Book-upc": book_upc,"Book-Id": book_id
    }
    db.child("college-connectivity").child("details").push(record)
import pyrebase

# // Your web app's Firebase configuration
# // For Firebase JS SDK v7.20.0 and later, measurementId is optional
config = {
    "apiKey": "AIzaSyC8BvN_FqUGTq1njRY6mTNEK6fWGkY9Bmk",
    "authDomain": "my-memory-3b3bd.firebaseapp.com",
    "databaseURL":
    "https://console.firebase.google.com/u/0/project/my-memory-3b3bd/storage/my-memory-3b3bd.appspot.com/files",
    "projectId": "my-memory-3b3bd",
    "storageBucket": "my-memory-3b3bd.appspot.com",
    "serviceAccount": "serviceAccountKey.json"
}

firebase_storage = pyrebase.initialize_app(config)
storage = firebase_storage.storage()

GROUP_NAME = "nogizaka"


def uploadPic(path, name):
    # storage.child("saka").child(GROUP_NAME).child(path).put(f"{name}.jpeg")
    storage.child("saka").child(GROUP_NAME).child(f"{name}.jpeg").put(path)
    url = storage.child("saka").child(GROUP_NAME).child(
        f"{name}.jpeg").get_url(None)
    return url


def main(DIR_NAME, FILENAMES):
    url_infos = {}
    for file_name in FILENAMES:
import pyrebase

config = {
    "apiKey": "AIzaSyDOUI-nKfhSTfvYTd8CHyehsbyOE48vGEc",
    "authDomain": "personal-bot-14b45.firebaseapp.com",
    "databaseURL": "https://personal-bot-14b45.firebaseio.com",
    "projectId": "personal-bot-14b45",
    "storageBucket": "personal-bot-14b45.appspot.com",
}

# initialise
firebase = pyrebase.initialize_app(config)

# Auth Instance
auth = firebase.auth()
db = firebase.database()


class Authentication:
    @staticmethod
    def create_user_account(email, password):
        print('Authentication - Create User')
        auth.create_user_with_email_and_password(email, password)

    @staticmethod
    def log_user_account(email, password):
        print('Authentication - Log User')
        auth.sign_in_with_email_and_password(email, password)

    # decorators
    @staticmethod
Exemple #17
0
from models.firebaseAuth import *
from models.databaseConfig import *
import pyrebase
import string, random
import requests
from datetime import datetime
import pandas as pd
import os

app = Flask(__name__)

# import secrets
# secrets.token_urlsafe(16)
app.config['SECRET_KEY'] = 'OYsOFfvZ-6DRJomg04GTig'

users = pyrebase.initialize_app(userAuthConfig)
auth = users.auth()
userDb = users.database()
isAuthenticated = False


# Login Page
@app.route('/', methods=["GET", "POST"])
def login():
    if request.method == "GET":
        session.clear()
        return render_template('login.html')
    
    elif request.method == 'POST':
        if request.form['auth'] == 'SignIn':
            try:
Exemple #18
0
def get_firebase_instance():
    firebase = pyrebase.initialize_app(DB_CONFIG)
    auth = firebase.auth()
    user = auth.sign_in_with_email_and_password("*****@*****.**",
                                                "cl0udYYY$")
    return firebase
Exemple #19
0
    "storageBucket": "hajonsoft2020.appspot.com",
    "messagingSenderId": "309798473169",
    "appId": "1:309798473169:web:a7e58104d84b8e08d0a4f0"
}

archiveConfig = {
    "apiKey": "AIzaSyCTsSz6OgYo7Ed5QiQ-c0x9gx7sKi0T4g4",
    "authDomain": "archive-tables.firebaseapp.com",
    "databaseURL": "https://archive-tables.firebaseio.com",
    "projectId": "archive-tables",
    "storageBucket": "archive-tables.appspot.com",
    "messagingSenderId": "934861122008",
    "appId": "1:934861122008:web:760cb5c013e10016d12aad"
}

archive_firebase = pyrebase.initialize_app(archiveConfig)
archive_db = archive_firebase.database()

hos_firebase = pyrebase.initialize_app(hosConfig)
hos_db = hos_firebase.database()


def getCustomers():
    data = archive_db.child('customers').get()
    return data.val()


def merge(data):
    result = {}
    for country_companies in data.items():
        country = country_companies[0]
Exemple #20
0
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 15:21:26 2020

@author: root
"""

from flask import Flask, render_template, request
from firebase import firebase
import configurations
import pyrebase

app = Flask(__name__)
email = "null"

firebsevar = pyrebase.initialize_app(config=configurations.config)
db = firebsevar.database()
msg = " "


@app.route('/')
def Base():
    return render_template('form.html', msg="")


@app.route('/sub_form', methods=['POST', 'GET'])
def sub_form():

    if request.method == 'POST':

        f = request.files['file']
from sklearn.cluster import KMeans
from math import radians, sin, cos, acos
import pandas as pd

from itertools import tee
df = pd.read_csv('C:/Users/Nachiket/Desktop/cabtime3.csv', sep=',')
x = df['longitude'].values
y = df['latitude'].values
X = np.array(list(zip(x, y)))
kmeans = KMeans(n_clusters=11)
kmeans.fit(X)

i = 0
while i < 50:
    i = i + 1
    firebase = pb.initialize_app(config)
    x = firebase.database().child("College").get()
    y = firebase.database().child("College")
    z = firebase.database().child("College")
    w = firebase.database().child("College")
    cc = []

    ab = firebase.database()
    for u in x.each():
        cc.append(u.val())
    print(cc[2])
    if cc[2] == 1:
        lat = y.child("mycor").child("lat").get().val()
        lon = z.child("mycor").child("long").get().val()
        slat = radians(lat)
        slon = radians(lon)
Exemple #22
0
time.sleep(5)

i2c_bus = busio.I2C(SCL,SDA)
stemma = Seesaw(i2c_bus, addr=0x36)
schedule = sched.scheduler(time.time, time.sleep)

# Learn how to set up a Firebase Realtime Database Here: https://firebase.google.com/
#-------Pyrebase-------#
pyrebase_config = {
    "apiKey": "Firebase API Key Here",
    "authDomain": "Project Domain Here",
    "databaseURL": "Realtime Database Here",
    "storageBucket": "Storage Bucket URL Here"
}

app = pyrebase.initialize_app(pyrebase_config)
live = LiveData(app, '/my_data')

# Get a snapshot of all data at the path
db = app.database()
#----------------------#


# Average 100 samples of moisture
def moistureAvg():
    total = 0
    for i in range(100):
        total += stemma.moisture_read()
    return ("{:0.0f}".format(total / 100))

Exemple #23
0
import pyrebase

firebaseConfig = {
    "apiKey": "AIzaSyDEDszA-TxMHw4LRPqez66qptQQ7xwtMLA",
    "authDomain": "emp-todo-management-system.firebaseapp.com",
    "databaseURL": "https://emp-todo-management-system.firebaseio.com",
    "projectId": "emp-todo-management-system",
    "storageBucket": "emp-todo-management-system.appspot.com",
    "messagingSenderId": "650841791756",
    "appId": "1:650841791756:web:5b4c09b8b6f223dea1bd29",
    "measurementId": "G-R3KSXQKJ04"
}

emp_todo = pyrebase.initialize_app(firebaseConfig)

fire_auth = emp_todo.auth()
fire_db = emp_todo.database()

# Firebase CRUD Operations


def create_emp(username=None, email=None, password=None):
    user = fire_auth.create_user_with_email_and_password(email, password)
    user_data = {"username": username, "email": email}
    fire_db.child("users").child(
        user["localId"]).child("profile").set(user_data)


#create the task and storing into the firebase db
def create_task(uid=None, title=None, description=None, spent_time=None):
    task_data = {
Exemple #24
0
import discord
from discord.ext import commands
import os
import random
from disputils import BotEmbedPaginator
import pyrebase
import json
from decouple import config

links_str = """
[Youtube](https://www.youtube.com/channel/UCq4FMXXgsbsZmw5A-Mr7zSA) , [GitHub](https://GitHub.com/ATCtech) , [Twitter](https://twitter.com/ATC_YT_2014) , [Instagram](https://instagram.com/weebletkun) , [Reddit](https://www.reddit.com/u/TECHIE6023) , [Fiverr](https://fiverr.com/atctech)
[Support Server](https://discord.gg/7cnnXB)
[Vibhi Chan Invite Link](https://discord.com/api/oauth2/authorize?client_id=746984468199374908&permissions=8&scope=bot)
"""

firebase = pyrebase.initialize_app(json.loads(config("FIREBASE")))
db = firebase.database()


class Help(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def help(self, ctx):
        global help_str
        rolepl = ""
        try:
            d = db.child("RP").child("GIF").get().val()
            for c in d:
                rolepl += c + " , "
def authenticator(config):
    global user_data
    firebase = pyrebase.initialize_app(config)
    db = firebase.database()
    user_data = db.child("user_data").get().val()
Exemple #26
0
 def __init__(self, config):
     self.firebase = pyrebase.initialize_app(config)
     self.db = self.firebase.database()
Exemple #27
0
    def get(self, request, course_code):
        headers = {
            "Authorization": "bearer %s" % +survey_monkey_key,
            "Content-Type": "application/json"
        }
        question = request.GET.get('question')
        ans_1 = request.GET.get('ans-1')
        ans_2 = request.GET.get('ans-2')
        ans_3 = request.GET.get('ans-3')
        ans_4 = request.GET.get('ans-4')
        youtube = request.GET.get('youtube')
        survey = request.GET.get('survey')
        dirname = os.path.dirname(__file__)
        filename = os.path.join(
            dirname,
            'smartlearn-51f0a-firebase-adminsdk-c8k6r-104d23d108.json')

        firebase = pyrebase.initialize_app(config)
        auth = firebase.auth()
        db = firebase.database()
        db.child("youtube_code").set(youtube)
        db.child("surveymonkey_code").set(survey)
        correct = request.GET.get('correct')
        correct_answer = ''
        if correct == 'A':
            correct_answer = ans_1
        elif correct == 'B':
            correct_answer = ans_2
        elif correct == 'C':
            correct_answer = ans_3
        elif correct == 'D':
            correct_answer = ans_4
        client = requests.session()
        HOST = "https://api.surveymonkey.net"
        question_data = {
            "headings": [{
                "heading": question
            }],
            "family": "single_choice",
            "subtype": "vertical",
            "answers": {
                "choices": [{
                    "text": ans_1,
                    "visible": True,
                    "position": 1
                }, {
                    "text": ans_2,
                    "visible": True,
                    "position": 2
                }, {
                    "text": ans_3,
                    "visible": True,
                    "position": 3
                }]
            },
            "position": 3
        }
        course_name = ""
        courses = db.child("courses").get().val()
        for course in courses.keys():
            key = course
            value = courses[course]["code"]
            if value == course_code:
                course_name = key

        print(courses.keys())
        survey_id = db.child("courses").child(course_name).child(
            "survey_id").get().val()
        page_id = db.child("courses").child(course_name).child(
            "page_id").get().val()
        CREATE_QUESTION_ENDPOINT = "/v3/surveys/" + survey_id + "/pages/" + page_id + "/questions"
        question_uri = "%s%s" % (HOST, CREATE_QUESTION_ENDPOINT)
        self.create_question(question_data, question_uri, headers)
        #requests.post(uri,data=data,headers=headers)
        print(correct_answer)
        return render(request,
                      "details.html",
                      context={'course_code': course_code})
Exemple #28
0
import pyrebase
import firebase_config

firebase = pyrebase.initialize_app(firebase_config.CONFIG)
storage = firebase.storage()

path_on_cloud = "images/battlefiel 4/01.jpg"  # Path on cloud to upload it
path_on_local = "files/02.jpg"  # File to upload from local

storage.child(path_on_cloud).put(path_on_local)
print("Uploaded to Firebase Storage.")
Exemple #29
0
        'chat_id': chat_id,
        'user': {
            'id': user_id,
            'name': user_name
        },
        'reminder_time': f'{reminder_time.timestamp()}',
        'reply_id': reply_id
    }

    __db.child('reminders').push(data, __user['idToken'])

    bot.sendMessage(
        chat_id,
        f'[@{user_name}](tg://user?id={user_id}) i will remind you this in {time_str}',
        reply_to_message_id=reply_id,
        parse_mode='Markdown')


firebase_config = {
    "apiKey": FIREBASE_KEY,
    "authDomain": "giorginoteck-bot-1529002203876.firebaseapp.com",
    "databaseURL": "https://giorginoteck-bot-1529002203876.firebaseio.com/",
    "storageBucket": "giorginoteck-bot-1529002203876.appspot.com"
}

__firebase = pyrebase.initialize_app(firebase_config)
__auth = __firebase.auth()
__user = __auth.sign_in_with_email_and_password('*****@*****.**',
                                                FIREBASE_PASSWORD)
__db = __firebase.database()
Exemple #30
0
import geocoder
import re
import populartimes
from operator import itemgetter, attrgetter
import pyrebase
from flask_cors import CORS

key = 'AIzaSyANqmnEgWqv-bZR0vXTQopHPPfiwWkkkqE'
config = {
    "apiKey": 'AIzaSyAqEFmVsDH5PmYM2MGng6bLUJh5CHsS9pU',
    "authDomain": "dinefind-e3e7c.firebaseapp.com",
    "databaseURL": "https://dinefind-e3e7c.firebaseio.com",
    "storageBucket": "dinefind-e3e7c.appspot.com"
}

firebase = pyrebase.initialize_app(config)  #Firebase object
db = firebase.database()  #Firebase database object
auth = firebase.auth()  #Firebase authentication object
storage = firebase.storage()  #Firebase storage object
app = Flask(__name__)
CORS(app)


def location():
    g = geocoder.ip('me')
    return "{}, {}".format(g.latlng[0], g.latlng[1])


def chain():
    f = open("chain.txt", "r")
    final = []
import requests
from lxml import html
import pyrebase
from difflib import Differ
import sendgrid
import os
from sendgrid.helpers.mail import *

FIREBASE = pyrebase.initialize_app({
	'apiKey':
	'AIzaSyCjBDyhwbXcp9kEIA2pMHLDGxmCM4Sn6Eg',
	'authDomain':
	'canigraduate-43286.firebaseapp.com',
	'databaseURL':
	'https://canigraduate-43286.firebaseio.com',
	'storageBucket':
	'canigraduate-43286.appspot.com',
	'serviceAccount':
	'backend/uchicago/service_account_key.json'
})


def watcher(program, updates):
	url = db.child('programs').child(program).child('metadata').child(
		'catalog').get().val()
	xpath = db.child('programs').child(program).child('metadata').child(
		'source').get().val()
	stored_requirement = db.child('programs').child(program).child(
		'page-state').get().val()
	tree = html.fromstring(requests.get(url).content)
	current_requirement = tree.xpath(xpath)[0].text_content()
def main(event, context):

    config = {
      "apiKey": event.get("apiKey"),
      "authDomain": event.get("authDomain"),
      "databaseURL": event.get("databaseURL"),
      "storageBucket": event.get("storageBucket"),
    }
    firebase = pyrebase.initialize_app(config)
    auth = firebase.auth()
    user = auth.sign_in_with_email_and_password(event.get("firebaseEmail"), event.get("firebasePassword"))
    db = firebase.database()

    warn_only = False

    print user
    print db

    warn_only_config = event.get("warn_only")
    if warn_only_config and str(warn_only_config).lower() == "true":
        warn_only = True


    if not u'cluster' in event:
        raise Exception(
          "Key u'cluster' not found in the event object! Which cluster should I scan?!"
        )

    ecs_client = boto3.client("ecs")

    resp = ecs_client.list_container_instances(
      cluster=event[u'cluster']
    )

    instances = resp[u'containerInstanceArns']

    print instances

    try:
        nxt_tok = resp[u'nextToken']

        while True:
            resp = ecs_client.list_container_instances(
              cluster=event[u'cluster'],
              nextToken=nxt_tok
            )

            instances += resp[u'containerInstanceArns']
            nxt_tok = resp[u'nextToken']
    except KeyError:
        pass

    resp = ecs_client.describe_container_instances(
      cluster=event[u'cluster'],
      containerInstances=instances
    )

    ec2 = boto3.resource("ec2")
    autoscale_client = boto3.client("autoscaling")

    terminated = []
    trackedInFirebase = []

    # set amount of failures instances can have, default is 2
    fail_after = 2
    if event.get("fail_after"):
        fail_after = event.get("fail_after")

    print "about to check instances"

    for inst in resp[u'containerInstances']:

        ec2instanceId = str(inst[u'ec2InstanceId'])
        authToken = user['idToken']
        instanceIdExists = db.child(ec2instanceId).get(authToken).val() != None

        # check if agent is connected
        if inst[u'agentConnected']:
            if instanceIdExists:
                db.child(ec2instanceId).remove(authToken)

        # check if agent is not connected
        if not inst[u'agentConnected']:

            numberOfFailures = db.child(ec2instanceId).get(authToken).val()[ec2instanceId]

            # if instance id does not exist in firebase, then add it to firebase
            if not instanceIdExists:
                data = { ec2instanceId : 1 }
                db.child(ec2instanceId).set(data, authToken)
                trackedInFirebase.append((ec2instanceId, 1))

            # if instance id exists but has not reached fail_after, then increment number of fails
            elif instanceIdExists and numberOfFailures < fail_after:
                data = { ec2instanceId : numberOfFailures + 1 }
                db.child(ec2instanceId).set(data, authToken)
                trackedInFirebase.append((ec2instanceId, numberOfFailures+1))

            # if instance id exists in firebase and instance has reached fail_after, then terminate
            else:

                # delete instance id key from firebase
                db.child(ec2instanceId).remove(authToken)

                bad_inst = ec2.Instance(id=ec2instanceId)

                autoscalegroup = [x[u'Value'] for x in bad_inst.tags 
                                  if x[u'Key'] == u'aws:autoscaling:groupName'][0]

                if not warn_only:
                    # Danger! Detaching Instance from autoscaling group
                    autoscale_client.detach_instances(
                        InstanceIds=[bad_inst.id],
                        AutoScalingGroupName=autoscalegroup,
                        ShouldDecrementDesiredCapacity=False
                    )

                    # Danger! Terminating Instance
                    bad_inst.terminate()
                    print "Detaching and Terminating: %s in autoscale group %s" \
                      % (bad_inst.id, autoscalegroup)

                terminated.append(bad_inst.id)

    print "finished checking instances"

    # If instances were found for tracking in firebase and we have an SNS topic ARN,
    # send an informative message.
    if len(trackedInFirebase) != 0 and u'snsLogArn' in event:
        sns = boto3.resource("sns")
        topic = sns.Topic(event[u'snsLogArn'])

        message = "ecs-agent-monitor function running in AWS Lambda has detected the following: "

        for (instanceId, failures) in trackedInFirebase:
            msg = """"\
The instance `%s' failed. It has failed %i times. It will be terminated if it fails %i times." 
""" % (instanceId, failures, fail_after)
            message += msg    

        topic.publish(
            Subject="AWS Lambda: ECS-Agent-Monitor",
            Message=message
        )
        

    print "finished publishing message concerning instances tracked in firebase"

    # If instances were found for termination and we have an SNS topic ARN,
    # send an informative message.
    if len(terminated) != 0 and u'snsLogArn' in event:
        sns = boto3.resource("sns")
        topic = sns.Topic(event[u'snsLogArn'])

        message = """\
The ecs-agent-monitor function running in AWS Lambda has detected %i EC2
Instances in the `%s' ECS cluster whose `ecs-agent' process has died.

These are:
%s

""" % (len(terminated), event[u'cluster'], "\n".join(terminated))
        
        if not warn_only:
            message = ("%sThese instances have been detached from their "
                       "autoscaling groups and terminated."  % message)
        
        topic.publish(
            Subject="AWS Lambda: ECS-Agent-Monitor",
            Message=message
        )
    

    # Warn if logging is impossible
    if u'snsLogArn' not in event:
        print "Warn: key u'snsLogArn' not found in the event object, so logging is disabled."
def main():
    sensehat = SenseHat()
    sensehat.set_imu_config(True, True, True)
    velocityMatrix = [0.0, 0.0, 0.0]

    resultMatrixKeys = ['x', 'y', 'z']

    velocityMatrix = dict(zip(resultMatrixKeys, velocityMatrix))
    displacementX = 0
    displacementY = 0
    displacementZ = 0

    sensehat.show_message("calibrating", 0.1, [100, 0, 0])
    sensehat.show_letter('!', [100, 0, 0])
    gCoeff = calculateGCoeff(sensehat)
    sensehat.show_message("Complete", 0.1, [0, 100, 0])
    flag = True
    while flag:
        starttime = time.time()
        '''get raw data'''
        accel_raw = sensehat.get_accelerometer_raw()
        orient_rad = sensehat.get_orientation_radians()
        orient_deg = sensehat.get_orientation_degrees()

        external_temp = sensehat.get_temperature()
        pressure = sensehat.get_pressure()

        eulermatrixtrans = createTransformMatrix(orient_rad)

        accel_procc = removeGravity(accel_raw, eulermatrixtrans, gCoeff)

        accel_real = matrixMultiply3x9(accel_procc, eulermatrixtrans)

        endtime = time.time()
        '''calculate velocity change and displacement'''
        total_time = starttime - endtime
        '''if motion is detected we output distance moved'''
        if abs(accel_procc[0]) > 0.03 or abs(accel_procc[1]) > 0.03 or abs(
                accel_procc[2]) > 0.03:
            print(
                ("acceleration x = {0},y={1},z={2}, degrees to north = {3},{4}"
                 .format(accel_real['x'], accel_real['y'], accel_real['z'],
                         orient_rad, orient_deg)))

        config = {
            "apiKey": "AIzaSyA20qu9ddnRJPAQgGpn9ySQLuqjLH2WWPI",
            "authDomain": "firefightingmonitoringsystem.firebaseapp.com",
            "databaseURL":
            "https://firefightingmonitoringsystem.firebaseio.com/",
            "storageBucket": "firefightingmonitoringsystem.appspot.com"
        }

        fireBase = pyrebase.initialize_app(config)
        db = firebase.database()
        '''Need to add acceleration data'''
        data = {
            "external_temp": external_temp,
            "pressure": pressure,
        }

        results = db.push(data)
        print(results)

    return
Exemple #34
0
from flask import Flask, render_template, url_for, redirect, request, jsonify
import pyrebase
import pickle
import pandas as pd

app = Flask(__name__)

loaded_model = pickle.load(open('logistic_model.sav', 'rb'))

firebase = pyrebase.initialize_app('CONFIG_DATABASE')

auth = firebase.auth()

@app.route('/', methods = ['GET', 'POST'])
def index():

    unsuccessful = 'Please check your credentials'
    successful = 'Login Successful'

    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        try:
            auth.sign_in_with_email_and_password(email, password)
            return render_template('logout.html', s = successful)
        except:
            return render_template('login.html', us = unsuccessful)

    return render_template('login.html')

@app.route('/register', methods = ['GET', 'POST'])
Exemple #35
0
from shapely.ops import nearest_points

import classifier
import eval
import gdop
import hmm
from config import *
from draw import draw
from fit_data import *
from mqtt import subscriber
from nls import nls
from path_loss import log
from trilateration import trilaterate
from utils import *

firebase = pyrebase.initialize_app(FIREBASE)
db = firebase.database()

dict_of_macs = TRILATERATION['macs']
window_start = convert_date_to_secs(TRILATERATION['start'])
rel_hist = {}
try:
    sem_hist = json.loads(open('data/hist/semantic3.json').read())
except:
    sem_hist = {}
last_rss = [-60] * len(TRILATERATION['aps'])
y_true = []
y_pred = []

with open('data/usernames.csv', 'r') as f:
    reader = csv.reader(f)
import os

from flask import Flask

from flask_login import LoginManager
from config import basedir, FIREBASE_CONFIG

import pyrebase
from firebase_admin import credentials

app = Flask(__name__)
app.config.from_object('config')

#lm = LoginManager()
#lm.init_app(app)
#lm.login_view="account"

#firebase = firebase.FirebaseApplication('https://final-33b0a.firebaseio.com/',None)
cred = credentials.Certificate(
    '/home/ubuntu/551final/app/final_33b0a_firebase_adminsdk_vjuqw_d474b38d4b.json'
)
fbapp = pyrebase.initialize_app(FIREBASE_CONFIG)
auth = fbapp.auth()
db = fbapp.database()
storage = fbapp.storage()

from app import views
#from app import models
Exemple #37
0
def connect_db():
    '''connect to firebase'''

    firebase = pyrebase.initialize_app(config)
    db = firebase.database()
    return db
Exemple #38
0
""" PLEASE DON'T CHANGE LINES 1-16 - MA """
import datetime
import time
import pyrebase
import sys
from flask_app import errors

try:
    from keys import FIREBASE_KEYS
except IOError:
    print("Keys File not Found. Online Access")

FIREBASE = pyrebase.initialize_app(FIREBASE_KEYS)
FIREBASE_AUTH = FIREBASE.auth()
FIREBASE_USER = FIREBASE_AUTH.sign_in_with_email_and_password(
                                                             "*****@*****.**",
                                                             "tester")
DB = FIREBASE.database()
white_listed_collections = ["Dogs", "Person", "donations", "events", "forms"]


def get_firebase_collection(collection):
    """
    Makes a get call to FireBase based on what collection the user wants to see
    Checks requested collection against a whitelist of available collections
    """

    if collection not in white_listed_collections:
        raise errors.InvalidUsage("We are currently not storing \
                                  this data.", status_code=410)
    return DB.child(collection).get().val()
Exemple #39
0
from datetime import timedelta
from time import sleep

# import other file
from runningmate_app import make_friends as make_friends

# initialize our running app
config_running_app = {
    "apiKey": "AIzaSyCjQCwrJHZKAOiNG04ycZnhtIQpGTw5yh4",
    "authDomain": "running-mate-7bb1b.firebaseapp.com",
    "databaseURL": "https://running-mate-7bb1b.firebaseio.com",
    "projectId": "running-mate-7bb1b",
    "storageBucket": "running-mate-7bb1b.appspot.com",
    "messagingSenderId": "610614312598"
}
running_app_firebase = pyrebase.initialize_app(config_running_app)
running_app_db = running_app_firebase.database()


# find other players
def find_other_player(member_id_room_no, member_id):

    # define variables
    other_player = list()
    global running_app_db

    room_data_player = running_app_db.child("running_room").child(
        member_id_room_no).child("經緯度").get()
    for each_player in room_data_player.each():
        if each_player.key() != member_id:
            other_player.append(each_player.key())
Exemple #40
0
    def logMetadata(self):
        #MySQL
        fp = open("dbPassword.txt", "r")
        dbPass = fp.readline()
        dbPass = dbPass.rstrip('\n')
        fp.close()

        #Firebase
        fpFb = open("fbkey.txt", "r")
        fbKey = fpFb.readline()
        fbKey = fbKey.rstrip('\n')
        fpFb.close()
        self.attackerNum += 1

        self.ipAddr = self.transport.getPeer().address.host
        self.logFolder = self.ipAddr + '-' + str(
            self.sessionNum) + '-commands.txt'
        while (os.path.isfile(
                "/opt/tomcat/webapps/ActiveHoneypotWeb/logfiles/" +
                self.logFolder)):
            self.sessionNum += 1
            self.logFolder = self.ipAddr + '-' + str(
                self.sessionNum) + '-commands.txt'

        access = datetime.now()
        accessTime = str(access.hour) + ":" + str(access.minute) + ":" + str(
            access.second)
        accessDate = str(access.year) + "/" + str(access.month) + "/" + str(
            access.day)

        URL = 'http://ip-api.com/json/' + self.ipAddr
        PARAMS = {'fields': '57597'}
        r = requests.get(url=URL, params=PARAMS)
        data = r.json()
        status = data['status']
        lat = lon = ""
        print(data)
        if (status != 'fail'):
            city = data['city']
            country = data['country']
            state = data['regionName']
            lat = str(data['lat'])
            lon = str(data['lon'])

            #Insert to Database
            db = MySQLdb.connect(
                "activehoneypot-instance1.c6cgtt72anqv.us-west-2.rds.amazonaws.com",
                "ahpmaster", dbPass, "activehoneypotDB")
            cursor = db.cursor()
            sql = "INSERT INTO `activehoneypotDB`.`attacker` (`ip_address`, `username`, `passwords`, `time_of_day_accessed`, `logFile`, `sessions`, `country`, `city`, `state`, `date_accessed`, `latitude`, `longitude`) VALUES ('%s', '%s','%s', '%s', '%s','%s', '%s','%s', '%s', '%s','%s', '%s')" % (
                self.ipAddr, 'root', 'password', accessTime, self.logFolder,
                self.sessionNum, country, city, state, accessDate, lat, lon)

            try:  #Execute SQL command
                cursor.execute(sql)
                db.commit()
                print("Commit logMetadata")
            except:
                db.rollback()
                print("Can't Commit logMetadata")
            db.close()

            fbConfig = {
                'apiKey': fbKey,
                'authDomain': 'honeypot-1c941.firebaseapp.com',
                'databaseURL': 'https://honeypot-1c941.firebaseio.com',
                'storageBucket': 'honeypot-1c941.appspot.com'
            }
            fb = pyrebase.initialize_app(fbConfig)
            fddb = fb.database()
            data = {
                "attackerID": self.attackerNum,
                "ip_address": self.ipAddr,
                "username": "******",
                "passwords": "password",
                "time_of_day_accessed": accessTime,
                "logFile": self.logFolder,
                "sessions": self.sessionNum,
                "country": country,
                "city": city,
                "state": state,
                "date_accessed": accessDate,
                "latitude": lat,
                "longitude": lon
            }
            fddb.child("attacks").push(data)

        elif (data['message'] == 'private range'):
            db = MySQLdb.connect(
                "activehoneypot-instance1.c6cgtt72anqv.us-west-2.rds.amazonaws.com",
                "ahpmaster", dbPass, "activehoneypotDB")
            cursor = db.cursor()
            sql = "INSERT INTO `activehoneypotDB`.`attacker` (`ip_address`, `username`, `passwords`, `time_of_day_accessed`, `logFile`, `sessions`,`country`, `date_accessed`) VALUES ('%s', '%s','%s', '%s', '%s','%s', '%s', '%s')" % (
                self.ipAddr, 'root', 'password', accessTime, self.logFolder,
                self.sessionNum, "localhost", accessDate)

            fbConfig = {
                'apiKey': fbKey,
                'authDomain': 'honeypot-1c941.firebaseapp.com',
                'databaseURL': 'https://honeypot-1c941.firebaseio.com',
                'storageBucket': 'honeypot-1c941.appspot.com'
            }
            fb = pyrebase.initialize_app(fbConfig)
            fbdb = fb.database()
            data = {
                "attackerID": self.attackerNum,
                "ip_address": self.ipAddr,
                "username": "******",
                "passwords": "password",
                "time_of_day_accessed": accessTime,
                "logFile": self.logFolder,
                "sessions": self.sessionNum,
                "date_accessed": accessDate
            }
            fbdb.child("attacks").push(data)

            try:  #Execute SQL command
                cursor.execute(sql)
                db.commit()
                print("Commit logMetadata")
            except:
                db.rollback()
                print("Can't Commit logMetadata")
            db.close()

        else:
            print("Can't Commit logMetadata because ", data['message'], ".")
Exemple #41
0
def honeypotHashFunction(username, passwordFromNetwork, passwordFromFile):
    #print("Username: "******"utf-8"))
    #print("Network Given Password: "******"utf-8"))

    if ((passwordFromNetwork.decode("utf-8")) !=
        (passwordFromFile.decode("utf-8"))):
        file = open('failedpasswordattempts', "a+")
        file.write(
            username.decode("utf-8") + ":" +
            passwordFromNetwork.decode("utf-8") + "\n")
        file.close()

        #INSERT to database
        fp = open("dbPassword.txt", "r")
        dbPass = fp.readline()
        dbPass = dbPass.rstrip('\n')
        fp.close()
        access = datetime.now()
        accessTime = str(access.hour) + ":" + str(access.minute) + ":" + str(
            access.second)
        accessDate = str(access.year) + "/" + str(access.month) + "/" + str(
            access.day)

        print("tryingToOpenDb")
        db = MySQLdb.connect(
            "activehoneypot-instance1.c6cgtt72anqv.us-west-2.rds.amazonaws.com",
            "ahpmaster", dbPass, "activehoneypotDB")
        cursor = db.cursor()
        sql = "INSERT INTO `activehoneypotDB`.`login_attempts` (`usernames`, `passwords`, `usernames_passwords`, `time_access`, `date_access`) VALUES ('%s','%s', '%s', '%s','%s')" % (
            username.decode("utf-8"), passwordFromNetwork.decode("utf-8"),
            username.decode("utf-8") + ":" +
            passwordFromNetwork.decode("utf-8"), accessTime, accessDate)

        try:  #Execute SQL command
            cursor.execute(sql)
            db.commit()

        except MySQLdb.Error as e:
            print(e)
        except:
            print("can't execute passwords INSERT")
            db.rollback()
        ipAddr = "0.0.0.0"
        state = city = "Failed Login"
        country = ""
        sql2 = "INSERT INTO `activehoneypotDB`.`attacker` (`ip_address`, `username`, `passwords`, `time_of_day_accessed`, `logFile`, `sessions`, `country`,`state`, `city`, `date_accessed`) VALUES ('%s', '%s','%s', '%s', '%s', '%s', '%s','%s', '%s','%s')" % (
            ipAddr, username.decode("utf-8"),
            passwordFromNetwork.decode("utf-8"), accessTime, "notLoggedIn.txt",
            "0", country, state, city, accessDate)

        #Firebase
        fp = open("fbkey.txt", "r")
        fbKey = fp.readline()
        fbKey = fbKey.rstrip('\n')
        fp.close()

        fbConfig = {
            'apiKey': fbKey,
            'authDomain': 'honeypot-1c941.firebaseapp.com',
            'databaseURL': 'https://honeypot-1c941.firebaseio.com',
            'storageBucket': 'honeypot-1c941.appspot.com'
        }
        fb = pyrebase.initialize_app(fbConfig)
        fbdb = fb.database()
        data = {
            "ip_address": ipAddr,
            "username": username.decode("utf-8"),
            "passwords": passwordFromNetwork.decode("utf-8"),
            "time_of_day_accessed": accessTime,
            "logFile": "notLoggedIn.txt",
            "date_accessed": accessDate
        }
        fbdb.child("attacks").push(data)

        try:  #Execute SQL command
            cursor.execute(sql2)
            db.commit()
            print("Commit sql2")
        except:
            db.rollback()
            print("Can't Commit sql2")
        db.close()

    return passwordFromNetwork
Exemple #42
0
import pyrebase

import time
import random
from smtpEmail import create_message, send_message

# JSON object used to configure the firebase object
config = {
  "apiKey": "AIzaSyD4Px2vgieA7bKPnjjI1CEPW5AbBg_lbXY",
  "authDomain": "peed-0xdeadbeef-lab-1.firebaseapp.com",
  "databaseURL": "https://peed-0xdeadbeef-lab-1.firebaseio.com/",
  "storageBucket": "peed-0xdeadbeef-lab-1.appspot.com"
}

# Initialize firebase and the firebase database objects
firebase = pyrebase.initialize_app(config)
database = firebase.database()

# Remove all data currently under the "Temperatures" heading on the database
database.child("Temperatures").remove()

# Reset the 'Button' entry in the data base. (might remove this, will talk to Jason....)
database.child().update({'Button': 0})

# Initialize serial connection. May need to change COM #
ser = serial.Serial('COM6', baudrate=9600, timeout=1)

ser.write(b't')
response = ser.readline().decode('ascii')
count = 0
while count < 10:
Exemple #43
0
 def _create_firebase(self):
     firebase = pyrebase.initialize_app(self.config().get_auth_object())
     self.auth = firebase.auth()
     self.user = self.auth.sign_in_with_email_and_password(self.userEmail(),
                                                      self.userPassword())
     self.db = firebase.database()