Ejemplo n.º 1
0
def get_user_id_by_email(email):
    sql = f'''
        select u.id
        from users.users as u
        where u.email = '{email}'
    '''

    msg = {
        'body': {
            'action': 'run',
            'queries': [sql]
        }
    }

    print(msg)

    method, response = db_handler(msg)
    print(type(response))
    print(response)

    if method == 'ok':
        body = ast.literal_eval(response[0])
        print(body)
        return body[0]['id']

    return None
def get_site_settings_values():
    sql = f'''
        select 	site_visibility,
                title,
                fontsize,
                selfurl,
                coloraccent,
                isdarkmode,
                description,
                copyright,
                websiteurl,
                brandmail,
                brandlogourl,
                faviconurl,
                appiconurl
        from settings.site_settings
    '''

    msg = {'body': {'action': 'run', 'queries': [sql]}}

    method, response = db_handler(msg)

    if method == 'ok':
        response_dict = response[0][1:-1]
        return ok(json.loads(response_dict))
    else:
        return internal_server_error()
    def run(self):
        while not self.stop_event.is_set():
            # get data from telegram-cli
            cmd = ["telegram-cli", "-b", "-W", "-D", "--json", "-e chat_info " + GROUP_NAME]
            s = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            data = s.communicate()[0].decode("utf-8")
            data = self.remove_shit(data)

            # processing data
            members = data["members"]

            self.__db = db.db_handler(DATABASE)
            banned_users = self.__db.get_banned_usernames()
            self.__db.close_database()

            banned_usernames = []
            banned_ids = []
            for user in banned_users:
                banned_usernames.append(user[0])
                banned_ids.append(user[1])

            for member in members:
                if "username" in member:
                    if member["username"] in banned_usernames:
                        if member["id"] not in banned_ids:
                            self.__db = db.db_handler(DATABASE)
                            self.__db.add_user_id(member["id"], member["username"])
                            self.__db.close_database()
                if member["id"] in banned_ids:
                    cmd = [
                        "telegram-cli",
                        "-b",
                        "-W",
                        "-D",
                        "--json",
                        "-e chat_del_user " + GROUP_NAME + " " + member["print_name"],
                    ]
                    s = subprocess.Popen(cmd, stdout=subprocess.PIPE)
                    data = s.communicate()[0].decode("utf-8")
                    data = self.remove_shit(data)

            self.stop_event.wait(1.0)
Ejemplo n.º 4
0
    def run(self):
        while not self.stop_event.is_set():
            # get data from telegram-cli
            cmd = ['telegram-cli','-b','-W','-D','--json','-e chat_info ' + GROUP_NAME]
            s = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            data = s.communicate()[0].decode('utf-8')
            data = self.remove_shit(data)
       
            # processing data
            members = data['members']
                        
            self.__db = db.db_handler(DATABASE)
            banned_users = self.__db.get_banned_usernames()
            self.__db.close_database()
            
            banned_usernames = []
            banned_ids = []
            for user in banned_users:
                banned_usernames.append(user[0])
                banned_ids.append(user[1])

            for member in members:
                if 'username' in member:
                    if member['username'] in banned_usernames:
                        if member['id'] not in banned_ids:
                            self.__db = db.db_handler(DATABASE)
                            self.__db.add_user_id(member['id'], member['username'])
                            self.__db.close_database()
                if 'print_name' in member:
                    if member['print_name'] in banned_usernames:
                        if member['id'] not in banned_ids:
                            self.__db = db.db_handler(DATABASE)
                            self.__db.add_user_id(member['id'], member['username'])
                            self.__db.close_database()
                if member['id'] in banned_ids:
                    cmd = ['telegram-cli','-b','-W','-D','--json','-e chat_del_user ' + GROUP_NAME + ' ' + member['print_name']]
                    s = subprocess.Popen(cmd, stdout=subprocess.PIPE)
                    data = s.communicate()[0].decode('utf-8')
                    data = self.remove_shit(data)

            self.stop_event.wait(1.0)
Ejemplo n.º 5
0
    def checkCoinOrigin(self, coin):
        #print "verify_coincoin origin check"
        dbh = db_handler()
        r_deatail = dbh.getRootBlockChainDetail(coin)
        print r_deatail

        for document in r_deatail:
            #print  document["TRANSACTION"][0]["MINER"]
            m1 = document["TRANSACTION"][0]["MINER"]

        if (m1 == "M_2"):
            dbh.delectCoinDetail(coin)
            return True
        else:
            #print "Store coin"
            return False
def patch_site_settings_values(**kwargs):
    body = kwargs.get('body')
    email = kwargs.get('email')

    settings = {
        'site_visibility': body.get('site_visibility', ''),
        'title': body.get('title', ''),
        'fontsize': body.get('fontsize', ''),
        'coloraccent': body.get('coloraccent', ''),
        'isdarkmode': body.get('isdarkmode', ''),
        'description': body.get('description', ''),
        'copyright': body.get('copyright', ''),
        'websiteurl': body.get('websiteurl', ''),
        'brandmail': body.get('brandmail', ''),
        'brandlogourl': body.get('brandlogourl', ''),
        'faviconurl': body.get('faviconurl', ''),
        'appiconurl': body.get('appiconurl', '')
    }

    schema_validation = Validator(PATCH_ADMIN_SETTINGS_SCHEMA)

    remove_empty_values_of_dict(settings)

    resp = None
    if schema_validation.validate(settings):

        query = dynamic_update_query(
            settings, 'settings.site_settings', '', email)

        print(query)

        msg = {
            'body': {
                'action': 'run',
                'queries': [query]
            }
        }

        method, result = db_handler(msg)

        print(result)

        if method == 'ok':
            resp = settings
    else:
        return bad_request(schema_validation.errors)
    return ok(resp)
Ejemplo n.º 7
0
    def handleSenz(self, senz):
        """
        Handle differennt types of senz from here. This function will be called
        asynchronously. Whenc senz message receives this function will be
        called by twisted thread(thread safe mode via twisted library)
        """

        #print "Hanlder "  ,senz.attributes ,senz.type ,senz.receiver,senz.sender
        logger.info('senz received %s' % senz.type)
        dbh = db_handler()

        # tempory adding function
        if (senz.receiver == None):
            dbh.testData()

        # print senz.type=="DATA" and senz.receiver !=None
        if (senz.type == "DATA" and senz.receiver != None):
            flag = senz.attributes["#f"]
            if(flag=="ct"):
                logger.info('Doing p2p Transaction ::%s' % senz)
                #print (senz.attributes)
                dbh.addCoinWiseTransaction(senz.attributes)

            else:
                dbh.addCoinWiseTransaction(senz.attributes)  # ddd added coinWiseTransaction method
        elif (senz.type == "SHARE"):
            # print dbh.calulateCoinsValue()
            flag = senz.attributes["#f"]
            if(flag=="cv"):
                senze = 'PUT #COIN_VALUE %s ' % (dbh.calulateCoinsValue())
                senz = str(senze) + "@%s  ^%s" % (senz.sender, clientname)
                signed_senz = sign_senz(senz)
                logger.info('Auto Excute: %s' % signed_senz)
                self.transport.write(signed_senz)
            if(flag=="ctr"):
                logger.info('Request Massage Transaction :: %s' % senz)

        elif (senz.type == "DELETE"):
            coin = senz.attributes["#COIN"]
            dbh.delectCoinDetail(coin)

        elif (senz.type=="UNSHARE"):
            pass
Ejemplo n.º 8
0
def get_permissions_by_user_id(user_id):
    sql = f'''
        select pt.name
        from roles.permission_type as pt
        inner join roles.permission as p on p.permission_type_id = pt.id
        inner join roles.permission_role as pr on pr.permission_id = p.id
        inner join roles.role as r on r.id = pr.role_id
        inner join users.users as u on u.role_id = r.id
        where u.id = '{user_id}'
    '''

    msg = {'body': {'action': 'run', 'queries': [sql]}}

    method, response = db_handler(msg)

    if method == 'ok':
        print(response)
        return response[0]

    return None
Ejemplo n.º 9
0
 def __init__(self):
     super().__init__()
     self.stop_event = Event()
     self.__db = db.db_handler(DATABASE)
     self.__db.create_table()
     self.__db.close_database()
Ejemplo n.º 10
0
from utils import hash_sha1
from db import db_handler

USER = '******'
PASSWD = 'passwd'
PASSWD_HASH = hash_sha1(PASSWD)
PASS2 = hash_sha1('coucou')

db = db_handler()

db.edit('INSERT INTO user (username, passwd_hash) VALUES (?, ?)', (
    USER,
    PASSWD_HASH,
))

db.edit('INSERT INTO user (username, passwd_hash) VALUES (?,?)',
        ('Pouet', PASS2))

res = db.query("SELECT * FROM user")
print(res[0]['username'])

res = db.get_user_password(USER)
print(res)

res = db.get_user_password('test2')
print(res)

db.close()
Ejemplo n.º 11
0
    def handleSenz(self, senz):
        """
        Handle differennt types of senz from here. This function will be called
        asynchronously. Whenc senz message receives this function will be
        called by twisted thread(thread safe mode via twisted library)
        """
        #print "Hanlder ", senz.attributes, senz.type, senz.receiver, senz.sender

        logger.info('senz received %s' % senz.type)
        dbh = db_handler()

        if (senz.type == 'PUT'):
            #print "Coin value :", senz.attributes["#COIN_VALUE"]
            senze = 'UNSHARE #COIN_VALUE '
            senz = str(senze) + "@%s  ^%s" % (senz.sender, clientname)
            signed_senz = sign_senz(senz)
            logger.info('read senz: %s' % signed_senz)
            self.transport.write(signed_senz)

        elif (senz.type == "SHARE"):
            flag = senz.attributes["#f"]
            if (flag == "cc"):

                format_date =datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S").replace(" ", "")
                #print "formateDate" + format_date.replace(" ", "") +"Sender " + senz.sender

                cah = minning_algo()
                coin = cah.getCoin(senz.attributes["#S_PARA"]+""+format_date+""+senz.sender)

                senze_c = 'PUT #COIN %s #TIME %s ' % (coin,format_date)
                senz_c = str(senze_c) + "@%s  ^%s" % (senz.sender, clientname)
                signed_senzc = sign_senz(senz_c)

                dbh.addMinerDetail(senz.attributes, coin ,format_date)
                #add_detail_to_block_chain
                dbh.addCoinWiseTransaction(senz, coin, format_date)


                logger.info('Auto Excute: %s' % signed_senzc)
                self.transport.write(signed_senzc)

                self.sendTDetailsToBase(senz,coin,format_date)
                self.sendTDetailsToMiners(senz, coin, format_date)

            if(flag =="ccb"):
                logger.info('Mining new coin  Verify Request::%s' % senz)
                coin =senz.attributes["#COIN"]
                format_date = senz.attributes["#FORMAT_DATE"]
                #print (senz.attributes)
                verify_state = self.verifyCoin(coin ,senz.attributes["#S_PARA"], format_date , senz.attributes["#RECIVER"])
                #print  verify_state
                if(verify_state==True):
                    dbh.addCoinWiseTransaction(senz, coin, format_date)
                else:
                    dbh.faildVerification(senz, coin, format_date)

            if (flag == "b_vct"):
                logger.info('Recived tranaction block verification request ::%s' % senz)
                coin = senz.attributes["#COIN"]
                coin_sender = senz.attributes["#COIN_SENDER"]


                # check coin privious sender and reciver - privous block


                # if valied update probability value
                self.updateProbabilityState(senz);

            # App to Miner Trasaction request accept
            if (flag == "ctr"):
                logger.info('Request Massage p2p Transaction :: %s' % senz)
                senze_c = 'PUT #MSG %s ' % ("ShareDone")
                senz_c = str(senze_c) + "@%s  ^%s" % (senz.sender, clientname)
                signed_senzc = sign_senz(senz_c)
                self.transport.write(signed_senzc)



            if (flag == "b_ct_ack"):
                logger.info('Transaction fail ACK:: %s' % senz) #detail should remove db
                coin = senz.attributes["#COIN"];
                coin_sender = senz.attributes["#COIN_SENDER"]
                coin_reciver = senz.attributes["#COIN_RECIVER"]
                dbh.removeNotVerificationBlock(senz,coin, coin_sender, coin_reciver)
                dbh.faildVerification(senz, coin, "")


        # print senz.type=="DATA" and senz.receiver !=None
        elif (senz.type == "DATA" and senz.receiver != None):
            flag = senz.attributes["#f"]
            coin = senz.attributes["#COIN"]
            time = senz.attributes["#time"]
            reciver = senz.attributes["#RECIVER"];
            if(reciver != ""):
                if (flag == "b_ct"):
                    logger.info('Doing p2p Transaction ::%s' % senz)
                    dbh.addCoinWiseTransaction(senz, coin, time)

                # recived Coin
                if (flag == "ct"):
                    if (reciver == "node3"):
                        logger.info('Recived Coin ::%s' % senz)
                        # check valitdity (final block check)
                        # if ok
                        senze_c = 'PUT #MSG %s ' % ("Transaction_Success")
                        senz_c = str(senze_c) + "@%s  ^%s" % (senz.sender, clientname)
                        signed_senzc = sign_senz(senz_c)
                        self.transport.write(signed_senzc)

                        # check coin own coin or not
                        coin_origin = self.checkCoinOrigin(coin)
                        if (coin_origin == True):
                            # delect coin and broadcast it
                            senze_c = 'DELETE #MSG %s #COIN %s ' % ("DELETE COIN", str(coin))
                            senz_c = str(senze_c) + "@%s  @%s ^%s" % ("node1", "baseNode", clientname)
                            signed_senzc = sign_senz(senz_c)
                            self.transport.write(signed_senzc)
                        else:
                            # if not own coin store folder and update block chain
                            dbh.addCoinWiseTransaction(senz, coin, time)
                            self.creatCoinScript(senz, coin)
                    else:
                        dbh.addCoinWiseTransaction(senz, coin, time)




        elif (senz.type == "DELETE"):
            coin = senz.attributes["#COIN"]
            dbh.delectCoinDetail(coin)



        elif (senz.type=="UNSHARE"):
            pass