Exemplo n.º 1
0
def setup_mongo():
    client = pymongo.MongoClient(app_server.mongodb_url)
    database = client.get_default_database()

    collections.update({
        'system': database.system,
        'administrators': database.administrators,
        'users': database.users,
        'organizations': database.organizations,
        'servers': database.servers,
    })
    collections['administrators'].ensure_index('username', unique=True)
    collections['users'].ensure_index([
        ('org_id', pymongo.ASCENDING),
        ('type', pymongo.ASCENDING),
    ])
    collections['users'].ensure_index([
        ('org_id', pymongo.ASCENDING),
        ('name', pymongo.ASCENDING),
    ])
    collections['organizations'].ensure_index('type')
    collections['servers'].ensure_index('name')

    from administrator import Administrator
    if not Administrator.get_collection().find_one():
        Administrator(
            username=DEFAULT_USERNAME,
            password=DEFAULT_PASSWORD,
            default=True,
        ).commit()
Exemplo n.º 2
0
 def __init__(self):
     self.control = POSController()
     self.admin = Administrator()
     self.now = datetime.datetime.now()
     self.stockingdate = self.now.date()
     self.ondiscount = False
     self.invoiceno = 1
Exemplo n.º 3
0
def main():
    # connect to database
    connection = sql_connect()
    cnx = connection[0]
    cursor = connection[1]

    USER_TYPES = {
        1: Librarian(cursor, cnx),
        2: Administrator(cursor, cnx),
        3: Borrower(cursor, cnx),
    }

    while True:
        user_type = entryPrompt()
        if user_type == 'quit':
            print(constants.QUIT_MESSAGE)
            break
        func = USER_TYPES.get(user_type)
        if not func:
            print(constants.INCORRECT_INPUT)
        else:
            continue_driver = func.driver()
            if not continue_driver:
                print(constants.QUIT_MESSAGE)
                break

    # close cursor and connection
    sql_close(cnx, cursor)
Exemplo n.º 4
0
 def __init__(self):
     self.admin = Administrator()
     self.product = Product()
     self.bag_type = 0
     self.discounted_price = 0
     self.now = datetime.datetime.now()
     self.cart = []
     self.itemname = []
     self.itemquantity = []
     self.itemprice = []
     self.invoiceno = 0
     self.totalprice = 0
Exemplo n.º 5
0
def citeste(nume_fis):
    try:
        f = open(nume_fis)
    except Exception as e:
        print(e)
        print("Eroare la deschiderea fisierului", nume_fis)
        return []

    ang_lst = []

    linii_lst = f.readlines()
    print(linii_lst)

    f.close()

    for linie in linii_lst:
        linie = linie.strip()
        if linie != "":
            lst_elems = linie.split(" ", 4)
            print(lst_elems)
            if lst_elems[0] == "v":
                a = Vanzator(lst_elems[1].strip(), lst_elems[2].strip(),
                             lst_elems[3].strip())
                #ang_lst.append(v)
            elif lst_elems[0] == "a":
                a = Administrator(lst_elems[1].strip(), lst_elems[2].strip(),
                                  int(lst_elems[3].strip()),
                                  lst_elems[4].strip())
            elif lst_elems[0] == "aa":
                a = Ajutor_adminisatrator(lst_elems[1].strip(),
                                          lst_elems[2].strip(),
                                          int(lst_elems[3].strip()),
                                          lst_elems[4].strip())

            else:
                print("Date invalide")
                continue

            ang_lst.append(a)

    return ang_lst
Exemplo n.º 6
0
 def log_in():
     username = input("please enter your username: "******"there is not such a user!")
             return
     counter = 0
     while True:
         entered_password = input('please enter your password: '******'utf8')).hexdigest() == password:
             print('-----------------welcome------------------')
             if status == 'student':
                 with open('students.csv', 'r') as students_info:
                     csv_reader = csv.reader(students_info)
                     for student in csv_reader:
                         if student[0] == username:
                             return Student(student[0], student[1],
                                            student[2], student[3])
             elif status == 'administrator':
                 return Administrator(username)
         elif counter == 2:
             print('your account is locked!')
             with open('locked_users.txt', 'a') as locked_file:
                 locked_file.write(f'{username}\n')
             break
         else:
             print('wrong password!')
             counter += 1
Exemplo n.º 7
0
def check_auth(username, password, remote_addr=None):
    from administrator import Administrator

    if remote_addr:
        # TODO
        cache_key = 'ip_' + remote_addr
        count = cache_db.list_length(cache_key)
        if count and count > 10:
            raise flask.abort(403)

        # TODO
        key_exists = cache_db.exists(cache_key)
        cache_db.list_rpush(cache_key, '')
        if not key_exists:
            cache_db.expire(cache_key, 20)

    administrator = Administrator.find_user(username=username)
    if not administrator:
        return
    if not administrator.test_password(password):
        return
    return administrator
Exemplo n.º 8
0
def check_session():
    from administrator import Administrator

    auth_token = flask.request.headers.get('Auth-Token', None)
    if auth_token:
        auth_timestamp = flask.request.headers.get('Auth-Timestamp', None)
        auth_nonce = flask.request.headers.get('Auth-Nonce', None)
        auth_signature = flask.request.headers.get('Auth-Signature', None)
        if not auth_token or not auth_timestamp or not auth_nonce or \
                not auth_signature:
            return False
        auth_nonce = auth_nonce[:32]

        try:
            if abs(int(auth_timestamp) - int(time.time())) > AUTH_TIME_WINDOW:
                return False
        except ValueError:
            return False

        # TODO
        cache_key = 'auth_nonce-%s' % auth_nonce
        if cache_db.exists(cache_key):
            return False

        administrator = Administrator.find_user(token=auth_token)
        if not administrator:
            return False

        auth_string = '&'.join([
            auth_token, auth_timestamp, auth_nonce, flask.request.method,
            flask.request.path] +
            ([flask.request.data] if flask.request.data else []))

        if len(auth_string) > AUTH_SIG_STRING_MAX_LEN:
            return False

        auth_test_signature = base64.b64encode(hmac.new(
            administrator.secret.encode(), auth_string,
            hashlib.sha256).digest())
        if auth_signature != auth_test_signature:
            return False

        # TODO
        cache_db.expire(cache_key, int(AUTH_TIME_WINDOW * 2.1))
        cache_db.set(cache_key, auth_timestamp)

        flask.request.administrator = administrator
    else:
        from pritunl import app_server
        if not flask.session:
            return False

        admin_id = flask.session.get('admin_id')
        if not admin_id:
            return False

        administrator = Administrator.get_user(id=admin_id)
        if not administrator:
            return False

        if not app_server.ssl and flask.session.get(
                'source') != get_remote_addr():
            flask.session.clear()
            return False

        if SESSION_TIMEOUT and int(time.time()) - \
                flask.session['timestamp'] > SESSION_TIMEOUT:
            flask.session.clear()
            return False

        flask.request.administrator = administrator
    return True
Exemplo n.º 9
0
from administrator import Administrator
from bulletinboard import BulletinBoard
from candidate import Candidate

admin = Administrator.get_instance()
cand1 = Candidate("cand1")
cand2 = Candidate("cand2")

bb = BulletinBoard.get_instance()

admin.setup([cand1.public_key, cand2.public_key])
admin.credential_dispatch()
bb.show()
Exemplo n.º 10
0
def handle_client(client):  # Takes client socket as argument.
    """Handles a single client connection."""

    f = open("server/data/list.txt", encoding="utf8")  # файл со списком учеников и администраторов
    students = []  # список студентов
    admins = []  # список админов
    text = f.read().splitlines()
    for line in text:
        spl = line.split("*")
        if spl[3] == "admin":
            adm = Administrator()
            adm.set_surname(spl[0])
            adm.set_name(spl[1])
            adm.set_patronym(spl[2])
            adm.set_password(spl[4])
            admins.append(adm)
        else:
            stud = Student()
            stud.set_surname(spl[0])
            stud.set_name(spl[1])
            stud.set_patronym(spl[2])
            stud.set_login(spl[3])
            stud.set_password(spl[4])
            stud.set_course(int(spl[5]))
            stud.set_group(spl[6])
            stud.set_subgroup(int(spl[7]))
            students.append(stud)
    f.close()

    g = open("server/data/disciplines.txt", encoding="utf8")  # файл со списком дисциплин
    disciplines = []
    text = g.read().splitlines()
    for line in text:
        spl = line.split("*")
        subj = Discipline()
        subj.set_name(spl[0])
        subj.set_course(spl[1])
        subj.set_credits(spl[2])
        subj.set_vedomost(spl[3])
        disciplines.append(subj)
    g.close()

    flag = "0"
    while flag == "0":
        login = client.recv(1024).decode("utf8")
        password = client.recv(1024).decode("utf8")
        for stud in students + admins:
            if stud.get_login() == login and stud.get_password() == password:
                client.send(bytes("1", "utf8"))  # логин и пароль верны
                flag = "1"
                user = stud.get_surname()
                break
        if flag == "0":
            client.send(bytes("0", "utf8"))

    msg = client.recv(1024).decode("utf8")  # получаем код продвинутого\упрощенного меню

    if msg == "1":  # продвинутое меню для администратора
        while True:
            msg1 = client.recv(1024).decode("utf8")
            if msg1 == "5":  # внести изменения в учетную запись
                surname = client.recv(1024).decode("utf8")
                flag = "0"
                for stud in students:
                    if stud.get_surname() == surname:
                        flag = "1"
                        break
                client.send(bytes(flag, "utf-8"))
                if flag == "1":
                    z = client.recv(1024).decode("utf8")
                    if z == "1":  # меняем фамилию
                        new_surname = client.recv(1024).decode("utf8")
                        stud.set_surname(new_surname)
                        new_login = translit(stud.get_name()[0] + stud.get_patronym()[0] + new_surname)
                        stud.set_login(new_login)
                        client.send(bytes("Фамилия и логин изменены", "utf8"))
                        # меняем старую фамилию в ведомостях
                        for subj in disciplines:
                            m = subj.find_mark(surname)
                            f = open(subj.get_vedomost(), encoding="utf8")
                            text = f.read().splitlines()
                            new_lines = []
                            for line in text:
                                if surname in line:
                                    new_lines.append(new_surname + " " + m)
                                else:
                                    new_lines.append(line)
                            f.close()
                            f = open(subj.get_vedomost(), "w", encoding="utf8")
                            for line in new_lines:
                                f.write("%s\n" % line)
                            f.close()

                    elif z == "2":  # имя
                        new_name = client.recv(1024).decode("utf8")
                        stud.set_name(new_name)
                        new_login = translit(new_name[0] + stud.get_patronym()[0] + stud.get_surname())
                        stud.set_login(new_login)
                        client.send(bytes("Имя и логин изменены", "utf8"))
                    elif z == "3":
                        new_patronym = client.recv(1024).decode("utf8")
                        stud.set_patronym(new_patronym)
                        new_login = translit(stud.get_name()[0] + new_patronym[0] + stud.get_surname())
                        stud.set_login(new_login)
                        client.send(bytes("Отчество и логин изменены", "utf8"))
                    elif z == "4":  # курс
                        new_course = client.recv(1024).decode("utf8")
                        stud.set_course(int(new_course))
                        client.send(bytes("Курс изменен", "utf8"))
                    elif z == "5":
                        new_group = client.recv(1024).decode("utf8")
                        stud.set_group(new_group)
                        client.send(bytes("Группа изменена", "utf8"))
                    else:
                        new_subgroup = client.recv(1024).decode("utf8")
                        stud.set_subgroup(int(new_subgroup))
                        client.send(bytes("Подгруппа изменена", "utf8"))
                    # перезапись файла list.txt
                    update_file(students, admins)
                else:
                    client.send(bytes("Данного студента нет в системе", "utf8"))

            elif msg1 == "6":
                stud = Student()
                surname = client.recv(1024).decode("utf8")
                stud.set_surname(surname)
                name = client.recv(1024).decode("utf8")
                stud.set_name(name)
                patronym = client.recv(1024).decode("utf8")
                stud.set_patronym(patronym)

                # генерация логина
                login = translit(name[0] + patronym[0] + surname)
                stud.set_login(login)

                # генерация пароля
                password = generate_password()
                stud.set_password(password)

                course = client.recv(1024).decode("utf8")
                stud.set_course(int(course))
                group = client.recv(1024).decode("utf8")
                stud.set_group(group)
                subgroup = client.recv(1024).decode("utf8")
                stud.set_subgroup(int(subgroup))
                students.append(stud)
                f = open("server/data/list.txt", "a", encoding="utf8")  # открытие файла на дозапись
                f.write(
                    surname + "*" + name + "*" + patronym + "*" + login + "*" + password + "*" + course + "*" + group + "*" + subgroup + "\n")
                f.close()
                client.send(bytes("Регистрация прошла успешно", "utf8"))

            elif msg1 == "7":  # удаление
                flag = 0
                surname = client.recv(1024).decode("utf8")
                for stud in students:
                    if stud.get_surname() == surname:
                        flag = 1
                        students.remove(stud)
                        update_file(students, admins)
                        client.send(bytes("Студент отчислен!", "utf8"))
                        break
                if flag == 0:
                    client.send(bytes("Данного студента не было в системе", "utf8"))

            elif msg1 == "1":  # зачетка
                flag = 0
                surname = client.recv(1024).decode("utf8")
                for stud in students:
                    if stud.get_surname() == surname:
                        flag = 1
                        msg = str(stud.get_surname()) + " " + str(stud.get_name()) + " " + str(stud.get_patronym()) + \
                              "\n" + "Студент бакалавриата " + str(
                            stud.get_course()) + " курс" + "\n" + "-------------------------------------------------"
                        for obj in disciplines:
                            if int(obj.get_course()) <= int(stud.get_course()):
                                msg = msg + "\n" + str(obj.get_name()) + " " + str(obj.find_mark(str(stud.get_surname())))
                        client.send(bytes(msg, "utf8"))
                        break
                if flag == 0:
                    client.send(bytes("Данного студента нет в системе", "utf8"))

            elif msg1 == "2":  # рейтинг
                msg = show_rating(students, disciplines)
                client.send(bytes(msg, "utf8"))

            elif msg1 == "3":  # смена пароля
                password = client.recv(1024).decode("utf8")
                for adm in admins:
                    if adm.get_surname() == user:
                        adm.set_password(password)
                update_file(students, admins)
                client.send(bytes("Пароль изменен", "utf8"))

            else:  # закрываем соединение
                client.send(bytes("До свидания!", "utf8"))
                client.close()
                break

    else:
        while True:
            msg = client.recv(1024).decode("utf8")  # меню
            if msg == "1":  # зачетка
                msg = str(stud.get_surname()) + " " + str(stud.get_name()) + " " + str(stud.get_patronym()) + \
                      "\n" + "Студент бакалавриата " + str(
                    stud.get_course()) + " курс" + "\n" + "-------------------------------------------------"
                for obj in disciplines:
                    msg = msg + "\n" + str(obj.get_name()) + " " + str(obj.find_mark(str(stud.get_surname())))
                client.send(bytes(msg, "utf8"))
            elif msg == "2":  # рейтинг
                msg = show_rating(students, disciplines)
                client.send(bytes(msg, "utf8"))
            elif msg == "3":
                password = client.recv(1024).decode("utf8")
                for stud in students:
                    if stud.get_surname() == user:
                        stud.set_password(password)
                update_file(students, admins)
                client.send(bytes("Пароль изменен", "utf8"))
            else:
                client.send(bytes("До свидания!", "utf8"))
                client.close()
                break
iscream = IceCreamStand("the fainting goat", "deserts")
iscream.describe_restaurant()
iscream.open_restaurant()
iscream.ice_cream_flavors(["vanilla", "cherry", "salted carmel", "chocolate"])
#Event the IceCreamStand() subclass works perfectly.

##9-11:
import user_admin

user1 = user_admin.Administrator("mason", "karsevar", "data scientist",
                                 "seattle", "hiking")
user1.describe_user()
user1.greet_user()
#These commends from the User2 parent class work perfectly. I need to see
#if the subclass works perfectly as well.

user1.privileges.privileges = ["managing user data", "barring bad actors"]
user1.privileges.show_privileges()
#Sweet these commands worked perfectly!!!
#I can finally move onto the next chapter.

##9-12:
from administrator import Administrator
admin2 = Administrator("alice", "karsevar", "project manager", "san francisco",
                       "hiking")
admin2.describe_user()
admin2.greet_user()
admin2.privileges.privileges = ["bar bad actors", "delete messages"]
admin2.privileges.show_privileges()
#Sweet everything works perfectly.