Exemplo n.º 1
0
def register_user(username, passwd, email): # Returns an error message or None
    if passwd == "": return "The password can't be empty!"
    if email: # validate the email only if it is provided
        result = validate_email_address(email)
        if result: return result
    username = username.strip()
    if not re.match(nick_regex, username): return "Invalid username!"

    crypted_pw = encrypt_pw(passwd)

    try:
        conn = sqlite3.connect(password_db)
        c = conn.cursor()
        c.execute("select username from dglusers where username=? collate nocase",
                  (username,))
        result = c.fetchone()

        if result: return "User already exists!"

        c.execute("insert into dglusers(username, email, password, flags, env) values (?,?,?,0,'')",
                  (username, email, crypted_pw))

        conn.commit()

        return None
    finally:
        if c: c.close()
        if conn: conn.close()
Exemplo n.º 2
0
def send_forgot_password(email):  # type: (str) -> Tuple[bool, Optional[str]]
    """
    Returns:
        (email_sent: bool, error: string)
    """
    if not email:
        return False, "Email address can't be empty"
    email_error = validate_email_address(email)
    if email_error:
        return False, email_error

    with crawl_db(password_db) as db:
        db.c.execute("select id from dglusers where email=? collate nocase",
                     (email, ))
        result = db.c.fetchone()
    if not result:
        return False, None

    userid = result[0]
    token = create_password_token(userid)
    msg_body_plaintext, msg_body_html = generate_token_email(token)

    send_email(email, 'Request to reset your password', msg_body_plaintext,
               msg_body_html)

    return True, None
Exemplo n.º 3
0
def register_user(username, passwd,
                  email):  # type: (str, str, str) -> Optional[str]
    """Returns an error message or None on success."""
    if passwd == "":
        return "The password can't be empty!"
    if email:  # validate the email only if it is provided
        result = validate_email_address(email)
        if result:
            return result
    username = username.strip()
    if not re.match(nick_regex, username):
        return "Invalid username!"

    crypted_pw = encrypt_pw(passwd)

    with crawl_db(password_db) as db:
        db.c.execute(
            "select username from dglusers where username=? collate nocase",
            (username, ))
        result = db.c.fetchone()

    if result:
        return "User already exists!"

    with crawl_db(password_db) as db:
        query = """
            INSERT INTO dglusers
                (username, email, password, flags, env)
            VALUES
                (?, ?, ?, 0, '')
        """
        db.c.execute(query, (username, email, crypted_pw))
        db.conn.commit()

    return None
def admin_edit_user(utable, js):
    field = js.get("field", "").strip()
    new_value = js.get("new_value", "").strip()
    prev_value = getattr(utable, field, sentinel)
    if prev_value == sentinel:
        return {"error": "??????"}

    if prev_value == new_value:
        return {"user_data": utable.as_json}
    if field == "current_level":
        set_level(utable, new_value)
        return {"user_data": utable.as_json}
    elif field == "last_question_answered_at":
        set_last_question_answered_at(utable, new_value)
        return {"user_data": utable.as_json}
    elif field == "email":
        if not validate_email_address(new_value):
            return {"error": "Invalid email"}
        utable.has_verified_email = False
    try:
        setattr(utable, field, new_value)
        save_to_db()
        return {"user_data": utable.as_json}
    except Exception:
        return {
            "error":
            "Could not update" if field != "email" else
            "Could not update email, maybe another account is using that address"
        }
Exemplo n.º 5
0
 def __init__(
     self,
     user: str = None,
     name: str = None,
     email: str = None,
     school: str = None,
     password_hash: str = None,
     ig_user_id: str = None,
     is_admin: bool = False,
     is_disqualified: bool = False,
     last_question_answered_at: int = 0,
     has_verified_email: bool = False,
 ):
     if any(
             self.is_invalid_data(x)
             for x in (user, name, email, password_hash)):
         raise Exception("Invalid Data")
     self.user = user.lower()
     self.password_hash = password_hash
     self.name = name
     self.email = validate_email_address(email)
     self.school = school
     self.ig_user_id = ig_user_id
     self.current_level = 0
     self.is_admin = is_admin
     self.is_disqualified = is_disqualified
     self.has_verified_email = has_verified_email
     self.last_question_answered_at = (last_question_answered_at
                                       or js_time()
                                       )  # javascript times in ms
Exemplo n.º 6
0
def send_forgot_password(email): # Returns a tuple where item 1 is a truthy value when an email was sent, and item 2 is an error message or None
    if not email: return False, "Email address can't be empty"
    email_error = validate_email_address(email)
    if email_error: return False, email_error

    try:
        # lookup user-provided email
        conn = sqlite3.connect(password_db)
        c = conn.cursor()
        c.execute("select id from dglusers where email=? collate nocase",
                  (email,))
        result = c.fetchone()

        # user was found
        if result:
            userid = result[0]
            # generate random token
            token_bytes = os.urandom(32)
            token = urlsafe_b64encode(token_bytes)
            # hash token
            token_hash_obj = hashlib.sha256(token)
            token_hash = token_hash_obj.hexdigest()
            # store hash in db
            c.execute("insert into recovery_tokens(token, token_time, user_id) "
                      "values (?,datetime('now'),?)", (token_hash, userid))
            conn.commit()

            # send email
            url_text = config.lobby_url + "?ResetToken=" + token

            msg_body_plaintext = """Someone (hopefully you) has requested to reset the password for your account at """ + config.lobby_url + """.

If you initiated this request, please use this link to reset your password:

    """ + url_text + """

If you did not ask to reset your password, feel free to ignore this email.
"""

            msg_body_html = """<html>
  <head></head>
  <body>
    <p>Someone (hopefully you) has requested to reset the password for your account at """ + config.lobby_url + """.<br /><br />
       If you initiated this request, please use this link to reset your password:<br /><br />
       &emsp;<a href='""" + url_text + """'>""" + url_text + """</a><br /><br />
       If you did not ask to reset your password, feel free to ignore this email.
    </p>
  </body>
</html>"""

            send_email(email, 'Request to reset your password',
                        msg_body_plaintext, msg_body_html)

            return True, None

        # email was not found, do nothing
        return False, None
    finally:
        if c: c.close()
        if conn: conn.close()
Exemplo n.º 7
0
def send_forgot_password(email): # Returns a tuple where item 1 is a truthy value when an email was sent, and item 2 is an error message or None
    if not email: return False, "Email address can't be empty"
    email_error = validate_email_address(email)
    if email_error: return False, email_error

    try:
        # lookup user-provided email
        conn = sqlite3.connect(password_db)
        c = conn.cursor()
        c.execute("select id from dglusers where email=? collate nocase",
                  (email,))
        result = c.fetchone()

        # user was found
        if result:
            userid = result[0]
            # generate random token
            token_bytes = os.urandom(32)
            token = urlsafe_b64encode(token_bytes)
            # hash token
            token_hash_obj = hashlib.sha256(token)
            token_hash = token_hash_obj.hexdigest()
            # store hash in db
            c.execute("insert into recovery_tokens(token, token_time, user_id) "
                      "values (?,datetime('now'),?)", (token_hash, userid))
            conn.commit()

            # send email
            url_text = config.lobby_url + "?ResetToken=" + token

            msg_body_plaintext = """Someone (hopefully you) has requested to reset the password for your account at """ + config.lobby_url + """.

If you initiated this request, please use this link to reset your password:

    """ + url_text + """

If you did not ask to reset your password, feel free to ignore this email.
"""

            msg_body_html = """<html>
  <head></head>
  <body>
    <p>Someone (hopefully you) has requested to reset the password for your account at """ + config.lobby_url + """.<br /><br />
       If you initiated this request, please use this link to reset your password:<br /><br />
       &emsp;<a href='""" + url_text + """'>""" + url_text + """</a><br /><br />
       If you did not ask to reset your password, feel free to ignore this email.
    </p>
  </body>
</html>"""

            send_email(email, 'Request to reset your password',
                        msg_body_plaintext, msg_body_html)

            return True, None

        # email was not found, do nothing
        return False, None
    finally:
        if c: c.close()
        if conn: conn.close()
Exemplo n.º 8
0
def change_email(user_id, email):  # type: (str, str) -> Optional[str]
    """Returns an error message or None on success."""
    result = validate_email_address(email)
    if result:
        return result

    with crawl_db(password_db) as db:
        db.c.execute("update dglusers set email=? where id=?",
                     (email, user_id))
        db.conn.commit()

    return None
Exemplo n.º 9
0
def change_email(user_id, email):  # Returns an error message or None
    result = validate_email_address(email)
    if result: return result

    try:
        conn = sqlite3.connect(password_db)
        c = conn.cursor()
        c.execute("update dglusers set email=? where id=?", (email, user_id))

        conn.commit()

        return None
    finally:
        if c: c.close()
        if conn: conn.close()
Exemplo n.º 10
0
def change_email(user_id, email): # Returns an error message or None
    result = validate_email_address(email)
    if result: return result

    try:
        conn = sqlite3.connect(password_db)
        c = conn.cursor()
        c.execute("update dglusers set email=? where id=?",
                  (email, user_id))

        conn.commit()

        return None
    finally:
        if c: c.close()
        if conn: conn.close()
Exemplo n.º 11
0
def edit(js: dict) -> dict:
    if not is_logged_in():
        return {"error": "Not Authenticated"}
    user = js.get("user", "").strip()
    field = js.get("field", "").strip()
    if field not in ["email", "school", "ig_user_id"]:
        return {"error": "cannot edit specified field"}
    new_value = js.get("new_value", "").strip()
    if user != get_current_user():
        return {"error": "Invalid credentials"}
    invalid_data_arr = []
    if not user:
        invalid_data_arr.append("user")
    if not field:
        invalid_data_arr.append("column")
    if not new_value:
        invalid_data_arr.append("value")

    if invalid_data_arr:
        return {"error": f"Missing data: {', '.join(invalid_data_arr)}"}

    user_table = get_user_by_id(user)

    attr = getattr(user_table, field, sentinel)
    if attr == sentinel:
        return {"error": "Invalid field"}
    if attr == new_value:
        # prevent a useless write
        return {"user_data": user_table.as_json}
    try:
        setattr(user_table, field, new_value)
        if field == "email":
            if not validate_email_address(new_value):
                return {"error": "Invalid email"}
            user_table.has_verified_email = False
        save_to_db()
        return {"user_data": user_table.as_json}
    except:
        return {
            "error":
            "Could not update" if field != "email" else
            "Could not update email, maybe another account is using that address"
        }
Exemplo n.º 12
0
 def test_validate_email_address(self, email, valid):
     result = util.validate_email_address(email)
     if valid:
         assert result is None
     else:
         assert result is not None
Exemplo n.º 13
0
 def _validate_email(self, mail: str):
     validate_email_address(mail)