Beispiel #1
0
def group_send():
    message = request.form['message']
    list = get_users()
    for user in list:
        uid = user[0]
        send._pri_m(message, uid)
    data = get_users()
    file = io.open('setting.json', 'r')
    setting = load(file)
    setting = dumps(setting, sort_keys=True, indent=4, separators=(',', ':'))
    return render_template("admin.html", list=data, setting=setting)
Beispiel #2
0
def user_remove(access):
    if not database.valid_access(access):
        return render_template("error.html", error="Page not found.")
    elif not database.is_admin(session["access"]):
        return redirect(url_for("unauthorized"))
    else:
        email = request.form["email"]
        users = database.get_users()

        if not database.user_exists(email):
            return render_template("users.html", users=users, access=access, error="User: "******" does not exist.")
        
        database.remove_user(email=email)
        users = database.get_users()
        return render_template("users.html", users=users, access=access, error=email + " has been removed permanantly.")
Beispiel #3
0
def main():
    db = database.connect()

    with db, db.cursor() as cursor:
        users = database.get_users(cursor)

    gevent.joinall([gevent.spawn(run_forever, db, user) for user in users])
Beispiel #4
0
def user_render(access):
    if not database.valid_access(access):
        return render_template("error.html", error="Page not found.")
    elif not database.is_admin(session["access"]):
        return redirect(url_for("unauthorized"))
    else:
        users = database.get_users()
        if request.method == "POST":
            email = request.form["email"]
            password = request.form["password"]
            password2 = request.form["password-two"]
            new_access = request.form["access"]
            name = request.form["name"]
            location = request.form["location"]
            # Change this to create a user if authentic email
            if password != password2:
                return render_template("users.html", users=users, access=access, error="Passwords for " + email + " do not match.")

            if database.user_exists(email):
                return render_template("users.html", users=users, access=access, error="User: "******" already exists.")
            
            database.create_user(email, password, name, new_access, location)

            token = security.generate_confirmation_token(email)
            confirm_url = url_for("confirm", token=token, _external=True)
            html = render_template("account.html", confirm_url=confirm_url, access = new_access, password=password)
            subject = "Please confirm your email"
            send_email(email, subject, html)
            print("CONFIRM: ", confirm_url)
            print("EMAIL: ", email)
            return render_template("users.html", users=users, access=access, error="An authentication email has been send to: " + email)
        else:
            return render_template("users.html", users=users, access=access)
def update_job(context):
    with db.connection() as cursor:
        updates = jobs.check_updates(
            jobs.get_last_data(db.get(cursor, "*", "country", multiple=True)),
            jobs.get_current(),
        )

    for country in updates.keys():
        for data in updates[country].keys():
            if "difference" not in data and "today" not in data:
                with db.connection() as cursor:
                    db.update(
                        cursor,
                        "country",
                        data,
                        updates[country][data]["total"],
                        "name",
                        country,
                    )

    with db.connection() as cursor:
        users = db.get_users(cursor)

    messages = jobs.generate_update_message(updates)

    for user in users:
        if user[1] in messages.keys():
            try:
                context.bot.send_message(chat_id=user[0],
                                         text=messages[user[1]])
            except telegram.error.Unauthorized:
                with db.connection() as cursor:
                    db.delete_user(cursor, user[0])
Beispiel #6
0
def main():
    print "[+] Starting Twitter Crawler Export Tool"
    result = []
    user_list = database.get_users()
    for user in user_list:
        print "[+] Proccessing User: %s" % user

        try:
            friends = database.get_friends(user)
        except:
            print "[-] Error No Friend Data Found For %s Omitting" % user
            friends = []

        try:
            followers = database.get_followers(user)
        except:
            print "[-] Error No Follower Data Found For %s Omitting" % user
            followers = []

        result.append({
            "screen_name": user,
            "friends": friends,
            "followers": followers
        })

    file = open("export.json", "w")
    file.write(json.dumps(result))
    file.close()
    print "[+] Success Data Saved As export.json"
Beispiel #7
0
    def wrapper_func(*args, **kwargs):
        """ Wrapper function """
        try:
            email_arg_index = argspec.args.index("email")
            email = args[email_arg_index]

            # Try to grab this users ID. If the user doesnt exist, create a warning
            # and run the function without checking the permission_id.
            try:
                target_u_id = next(u['u_id'] for u in database.get_users()
                                   if u['email'] == email)
                target_perm_id = database.get_permission_dict(target_u_id).get(
                    'permission_id')
                if target_perm_id == 66:
                    raise error.AccessError(
                        description="The account registered to this email has"
                        + " been removed from the slakr. " +
                        "[I'm sorry Dave, I'm afraid I can't do that]")
                else:
                    return func(*args, **kwargs)
            except StopIteration:
                print(
                    "\033[93m" +
                    "WARNING: This email was not found  - running function " +
                    f"{func.__name__} without permission_id check." +
                    "\033[0m")
                return func(*args, **kwargs)

        except ValueError:
            print("\033[93m" +
                  "WARNING: email arg not found - running function " +
                  f"{func.__name__} without email check." + "\033[0m")
            return func(*args, **kwargs)
def ledger():
    form = forms.UploadLedgerCSVForm(
        CombinedMultiDict((request.files, request.form)))
    if form.validate_on_submit():
        f = form.csv_file.data
        file_uuid = str(uuid.uuid4())[0:8]
        base_dir = "static/files/bank/"
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)
        file_path = f"{base_dir}/{file_uuid}.csv"
        if not os.path.isfile(file_path):
            f.save(file_path)
            try:
                google_sheets.import_bank_csv(file_path)
                flash("Transactions uploaded successfully.", "success")
            finally:
                os.remove(file_path)
        else:
            flash("Failed to upload - File of same name already exists.",
                  "danger")
        return redirect(url_for("trustee_routes.ledger"))

    status, cookie = logins.validate_cookie(request.cookies.get('jam_login'))
    volunteers = database.get_users(include_inactive=True)
    base_transactions = google_sheets.get_transaction_table(logins=volunteers)
    transactions = []
    for transaction in base_transactions:
        if transaction.bank_date:
            transaction.user_id = cookie.user.user_id
            transactions.append(transaction)
    return render_template("trustee/ledger.html",
                           transactions=transactions,
                           trustees=volunteers,
                           container_name="container-wide",
                           form=form)
def auth_login(email, password):
    """ Login user with given email and password. """

    # Check if email entered belongs to a user
    password_data = database.get_password_data(email)
    if password_data is None:
        raise error.InputError(
            description="The email you entered is incorrect")

    # Hash the password and see if it matches the hashed passowrd in the database
    passcode = hashlib.sha256(password.encode()).hexdigest()

    # Check if password matches email
    if password_data['password'] != passcode:
        raise error.InputError(
            description="The password you entered is incorrect")

    # find user's u_id from email given
    u_id = 0
    for user in database.get_users():
        if user['email'] == email:
            u_id = user['u_id']

    # Check if already logged in.
    if database.get_token_from_user(u_id) is not None:
        raise error.AccessError(
            description="Cannot login when already logged in!")

    # Generate a token
    payload = {'u_id': u_id}
    token = str(jwt.encode(payload, 'jwt_secret', algorithm='HS256'))

    dictionary = {'u_id': u_id, 'token': token}
    database.set_current_user(u_id, token)
    return dictionary
Beispiel #10
0
def main():
    print "[+] Starting Twitter Crawler Export Tool"
    result = []
    user_list = database.get_users()
    for user in user_list:
        print "[+] Proccessing User: %s" % user

        try:
            friends = database.get_friends(user)
        except:
            print "[-] Error No Friend Data Found For %s Omitting" % user
            friends = []

        try:
            followers = database.get_followers(user)
        except:
            print "[-] Error No Follower Data Found For %s Omitting" % user
            followers = []

        result.append({"screen_name": user, "friends": friends, "followers": followers})

    file = open("export.json", "w")
    file.write(json.dumps(result))
    file.close()
    print "[+] Success Data Saved As export.json"
Beispiel #11
0
def user_info():
    user_list = [{
        'id': u.u_id,
        'username': u.username
    } for u in db.get_users()]  #CHANGE
    print(user_list)
    response = jsonify({'users': user_list})
    return response, 200
Beispiel #12
0
def main():
    db = database.connect()

    with db, db.cursor() as cursor:
        users = database.get_users(cursor)

    gevent.joinall([gevent.spawn(run_forever, db, user)
                    for user in users])
Beispiel #13
0
Datei: api.py Projekt: gbnk0/nmt
async def get_users(request):

    results = {"results": []}
    users = db.get_users()
    for u in users:
        u.pop('password', None)

    results['results'] = users
    return response.json(results, status=200)
def ledger_upload_link(transaction_id):
    form = forms.AddTransactionReceiptForm(
        CombinedMultiDict((request.files, request.form)))

    users = database.get_users(include_inactive=True)
    transactions = google_sheets.get_transaction_table(users)
    for transaction in transactions:
        if int(transaction.transaction_id) == int(transaction_id):
            t = transaction
            break
    else:
        return "Transaction not found..."

    if request.method == 'POST' and form.validate():
        f = form.receipt.data
        month_year = form.receipt_date.data.strftime("%B-%Y").lower()
        file_type = f.filename.split(".")[-1]
        file_uuid = str(uuid.uuid4())[0:8]
        filename = f"{file_uuid}.{file_type}"
        base_dir = f"static/files/receipts/{month_year}"
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)
        file_path = f"{base_dir}/{filename}"
        if not os.path.isfile(file_path):
            f.save(file_path)
            flash("File upload successful.", "success")
            id_column_data = google_sheets.update_transaction_cell(
                transaction_id, google_sheets.T.RECEIPT_DATE,
                form.receipt_date.data.strftime("%d/%m/%Y"))
            google_sheets.update_transaction_cell(
                transaction_id,
                google_sheets.T.RECEIPT_URL,
                f"/{file_path}",
                id_column_data=id_column_data)
        else:
            flash("Failed to upload - File of same name already exists.",
                  "danger")
        return redirect(url_for("trustee_routes.ledger"))

    nearby_expenses = []
    if "PAYPAL" in t.bank_text:
        expenses = google_sheets.get_volunteer_expenses_table()
        nearby_expenses = []
        for expense in expenses:
            if not expense.payment_made_date:
                continue

            if abs(
                (t.bank_date - expense.payment_made_date).days
            ) < 3 and transaction.paid_out == expense.value and expense.paid_by_id:
                nearby_expenses.append(expense)

    return render_template("trustee/ledger_upload_link.html",
                           transaction=t,
                           expenses=nearby_expenses,
                           form=form)
Beispiel #15
0
 def get():
     try:
         data = get_users()
         return Response.success(status=200,
                                 message="Successful GET of page",
                                 data=data)
     except Exception as err:
         return Response.server_error(
             status=400,  # TODO: Create proper status for server error
             message="Server Error: {}".format(err))
def users_all(token):
    """
    returns a list of dictionaries for all users
    """
    # pylint: disable=unused-argument
    # NB: Supressed this warning because token is in fact used in
    # the decorator, however pylint doesn't check for this.
    users_list = ([usr for usr in database.get_users()
                   if database.get_permission_dict(usr['u_id']).get('permission_id') != 66])

    return {"users": users_list}
Beispiel #17
0
def get_volunteer_expenses_table(offset=3):
    expense_data = []
    _check_oauth_token()
    data = EXPENSE_SHEET.get_all_values()[offset:]
    login_users = database.get_users(include_inactive=True)
    for line in data:
        expense = Expense(line)
        expense.update_users(login_users)
        expense_data.append(expense)

    return expense_data
Beispiel #18
0
def users_graduate(access):
    if not database.valid_access(access):
        return render_template("error.html", error="Page not found.")
    elif not database.is_admin(session["access"]):
        return redirect(url_for("unauthorized"))
    else:
        grads = request.form["grads"]
        database.graduate_students(group=grads)

        users = database.get_users()

        return render_template("users.html", users=users, access=access, error=grads + " have been graduated.")
Beispiel #19
0
def user_profile_setemail(token, email):
    """
    Given input for email sets user's email if valid and not taken
    """
    users = database.get_users()
    for user in users:
        if user['email'] is email:
            raise error.InputError(description="This email is already taken")
    u_id = database.get_current_user(token)
    user = database.get_user_data(u_id)
    user['email'] = email
    database.set_user_data(user)
Beispiel #20
0
def user_profile_sethandle(token, handle_str):
    """
    given input for a handle name set user's handle
    """
    if (len(handle_str) > 20 or len(handle_str) < 2):
        raise error.InputError(
            description="Handle is not within 2-20 characters")
    users = database.get_users()
    for user in users:
        if user['handle_str'] is handle_str:
            raise error.InputError(description="Handle is already taken")
    u_id = database.get_current_user(token)
    user = database.get_user_data(u_id)
    user['handle_str'] = handle_str
    database.set_user_data(user)
def compute_match(start_user_id=None):
    print 'user id ', start_user_id
    graph = nx.DiGraph()
    for user_id in db.get_users():
        user = db.get_user(user_id)
        for card_id in user['wanted']:
            graph.add_edge(user_id, card_id)
        for card_id in user['collection']:
            graph.add_edge(card_id, user_id)
    cycles = nx.simple_cycles(graph)
    if start_user_id is None:
        return cycles
    for cycle in cycles:
        if start_user_id in cycle and len(cycle) > 2:
            return cycle
    return None
def create_handle_str(handle_str):
    """ Given a handle_str, look through database to see if it is already taken.
    Modify appropriately if taken. """

    number = 0
    handle_str_cpy = handle_str
    for user in database.get_users():
        if handle_str_cpy == user['handle_str']:
            if len(handle_str) < 20:
                handle_str_cpy = handle_str + str(number)
            else:
                handle_str = handle_str[:19]
                handle_str_cpy = handle_str + str(number)
            number += 1

    return handle_str_cpy
Beispiel #23
0
def admin():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        pwd = request.form['pwd']
        data = get_users()
        if check_admin(pwd):
            file = io.open('setting.json', 'r')
            setting = load(file)
            setting = dumps(setting,
                            sort_keys=True,
                            indent=4,
                            separators=(',', ':'))
            return render_template("admin.html", list=data, setting=setting)
        else:
            return render_template("login.html")
Beispiel #24
0
def import_bank_csv(csv_path):
    import csv

    transactions = []
    _check_oauth_token()
    with open(csv_path) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for line in list(csv_reader)[1:]:
            transactions.append(
                Transaction((None, line[0], None, None, line[2], None, None,
                             line[3], line[4], None, None, None, None, None,
                             None, None, None, None),
                            offset=0,
                            bank=True))
    logins = database.get_users(include_inactive=True)
    current_transactions = get_transaction_table(logins)
    new_transactions = []
    for new_transaction in transactions:
        duplicate = False
        for current_transaction in current_transactions:
            if new_transaction.bank_date == current_transaction.bank_date:
                if new_transaction.bank_text.strip(
                ) == current_transaction.bank_text.strip():
                    if new_transaction.paid_in == current_transaction.paid_in and new_transaction.paid_out == current_transaction.paid_out:
                        #print("Duplicate found... {}".format(new_transaction))
                        duplicate = True
                        break
                    else:
                        print(
                            "Money doesn't match for a transaction {} - {} vs {}"
                            .format(new_transaction.bank_text,
                                    new_transaction.paid_out,
                                    current_transaction.paid_out))
                        #raise Exception ("Money doesn't match for a transaction {} - {} vs {}".format(new_transaction.bank_text, new_transaction.paid_out, current_transaction.paid_out))
        if duplicate:
            continue
        new_transactions.append(new_transaction)
    transaction_id = current_transactions[-1].transaction_id
    for new_transaction in new_transactions:
        transaction_id = int(transaction_id) + 1
        new_transaction.transaction_id = transaction_id
        MAIN_SHEET.append_row(new_transaction.get_row(),
                              value_input_option='USER_ENTERED')
Beispiel #25
0
def hello_user():
    global from_number
    from_number = request.values.get('To', None)
    print type(from_number)
    resp = VoiceResponse()
    for x in database.get_users():
        if str(x['phone']) == str(from_number):
            resp.say("Hello " + str(x['name']), voice='alice')
    resp.say("Are you available for the delivery Now ?", voice='alice')
    g = Gather(
        numDigits=1,
        action="/handle-yn",
        timeout=2,
        method="POST",
    )
    g.say("If Yes, Press 1, if No Press 2.", voice='alice')
    resp.append(g)

    return str(resp)
Beispiel #26
0
def update_clients():
    """
    Refreshes the access tokens and updates the playlists for all clients in
    the cache
    """
    for user in db.get_users():
        if db.get_field(user, "active") != "false":
            print("updating", user)
            oauth = spotipy.oauth2.SpotifyOAuth(
                scope=constant.SCOPE,
                cache_handler=DatabaseCacheHandler(user),
                client_id=config.client_id,
                client_secret=config.client_secret,
                redirect_uri=config.redirect_uri)
            try:
                client = spotipy.Spotify(auth_manager=oauth)
                playlist.update_playlist(client, user)

                # reset the users error count if an update was successful
                db.update_user(user, "error_count", 0)
            except SpotifyException as e:
                # we hit a rate limit wait 60 seconds and retry
                if e.code == 429:
                    time.sleep(60)
                    try:
                        playlist.update_playlist(client)
                    except Exception as e:
                        log_error_to_database(user, e)
                else:
                    log_error_to_database(user, e)
            except Exception as e:
                log_error_to_database(user, e)

                # if a user passes a certain error threshold, mark them as
                # inactive, they probably revoked our access
                if db.get_field(user,
                                "error_count") > constant.ERROR_THRESHOLD:
                    try:
                        db.update_user(user, "active", "false")
                    except Exception:
                        print("Could not set user to inactive")
Beispiel #27
0
def dump_users(db_con, group=None, filename=None, report_format="csv"):
    """ writes the tweets to the reports folder.
        format must be one of csv or json
    """
    users, header = db.get_users(db_con, group)

    # set a default filename in the reports directory if none is provided
    if filename is None:
        filename = os.path.join("reports", "tweets.{0}".format(report_format))

    with open(filename, "wb") as f:
        if report_format == "json":
            f.write(json.dumps(users))

        elif report_format == "csv":
            writer = csv.writer(f, delimiter=",")

            writer.writerow(header)
            for user in users:
                writer.writerow([user[k].encode("utf-8") for k in header])
        else:
            raise Exception("Format must be csv or json")
Beispiel #28
0
def dump_users(db_con, group=None, filename=None, report_format="csv"):
    """ writes the tweets to the reports folder.
        format must be one of csv or json
    """
    users, header = db.get_users(db_con, group)

    # set a default filename in the reports directory if none is provided
    if filename is None:
        filename = os.path.join("reports", "tweets.{0}".format(report_format))

    with open(filename, "wb") as f:
        if report_format == "json":
            f.write(json.dumps(users))

        elif report_format == "csv":
            writer = csv.writer(f, delimiter=",")

            writer.writerow(header)
            for user in users:
                writer.writerow([user[k].encode("utf-8") for k in header])
        else:
            raise Exception("Format must be csv or json")
Beispiel #29
0
def get_users():
    return database.get_users()
Beispiel #30
0
    def run(self):
        print("Starting " + self.name)
        global running
        global doctor_test
        global doctor_id
        doctor_test = False

        # Prompt loop
        while running:
            cmd = input("> ")
            if cmd == "exit":
                running = False
                database.close()
                print("Exiting now")
                sys.exit(0)

            # command for logging in with username and password if the username and password are valid
            #  doctor_test is set to true and doctor id is set to the corresponding id so the database can be edited
            if cmd == "login":
                doctors = database.get_users_by_role('doc')
                print("Please login to make changes.")
                login_username = input("Username: "******"Password: "******"Logged in as doctor id: " + str(doctor_id))
                        doctor_test = True
                if not doctor_test:
                    print("Invalid credentials!")

            # when logging out doctor test is set to false so no changes can be made
            # doctor id is set to 0 so nobody can actually see who was the last doctor to log in
            if cmd == "logout" and doctor_test:
                doctor_test = False
                print("Logged out as doctor id: " + str(doctor_id))
                doctor_id = 0

            # to update credentials you must be logged in as a doctor and you have to verify your login data again
            if cmd == "update credentials" and doctor_test:
                user = database.get_user_by_uid(doctor_id)
                print("Please verify your login.")
                login_username = input("Old username: "******"Old password: "******"New username = "******"New password = "******"Credentials updated.")

            # to update a rfid tag you have to be logged in as a doctor and you have to input a user_id to which the new rfid will be bound
            if cmd == "update rfid" and doctor_test:
                user_id = input("User id = ")
                user = database.get_user_by_uid(user_id)
                if user is None:
                    print("No user with this id!")
                    continue

                new_rfid = input("New rfid = ")
                user.rfid = new_rfid
                database.update_user(user)
                database.commit()
                print("rfid updated.")

            # when logged in as a doctor you can get all users with their roles (but not password or rfid)
            if cmd == "get users" and doctor_test:
                users = database.get_users()
                print("id\trole")
                for user in users:
                    print(str(user.id) + "\t" + str(user.role))

            # when logged in you can get prescriptions for a single user or you can get all prescriptions
            if cmd == "get prescriptions" and doctor_test:
                choice = input("For all users y/n: ")
                prescriptions = database.get_prescriptions()
                if choice == "y":
                    print("id\tmedicine\tdescription")
                    for prescription in prescriptions:
                        print(str(prescription.id) + "\t"  + str(prescription.medicine_id) + "\t\t\t" + str(prescription.descr))
                elif choice == "n":
                    user_id = int(input("id = "))
                    print("id\tmedicine\tdescription")
                    for prescription in prescriptions:
                        if prescription.uid == user_id:
                            print(str(prescription.id) + "\t" + str(prescription.medicine_id) + "\t\t\t" + str(prescription.descr))
                else:
                    print("Invalid input!")

            # as a logged in doctor you can add prescriptions. you will be prompted for all the data
            if cmd == "add prescription" and doctor_test:
                prescriptions = database.get_prescriptions()
                prescription_list = []
                for prescription in prescriptions:
                    prescription_list.append(prescription.id)
                prescription_id = int(max(prescription_list) + 1)
                patient_id = int(input("Patient id = "))
                medicine_id = int(input("Medicine id = "))
                description = input("Description of use = ")
                max_dose = int(input("Daily max dose = "))
                min_time = int(input("Minimum time between dispenses in seconds = "))
                amount = int(input("Amount of medicine per dispense/dose = "))
                cur_dose = 0
                duration = int(input("Prescription duration in days = ")) * 86400
                date = int(calendar.timegm(time.gmtime()))

                # this part checks if the user is actually in the database else it prints "patient does not exist"
                users = database.get_users()
                patient_test = False
                for user in users:
                    if patient_id == user.id:
                        print("New prescription added with id: " + str(prescription_id))
                        database.insert_prescription(Prescription.parse_raw([prescription_id, patient_id, medicine_id, description, max_dose, min_time, amount, cur_dose, date, doctor_id, duration, date]))
                        database.commit()
                        patient_test = True
                if not patient_test:
                    print("Patient does not exist!")

            # as a logged in doctor you can remove a prescription by id
            if cmd == "remove prescription" and doctor_test:
                prescription_id = int(input("prescription id = "))
                database.remove_prescription(prescription_id)
                database.commit()
                print("Prescription removed.")

            # as a logged in doctor you can add new users. you get prompted for all data (and for username and pw if you are adding a doctor)
            if cmd == "add user" and doctor_test:
                users = database.get_users()
                user_list = []
                for user in users:
                    user_list.append(user.id)
                user_id = int(max(user_list) + 1)
                rfid = int(input("RFID = "))
                role = input("role(pat/doc/ref) = ")
                if role == 'doc':
                    new_username = input("New user username = "******"New user password = "******""
                    new_password = ""
                database.insert_user(User.parse_raw([user_id, rfid, role, new_username, new_password]))
                database.commit()
                print("New user added with id: " + str(user_id))

            # as a logged in doctor you can remove users by id
            if cmd == "remove user" and doctor_test:
                user_id = int(input("User id = "))
                database.remove_user(user_id)
                database.commit()
                print("User removed.")

            # you can always print out all existing commands
            if cmd == "help":
                commands = ["login",
                            "logout",
                            "exit",
                            "get prescriptions",
                            "add prescription",
                            "remove prescription",
                            "add user",
                            "remove user",
                            "update credentials",
                            "update rfid"]
                print("Commands:", commands)


         # threads.remove(self)
        print("Exiting " + self.name)
def auth_register(email, password, name_first, name_last):
    """ Register a user into the database given details in parameters. """

    # Check if email is already being used by another user
    for user in database.get_users():
        if user['email'] == email:
            raise error.InputError(
                description="The email you entered is already being used")

    # Check if password is less than 6 characters long
    if len(password) < 6:
        raise error.InputError(
            description="""The password you entered is less than 6 characters
                                           long""")

    # Check if name_first is between 1 and 50 characters inclusive in length
    if len(name_first) < 1 or len(name_first) > 50:
        raise error.InputError(
            description="""The first name you entered is not between 1 and 50
                                           characters in length inclusive""")

    # Check if name_last is between 1 and 50 characters inclusive in length
    if len(name_last) < 1 or len(name_last) > 50:
        raise error.InputError(
            description="""The last name you entered is not between 1 and 50
                                           characters in length inclusive""")

    # First we need to create a handle_str
    handle_str = name_first.lower() + name_last.lower()

    # If len(handle_str) > 20 then we need to cut the handle_str to an appropriate length
    if len(handle_str) > 20:
        handle_str = handle_str[:20]

    # Check if handle_str is already taken and modify appropriately
    handle_str = create_handle_str(handle_str)

    # Now we need to assign a u_id
    # u_id generated in order of registration
    # Add 1 to u_id of most recent user
    u_id = database.generate_u_id()

    # Now we add user to the list of dictionaries
    user = {
        'u_id': u_id,
        'email': email,
        'name_first': name_first,
        'name_last': name_last,
        'handle_str': handle_str,
        'profile_img_url': DEFAULT_USER_IMG
    }

    # Now check if this is the first person to join the slackr
    if database.get_users() == []:
        database.set_permissions(u_id, 1)
    else:
        database.set_permissions(u_id, 2)

    database.set_user_data(user)

    # Encode the password
    passcode = hashlib.sha256(password.encode()).hexdigest()

    # Associate email to password in PASSWORD_DATA
    database.set_password(email, passcode)

    # We now login the user using auth_login
    return auth_login(email, password)
Beispiel #32
0
def users():
    with db, db.cursor() as cursor:
        users = database.get_users(cursor)
    return flask.render_template('users.html', users=users)
Beispiel #33
0
def manage_users():
    users = database.get_users(include_inactive=True)
    users = sorted(users, key=lambda x: x.active, reverse=True)
    return render_template("admin/manage_users.html", users=users)
def get_users():
    users = db.get_users()
    if (len(users) == 0):
        return make_response(jsonify({'error': 'There are no users in the database!'}), 404)
    else:
        return make_response(jsonify(users), 200)
def manage_users():
    users = database.get_users()
    return render_template("admin/manage_users.html", users=users)
Beispiel #36
0
def get_users():
    page['title'] = 'Users'
    users = database.get_users()
    return render_template('users.html', page = page, users = users)
def get_data():
    return get_users()