Пример #1
0
async def login_access_token(
    *,
    db: Session = Depends(deps.get_db),
    user_info: sys_user_schema.UserEmailAuth,
) -> Any:
    """
    用户JWT登录
    :param db:
    :param user_info:
    :return:
    """

    # 验证用户
    user = curd_user.authenticate(db,
                                  email=user_info.username,
                                  password=user_info.password)
    if not user:
        logger.info(
            f"用户邮箱认证错误: email{user_info.username} password:{user_info.password}"
        )
        return response_code.resp_4003(message="username or password error")
    elif not curd_user.is_active(user):
        return response_code.resp_4003(message="User email not activated")

    access_token_expires = timedelta(
        minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)

    # 登录token 存储了user.id 和 authority_id
    return response_code.resp_200(
        data={
            "token":
            security.create_access_token(user.id,
                                         user.authority_id,
                                         expires_delta=access_token_expires),
        })
Пример #2
0
async def websocket_endpoint(ws: WebSocket, token: str):
    """
    :param ws:
    :param token:
    :return:
    """
    user_sub = check_jwt_token(token)
    user_id = user_sub.get("sub")

    await ws_manager.connect(user_id, ws)
    logger.info(f"{user_id}-连接WebSocket")

    # 广播
    # await ws_manager.broadcast({"username": user, "message": "enter chat room"})

    try:
        while True:
            data = await ws.receive_json()
            logger.info(f"接收数据{data}, {type(data)}")

            message_type = data.get("messageType")
            to_target_id = data.get("toTargetId")  # 用户id 或者 组id

            # 发送给自己
            # await ws_manager.send_personal_message(data, ws)

            if message_type == 1000:
                # 发送给客户端格式
                # {
                #   "userId": "xx",
                #   "toTargetId": "xxx",
                #   "message": "xx"
                # }
                send_json = {
                    "userId": user_id,
                    "messageType": message_type,
                    "toTargetId": to_target_id,
                    "message": data["message"],
                    "timestamp": data["timestamp"]
                }
                logger.info(f"发送给他人{message_type}-{send_json}")
                # await ws_manager.send_personal_message(send_json, ws)
                await ws_manager.send_other_message(send_json, to_target_id)
            # else:
            #     # 群发
            #     logger.info(f"群发数据-{data}")
            #     await ws_manager.broadcast({"username": user, "message": data['message']})

    except WebSocketDisconnect:
        logger.info(f"{user_id}-离开")
        # 关闭连接
        ws_manager.disconnect(user_id, ws)
        # await ws_manager.broadcast({"user": user, "message": "离开"})
    except ConnectionClosedOK:
        # 关闭连接
        ws_manager.disconnect(user_id, ws)
        logger.info(f"{user_id}-页面关闭离开")
Пример #3
0
def confirmed_check():
    """
    同时满足以下3 个条件时,before_app_request 处理程序会拦截请求。
    (1) 用户已登录(current_user.is_authenticated() 必须返回True)。
    (2) 用户的账户还未确认。
    (3) 请求的端点(使用request.endpoint 获取)为指定的端点
    """
    confirm_check = ['post.add_post', 'main.edit_userinfo', 'post.edit_post']
    if current_user.is_authenticated:
        #current_user.ping()
        logger.info(request.endpoint)
        if not current_user.confirmed \
                and request.endpoint in confirm_check:
            return redirect(url_for('main.unconfirmed'))
Пример #4
0
def send_email():
    """View function for about page"""

    logger.info("send  a test email .")
    user1 = User()
    user1.username = '******'
    send_mail('TEST MAIL',
              '*****@*****.**',
              'main/email/confirm',
              user=user1,
              token='token')
    #send_mail('TEST MAIL', '*****@*****.**')

    return redirect(url_for('main.index'))
Пример #5
0
def register():
    """View function for Register."""

    # Will be check the username whether exist.
    form = RegisterForm()

    if form.validate_on_submit():
        new_user = User()
        # new_user = User(username=form.username.data,
        #                 password=form.password.data)
        new_user.username = form.username.data
        new_user.password = '******'  #default password
        new_user.nick_name = form.nickname.data
        new_user.full_name = form.fullname.data
        new_user.address = form.address.data
        new_user.birthday = form.birthday.data
        new_user.gender = form.gender.data
        new_user.status = 1  #0:禁用,2:启用
        new_user.confirmed = False  #未确认

        mail = Mail(form.email.data)
        mail.user_id = new_user.id
        mail.status = 1

        if new_user.address != None:
            logger.info(new_user.address)
        db.session.add(new_user)
        db.session.add(mail)
        db.session.commit()

        logger.info("send  a confirmation email .")

        token = new_user.generate_confirmation_token()
        send_mail('Confirm Your Account',
                  form.email.data,
                  'main/email/confirm',
                  user=new_user,
                  token=token)
        # send_email(form.email.data, 'Confirm Your Account',
        #            'main/email/confirm', user=new_user, token=token)
        flash('A confirmation email has been sent to you by email.',
              category="success")
        # flash('Your user has been created, please login.',category="success")

        return redirect(url_for('main.login'))
    return render_template('main/register.html', form=form)
Пример #6
0
def edit_user():
    data = request.form.to_dict()
    user = User.query.filter_by(id=data.get('id')).first()
    is_update = False
    if not user == None:
        for attr, val in data.items():
            if hasattr(User, attr):  # 检查实例是否有这个属性
                if attr == 'username':
                    logger.info("用户名不支持修改!")
                    continue
                if not val == None:
                    setattr(User, attr, val)  # same as: a.name =
                    is_update = True
        if is_update:
            user.modified_time = datetime.now()
            db.session.add(user)
            db.session.commit()
    else:
        return jsonify({'msg': 'user not exist !'})
    action_log(request, '修改用户信息')
    return jsonify({'msg': 'ok !'})
Пример #7
0
# @Software: PyCharm
# @Github  : github/CoderCharm
# @Email   : [email protected]
# @Desc    :
"""

配置文件区分生产和开发

我这种是一种方式,简单直观
还有一种是服务一个固定路径放一个配置文件如 /etc/conf 下 xxx.ini 或者 xxx.py文件
然后项目默认读取 /etc/conf 目录下的配置文件,能读取则为生产环境,
读取不到则为开发环境,开发环境配置可以直接写在代码里面(或者配置ide环境变量)

根据环境变量ENV是否有值 区分生产开发

"""

import os
from app.common import logger

# 获取环境变量
env = os.getenv("ENV", "")
if env:
    # 如果有虚拟环境 则是 生产环境
    logger.info("----------生产环境启动------------")
    from .production_config import settings
else:
    # 没有则是开发环境
    logger.info("----------开发环境启动------------")
    from .development_config import settings
Пример #8
0
 def send_async_mail(self, app, msg):
     with app.app_context():
         from app.common.extensions import mail
         logger.info("start send mail")
         mail.send(msg)