def reset_password(self, email, reset_code, new_password):
     """
     Reset password with the reset code
     """
     result = None
     try:
         existed_reset = self._database['resetpassword'].find_one({'email': email,'reset_code':reset_code})
         if existed_reset:
             created_day = existed_reset['created_date']
             delta = datetime.datetime.utcnow() - created_day
             if delta.total_seconds() < RESET_PASSWORD_EXPIRED_TIME:
                 salt = random_string_generator()
                 password_hash = hash_password_salt(new_password, salt)
                 user = self.exist_email(email)
                 username = user['username']
                 result = self._auth_collection.update({'username': username,}, 
                                                                       {'$set':{'salt':salt, 'password': password_hash}},
                                                                       safe=True, 
                                                                       multi=False)                    
             else:
                 result = None
             """mongodb will delete old reset code for us"""
             self._database['resetpassword'].remove({'email': email,})
     except pymongo.errors.AutoReconnect:
         logger.error("Auto reconnect")
     except:
         logger.error("Unexpected Error: " + traceback.format_exc())            
     return result                
 def POST(
     self, username, password, email, phone=None, recaptcha_challenge_field=None, recaptcha_response_field=None
 ):
     username = username.lower()
     full_username = "******".format(username, XMPP_DOMAIN_NAME)
     """check captcha"""
     if "X-Real-IP" in cherrypy.request.headers:
         ip_remote = cherrypy.request.headers["X-Real-IP"]
     else:
         ip_remote = cherrypy.request.remote.ip
     if self.check_captcha:
         check = self.check_captcha.verify_captcha(recaptcha_challenge_field, recaptcha_response_field, ip_remote)
         if not check:
             return to_json({"result": 2, "description": "Wrong captcha."})
     """register"""
     if self.check_register_value(username, password, email, phone):
         avatar_random = random.randint(0, 24)
         created_auth = self._auth_db.create_user(username, password, email, phone)
         # create a userinfo record
         created_info = self._userinfo_db.create_user(full_username, avatar_id=avatar_random)
         verification_code = random_string_generator(12)
         verified = self.send_verification_email(username, email, verification_code)
         if created_auth and created_info:
             return to_json({"result": 0, "description": "Registration is successful."})
         else:
             return to_json({"result": 4, "description": "Duplicate username or email."})
     else:
         return to_json({"result": 3, "description": "Invalid input value."})
     return to_json({"result": 1, "description": "Registration error."})
 def POST(self, session_token, recaptcha_challenge_field=None, recaptcha_response_field=None):
     
     authenticated = self._session_db.get_token(session_token)
     if not authenticated:
         return to_json({'result': 3, 'description': 'Invalid session.'})
     if authenticated:
         username = authenticated['username']
         verification_code = random_string_generator(12)
         email = self._auth_db.exist_user(username)['email']
         res = self.send_verification_email(username, email, verification_code)
         if res:
             return to_json({'result': 0, 'description': 'Request is successful.'})
     return to_json({'result': 1, 'description': 'Request failed.'})
 def create_user(self, username, password, email, phone=None):
     """
     Create an user in authentication database. Username or email is unique in the collection.
     """
     result = None
     username = username.lower()
     try:
         """salt for password's hash"""
         salt = random_string_generator()
         """password's hash"""
         password_hash = hash_password_salt(password, salt)
         """encrypt email with AES"""
         encryption_iv = Random.new().read(AES.block_size)
         cipher = AES.new(ENCRYPTION_AES_KEY, AES.MODE_CFB, encryption_iv)
         encrypted_email_string = ''.join([encryption_iv,cipher.encrypt(email)])
         encrypted_email_base64 = base64.b64encode(encrypted_email_string)            
         hash_email = hashlib.md5('{}{}'.format(email,SECRET_SALT)).hexdigest()
         """encrypt phone with AES"""
         encrypted_phone_base64 = None
         hash_phone = None
         if phone:
             encryption_iv = Random.new().read(AES.block_size)
             cipher = AES.new(ENCRYPTION_AES_KEY, AES.MODE_CFB, encryption_iv)
             encrypted_phone_string = ''.join([encryption_iv,cipher.encrypt(phone)])
             encrypted_phone_base64 = base64.b64encode(encrypted_phone_string)
             hash_phone = hashlib.md5('{}{}'.format(phone,SECRET_SALT)).hexdigest()
         _newuser = {'username': username, 
                     'password': password_hash,
                     'salt': salt,
                     'email': encrypted_email_base64,
                     'hash_email': hash_email,
                     'phone': encrypted_phone_base64,
                     'hash_phone': hash_phone,
                     'verified': False,
                     }
         result = self._auth_collection.insert(_newuser, safe=True)
     except pymongo.errors.DuplicateKeyError:
         logger.error("Duplicate username or email.")
     except pymongo.errors.AutoReconnect:
         logger.error("Auto reconnect.")
     except:
         logger.error("Unexpected Error.")
         #raise
     """if result:
         if not verification_code:
             verification_code = random_string_generator(12)
         verified = self.create_email_verification_code(verification_code, username)
         if not verified:
             logger.error('Cannot create verification code.')"""        
     return result
 def POST(self, email, recaptcha_challenge_field=None, recaptcha_response_field=None):
     if 'X-Real-IP' in cherrypy.request.headers:
         ip_remote = cherrypy.request.headers['X-Real-IP']
     else:
         ip_remote = cherrypy.request.remote.ip
     if self.check_captcha:
         check = self.check_captcha.verify_captcha(recaptcha_challenge_field, recaptcha_response_field,ip_remote)
         if not check:
             return to_json({'result': 2, 'description': 'Wrong captcha.'})
         
     reset_code = random_string_generator(12)
     email = email.lower()
     res = self.send_reset_password_email(email, reset_code)
     if res:
         return to_json({'result': 0, 'description': 'Reset password email sent.'})
     return to_json({'result': 1, 'description': 'Request resetting password failed.'})                                
 def change_password(self, username, old_password, new_password):
     """
     Change current password to new password
     """
     result = None
     try:
         if self.authenticate_user(username, old_password):
             salt = random_string_generator()
             password_hash = hash_password_salt(new_password, salt)
             result = self._auth_collection.update({'username': username,}, 
                                                                   {'$set':{'salt':salt, 'password': password_hash}},
                                                                   safe=True, 
                                                                   multi=False)
     except pymongo.errors.AutoReconnect:
         logger.error("Auto reconnect")
     except:
         logger.error("Unexpected Error: " + traceback.format_exc())            
     return result
    def generate_name(self):
        """
        generate a random name
        """
        result = ""
        name_len = random.choice(NAME_LENGTH_RANGE)
        first_char = random.choice(self._first_letter)
        result = result + first_char
        cur_char = first_char
        for _ in range(0, name_len - 1):
            next_char = random.choice(self._next_letter[cur_char])
            result = result + next_char
            cur_char = next_char
        return result


if __name__ == "__main__":
    list_name = []
    randomname = RandomName("name_latin.txt")
    for _ in range(1000):
        while True:
            _name = randomname.generate_name()
            if _name not in list_name:
                list_name.append(_name)
                break
    f_out = open("userlist.txt", "w")
    for _name in list_name:
        _password = random_string_generator(20)
        f_out.write(_name + " " + _password + "\n")
    f_out.close()