Example #1
0
def load_logged_in_user():
    user_id = session.get('user_id')
    if not user_id:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
Example #2
0
def configure(print):
    if req.method == 'POST':
        old_pw = req.form['old-pw'].lstrip().rstrip()
        new_pw = req.form['new-pw'].lstrip().rstrip()
        new_pw_confirm = req.form['new-pw-confirm'].lstrip().rstrip()
        username = g.user['username']

        err = None
        if not check_password_hash(g.user['password'], old_pw):
            err = ERR.CONFIGURE.FAIL.PW
        if new_pw is not None and new_pw != new_pw_confirm:
            err = ERR.REGISTER.WRONG.PW

        if not err:
            db = get_db()
            err = ERR.CONFIGURE.SUCCESS
            if new_pw is not None:
                db.execute(
                    "UPDATE user SET username = ?, password = ? WHERE email = ?",
                    (username, generate_password_hash(new_pw),
                     g.user['email']))
            else:
                db.execute("UPDATE user SET username = ? WHERE email = ?",
                           (username, ))
            db.commit()
            print("Success / user_id:{}".format(g.user['id']))

        flash(err)
        print("Fail / user_id:{}".format(g.user['id']))
        return redirect(url_for('auth.configure'))
    data = dict(VERIFIED=g.user['verified'])
    print("Access config page / user_id:{}".format(g.user['id']))
    return render_template('auth/configure.html', data=data)
Example #3
0
def login(print):
    if g.user:
        print("Already Login / user_id:{}".format(g.user['id']))
        return redirect(url_for('mark.index'))
    if req.method == 'POST':
        pw = req.form['pw'].lstrip().rstrip()
        email = req.form['email'].lstrip().rstrip()
        db = get_db()
        err = None

        user = db.execute('SELECT * FROM user WHERE email = ?',
                          (email, )).fetchone()

        if not user:
            err = ERR.LOGIN.INCORRECT.EMAIL
        elif not check_password_hash(user['password'], pw):
            err = ERR.LOGIN.INCORRECT.PW
        else:
            pass
        if not err:
            session.clear()
            session['user_id'] = user['id']
            print("Login / user_i:{}".format(user['id']))
            return redirect(url_for('mark.index'))
        flash(err)
    return render_template('auth/login.html')
Example #4
0
def del_user(print):
    user_id = g.user['id']
    email = g.user['email']
    db = get_db()
    db.execute('DELETE FROM user WHERE id=?', (user_id, ))
    db.execute('DELETE FROM mark WHERE user_id=?', (user_id, ))
    db.commit()
    flash("{} {}".format(email, ERR.DEL.USER))
    print("user_id:{}, email:{} removed".format(user_id, email))
    return redirect(url_for('auth.logout'))
Example #5
0
def get_ogtag(print, link):
    db = get_db()
    bin_og = db.execute('SELECT bin_meta FROM meta WHERE link=?',
                        (link, )).fetchone()
    if not bin_og:
        return None
    else:
        bin_og = bin_og['bin_meta']
        meta_og = mg.unpackb(bin_og, raw=False)
        meta_og = objFromDict(meta_og)
        return meta_og
Example #6
0
def del_link(print, link):
    db = get_db()
    index = req.url.index('/del/')
    link = req.url[index + len('/del/'):]
    link = complete_link(link)
    db.execute('DELETE FROM mark WHERE user_id=? AND link=?',
               (g.user['id'], link))
    db.commit()
    print("Delete / link:{}, user_id:{}".format(link, g.user['id']))
    flash(ERR.DEL.LINK)
    return redirect(url_for('mark.index'))
Example #7
0
def visit_link(print, link):
    db = get_db()
    index = req.url.index('/link/')
    link = req.url[index + len('/link/'):]
    link = complete_link(link)
    user_id = g.user['id']
    db.execute(
        'UPDATE mark SET view_count=view_count+1 WHERE user_id=? AND link=?',
        (user_id, link))
    db.commit()
    print("link:{}, user_id:{}".format(link, user_id))
    return redirect(link)
Example #8
0
def verify(print):
    email_hash = req.args.get('h')
    #still thinking... is timestamp required?
    time = req.args.get('timestamp')
    if not email_hash or not time: abort(404)
    db = get_db()
    user = db.execute('SELECT id,email FROM user WHERE email_hash = ?',
                      (email_hash, )).fetchone()

    if user:
        db.execute('UPDATE user SET verified=? WHERE id=?', (1, user['id']))
        db.commit()
        print("Verified / user_id:{}, email:{}".format(user['id'],
                                                       user['email']))
        return render_template('auth/verified.html', email=user['email'])
    else:
        abort(404)
Example #9
0
def add_tag(print):
    db = get_db()
    if req.method == 'POST':
        tag = req.form['tag'].lstrip().rstrip()
        link = complete_link(req.form['link'].lstrip().rstrip())
        user_id = g.user['id']
        if not tag:
            return redirect(url_for('mark.index'))
        tag = tag.replace(' ', '')
        if not tag.startswith('#'):
            tag = "#{}".format(tag)

        db.execute('UPDATE mark SET tag = tag||? WHERE user_id=? AND link=?',
                   (tag, user_id, link))
        db.commit()
        print("tag:{}, user_id:{}, link:{}".format(tag, user_id, link))

        return redirect(url_for('mark.index'))
Example #10
0
def sign_up(print):
    if req.method == 'POST':
        username = req.form['username'].lstrip().rstrip()
        pw = req.form['pw'].lstrip().rstrip()
        pw_confirm = req.form['pw-confirm'].lstrip().rstrip()
        email = req.form['email'].lstrip().rstrip()
        db = get_db()
        err = None
        if not username: err = ERR.REGISTER.REQUIRED.USERNAME
        elif not pw: err = ERR.REGISTER.REQUIRED.PW
        elif pw != pw_confirm: err = ERR.REGISTER.WRONG.PW
        elif not email: err = ERR.REGISTER.REQUIRED.EMAIL
        elif db.execute('SELECT id FROM user WHERE email = ?',
                        (email, )).fetchone():
            err = "{} {}".format(email, ERR.REGISTER.ENROLLED)
        elif db.execute(
                'SELECT id FROM user WHERE username = ?',
            (username, )).fetchone() or not available_username(username):
            err = "{} {}".format(username, ERR.REGISTER.ENROLLED)
        else:
            pass

        if not err:
            email_hash = hash(email)
            try:
                db.execute(
                    'INSERT INTO user (username,email,email_hash,password) VALUES (?,?,?,?)',
                    (username, email, email_hash, generate_password_hash(pw)))
                db.commit()
                #TODO : send email to verify email address
                flash(ERR.REGISTER.SUCCESS)
                print("Sign-up / username:{}, email:{}".format(
                    username, email))
                authenticate_user(username, email, email_hash, req.host)
                return redirect(url_for('auth.login'))
            except:
                print(tb.format_exc())
                err = ERR.REGISTER.WRONG.EMAIL
        flash(err)
    print("Access register page")
    return render_template('auth/register.html')
Example #11
0
def tag_index(print):
    db = get_db()
    tag = req.args.get('tag')
    user_id = g.user['id']
    marks = db.execute(
        "SELECT * FROM mark WHERE user_id={} AND tag LIKE '%{}%' ORDER BY id DESC"
        .format(user_id, tag)).fetchall()
    tags = generate_tag_table(marks)
    all_tags = db.execute('SELECT tag FROM mark WHERE user_id = ?',
                          (g.user['id'], )).fetchall()
    all_tags = generate_tag_table(all_tags)
    tag_counter = count_tag_table(all_tags)
    og_tags = {mark: get_ogtag(mark['link']) for mark in marks}
    data = dict(marks=marks,
                counts=len(marks),
                tags=tags,
                target_tag=tag,
                tag_counter=tag_counter,
                og_tags=og_tags)
    print("Tag selected / tag:{}, user_id:{}".format(tag, g.user['id']))
    return render_template('mark/marks.html', data=data)
Example #12
0
def del_tag(print):
    if req.method != 'POST':
        return redirect(url_for('mark.index'))

    link = req.form['link'].lstrip().rstrip()
    tag = req.form['tag'].lstrip().rstrip()
    db = get_db()
    if link is not None and tag is not None:
        user_id = g.user['id']
        tags = db.execute('SELECT tag FROM mark WHERE user_id=? AND link=?',
                          (user_id, link)).fetchone()['tag']
        if tags:
            tags = tags.split('#')
            tags = [t for t in tags if t != tag]
            update_tag = ""
            for t in tags:
                update_tag += "#{}".format(t)
            db.execute('UPDATE mark SET tag=? WHERE user_id=? AND link=?',
                       (update_tag, user_id, link))
            db.commit()
            print("tag:{}, user_id:{}, link:{}".format(tag, user_id, link))
    return redirect(url_for('mark.index'))
Example #13
0
def add_ogtag(print, link, default_img=None):
    db = get_db()
    req = Request(link, headers={'User-Agent': 'Mozilla/5.0'})
    print(req.__dict__)
    context = ssl._create_unverified_context()
    try:
        html = urlopen(req, context=context, timeout=2)
        meta_og = og.OpenGraph(html=html.read(), scrape=True)
    except:
        print(tb.format_exc())
        meta_og = og.OpenGraph()
    if not meta_og.valid_attr('title'): meta_og.title = req.host
    if not meta_og.valid_attr('image'): meta_og.image = default_img
    if not meta_og.valid_attr('description'): meta_og.description = link

    print(meta_og)
    if meta_og.image is not None and not meta_og.image.startswith(
            'http') and meta_og.image != "":
        if meta_og.image.startswith('/'):
            root = req.host
        else:
            root = req.host + req.selector[:req.selector.rfind('/')]
        imgsrc = "{}://{}/{}".format('http', root, meta_og.image)
        meta_og.image = imgsrc

    bin_og = mg.packb(meta_og, use_bin_type=True)
    already_inserted = db.execute('SELECT id FROM meta WHERE link=?',
                                  (link, )).fetchone()
    if already_inserted:
        db.execute('UPDATE meta SET bin_meta=? WHERE link=?', (bin_og, link))
    else:
        db.execute('INSERT INTO meta (link,bin_meta)VALUES(?,?)',
                   (link, bin_og))
    db.commit()
    print("refresh og tag / link:{}".format(link))
    return True
Example #14
0
def index(print, link=None):
    db = get_db()
    if link is not None and '/' in link:
        index = link.index('/')
        username = link[:index]
        if not available_username(username):
            return abort(404)

        index = req.url.index("{}/".format(username))
        link = req.url[index + len(username) + 1:]
        #complete link url to redirect
        link = complete_link(link)

        #return "{} {}".format(username,link)
        user = db.execute(
            'SELECT id,email,verified FROM user WHERE username = ?',
            (username, )).fetchone()

        if not user:
            print("Not user / username:{}, link:{}".format(username, link))
            return render_template('mark/no_user.html',
                                   username=username,
                                   link=link)

        if user['verified'] != 1:
            flash(ERR.UNVALID.VERIFY)
            print("Unverified / user_id:{}".format(user['id']))
            return redirect(url_for('auth.login'))

        already_inserted = db.execute(
            'SELECT link FROM mark WHERE user_id=? AND link=?',
            (user['id'], link)).fetchone()

        if already_inserted:
            print("Already_inserted / user_id:{}, link:{}".format(
                user['id'], link))
            return render_template('mark/already_inserted.html',
                                   username=username,
                                   link=link)
        else:
            add_ogtag(link)
            db.execute('INSERT INTO mark (user_id,link) VALUES (?,?)',
                       (user['id'], link))
            db.commit()
            #TODO : send email
            print("Add link / user_id:{}, link:{}".format(user['id'], link))
            return redirect(link)

    if link: abort(404)
    if not g.user:
        #render introduction
        print("Unknown user visits ppaa.me /")
        return render_template('mark/index.html')
    else:
        marks = db.execute(
            'SELECT * FROM mark WHERE user_id = ? ORDER BY id DESC',
            (g.user['id'], )).fetchall()
        tags = generate_tag_table(marks)
        tag_counter = count_tag_table(tags)
        og_tags = {mark: get_ogtag(mark['link']) for mark in marks}
        data = dict(marks=marks,
                    counts=len(marks),
                    tags=tags,
                    tag_counter=tag_counter,
                    og_tags=og_tags)
        print("Access marks / user_id:{}".format(g.user['id']))
        return render_template('mark/marks.html', data=data)