def p_retrieve_password(email, code, password, password2): """ 密码重设 :param account: :param code: :param password: :param password2: :return: """ data = {} if not email: data = { 'msg': gettext('Account does not exist'), 'msg_type': 'e', "http_status": 404 } return data s, r = email_format_ver(email=email) if s: user = get_one_user(email=email) else: data = {"msg": r, "msg_type": "e", "http_status": 403} return data if user: r = verify_code(code, email=user["email"]) else: data = { 'msg': gettext('Account does not exist'), 'msg_type': 'e', "http_status": 404 } return data if not r: data = { 'msg': gettext('Email or SMS verification code error'), 'msg_type': 'e', "http_status": 401 } else: if user: r = password_format_ver(password) if not r: data = {"msg": r, "msg_type": "e", "http_status": "403"} return data elif password != password2: data = { 'msg': gettext('Two password is not the same'), 'msg_type': 'w', "http_status": 400 } else: password_hash = generate_password_hash(password) # 将jwt_login_time设为{}退出所有jwt登录的用户 r = update_one_user(user_id=str(user["_id"]), updata={ "$set": { "password": password_hash, "jwt_login_time": {} } }) if r.modified_count: oplog = { 'op_type': 'retrieve_pass', 'time': time.time(), 'status': 's', 'info': '', 'ip': request.remote_addr } insert_op_log(oplog, user_id=user["_id"]) # 发送邮件 subject = gettext("Password reset notification") body = "Your account <a>{}</a> has reset your password. <br>Please keep it safe.".format( user["email"]) data = { "title": subject, "body": body, "other_info": gettext("End"), } html = get_email_html(data) send_email(subject=subject, recipients=[user["email"]], html_msg=html) data = { 'msg': gettext( 'Password reset successfully.Please return to login page to login' ), 'msg_type': 's', "http_status": 201 } logout_user() else: data = { "msg_type": "w", "msg": gettext("Reset password failed(unknown error)"), "http_status": 400 } return data return data
def create_code_send(account, account_type): """ 创建email和message验证码 :param account: :param account_type: :return: """ _str = "" type = get_config("verify_code", "SEND_CODE_TYPE") if type: temp_str_list = [] # 如果存在设置 if "string" in type and type["string"]: for t in range(int(type["string"])): c = _rndChar(i=1) temp_str_list.append(c) if "int" in type and type["int"]: for t in range(int(type["int"])): c = _rndChar(i=2) temp_str_list.append(c) # 打乱 random.shuffle(temp_str_list) for c in temp_str_list: _str = "{}{}".format(_str, c) else: for t in range(6): i = random.randint(1, 2) c = _rndChar(i=i) _str = "{}{}".format(_str, c) if account_type == "email": _code = { 'str': _str, 'time': time.time(), 'to_email': account, "type": "msg" } mdbs["web"].db.verify_code.insert_one(_code) subject = gettext("Verification code") data = { "title": subject, "body": email_code_html_body(_str), "other_info": "", } html = get_email_html(data) msg = {"subject": subject, "recipients": [account], "html_msg": html} send_email(msg=msg, ctype="code") return { "msg": gettext("Has been sent. If not, please check spam"), "msg_type": "s", "custom_status": 201 } elif account_type == "mobile_phone": _code = { 'str': _str, 'time': time.time(), 'to_tel_number': account, "type": "msg" } mdbs["web"].db.verify_code.insert_one(_code) content = gettext( "[{}] Your verification code is: {}. " "If you do not send it, please ignore it. " "Please do not tell the verification code to others").format( get_config("site_config", "APP_NAME"), _str) s, r = send_mobile_msg([account], content) if not s: mdbs["web"].db.verify_code.update_one( {"_id": ObjectId(_code['_id'])}, {"$set": { "error": r }}) return {"msg": r, "msg_type": "w", "custom_status": 400} return {"msg": r, "msg_type": "w", "custom_status": 201}
def p_sign_up(username, password, password2, code, email=None, mobile_phone_number=None): ''' 普通用户注册函数 :return: ''' data = {} if current_user.is_authenticated: data['msg'] = gettext("Is logged in") data["msg_type"] = "s" data["http_status"] = 201 data['to_url'] = request.argget.all('next') or get_config("login_manager", "LOGIN_IN_TO") return data # 用户名格式验证 s1, r1 = short_str_verifi(username, project="username") # 密码格式验证 s2, r2 = password_format_ver(password) if not s1: data = {'msg':r1, 'msg_type':"e", "http_status":422} elif mdb_user.db.user.find_one({"username": username}): # 是否存在用户名 data = {'msg': gettext("Name has been used"), 'msg_type': "w", "http_status": 403} elif not s2: data = {'msg': r2, 'msg_type': "e", "http_status": 400} return data elif password2 != password: # 检验两次密码 data = {'msg': gettext("The two passwords don't match"), 'msg_type': "e", "http_status": 400} if data: return data if email: # 邮件注册 # 邮箱格式验证 s, r = email_format_ver(email) if not s: data = {'msg':r, 'msg_type':"e", "http_status":422} elif mdb_user.db.user.find_one({"email": email}): # 邮箱是否注册过 data = {'msg': gettext("This email has been registered in the site oh, please login directly."), 'msg_type': "w", "http_status": 403} if data: return data # 检验验证码 r = verify_code(code=code, email=email) if not r: data = {'msg': gettext("Verification code error"), 'msg_type': "e", "http_status": 401} return data elif mobile_phone_number: # 手机注册 s, r = mobile_phone_format_ver(mobile_phone_number) if not s: data = {'msg': r, 'msg_type': "e", "http_status": 422} elif mdb_user.db.user.find_one({"mphone_num": mobile_phone_number}): # 手机是否注册过 data = {'msg': gettext("This number has been registered in the site oh, please login directly."), 'msg_type': "w", "http_status": 403} if data: return data # 检验验证码 r = verify_code(code=code, tel_number=True) if not r: data = {'msg': gettext("Verification code error"), 'msg_type': "e", "http_status": 401} return data if not data: # 用户基本信息 role_id = mdb_user.db.role.find_one({"default":{"$in":[True, 1]}})["_id"] user = user_model(username=username, email=email, mphone_num = mobile_phone_number, password=password, custom_domain=-1, role_id=str(role_id), active=True) r = mdb_user.db.user.insert_one(user) if r.inserted_id: if email: # 发送邮件 subject = gettext("Registration success notification") body = "Welcome to register <b>{}</b>.<br><a>{}</a> registered the account successfully.".format( get_config("site_config", "APP_NAME"), email ) data = {"title": subject, "body": body, "other_info": gettext("End"), } html = get_email_html(data) send_email(subject=subject, recipients=[email], html_msg=html) elif mobile_phone_number: # 发送短信 content = "[{}] Successful registration account.".format( get_config("site_config", "APP_NAME")) send_mobile_msg(mobile_phone_number, content) data = {'msg':gettext('Registered successfully'), 'to_url':'/sign-in', 'msg_type':'s',"http_status":201} else: data = {'msg': gettext('Data saved incorrectly, please try again'), 'msg_type': 'e', "http_status": 201} return data return data
def login_log(user, client): ''' 登录日志操作 :param user: 用户对象实例 :return: ''' # 更新登录日志 login_info = { 'time': time.time(), 'ip': request.remote_addr, 'geo': reader_city(request.remote_addr), 'client':client } user_login_log = mdb_user.db.user_login_log.find_one({'user_id': user.str_id}) if user_login_log and "login_info" in user_login_log: login_infos = user_login_log["login_info"] else: login_infos = [] login_infos.append(login_info) than_num = len(login_infos) - get_config("weblogger", "SING_IN_LOG_KEEP_NUM") if than_num > 0: del login_infos[0:than_num] mdb_user.db.user_login_log.update_one({'user_id': user.str_id}, {"$set": {"pass_error": 0, "login_info": login_infos} }, upsert=True) # 检查登录地区是否异常 anl = AbnormalLogin(login_infos[0:-1], login_info["geo"]) abr = anl.area() if abr == "abnormal": # 发送邮件 subject = gettext("Abnormal login") try: location = "{}/{}/{}".format( login_info["geo"]["subdivisions"]["name"], login_info["geo"]["country"]["name"], login_info["geo"]["continent"]["name"] ) except: location = None if location: body = gettext("<b>Abnormal login</b><br> Your account <a>{}</a>, is logined in " "<span style='color:#483D8B'>{}</span> " "on {} [UTC Time].<br>").format( user.email, location, time_to_utcdate(tformat="%Y-%m-%d %H:%M:%S") ) data = {"title": subject, "body": body, "other_info": gettext("End"), } html = get_email_html(data) send_email(subject=subject, recipients=[user.email], html_msg=html)
def add_user(): email = request.argget.all('email') mobile_phone_number = str_to_num( request.argget.all('mobile_phone_number', 0)) username = request.argget.all('username', '').strip() password = request.argget.all('password', '').strip() password2 = request.argget.all('password2', '').strip() data = {} # 用户名格式验证 s1, r1 = short_str_verifi(username, project="username") # 密码格式验证 s2, r2 = password_format_ver(password) if not s1: data = {'msg': r1, 'msg_type': "e", "custom_status": 422} elif mdbs["user"].db.user.find_one({"username": username}): # 是否存在用户名 data = { 'msg': gettext("Name has been used"), 'msg_type': "w", "custom_status": 403 } elif not s2: data = {'msg': r2, 'msg_type': "e", "custom_status": 400} return data elif password2 != password: # 检验两次密码 data = { 'msg': gettext("The two passwords don't match"), 'msg_type': "e", "custom_status": 400 } if data: return data if email: # 邮件注册 # 邮箱格式验证 s, r = email_format_ver(email) if not s: data = {'msg': r, 'msg_type': "e", "custom_status": 422} elif mdbs["user"].db.user.find_one({"email": email}): # 邮箱是否注册过 data = { 'msg': gettext( "This email has been registered in the site oh, please login directly." ), 'msg_type': "w", "custom_status": 403 } if data: return data elif mobile_phone_number: # 手机注册 s, r = mobile_phone_format_ver(mobile_phone_number) if not s: data = {'msg': r, 'msg_type': "e", "custom_status": 422} elif mdbs["user"].db.user.find_one({"mphone_num": mobile_phone_number}): # 手机是否注册过 data = { 'msg': gettext( "This number has been registered in the site oh, please login directly." ), 'msg_type': "w", "custom_status": 403 } if data: return data if not data: # 用户基本信息 role_id = mdbs["user"].db.role.find_one( {"default": { "$in": [True, 1] }})["_id"] if not email: email = None if not mobile_phone_number: mobile_phone_number = None user = user_model(username=username, email=email, mphone_num=mobile_phone_number, password=password, custom_domain=-1, role_id=str(role_id), active=True, is_adm_add_user=True) r = insert_one_user(updata=user) if r.inserted_id: if email: # 发送邮件 subject = gettext("Registration success notification") body = [ gettext("Welcome to register {}.").format( get_config("site_config", "APP_NAME")), gettext("{} registered the account successfully.").format( email) ] data = { "title": subject, "body": body, "username": username, "site_url": get_config("site_config", "SITE_URL") } html = get_email_html(data) msg = { "subject": subject, "recipients": [email], "html_msg": html } send_email(msg=msg, ctype="nt") elif mobile_phone_number: # 发送短信 content = gettext( "[{}] Successful registration account.").format( get_config("site_config", "APP_NAME")) send_mobile_msg(mobile_phone_number, content) data = { 'msg': gettext('Added successfully'), 'msg_type': 's', "custom_status": 201 } return data
def send_msg(): ''' 发送消息 :return: ''' title = request.argget.all("title") content = request.argget.all("content") content_html = request.argget.all("content_html") send_type = json_to_pyseq(request.argget.all("send_type",[])) username = json_to_pyseq(request.argget.all("username", [])) s, r = arg_verify([(gettext(gettext("title")), title), (gettext("content"), content_html), (gettext("send type"), send_type), (gettext("user name"), username)], required=True) if not s: return r data = {"msg":"", "msg_type":"s"} query = {"is_delete": {"$in": [False, 0, ""]}, "active": {"$in": [True, 1]}} if len(username) > 1 or username[0].lower() != "all": # 不是发给全部用户 query["username"] = {"$in": username} users = list(mdb_user.db.user.find(query, {"_id": 1, "email": 1, "mphone_num":1})) # 清理消息中的临时img if "email" not in send_type: # 删除所有上传的图片 srcs = [] else: # 保留邮件内容中使用的图片 srcs = richtext_extract_img(richtext=content_html) imgs = clean_tempfile(user_id=current_user.str_id, type="image", old_file=[], keey_file=srcs) if imgs: # 保存邮件中上传的图片记录, 以便之后删除 mdb_sys.db.sys_msg_img.insert({"time":time.time(), "imgs":imgs, "send_user_id":current_user.str_id, "title":title}) for send_t in send_type: if send_t == "on_site": for user in users: insert_user_msg(user_id=user["_id"], ctype="notice", label="sys_notice", title=title, content={"text":content}, is_sys_msg=True) if users: data["msg"] = "{}. {}".format(data["msg"], gettext("Station news success")) else: data["msg"] = "{}. {}".format(data["msg"], gettext("No relevant user")) data["msg_type"] = "w" elif send_t == "email": to_emails = [] for user in users: to_emails.append(user["email"]) if to_emails: send_email(subject=title, recipients=to_emails, html_msg=content_html) data["msg"] = "{}. {}".format(data["msg"], gettext("Mail message is being sent")) else: data["msg"] = "{}. {}".format(data["msg"], gettext("There is no such email address user")) data["msg_type"] = "w" elif send_t == "sms": # 发送短信 to_mnumber = [] for user in users: if "mphone_num" in user: to_mnumber.append(user["mphone_num"]) if to_mnumber: send_mobile_msg(to_mnumber, content) data["msg"] = "{}. {}".format(data["msg"], gettext("SMS sent")) else: data["msg"] = "{}. {}".format(data["msg"], gettext("No user mobile phone number was obtained")) data["msg_type"] = "w" data["msg"]= data["msg"].strip(". ") data["http_status"] = 201 return data
def login_log(user, client): """ 登录日志操作 :param user: 用户对象实例 :return: """ # 更新登录日志 login_info = { 'time': time.time(), 'ip': request.remote_addr, 'geo': reader_city(request.remote_addr), 'client': client } user_login_log = mdbs["user"].db.user_login_log.find_one( {'user_id': user.str_id}) if user_login_log and "login_info" in user_login_log: login_infos = user_login_log["login_info"] else: login_infos = [] login_infos.append(login_info) than_num = len(login_infos) - \ get_config("weblogger", "SING_IN_LOG_KEEP_NUM") if than_num > 0: del login_infos[0:than_num] mdbs["user"].db.user_login_log.update_one({'user_id': user.str_id}, {"$set": {"pass_error": 0, "login_info": login_infos} }, upsert=True) # 检查登录地区是否异常 anl = AbnormalLogin(login_infos[0:-1], login_info["geo"]) abr = anl.area() if abr == "abnormal": # 发送邮件 subject = gettext("Abnormal login") try: location = "{}/{}/{}".format( login_info["geo"]["subdivisions"]["name"], login_info["geo"]["country"]["name"], login_info["geo"]["continent"]["name"] ) except BaseException: location = None if location: body = [ gettext("Abnormal login"), gettext("Your account {} , is logined in {} on {} [UTC Time].").format( user.email, location, time_to_utcdate(tformat="%Y-%m-%d %H:%M:%S") ) ] data = { "title": subject, "username": user["username"], "body": body, "site_url": get_config("site_config", "SITE_URL") } html = get_email_html(data) msg = { "subject": subject, "recipients": [user["email"]], "html_msg": html } send_email(msg=msg, ctype="nt")