コード例 #1
0
def checklogin(username, password, role):
    hasher = Hashing()
    sqlstr = 'select * from users'
    cur = conn.execute(sqlstr)
    rows = cur.fetchall()
    cor = False
    if role.lower() == "none":
        for row in rows:
            if hasher.check(password, row[1]) and username == row[0]:
                global apis
                #session["user"] = user
                #session["role"] = row[2]
                #gensession()
                cor = True
                return {'value': True}
            #else:
            #pass
        if not cor:
            return {'value': 'PWINC'}
    else:
        for row in rows:
            if hasher.check(password,
                            row[1]) and username == row[0] and role == row[2]:
                global apis
                #session["user"] = user
                #session["role"] = row[2]
                #gensession()
                cor = True
                return {'value': True}
            elif hasher.check(password, row[1]) and username == row[0]:
                return {'value': 'RINC'}
            #else:
            #pass
        if not cor:
            return {'value': 'PWINC'}
コード例 #2
0
ファイル: node_server.py プロジェクト: brian-gavin/difuse
    def __init__(self, bootstrap_ip, fuse_mount):
        """
        init the node server, join the cluster, construct the listening socket
        """
        self.fuse_mount = fuse_mount
        self.bootstrap_ip = bootstrap_ip

        # establish server socket
        self.sock = socket.socket()
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((HOST, protocol.PORT))
        self.sock.listen(5)

        # Send JOIN to the bootstrap and initialize the Hashing data structures
        req_pkt = protocol.construct_packet(protocol.Verbs.JOIN,
                                            protocol.Status.OK, {})
        try:
            # send JOIN and receive IP_TABLE
            header, payload = protocol.sock_send_recv(bootstrap_ip, req_pkt,
                                                      protocol.BOOTSTRAP_PORT)
            logging.debug(f'received {header}')
            if header.status != protocol.Status.OK.name:
                raise IOError('Did not received status: ok')

            # init the hashing object using the Bootstrap's data
            ip_table = Hashing.deserializable_ip_table(payload['ip_table'])
            hash_unit = sorted(ip_table.keys())
            id_hash = Hashing.difuse_hash(payload['ip'])
            hashing.HASHING_OBJ = Hashing(hash_unit, ip_table, id_hash)
            logging.info(f'ID: {id_hash}')
            # if files need to be relocated, relocate them
            relocate_files()
        except IOError as ex:
            logging.exception(ex)
コード例 #3
0
ファイル: server.py プロジェクト: MWOSOfficial/Blueberry
def chklogin(user, pw):
    global conn
    cor = False
    if "a" == "a":
        hasher = Hashing()
        session.permanent = True
        user = user
        passwd = pw
        sqlstr = 'select * from users'
        cur = conn.execute(sqlstr)
        rows = cur.fetchall()
        #print(rows)
        #print(rows[5][0])
        for row in rows:
            #print('!')
            if hasher.check(passwd, row[1]) and user == row[0]:
                #session["user"] = user
                #session["role"] = row[2]
                #gensession()
                cor = True
                return [True, user, row[2]]
            #else:
            #pass
        if not cor:
            return [False, 0]
コード例 #4
0
ファイル: server.py プロジェクト: MWOSOfficial/Blueberry
def login():
    global conn
    stmt = """SELECT count(*) FROM sqlite_master WHERE type='table' AND name='users';"""
    cur = conn.execute(stmt)
    result = cur.fetchone()
    if 1 + 1 != 2:
        pass
    #if result[0] == 0:
    #flash("Your Server Haven't Been Setup Yet.")
    #return redirect(url_for("oobe.start"))
    else:
        #print(chklogin("a","a"))
        cor = False
        if request.method == "POST":
            hasher = Hashing()
            session.permanent = True
            user = request.form["nm"]
            passwd = request.form["pass"]
            sqlstr = 'select * from users'
            tmp = conn.execute(sqlstr)
            #print(tmp)
            rows = tmp.fetchall()
            #print(rows)
            #print(rows[5][0])
            for row in rows:
                #print('!')
                if hasher.check(passwd, row[1]) and user == row[0]:
                    if user == "" or passwd == "":
                        flash(lang["msg12"])
                        return redirect(url_for("login"))
                    else:
                        session["user"] = user
                        session["role"] = row[2]
                        gensession()
                        cor = True
                        flash(lang["msg2"])
                        return redirect(url_for("home"))
                #else:
                #pass
            if not cor:
                flash(lang["msg1"])
                return redirect(url_for("login"))

        else:
            if "role" in session:
                user = session["user"]
                flash(lang["msg3"])
                return redirect(url_for("home"))
            else:
                return render_template("nano/login.html",
                                       productname=productname,
                                       year=year)
コード例 #5
0
 def checkuser(self, username, password):
     hasher = Hashing()
     sqlstr = 'select * from users'
     self.cur = self.conn.execute(sqlstr)
     rows = self.cur.fetchall()
     cor = False
     for row in rows:
         if hasher.check(password, row[1]) and username == row[0]:
             cor = True
             return [True, row]
         #else:
         #pass
     if not cor:
         return [False]
コード例 #6
0
ファイル: node_const.py プロジェクト: brian-gavin/difuse
def relocate_files(relocate_all=False):
    """
    Scans the LOCAL_ROOT directory for files that need to be relocated and sends XFER_RES to each node where files
    should be transferred.
    :relocate_all: Default false. If true, all files on local root will be transferred to the successor
    :return: None
    """
    # table that maps an ID hash to a list of dictionary to send
    xfer_res_table = {id_hash: [] for id_hash in hashing.HASHING_OBJ.hash_unit}

    # build xfer res table for each file in the local root
    for filename in os.listdir(LOCAL_ROOT):
        file_hash = Hashing.difuse_hash(filename)
        try:
            file_succ = Hashing.succ(file_hash)
        except ZeroDivisionError: # thrown if last node exiting
            return
        logging.debug(f'filename: {filename} | file_hash: {file_hash}')
        if relocate_all or file_succ != hashing.HASHING_OBJ.id_hash:
            try:
                with open(join(LOCAL_ROOT, filename), 'rb') as f:
                    file_bytes = f.read()
                    xfer_res_table[file_succ].append({
                        'filename': filename,
                        'bytes': list(file_bytes)
                    })
            except Exception as ex:
                logging.exception(ex)
                pass
    # send the XFER_RES
    for id_hash, xfer_list in xfer_res_table.items():
        # no files to transfer, do not send anything
        if not xfer_list:
            continue

        conn_ip = hashing.HASHING_OBJ.ip_table[id_hash]
        logging.info(f'relocating {xfer_list} to {conn_ip}')
        xfer_res_pkt = protocol.construct_packet(protocol.Verbs.XFER, protocol.Status.OK, {'files': xfer_list})
        try:
            protocol.sock_send_recv(conn_ip, xfer_res_pkt)
        except Exception as ex:
            logging.exception(ex)
        else:
            for xfer_file in xfer_list:
                os.remove(join(LOCAL_ROOT, xfer_file['filename']))
コード例 #7
0
 def getavalibleticket(self):
     hasher = Hashing()
     sqlstr = 'select * from tickets'
     self.cur = self.conn.execute(sqlstr)
     rows = self.cur.fetchall()
     alls = []
     for row in rows:
         alls.append({"Price": row[1], "TypeName": row[2], "Type": row[0]})
     return alls
コード例 #8
0
ファイル: protocol.py プロジェクト: brian-gavin/difuse
def lookup(_bootstrap_ip, path):
    """
    Consistent hashing routine for Lookup
    :param _bootstrap_ip: Unused, keeps interface intact.
    :param path: path/filename to lookup
    :return: IP of the node that contains the path
    """
    file_hash = Hashing.difuse_hash(path)
    succ = hashing.HASHING_OBJ.succ(file_hash)
    return hashing.HASHING_OBJ.ip_table[succ]
コード例 #9
0
ファイル: bootstrap.py プロジェクト: brian-gavin/difuse
 def __init__(self, thread_cnt):
     """
     Initializes boostrap
     """
     self.queue = Queue()
     self.sock = None
     hashing.HASHING_OBJ  = Hashing([], {}, b'')
     for n in range(thread_cnt):
         logging.info(f'starting thread {n}')
         threading.Thread(target=work_routine, args=[self], name=f'Worker Thread {n}', daemon=True).start()
コード例 #10
0
ファイル: witmanager.py プロジェクト: orronai/WitProject
 def compare_two_list_files(
         add_files_list: List[str], commit_on_files_list: List[str],
         add_files_dir: str,
         commit_on_files_dir: str) -> Tuple[List[str], List[str]]:
     """Return the files that has changed and the not existing files."""
     untracked_files = []
     changed_files = []
     for file_path in add_files_list:
         if file_path not in commit_on_files_list:
             untracked_files.append(file_path)
         else:
             add_path = os.path.join(add_files_dir, file_path)
             commit_path = os.path.join(commit_on_files_dir, file_path)
             add_content, commit_content = WitStatus.compare_files_contents(
                 add_path, commit_path)
             hash_add_content = Hashing.by_content(add_content)
             hash_commit_content = Hashing.by_content(commit_content)
             if hash_add_content != hash_commit_content:
                 changed_files.append(file_path)
     return changed_files, untracked_files
コード例 #11
0
ファイル: node_server.py プロジェクト: brian-gavin/difuse
 def handle_left_node(_conn, payload):
     """
     handles a LEFT_NODE, removing a node's mapping from the IP Table and hash unit
     :param conn: open connection
     :param payload: payload: will contain the IP of the node that left
     :return: None
     """
     try:
         hashing.HASHING_OBJ.remove_node(Hashing.difuse_hash(payload['ip']))
     except KeyError as ex:
         logging.exception(ex)
コード例 #12
0
 def chkrole(self, user, role):
     hasher = Hashing()
     sqlstr = 'select * from users'
     self.cur = self.conn.execute(sqlstr)
     rows = self.cur.fetchall()
     cor = False
     for row in rows:
         if user == row[0] and role == row[2]:
             cor = True
             return True
     if not cor:
         return False
コード例 #13
0
 def checkuserexists(self, username):
     hasher = Hashing()
     sqlstr = 'select * from users'
     self.cur = self.conn.execute(sqlstr)
     rows = self.cur.fetchall()
     cor = False
     for row in rows:
         if username == row[0]:
             cor = True
             return True
         #else:
         #pass
     if not cor:
         return False
コード例 #14
0
 def addconsumer(self, username, password, fullname):
     hasher = Hashing()
     sqlstr = 'select * from users'
     self.cur = self.conn.execute(sqlstr)
     rows = self.cur.fetchall()
     for row in rows:
         if username == row[0]:
             exist = True
             return "Exist"
         else:
             sqlstr = f'insert into users values("{username}","{hasher.hash(password)}","Consumer","{fullname}")'
             self.conn.execute(sqlstr)
             self.conn.commit()
             return "OK"
コード例 #15
0
def genapi(user, passwd):
    hasher = Hashing()
    sqlstr = 'select * from users'
    cur = conn.execute(sqlstr)
    rows = cur.fetchall()
    cor = False
    for row in rows:
        if hasher.check(passwd, row[1]) and user == row[0]:
            global apis
            #session["user"] = user
            #session["role"] = row[2]
            #gensession()
            cor = True
            letters = string.ascii_letters
            letters = letters + string.digits
            apikey = ''.join(random.choice(letters) for i in range(64))
            apis[apikey] = [user, row[2]]
            #{'APIKEY':[Username,Role]}
            print("[Debug Information] API KEY LIST = " + str(apis))
            return {'value': apikey}
        #else:
        #pass
    if not cor:
        return {'value': '0x00000'}
コード例 #16
0
def commit(message: str, branch_id: Optional[str] = None) -> None:
    """Commit a new request for a backup."""
    wit = WitEditor()

    commit_id = Hashing.by_path(wit.stage_dir)
    commit_id_images_dir = os.path.join(wit.images_dir, commit_id)
    try:
        os.mkdir(commit_id_images_dir)
    except FileExistsError:
        _logger.exception('The %s image had already been committed', commit_id)
    else:
        wit.create_metadata_file(message, commit_id, branch_id)
        wit.image_copy_files(commit_id_images_dir)

        wit.update_references_file(commit_id)
        _logger.info('Commit %s has been created', commit_id)
コード例 #17
0
def chklogin(user,pw):
    global conn
    cor=False
    if "a" == "a":
        hasher=Hashing()
        session.permanent = True
        user = user
        passwd = pw
        sqlstr='select * from users'
        cur=conn.execute(sqlstr)
        rows=cur.fetchall()
        #print(rows)
        #print(rows[5][0])
        kernel=Kernel()
        tmp=kernel.checkuser(user, pw)
        if tmp[0] == False:
            return [False,0]
        else:
            return [tmp[0],tmp[1][0],tmp[1][2]]
コード例 #18
0
ファイル: bootstrap.py プロジェクト: brian-gavin/difuse
def handle_exit(_bootstrap, conn, addr, _payload):
    """
    Handles EXIT verb.

    Removes the entry from the IP Table and broadcasts LEFT_NODE to all nodes in the cluster
    """
    # remove node
    hashing.HASHING_OBJ.remove_node(Hashing.difuse_hash(addr[0]))

    # send ack
    try:
        res_pkt = protocol.construct_packet(protocol.Verbs.OK,
                                        protocol.Status.OK,
                                        {})
        conn.send(res_pkt)
    except IOError as ex:
        logging.exception(ex)

    # bcast LEFT_NODE
    protocol.broadcast_no_recv(protocol.Verbs.LEFT_NODE, {'ip': addr[0]})
コード例 #19
0
 def orderticket(self, type1, orderer):
     hasher = Hashing()
     sqlstr = 'select * from tickets'
     self.cur = self.conn.execute(sqlstr)
     rows = self.cur.fetchall()
     cor = False
     for row in rows:
         if type1 == row[0]:
             cor = True
     if cor:
         #Correct Type
         exists = self.checkuserexists(orderer)
         if exists:
             date = "0000-00-00"
             value = int(self.getvalue())
             sqlstr = f'insert into ticket values("{type1}","{str(value+1)}","{orderer}","{date}")'
             self.conn.execute(sqlstr)
             self.conn.commit()
             self.writevalue()
         else:
             return "ERR"
     else:
         return 'ERR'
コード例 #20
0
ファイル: server.py プロジェクト: MWOSOfficial/Blueberry
with open("lang\\en-US.json", encoding="utf-8") as file:
    lang = json.load(file)
    file.close()
with open(lc, encoding="utf-8") as file:
    license1 = file.readlines()
    file.close()
app = Flask(__name__)
app.register_blueprint(apimodule, url_prefix="/api")
app.register_blueprint(oobeui, url_prefix="/oobe")
app.secret_key = "ThEMoSTSeCuRePassWORdINThEWorLD"
year = datetime.now().strftime('%Y')
app.permanent_session_lifetime = timedelta(days=10)
build = "0110"
branch = "centralbeta1_5.210906"
fullbuildname = build + "." + branch
hasher = Hashing()


@app.route('/license')
def license():
    return render_template("nano/license.html",
                           productname=productname,
                           year=year,
                           license=license1)


def gensession():
    global session
    global sessionid
    letters = string.ascii_letters
    letters = letters + string.digits
コード例 #21
0
class Game:
    def __init__(self):
        self.board = Board()
        self.scores = [0, 0]
        self.fifty_move_count = 0
        self.positions = []
        self.hash = Hashing()

    def check_if_moves_available(self):
        """Checks if there are any legal moves that the side to move can make."""
        piece_list = list(
            filter(lambda x: x.colour == self.board.side_to_move,
                   self.board.piece_list))
        destinations = {}

        for i, row in enumerate(self.board.array):
            for j, square in enumerate(row):
                if square:
                    if square.colour != self.board.side_to_move:
                        destinations[(i, j)] = True
                else:
                    destinations[(i, j)] = False

        for piece in piece_list:
            for place, capture in destinations.items():
                promotion = None

                if (piece.symbol == "p") and (place[0] == (
                        7 if piece.colour == Colour.WHITE else 0)):
                    promotion = Queen

                move = Move(piece.symbol,
                            type(piece),
                            piece.colour,
                            piece.position,
                            place,
                            is_capture=capture,
                            promotion=promotion)

                if move.check_move(self.board):
                    return True

        return False

    def check_end_of_game(self):
        """Checks if the game is over due to checkmate, the fifty move rule, threefold repetition or a stalemate."""
        if self.fifty_move_count == 100:
            return True

        if self.positions.count(
                self.positions[-1]
        ) == 3:  # checks if the last move resulted in threefold repetition
            return True

        return not self.check_if_moves_available()

    def play_game(self):
        position = self.hash.zobrist_hash(self.board)
        self.positions.append(position)

        while True:
            print(self.board)

            user_input = input("Enter move ({}): ".format(
                self.board.side_to_move.name.title()))

            move = lanparser.convert_lan_to_move(user_input,
                                                 self.board.side_to_move)

            if not move:
                print("Please enter a move in the correct syntax.")

            elif not move.check_move(self.board):
                print("This move is not valid.")

            else:
                position = self.hash.update_hash(self.positions[-1], move,
                                                 self.board)
                self.positions.append(position)

                move.perform_move(self.board)

                if move.is_capture:
                    side = 1 if self.board.side_to_move == Colour.WHITE else 0
                    self.scores[side] += self.board.discarded_pieces[-1].value

                if (move.piece_symbol == "p") or move.is_capture:
                    self.fifty_move_count = 0
                else:
                    self.fifty_move_count += 1

                game_over = self.check_end_of_game()
                in_check = self.board.in_check[self.board.side_to_move.value]

                if game_over:
                    if in_check:
                        if self.board.side_to_move == Colour.WHITE:
                            winner = Colour.BLACK
                        else:
                            winner = Colour.WHITE
                    else:
                        winner = ""

                    if winner:
                        print("\n{} wins.\n".format(winner.name.title()))
                    else:
                        print("\nIt is a draw.\n")

                    print("White's score: {}".format(
                        self.scores[Colour.WHITE.value]))
                    print("Black's score: {}".format(
                        self.scores[Colour.BLACK.value]))

                    break

                else:
                    if in_check:
                        print("\n{} is in check.\n".format(
                            self.board.side_to_move.name.title()))

    def play_engine(self, colour_choice):
        engine = Engine()

        position = self.hash.zobrist_hash(self.board)
        self.positions.append(position)

        while True:
            print(self.board)

            if self.board.side_to_move.value != colour_choice:
                move = engine.find_move(self.board)
            else:
                user_input = input("Enter move ({}): ".format(
                    self.board.side_to_move.name.title()))
                move = lanparser.convert_lan_to_move(user_input,
                                                     self.board.side_to_move)

                while True:
                    if move:
                        if move.check_move(self.board):
                            break
                        else:
                            print("This move is not valid.")
                    else:
                        print("Please enter a move in the correct syntax.")

                    user_input = input("Enter move ({}): ".format(
                        self.board.side_to_move.name.title()))
                    move = lanparser.convert_lan_to_move(
                        user_input, self.board.side_to_move)

            position = self.hash.update_hash(self.positions[-1], move,
                                             self.board)
            self.positions.append(position)

            move.perform_move(self.board)

            if move.is_capture:
                side = 1 if self.board.side_to_move == Colour.WHITE else 0
                self.scores[side] += self.board.discarded_pieces[-1].value

            if (move.piece_symbol == "p") or move.is_capture:
                self.fifty_move_count = 0
            else:
                self.fifty_move_count += 1

            game_over = self.check_end_of_game()
            in_check = self.board.in_check[self.board.side_to_move.value]

            if game_over:
                if in_check:
                    if self.board.side_to_move == Colour.WHITE:
                        winner = Colour.BLACK
                    else:
                        winner = Colour.WHITE
                else:
                    winner = ""

                if winner:
                    print("\n{} wins.\n".format(winner.name.title()))
                else:
                    print("\nIt is a draw.\n")

                print("White's score: {}".format(
                    self.scores[Colour.WHITE.value]))
                print("Black's score: {}".format(
                    self.scores[Colour.BLACK.value]))

                break

            else:
                if in_check:
                    print("\n{} is in check.\n".format(
                        self.board.side_to_move.name.title()))
コード例 #22
0
ファイル: main.py プロジェクト: britishwolf/0xff-bot
from utilities import Utilities
from ctfs import CTFs
from fun import Fun

from discord.ext.commands import Bot
import discord
import asyncio
import os

#app_id = '519995591359594538'
TOKEN = os.environ["DISCORD_TOKEN"]
BOT_PREFIX = (".", "dad ")

client = Bot(command_prefix=BOT_PREFIX)

client.add_cog(Hashing(client))
client.add_cog(Encoding(client))
client.add_cog(Ciphers(client))
client.add_cog(Utilities(client))
client.add_cog(CTFs(client))
client.add_cog(Fun(client))


@client.event
async def on_ready():
    print("--------Logged in as " + client.user.name + "-----------")


@client.event
async def on_message(message):
    # print("Command received: " + str(message.content))
コード例 #23
0
 def __init__(self):
     self.board = Board()
     self.scores = [0, 0]
     self.fifty_move_count = 0
     self.positions = []
     self.hash = Hashing()