Пример #1
0
    def login():
        """Log user in"""

        # Forget any user_id
        session.clear()

        # User reached route via POST (as by submitting a form via POST)
        if request.method == "POST":

            username = request.form.get("username")

            # Ensure username was submitted
            if not username:
                return apology("must provide username", 403)

            # Ensure password was submitted
            elif not request.form.get("password"):
                return apology("must provide password", 403)

            # Ensure username exists and password is correct
            if not has_username(username) or not check_password_hash(
                    get_phash(username), request.form.get("password")):
                return apology("invalid username and/or password", 403)

            # Remember which user has logged in
            session["user_id"] = get_user_id(username)

            # Redirect user to home page
            return redirect("/")

        # User reached route via GET (as by clicking a link or via redirect)
        else:
            return render_template("login.html")
Пример #2
0
def register():
    """Registers the user."""
    if g.user:
        return redirect(url_for('timeline'))
    error = None
    if request.method == 'POST':
        if not request.form['username']:
            error = 'You have to enter a username'
        elif not request.form['email'] or \
                 '@' not in request.form['email']:
            error = 'You have to enter a valid email address'
        elif not request.form['password']:
            error = 'You have to enter a password'
        elif request.form['password'] != request.form['password2']:
            error = 'The two passwords do not match'
        elif get_user_id(request.form['username']) is not None:
            error = 'The username is already taken'
        else:
            db = get_db()
            db.execute('''insert into user (
              username, email, pw_hash) values (?, ?, ?)''',
              [request.form['username'], request.form['email'],
               generate_password_hash(request.form['password'])])
            db.commit()
            flash('You were successfully registered and can login now')
            return redirect(url_for('login'))
    return render_template('register.html', error=error)
Пример #3
0
def user_page(name):
    if request.method == 'POST':
        user_id = get_user_id(name)
        title = request.form['title']
        content = request.form['content']
        end_date = request.form['end_date']
        add_task(user_id, title, content, end_date)
    user_tasks = get_tasks(name)
    return render_template('user.html', name=name, tasks=user_tasks)
Пример #4
0
def run():
    # greeet
    helper.print_with_line(texts.welcome)
    # log in
    user_name = log_in()
    # get user id
    user_id   = db.get_user_id(user_name)

    while True:
        main_menu(user_id)
Пример #5
0
def add_order():
    """
    """
    date_placed = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    total =0
    products = []
    for x in session['cart']:
        products.append([x['item'], x['size'], x['quantity'], x['price']])
        total += x['price']*x['quantity']
    order_nr = db.add_new_order(db.get_user_id(session['username']), date_placed, products, total)
    session['cart'] = []
    return render_template("cart.html")
Пример #6
0
def follow_user(username):
    """Adds the current user as follower of the given user."""
    if not g.user:
        abort(401)
    whom_id = get_user_id(username)
    if whom_id is None:
        abort(404)
    db = get_db()
    db.execute('insert into follower (who_id, whom_id) values (?, ?)',
              [session['user_id'], whom_id])
    db.commit()
    flash('You are now following "%s"' % username)
    return redirect(url_for('user_timeline', username=username))
Пример #7
0
def unfollow_user(username):
    """Removes the current user as follower of the given user."""
    if not g.user:
        abort(401)
    whom_id = get_user_id(username)
    if whom_id is None:
        abort(404)
    db = get_db()
    db.execute('delete from follower where who_id=? and whom_id=?',
              [session['user_id'], whom_id])
    db.commit()
    flash('You are no longer following "%s"' % username)
    return redirect(url_for('user_timeline', username=username))
Пример #8
0
 def like(self):
     if self.liked:
         self.liked = False
     else:
         user_id = db.get_user_id(self.master.username.get())
         self.liked = True
         track = self.playlist[self.actual_song]
         track = track[75:-5]
         if track.find('\'') == 1:
             track = track[:track.index('\'')] + '\'' + track[track.
                                                              index('\''):]
         print(f'User_id:{user_id} Track:{track}')
         db.set_like(user_id, track)
def lambda_handler(event, context):

    if event['httpMethod'] == "POST":
        
        try:
            body = json.loads(event['body'])
            user_token = body['user_token']
            print("user_token: ",user_token)
            user_api_key = body['user_api_key']
            print("user_api_key: ",user_api_key)

            user_id = get_user_id(user_token)

            if user_id:
                valid = check_account(user_api_key)
                if valid:
                    set_clockify_api_key(user_id,user_api_key)
        except : 
            return {
            'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
                'Access-Control-Allow-Credentials' : True
            },
            'body': json.dumps({"valid":False})
        }

        return {
            'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
                'Access-Control-Allow-Credentials' : True
            },
            'body': json.dumps({"valid":valid})
        }

    else:
        return {
            'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
                'Allow': 'OPTIONS,POST,GET',
                'Access-Control-Allow-Credentials' : True,
            },
        }
Пример #10
0
def login():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    current_app.logger.info('{} hit /login'.format(ip))
    json_input = request.get_json(force=True)

    try:
        username = json_input['username']
        password = json_input['password']
    except KeyError as e:
        return jsonify({'Error':
                        'Invalid request: Missing required field.'}), 400
    except TypeError as e:
        return jsonify({'Error': 'Invalid request: Must be a json/dict.'}), 400

    if len(username) == 0 or username == '':
        return jsonify({'Error': 'Please provide a username.'}), 400
    if len(password) == 0:
        return jsonify({'Error': 'Please provide a password'}), 400

    if not re.match("^[A-Za-z_]*$", username):
        return jsonify({'Error': 'Invalid username.'}), 400

    if request.method == 'POST':
        try:
            user_id = get_user_id(username)
            if not user_id:
                return jsonify({'Error': 'User not found.'}), 400
            user = get_user(user_id)
        except TypeError as e:
            return jsonify({'Error': 'Bad username.'}), 400

        if user and user.check_password(password):
            access_token = create_access_token(identity=user_id, fresh=True)
            refresh_token = create_refresh_token(identity=user_id)

            current_app.logger.info('Login')
            add_log_event(200, username, 'Login', ip_address=ip)

            return jsonify({
                'Token': access_token,
                'Refresh': refresh_token
            }), 200
        elif not user:
            return jsonify({'Error': 'User not found.'}), 400
        else:
            current_app.logger.info('%s failed to log in', username)
            return jsonify({'Error': 'Wrong password.'}), 403
    else:
        return jsonify({'Error': 'Request must be POST'}), 405
Пример #11
0
def parse_mentions(message):
    usernames = list()
    for mention in filter(lambda e: e["type"] == "mention", message.entities):
        usernames.append(message.text[mention.offset + 1:mention.offset +
                                      mention.length])
    users = dict()
    not_found_usernames = list()
    for un in usernames:
        try:
            uid = db.get_user_id(un)
        except:
            not_found_usernames.append(un)
        else:
            users[un] = uid
    return {"id": users, "not_found": not_found_usernames}
Пример #12
0
def return_room(room, username, user_id):
    new_name = room.name
    if room.is_dm:
        if user_id in room.name:  # new nomenclature: ID concatentation
            other_id = room.name.replace(user_id, '')
            if not other_id:  # DM with self – name should be self's username
                new_name = username
            else:  # lookup the name of the other user in the DM
                other_user = get_user(other_id)
                new_name = other_user.real_name
        elif username in room.name:  # old nomenclature: name concatenation
            other_username = room.name.replace(username, '')
            other_user_id = get_user_id(other_username)
            other_user = get_user(other_user_id)
            new_name = other_user.real_name
        else:  # unknown state (perhaps nomenclature changed once more)
            new_name = room.name
    return room.create_personalized_json(new_name)
Пример #13
0
def index():
    uid = get_user_id(session['current_user'])
    print uid, type(uid)
    if request.method == "POST":
        ids = [(ObjectId(k),request.json[k]) for k in request.json.keys()]
        for sample in ids:
            label_story(sample[1],uid,sample[0])
        return "{'a':1}"
    else:
        
        unlabeled_stories = get_unlabeled_stories(uid)
        #predict stories...
        for ul in unlabeled_stories:
            ul['_id'] = str(ul['_id'])
            try:
                ul['label'] = predict(ul['title'],uid)['label']
            except ZeroDivisionError:
                pass
        return render_template('index.html',stories=unlabeled_stories)
Пример #14
0
    def post(self):
        logging.debug("xsrf_cookie:" + self.get_argument("_xsrf", None))

        self.check_xsrf_cookie()

        username = self.get_argument("username")
        password = self.get_argument("password")

        logging.debug('AuthLoginHandler:post %s %s' % (username, password))
        user_id = db.get_user_id(username, password)

        if user_id != None:
            self.set_current_user(username)
            for waiter in waiters:
                print("new user notification")
                waiter[0].write_message({'newuser': username})
            self.redirect('/')

        else:
            self.render("login_error.html")
Пример #15
0
 def add_to_list(self):
     user_id = db.get_user_id(self.master.username.get())
     directory = db.get_songs_list(user_id)
     # appends song directory on disk to playlist in memory
     for song_dir in directory:
         self.playlist.append(song_dir)
Пример #16
0
def liked():
    uid = get_user_id(session['current_user'])
    liked_stories = get_liked_stories(uid)
    return render_template('liked.html',stories=liked_stories)
Пример #17
0
def toggle_room_admin(room_id):
    username = get_jwt_identity()
    user_id = get_user_id(username)
    toggle_admin(room_id, user_id)

    return jsonify({'Success': 'Toggled admin'})
Пример #18
0
    def __init__(self,mail="*****@*****.**"):
        self.uid = db.get_user_id(mail)

        if self.uid < 0 :
            self.uid = db.create_new_user(mail)
Пример #19
0
def update_last_seen(username):
    user_id = get_user_id(username)
    update_checkout(user_id)
Пример #20
0
def account():
    id = db.get_user_id("test@test")
    return "Hello / account" + str(id)
Пример #21
0
def orders():
    order_list = db.get_user_orders(db.get_user_id(session['username']))
    return render_template("orders.html", order_list=order_list)
Пример #22
0
def login(email, password):
    if db.auth_user(email, password):
        session['u_id'] = db.get_user_id(email)
        return True
    return False
Пример #23
0
def main():
    helper.print_with_line(texts.welcome)
    user_name = log_in()
    user_id = db.get_user_id(user_name)
    while True:
        helper.print_with_line(texts.menu, ref=True, n=0, title="Main menu")
        answer = helper.press_any_key(s="Enter your choice\n> ", inp=True)
        try:
            if answer == '1':
                data = interractive_get_index()
                print(data)

            elif answer == '2':
                db.fetch_nutrient(user_id=user_id,
                                  nutrients=['ndbno', 'name'],
                                  limit=15,
                                  printing=True)
                print("here is your most recent 15 entrees")
                ndbno = input(
                    "Enter food's NDBNO if you know or look it up in main menu:\n> "
                )
                data = fetch_nutrition(ndbno)
                db.log_food(data, user_id)

            elif answer == '3':
                helper.print_with_line(texts.vizualization_3,
                                       ref=True,
                                       n=30,
                                       title="Vizualization")
                sub_choice = helper.press_any_key(s="Enter your choice > ",
                                                  inp=True)
                if sub_choice == '1':
                    indexes = db.fetch_nutrient(user_id, nutrients=['269'])
                    render.bar_graph(indexes, name="Health Index over Time")
                elif sub_choice == '2':
                    sugar = db.fetch_nutrient(user_id, nutrients=['Index'])
                    render.bar_graph(sugar, name="Sugar Graph over Time")
                elif sub_choice == '3':
                    data = db.fetch_nutrient(user_id,
                                             nutrients=['269', 'Index'])
                    print(data)
                    render.bar_graph(data)

            elif answer == 'exit':
                helper.simple_print(texts.bye)
                break
            else:
                print("error #3")
                helper.print_with_line(texts.error.format(answer), ref=False)
                helper.pause(3)

        except Exception as err:
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            del exc_info

            print(err)
            print("error #4")
            helper.print_with_line(texts.fatal_error, ref=False)
            helper.pause(3)
            continue
Пример #24
0
    def __init__(self, mail="*****@*****.**"):
        self.uid = db.get_user_id(mail)

        if self.uid < 0:
            self.uid = db.create_new_user(mail)