def get_user_info(self, username=None, user_id=None): if user_id is not None: if use_mongoengine: return User.objects(id=user_id).first() elif use_peewee: with db.execution_context(): return User.get(User.id == user_id) if username is None: username = self.username if username is None: return None if self.ignore_check_user: user = DefaultNamespace() user.username = username user.is_admin = (username == "admin") user.password = "******" if (username == "admin") else "" user.id = hash(username) return user if use_mongoengine: return User.objects(username=username).first() elif use_peewee: with db.execution_context(): try: return User.get(User.username == username) except User.DoesNotExist: return None
def remove_user(self, username): if use_mongoengine: User.objects(username=username).delete() elif use_peewee: with db.execution_context(): query = User.delete().where(User.username == username) # type:peewee.Query query.execute()
def check_has_user(self, username): if use_mongoengine: return True if User.objects(username=username).count() else False elif use_peewee: with db.execution_context(): return True if User.select().where(User.username == username).count() else False else: return False
def change_role(self, username, role): if use_mongoengine: User.objects(username=username).update_one(role=role) elif use_peewee: with db.execution_context(): query = User.update(role=role).where(User.username == username) # type:peewee.Query query.execute() self.role = role
def api_login(): data = {"status": "error"} if flask.request.is_json: json = flask.request.get_json() username = json.get('username', None) password = json.get('password', None) validate_code = json.get('validate_code', None) if not validate_code: data["reason"] = "no_validate_code" return flask.jsonify(data) if not check_validate_code(validate_code): data["reason"] = "error_validate_code" return flask.jsonify(data) if username == '': username = "******" if username: user_info = self.check_user_password(username, password) if user_info: uid = str(uuid.uuid1()) signed_uid = itsdangerous.Signer(user_info.password, salt='LoginChecker:uid').sign( uid.encode(errors='ignore')).decode( errors='ignore') self.signed_uid = signed_uid self.username = username self.uid = uid self.is_admin = user_info.is_admin self.user_id = user_info.id self.role = user_info.role if use_mongoengine: user_login_data = UserLoginData(uid=uid, user=user_info, username=username, timestamp=int(time.time() * 1e3), datetime=datetime.now(), utc_datetime=datetime.utcnow()) user_login_data.save() logger.info("<username=%s,uid=%s> save login with mongodb" % (username, uid)) elif use_peewee: with db.execution_context(): UserLoginData.create(uid=uid, user=user_info, username=username, timestamp=int(time.time() * 1e3), datetime=datetime.now(), utc_datetime=datetime.utcnow()) logger.info("<username=%s,uid=%s> save login with peewee" % (username, uid)) data["status"] = "ok" data["username"] = self.username data["is_admin"] = self.is_admin data["role"] = self.role data["uid"] = self.signed_uid data["_csrf_token"] = get_csrf_token() resp = flask.make_response(flask.jsonify(data)) self.save_login_info_to_cookie(resp) return resp data["reason"] = "error_user" else: data["reason"] = "no_json" return flask.jsonify(data)
def delete_timeout_data(self, ttl=7): if isinstance(ttl, int): ttl = timedelta(days=ttl) old_datetime = datetime.utcnow() - ttl if use_mongoengine: result = UserLoginData.objects(utc_datetime__lt=old_datetime).delete() logger.info("delete %d timeout data" % result) elif use_peewee: with db.execution_context(): query = UserLoginData.delete().where(UserLoginData.utc_datetime < old_datetime) # type:peewee.Query result = query.execute() logger.info("delete %d timeout data" % result)
def change_password(self, username, password): password = self.generate_password_hash(password) if use_mongoengine: User.objects(username=username).update_one(password=password) user_logon_data_objects = UserLoginData.objects(username=username) # type:mongoengine.queryset.QuerySet user_logon_data_objects.delete() elif use_peewee: with db.execution_context(): query = User.update(password=password).where(User.username == username) # type:peewee.Query query.execute() query = UserLoginData.delete().where(UserLoginData.username == username) # type:peewee.Query query.execute()
def is_login(self): if self.username is None: username = flask.request.cookies.get('MEMBER_LOGIN', None) signed_uid = flask.request.cookies.get('UID', None) if username and signed_uid and (use_mongoengine or use_peewee): user_info = self.get_user_info(username) if user_info: try: uid = itsdangerous.Signer(user_info.password, salt='LoginChecker:uid').unsign( signed_uid).decode( errors='ignore') except itsdangerous.BadData: return False if use_mongoengine: user_login_data = UserLoginData.objects(uid=uid, user=user_info.id, username=username).first() if user_login_data: self.is_admin = user_info.is_admin self.username = username self.uid = uid self.signed_uid = signed_uid self.user_id = user_info.id self.role = user_info.role user_login_data.timestamp = int(time.time() * 1e3) user_login_data.datetime = datetime.now() user_login_data.utc_datetime = datetime.utcnow() user_login_data.save() logger.info("<username=%s,uid=%s> pass login with mongodb" % (username, uid)) return True return False elif use_peewee: with db.execution_context(): user_login_data = UserLoginData.get(UserLoginData.uid == uid, UserLoginData.user == user_info.id, UserLoginData.username == username) if user_login_data: self.is_admin = user_info.is_admin self.username = username self.uid = uid self.signed_uid = signed_uid self.user_id = user_info.id self.role = user_info.role user_login_data.timestamp = int(time.time() * 1e3) user_login_data.datetime = datetime.now() user_login_data.utc_datetime = datetime.utcnow() user_login_data.save() logger.info("<username=%s,uid=%s> pass login with peewee" % (username, uid)) return True return False return False return False return True
def change_username(self, username, new_username): if use_mongoengine: if self.check_has_user(new_username): raise UserWasExist User.objects(username=username).update_one(username=new_username) user_logon_data_objects = UserLoginData.objects(username=username) # type:mongoengine.queryset.QuerySet user_logon_data_objects.modify(username=new_username) elif use_peewee: if self.check_has_user(new_username): raise UserWasExist with db.execution_context(): query = User.update(username=new_username).where(User.username == username) # type:peewee.Query query.execute() query = UserLoginData.update(username=new_username).where( UserLoginData.username == username) # type:peewee.Query query.execute() self.username = new_username
def remove_login(self, response): username = self.username uid = self.uid del self.is_login response.delete_cookie('MEMBER_LOGIN') response.delete_cookie('UID') response.delete_cookie('IS_ADMIN') if username and uid: if use_mongoengine: UserLoginData.objects(uid=uid, username=username).delete() logger.info("<username=%s,uid=%s> remove login with mongodb" % (username, uid)) elif use_peewee: with db.execution_context(): query = UserLoginData.delete().where(UserLoginData.uid == uid, UserLoginData.username == username) # type:peewee.Query query.execute() logger.info("<username=%s,uid=%s> remove login with peewee" % (username, uid)) return response
def add_user(self, username, password, is_admin=False): password = self.generate_password_hash(password) if use_mongoengine: try: user = User(username=username, password=password, is_admin=is_admin) user.save() logger.info("create new user <username=%s,user_id=%s> into mongodb" % (username, user.id)) return user except mongoengine.NotUniqueError: raise UserWasExist elif use_peewee: try: with db.execution_context(): user = User.create(id=str(uuid.uuid4()), username=username, password=password, is_admin=is_admin) logger.info("create new user <username=%s,user_id=%s> into mysql" % (username, user.id)) return user except peewee.PeeweeException: raise UserWasExist
def __init__(self, only_post=True, ignore_check_user=False, delete_timeout_data=False): self.only_post = only_post self.ignore_check_user = ignore_check_user self.login_view = None self.logout_view = None self.register_view = None self.user_settings_view = None self.check_login_view = None if delete_timeout_data: Thread(target=self.delete_timeout_data).start() if use_mongoengine: pass elif use_peewee: with db.execution_context(): # Only create the tables if they do not exist. db.create_tables([User, UserLoginData], safe=True) else: self.ignore_check_user = True
def generate_validate_code_to_db(string=None): if string: if use_mongoengine: query_set = ValidateCode.objects(string=string) if query_set.count(): return query_set.first().base64_img elif use_peewee: with db.execution_context(): query_set = ValidateCode.select().where(ValidateCode.string == string) if query_set.count(): return query_set.first().base64_img start_time = time.time() img_bytes, strs = create_validate_code(string) end_time = time.time() logger.info("create_validate_code <%s> use time: %f s" % (strs, (end_time - start_time))) encode_img = base64_encode(img_bytes, return_type=str) size = len(encode_img) logger.info("encode_img length = %d" % size) start_time = time.time() if use_mongoengine: ValidateCode(string=string, base64_img=encode_img).save() elif use_peewee: with db.execution_context(): ValidateCode.create(string=string, base64_img=encode_img) end_time = time.time() logger.info("insert <%s> to mongodb use time: %f s" % (strs, (end_time - start_time))) return encode_img if use_peewee: with db.execution_context(): # Only create the tables if they do not exist. db.create_tables([ValidateCode], safe=True) time1 = time.time() total_size = 0 for num in range(10000): string = "%04d" % num if use_mongoengine: if ValidateCode.objects(string=string).count(): logger.info("validate_code <%s> was already in mongodb, skip it" % string) continue elif use_peewee: with db.execution_context(): if ValidateCode.select().where(ValidateCode.string == string).count(): logger.info("validate_code <%s> was already in mongodb, skip it" % string) continue # 把strs发给前端,或者在后台使用session保存 start_time = time.time() img_bytes, strs = create_validate_code(string) end_time = time.time() logger.info("create_validate_code <%s> use time: %f s" % (strs, (end_time - start_time))) encode_img = base64_encode(img_bytes, return_type=str) size = len(encode_img) total_size += size logger.info("encode_img length = %d" % size) logger.info("total_size = %d" % total_size) start_time = time.time() if use_mongoengine: ValidateCode(string=string, base64_img=encode_img).save() elif use_peewee: with db.execution_context(): ValidateCode.create(string=string, base64_img=encode_img) end_time = time.time() logger.info("insert <%s> to mongodb use time: %f s" % (strs, (end_time - start_time))) time2 = time.time() logger.info("total use time: %f s" % (time2 - time1)) logger.info("total_size = %d" % total_size)