Пример #1
0
def login():
    form = LoginForm()
    db = get_db()

    if form.validate_on_submit():
        user_cur = db.execute(
            'select id, username, password from users where username = ?',
            [form.username.data])
        user = user_cur.fetchone()

        try:
            if check_password_hash(user['password'], form.password.data):
                login_user(load_user(user['id']))
                return redirect(url_for('messenger'))

            return render_template('login.html',
                                   form=form,
                                   message='Incorrect password!')

        except TypeError:
            return render_template('login.html',
                                   form=form,
                                   message='You are not registered yet!')

    return render_template('login.html', form=form)
Пример #2
0
def validate_2fa(name):
    form = forms.SignTokenForm()
    if form.validate_on_submit():
        errorCode = json.loads(form.response.data)['errorCode']
        if errorCode != 0:
            flash("Token authentication failed", "error")
            return redirect(url_for('select_2fa'))
        device, c, t = complete_authentication(session['u2f_sign'],
                                               form.response.data, app_id)
        if t != 1:
            flash("Token authentication failed", "error")
            return redirect(url_for('select_2fa'))
        # Log in the user
        user = load_user(session['user'])
        flask_login.login_user(user)
        flash("Login complete", "success")
        return redirect(url_for('index'))
    key = models.U2FCredentials.query.filter_by(owner=session['user'],
                                                name=name).first()
    sign = begin_authentication(app_id, [key.device])
    session['u2f_sign'] = sign.json
    challenge = sign['challenge']
    registeredKeys = json.loads(sign['registeredKeys'][0])
    version = registeredKeys['version']
    keyHandle = registeredKeys['keyHandle']

    return render_template('validate_2fa.html',
                           challenge=challenge,
                           version=version,
                           keyHandle=keyHandle,
                           app_id=app_id,
                           form=form,
                           key=key)
def colorize(pid):
    user = load_user(pid)
    if user:
        user.randomizeColor()
        return responses.user_updated(request.url, user.pid)
    else:
        return responses.invalid(request.url, "User does not exist")
def index():
    form = IndexForm()
    if form.login.validate_on_submit() and form.login.submit.data:
        preparedQuery = 'SELECT * FROM Users WHERE username=?;'
        user = safe_query(preparedQuery, (form.login.username.data.lower(),), one=True)
        if user is None:
            flash('Sorry, invalid credentials!')
        elif check_password_hash(user['password'], form.login.password.data):
            app_user = load_user(int(user['id']))
            login_user(app_user)
            return redirect(url_for('stream'))
        else:
            flash('Sorry, invalid credentials!')

    elif form.register.validate_on_submit() and form.register.submit.data:
        preparedQuery = 'SELECT * FROM Users WHERE username=?;'
        existing_user = safe_query(preparedQuery, (form.register.username.data.lower(),), one=True)

        if existing_user is not None:
            flash('Sorry, invalid username!')
        elif form.register.password.data != form.register.confirm_password.data:
            flash('Passwords do not match!')
        else:
            preparedQuery = 'INSERT INTO Users (username, first_name, last_name, password) VALUES(?,?,?,?);'
            data = (form.register.username.data.lower(), form.register.first_name.data,
                form.register.last_name.data, generate_password_hash(form.register.password.data))
            safe_query(preparedQuery, data)
            return redirect(url_for('index'))
    return render_template('index.html', title='Welcome', form=form)
def user(pid):
    """
    GET - gets the user with pid
    PUT - updates the user with pid
    DELETE - removes the user with pid
    """
    user = load_user(pid)
    # print(current_user.pid)
    # print(str(current_user.pid) == str(pid))

    if user:

        if request.method == "DELETE" and current_user.is_admin:
            user.delete()
            return responses.success(url_for("user", pid=pid), "USER DELETED")

        elif request.method == "PUT" \
            and ( current_user.is_admin or current_user.pid == int(pid) ):

            # Allow user updates
            payload = None

            try:
                payload = json.loads(request.data.decode("utf-8"))
            except Exception as e:
                return responses.invalid(request.url, e)

            if not current_user.is_admin:
                keys = deepcopy(list(payload.keys()))
                for key in keys:
                    if key not in user.updatable_fields:
                        payload.pop(key)

            if payload:
                success = user.update(payload)
                if success:
                    return responses.user_updated(request.url, user.pid)
                else:
                    return responses.invalid(request.url,
                                             "Could not update user")
            else:
                return responses.invalid(request.url, "No data")

        elif request.method == "GET":
            response = """{{
                    "user": {user},
                    "open":{first_open},
                    "close":{last_close}
                }}""".format(user=user.to_json(),
                             first_open=models.Location.get_first_open(),
                             last_close=models.Location.get_last_close())
            return Response(response, mimetype="application/json")

        else:
            responses.invalid(request.url, "Method not supported")
    else:
        return responses.invalid(request.url, "User does not exist")
def user_schedule(pid):
    user = load_user(pid)
    if user:
        return render_template(
            "user_schedule.html",
            user=user,
            active_schedule=models.GlobalConfig.get().active_schedule)
    else:
        return responses.invalid(request.url, "User does not exist")
    pass
def schedule_data_to_events(s):

    events = []
    userColors = dict()
    id_counter = 1

    schedule_data = json.loads(s.to_json())
    # print (schedule_data['data'])
    for d in schedule_data['data']:
        for day, timeslots in d["schedule"].items():
            for i in range(len(timeslots)):
                for pid in timeslots[i]:
                    if pid != None:
                        # if not pid in userColors:
                        #     userColors[pid] = HSVtoRGB(random.random(), 0.5, 0.95)
                        u = load_user(pid)
                        l = load_location(d['code'])
                        if u and l:
                            events.append({
                                '_id':
                                id_counter,
                                'title':
                                str(u.first_name + " " + u.last_name[0] + "."),
                                'pid':
                                pid,
                                'location':
                                str(l.name),
                                'lcode':
                                l.code,
                                '_index':
                                i,
                                'start':
                                index2time(i),
                                'end':
                                index2time(i + 1),
                                'dow': [{
                                    "sun": 0,
                                    "mon": 1,
                                    "tue": 2,
                                    "wed": 3,
                                    "thu": 4,
                                    "fri": 5,
                                    "sat": 6
                                }[day]],
                                'textColor':
                                '#000000',
                                'backgroundColor':
                                u.color
                            })
                            id_counter += 1
    return events
Пример #8
0
def login():
    form = LoginForm()
    if request.method == "POST":
        pass
    # change this to actually validate the user
    if form.username.data:
        # login and validate the user...

        # missing
        # based on password and username
        # get user id, load into session
        user = load_user("1")
        login_user(user)
        #flash("Logged in successfully.")
        return redirect(request.args.get("next") or url_for("home"))
    return render_template("login.html", form=form)
Пример #9
0
def login():
    form = LoginForm()
    if request.method == "POST":
        pass
    # change this to actually validate the user
    if form.username.data:
        # login and validate the user...

        # missing
        # based on password and username
        # get user id, load into session
        user = load_user("1")
        login_user(user)
        #flash("Logged in successfully.")
        return redirect(request.args.get("next") or url_for("home"))
    return render_template("login.html", form=form)
def set_availability(pid):
    """
    View for a user to set their own availability
    Method:
        1) Generate the UI
        2) POST the updates to /api/user/<id>

    TODO: Found bug.  Admin can see all users.
    """
    user = load_user(pid)
    if user:
        return render_template(
            "user_availability.html",
            user=user,
            active_schedule=models.GlobalConfig.get().active_schedule)
    else:
        return responses.invalid(request.url, "User does not exist")
Пример #11
0
def login():
    if request.method == 'GET':
        if not users.count():
            return redirect(url_for('.firstregister'))

        return render_template('login.html')

    username = request.form['username']
    password = request.form['password']
    registered_user = users.find_one({'username': username})

    if bcrypt.hashpw(password, registered_user['password']) == registered_user['password']:
        user = load_user(registered_user['_id'])
        login_user(user)
        print current_user
        flash('Vous êtes authentifié')
    else:
        flash('Le login ou le password sont invalides' , 'error')
        return redirect(url_for('.login'))

    return redirect(request.args.get('next') or '/')
def my_schedule_data(code):
    """
    Returns the scheduled events of the current_user
    """
    s = models.Schedule.objects().get(sid=code)
    if s:
        events = []
        id_counter = 1
        if request.method == "GET":
            schedule_data = json.loads(s.to_json())
            # print (schedule_data['data'])
            for d in schedule_data['data']:
                for day, timeslots in d["schedule"].items():
                    for i in range(len(timeslots)):
                        for pid in timeslots[i]:
                            if pid == str(current_user.pid):
                                u = load_user(pid)
                                l = load_location(d['code'])
                                if u and l:
                                    events.append({
                                        '_id':
                                        id_counter,
                                        'title':
                                        str(u.first_name + " " +
                                            u.last_name[0] + "."),
                                        'pid':
                                        str(pid),
                                        'location':
                                        str(l.name),
                                        'lcode':
                                        l.code,
                                        '_index':
                                        i,
                                        '_endex':
                                        i + 1,
                                        'start':
                                        index2time(i),
                                        'end':
                                        index2time(i + 1),
                                        'dow': [{
                                            "sun": 0,
                                            "mon": 1,
                                            "tue": 2,
                                            "wed": 3,
                                            "thu": 4,
                                            "fri": 5,
                                            "sat": 6
                                        }[day]],
                                        'textColor':
                                        '#000000',
                                        'backgroundColor':
                                        u.color
                                    })
                                    id_counter += 1
            events = combineEvents(events)
            return Response(json.dumps(events), mimetype='application/json')

        else:
            return responses.invalid(url_for("schedule", code=code),
                                     "METHOD not supported.")
    else:
        return responses.invalid(url_for("schedule", code=code),
                                 "Schedule ID not found")
Пример #13
0
def test_init_load_user(client):
    try:
        from app import load_user
        load_user(1)
    except:
        pass