def your_passwords(): 
    if request.method == 'POST': 
        if 'Delete Password' in request.form.values():
            for key in request.form:
                split_key = key.split('_')
                if split_key[0] == 'delete':
                    id = split_key[1]

            query("""DELETE FROM passwords
                    WHERE id=?""", [id])   
            
            return redirect(url_for('your_passwords'))
        return redirect(url_for('your_passwords'))
    else: 
        if 'username' not in session: # User not logged in
            return redirect(url_for('login'))

        passwords = query("""SELECT id, website
                                FROM passwords
                                WHERE uid IN (
                                    SELECT id
                                    FROM users
                                    WHERE username=?
                                )""", [session['username']])
        
        context = {
            'passwords': [list(row) for row in passwords]
        }

        return render_template('your_passwords.html', **context)
Beispiel #2
0
def signup():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        user_exists_check = query(
            """SELECT *
                                        FROM users
                                        WHERE username = ?""", [username])

        if len(user_exists_check):
            flash('User already exists')
            return redirect('signup')

        hashed_password = hashpw(password.encode(), gensalt(14))

        query(
            """INSERT INTO USERS
                (username, password)
                VALUES (?, ?)""",
            [username, hashed_password.decode()])

        session['username'] = username

        return redirect(url_for('login'))
    else:
        if 'username' in session:  # User already logged in
            return redirect(url_for('login'))
        else:
            return render_template('signup.html')
Beispiel #3
0
def register(form):
    err_codes = ['6']

    if not is_valid_email(form['email']):
        err_msg = "The given email has a bad format."
        err_codes.append('1')
        return util.make_result(err_msg, err_codes)

    q = 'SELECT uid FROM user WHERE uid=?'
    d = [form['uid']]
    r, err = db.query(q, d)
    if err is not None:
        return err

    if r != []:
        err_msg = 'uid "{}" is already taken.'.format(form['uid'])
        err_codes.append('2')
        return util.make_result(err_msg, err_codes)

    q = 'INSERT INTO user VALUES (?, ?, ?, ?, ?)'
    d = [
        form['uid'], form['lastname'], form['firstname'], form['email'],
        hash_pw(form['passwd'])
    ]
    r, err = db.query(q, d)
    if err is not None:
        return err

    msg = 'Registered as {}'.format(form['uid'])
    return util.make_result(msg, ['0'])
def revoke_key(form):
    try:
        err_codes = ['1']

        q = 'SELECT * FROM cert WHERE uid=? AND is_activated=1'
        d = [session['uid']]
        r, err = db.query(q, d)
        if err is not None:
            return err

        if r == []:
            err_msg = 'No activated certificate, {}'.format(session['uid'])
            err_codes.append('1')
            return util.make_result(err_msg, err_codes)

        revoked_time = get_time()
        if not validate_pgp_key_fmt(r[0]['key']):
            err_msg = 'Invalid PGP key format, {}'.format(session['uid'])
            err_codes.append('2')
            return util.make_result(err_msg, err_codes)

        q = 'UPDATE cert SET is_activated=0, revoked_time=? WHERE issued_time=? AND uid=? AND is_activated=1'
        d = [revoked_time, r[0]['issued_time'], session['uid']]
        r, err = db.query(q, d)
        if err is not None:
            return err

        msg = 'Revoked key, {}'.format(session['uid'])
        return util.make_result(msg, ['0'])

    except:
        msg = "Unknown error occured, {}".format(session['firstname'])
        return util.make_result(msg)
Beispiel #5
0
def login():
    if request.method == 'POST':
        if 'logout' in request.form:  # User logged out
            session.pop('username')
            context = {'logged_in': False}
            return render_template('login.html', **context)

        username = request.form['username']
        password = request.form['password']

        target_user = query(
            """SELECT username, password 
                                FROM users 
                                WHERE username=?""", [username])

        if not len(target_user):  # User not found
            flash('Username not found')
            return redirect(url_for('login'))

        target_username, target_password = target_user[0]

        if checkpw(password.encode(), target_password.encode()):
            session['username'] = username
            context = {'logged_in': True, 'username': username}
            return render_template('login.html', **context)
        else:  # Password incorect
            flash('Password incorrect')
            return redirect(url_for('login'))
    else:
        if 'username' in session:  # User is logged in
            context = {'logged_in': True, 'username': session['username']}
            return render_template('login.html', **context)
        else:
            context = {'logged_in': False}
            return render_template('login.html', **context)
Beispiel #6
0
def write(**kwargs):
  query_args = {
    "filters": kwargs.get("filters", []),
  }
  fields = kwargs.get("select", default_fields)

  all_weapons = False
  if "all_weapons" in fields:
    fields.remove("all_weapons")
    all_weapons = True

  with open(filename, 'w', encoding="utf8") as f:
    writer = csv.writer(f)
    if all_weapons:
      writer.writerow(fields + ["weapon1", "type", "range", "aoe", "damage", "reload",
                                "weapon2", "type", "range", "aoe", "damage", "reload",
                                "weapon3", "type", "range", "aoe", "damage", "reload"])
    else:
      writer.writerow(fields)

    for (key, row) in db.query(**query_args):
      row = convert_to_list(row, fields, all_weapons)
      writer.writerow(row)
  
  print(f"Results output to {filename}")
def upload_key(form):
    try:
        key, err = load_pgp_key(form['key'])
        if err is not None:
            return err

        raw_r = revoke_key({})
        r = json.loads(raw_r)
        if r['code'] not in ['0', '111']:
            return raw_r

        uid = r['msg'].strip().split()[-1]

        q = 'SELECT lastname, firstname, email FROM user WHERE uid=?'
        d = [uid]
        r, err = db.query(q, d)
        if err is not None:
            return err

        assert r != []

        issued_time = get_time()
        key_str = str(key)

        cert, err = make_cert(issued_time, uid, key_str, 1, r[0]['lastname'],
                              r[0]['firstname'], r[0]['email'])
        if err is not None:
            return err

        q = 'INSERT INTO cert VALUES (?, ?, ?, ?, ?)'
        d = [issued_time, None, uid, key_str, 1]
        r, err = db.query(q, d)
        if err is not None:
            return err

        msg = 'Uploaded and signed PGP key, {}'.format(session['firstname'])
        return util.make_result(msg, ['0'])

    except:
        msg = "Unknown error occured, {}".format(session['firstname'])
        return util.make_result(msg)
def verify_cert(form):
    try:
        err_codes = ['3']

        try:
            cert = json.loads(form['cert'])
            data = json.loads(cert['data'])
        except json.decoder.JSONDecodeError:
            err_msg = "Not in JSON format, {}".format(session['firstname'])
            err_codes.append('1')
            return util.make_result(err_msg, err_codes)

        missing_fields = util.get_missing_fields(get_cert_fields(), data)
        if missing_fields:
            err_msg = '{} is missing, {}'.format(missing_fields,
                                                 session['firstname'])
            err_codes.append('2')
            return util.make_result(err_msg, err_codes)

        if not verify_by_ca(cert['data'], cert['sign']):
            err_msg = "Type is not acceptable, {}".format(session['firstname'])
            err_codes.append('3')
            return util.make_result(err_msg, err_codes)

        key, err = load_pgp_key(data['key'])
        if err is not None:
            return err

        q = 'SELECT * FROM cert WHERE issued_time=? AND uid=? AND key=? AND is_activated=?'
        d = [
            data['issued_time'], data['uid'], data['key'], data['is_activated']
        ]
        r, err = db.query(q, d)
        if err is not None:
            return err

        assert r != []

        if data['is_activated'] == 0:
            err_msg = "Revoked cert, {}".format(session['firstname'])
            err_codes.append('4')
            return util.make_result(err_msg, err_codes)
        elif data['is_activated'] == 1:
            msg = "Valid cert, {}".format(session['firstname'])
            return util.make_result(msg, ['0'])
        else:
            assert False

    except:
        msg = "Unknown error occured, {}".format(session['firstname'])
        return util.make_result(msg)
Beispiel #9
0
def login(form):
    err_codes = ['7']

    q = 'SELECT * FROM user WHERE uid=? AND passwd=?'
    d = [form['uid'], hash_pw(form['passwd'])]
    r, err = db.query(q, d)
    if err is not None:
        return err

    if r == []:
        err_msg = 'uid or passwd is wrong'
        err_codes.append('1')
        return util.make_result(err_msg, err_codes)

    for k in r[0].keys():
        if k != 'passwd':
            session[k] = r[0][k]

    msg = 'Logined as {}'.format(session['uid'])
    return util.make_result(msg, ['0'])
Beispiel #10
0
def change_info(form):
    try:
        err = validate_change_info_form(form)
        if err is not None:
            return err

        v = hash_pw(form['v']) if form['k'] == 'passwd' else form['v']

        q = 'UPDATE user SET {}=? WHERE uid=?'.format(form['k'])
        d = [v, session['uid']]
        r, err = db.query(q, d)
        if err is not None:
            return err

        msg = 'Changed {} as {}, {}'.format(form['k'], form['v'],
                                            session['firstname'])
        return util.make_result(msg, ['0'])

    except:
        msg = "Unknown error occured, {}".format(session['firstname'])
        return util.make_result(msg)
Beispiel #11
0
def view_password(id):
	if 'username' not in session:
		return redirect(url_for('login'))

	password = query("""SELECT website, password 
						FROM passwords
						WHERE uid IN (
							SELECT id
							FROM users
							WHERE username=?)
						AND id=?""", [session['username'], id])
	
	if not len(password): # Password not found
		return redirect(url_for('your_passwords'))
	
	website, password = password[0] # Destructures tuple

	decoded_password = b64decode(password.encode()).decode()

	context = {'password': decoded_password, 'website': website}

	return render_template('view_password.html', **context)
Beispiel #12
0
def write(**kwargs):
    # get parameters for the kwargs
    query_args = {
        "filters": kwargs.get("filters", []),
    }
    fields = kwargs.get("select", default_fields)
    data = kwargs.get("data", {})
    # load the db with the _data
    for key, value in data.items():
        db.put(key, value)

    # check if we should combine the weapons or separate them out
    all_weapons = False
    if "all_weapons" in fields:
        fields.remove("all_weapons")
        all_weapons = True

    # open the csv file
    with open(filename, 'w', encoding="utf8") as f:
        writer = csv.writer(f)
        # when we select all weapons then we need to add the rows to the output
        if all_weapons:
            writer.writerow(fields + [
                "weapon1", "type", "range", "aoe", "damage", "reload",
                "weapon2", "type", "range", "aoe", "damage", "reload",
                "weapon3", "type", "range", "aoe", "damage", "reload"
            ])
        else:
            writer.writerow(fields)

        # query the db and write the rows
        for (key, row) in db.query(**query_args):
            row = convert_to_list(row, fields, all_weapons)
            writer.writerow(row)

    print(f"Results output to {filename}")
Beispiel #13
0
def get_cert(form):
    try:
        err_codes = ['2']

        if form['is_activated'] not in ['0', '1']:
            err_msg = "'is_activated' must be 0 or 1, {}".format(
                session['firstname'])
            err_codes.append('1')
            return util.make_result(err_msg, err_codes)

        if 'offset' in form:
            if not form['offset'].isdigit():
                err_msg = "'offset' must be int, {}".format(
                    session['firstname'])
                err_codes.append('2')
                return util.make_result(err_msg, err_codes)
            else:
                offset = int(form['offset'])
                if offset < 0:
                    err_msg = "'offset' must be positive, {}".format(
                        session['firstname'])
                    err_codes.append('3')
                    return util.make_result(err_msg, err_codes)
        else:
            offset = 0

        q = 'SELECT * FROM user WHERE uid=?'
        d = [form['uid']]
        r_users, err = db.query(q, d)
        if err is not None:
            return err

        if r_users == []:
            err_msg = "No user for the given uid, {}".format(
                session['firstname'])
            err_codes.append('4')
            return util.make_result(err_msg, err_codes)

        q = 'SELECT * FROM cert WHERE uid=? AND is_activated=? ORDER BY issued_time DESC LIMIT 10 OFFSET ?'
        d = [form['uid'], form['is_activated'], offset]
        r_certs, err = db.query(q, d)
        if err is not None:
            return err

        certs = []
        for r_cert in r_certs:
            cert, err = make_cert(r_cert['issued_time'], r_cert['uid'],
                                  r_cert['key'], r_cert['is_activated'],
                                  r_users[0]['lastname'],
                                  r_users[0]['firstname'], r_users[0]['email'])
            if err is not None:
                return err

            certs.append(cert)

        msg = json.dumps(certs)
        return util.make_result(msg, ['0'])

    except:
        msg = "Unknown error occured, {}".format(session['firstname'])
        return util.make_result(msg)