Exemple #1
0
async def recover_password(schema_in: ResetPassword):
    """
    Password Recovery
    """
    await verify_code(schema_in.vcode_id, schema_in.vcode)
    await verify_auth_code(schema_in.phone, schema_in.email,
                           schema_in.sms_code)
    if schema_in.phone:
        user = await MarketUser.get_or_none(phone=schema_in.phone)
    else:
        user = await MarketUser.get_or_none(email=schema_in.email)

    if not user:
        raise HTTPException(
            status_code=404,
            detail=
            "The user with this email/phone does not exist in the system.",
        )
    user.password = get_password_hash(schema_in.password, user.uuid.hex)
    await user.save()
    # verify_code = "1234"
    # if schema_in.phone:
    #     send_sms(verify_code)
    # else:
    #     send_email(verify_code)
    return CommonOut(msg="Password recovery message sent")
Exemple #2
0
async def recover_password(schema_in: ResetPassword):
    """
    Password Recovery
    """
    await verify_code(schema_in.vcode_id, schema_in.vcode)
    await verify_auth_code(schema_in.phone, schema_in.email,
                           schema_in.sms_code)
    if schema_in.phone:
        user = await MarketUser.query.where(MarketUser.phone == schema_in.phone
                                            ).gino.first()
        #password = await MarketUser.select('password').where(MarketUser.phone==schema_in.phone).gino.scalar()
    else:
        user = await MarketUser.query.where(MarketUser.email == schema_in.email
                                            ).gino.first()
        #password = await MarketUser.select('password').where(MarketUser==schema_in.email).gino.scalar()

    if not user:
        #if not password:
        raise HTTPException(
            status_code=404,
            detail=
            "The user with this email/phone does not exist in the system.",
        )
    #await user.password == get_password_hash(schema_in.password)
    await user.update(
        password=get_password_hash(schema_in.password, user.uuid.hex)).apply()
    #await user.save()
    # verify_code = "1234"
    # if schema_in.phone:
    #     send_sms(verify_code)
    # else:
    #     send_email(verify_code)
    return CommonOut(msg="Password recovery message sent")
Exemple #3
0
async def update_password(
    update_in: UpdatePassword,
    current_user: MarketAdminUser = Depends(require_active_admin)):
    if not verify_password(update_in.old_pwd, current_user.password,
                           current_user.uuid.hex):
        raise HTTPException(status_code=400, detail="密码错误")
    user = await MarketAdminUser.get(id=current_user.id)
    user.password = get_password_hash(update_in.new_pwd, current_user.uuid.hex)
    await user.save()
    return CommonOut()
Exemple #4
0
async def register_user(user_in: UserCreate, response: Response):
    """
    Create new user.
    """
    # 验证验证码
    # await verify_code(user_in.vcode_id, user_in.vcode)
    await verify_auth_code(user_in.phone, user_in.email, user_in.sms_code)

    get_filter = Q(name=user_in.name)
    if not (user_in.phone or user_in.email):
        raise HTTPException(status_code=400, detail="Must specify phone/email")

    if user_in.phone:
        get_filter = Q(phone=user_in.phone)
    if user_in.email:
        get_filter |= Q(email=user_in.email)
    user = await MarketUser.get_or_none(get_filter)
    if user:
        raise HTTPException(
            status_code=403,
            detail="该账号已存在,请登录!",
        )
    try:
        market = await StrategyMarket.get(id=config.MARKET_ID)
    except DoesNotExist:
        raise HTTPException(status_code=500, detail="配置错误,请联系管理员!")
    password = user_in.password
    if len(password) > 16:
        raise HTTPException(
            status_code=403,
            detail="密码不能超过16位",
        )
    elif len(password) < 8:
        raise HTTPException(
            status_code=403,
            detail="密码不能少于8位",
        )
    user_data = user_in.dict()
    user_data["uuid"] = uuid.uuid1().hex
    user_data["password"] = get_password_hash(password, user_data["uuid"])
    user_data["market"] = market
    user_data["status"] = UserStatus.normal
    # user_data["market"] = get_password_hash(user_in.password, user_data["uuid"])
    user = MarketUser(**user_data)
    await user.save()

    access_token_expires = timedelta(
        minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(data={"uuid": user.uuid.hex},
                                       expires_delta=access_token_expires)
    # response.headers[APIKEY_HEADER_NAME] = access_token
    response.set_cookie(key=APIKEY_HEADER_NAME, value=access_token)
    return UserToken(**user.__dict__, token=access_token)
Exemple #5
0
async def update_password(
    update_in: UpdatePassword,
    current_user: MarketUser = Depends(require_active_user)):
    """
    Reset password
    """
    if not verify_password(update_in.old_pwd, current_user.password):
        raise HTTPException(status_code=400, detail="incorrect password")

    current_user.password = get_password_hash(update_in.new_pwd)
    await current_user.save()
    return CommonOut()
Exemple #6
0
async def add_admin(
        schema_in: AdminUserCreate,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """添加管理员,需要总后台超管权限"""
    if current_user.scope1 != "aq" or current_user.scope2 != int(
            UserScope2.su):
        return CommonOut(errCode=-100, errMsg="添加失败,没有权限")
    marketadminuser = await MarketAdminUser.query.gino.all()
    print(marketadminuser, type(marketadminuser),
          'marketadminuser-------111111111111')
    name_list = []
    phone_list = []
    email_list = []
    for i in marketadminuser:
        name_list.append(i.name)
        phone_list.append(i.phone)
        email_list.append(i.email)
    print(name_list, 'name_list----222222222222222222')
    print(phone_list, 'phone_list---333333333333333333')
    print(email_list, 'email_list--------4444444444444')
    if name_list:
        if schema_in.name in name_list:
            return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")
    if phone_list:
        if schema_in.phone in phone_list:
            return CommonOut(errCode=-1, errMsg="添加失败,请检查手机号是否重复")
    if email_list:
        if schema_in.email in email_list:
            return CommonOut(errCode=-1, errMsg="添加失败,请检查邮箱是否重复")

    data = schema_in.dict()
    data["uuid"] = uuid.uuid1()
    data["password"] = get_password_hash(data["password"], data["uuid"].hex)
    try:
        await MarketAdminUser.create(uuid=data["uuid"],
                                     name=schema_in.name,
                                     phone=schema_in.phone,
                                     email=schema_in.email,
                                     password=data["password"],
                                     scope1=SUPER_SCOPE,
                                     scope2=UserScope2.simble,
                                     status=UserStatus.normal,
                                     create_dt=datetime.datetime.now(),
                                     update_dt=datetime.datetime.now())
    except Exception:
        logger.exception("create package failed: %s", schema_in.json())
        print(Exception, 'exp---2222222222')
        return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")

    return CommonOut()
Exemple #7
0
async def update_password(
    update_in: UpdatePassword,
    current_user: MarketUser = Depends(require_active_user)):
    """
    Reset password
    """
    if not verify_password(update_in.old_pwd, current_user.password,
                           current_user.uuid.hex):
        raise HTTPException(status_code=400, detail="incorrect password")

    user = await MarketUser.get(id=current_user.id)
    user.password = get_password_hash(update_in.new_pwd, current_user.uuid.hex)
    await user.save()
    # return {"msg": "Password updated successfully"}
    return CommonOut()
Exemple #8
0
async def change_password(
        update_in: AdminUpdatePassword,
        current_user: MarketAdminUser = Depends(require_active_admin),
):
    """更改密码"""
    #print(verify_password(update_in.old_pwd, current_user.password,current_user.uuid.hex),'passwort=====222222')
    if not verify_password(update_in.old_pwd, current_user.password,
                           current_user.uuid.hex):
        raise HTTPException(status_code=400, detail="incorrect password")

    #current_user.password = get_password_hash(update_in.new_pwd, current_user.uuid.hex)
    #await current_user.save()
    await current_user.update(
        password=get_password_hash(update_in.new_pwd, current_user.uuid.hex)
    ).apply()
    return CommonOut()
Exemple #9
0
async def add_admin(
        schema_in: AdminUserCreate,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """添加管理员,需要总后台超管权限"""
    if current_user.scope1 != "aq" or current_user.scope2 != UserScope2.su:
        return CommonOut(errCode=-100, errMsg="添加失败,没有权限")

    data = schema_in.dict()
    data["uuid"] = uuid.uuid1()
    data["password"] = get_password_hash(data["password"], data["uuid"].hex)
    try:
        await MarketAdminUser.create(**data)
    except Exception:
        logger.exception("create package failed: %s", schema_in.json())
        return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")

    return CommonOut()
Exemple #10
0
async def create_first_user():
    from market.models.const import SUPER_SCOPE, UserScope2
    from market.models import MarketAdminUser
    from market.core.security import get_password_hash

    # user = await MarketAdminUser.get_or_none(email=config.FIRST_SUPERUSER)
    user = await MarketAdminUser.query.where(
        MarketAdminUser.email == config.FIRST_SUPERUSER).gino.first()
    if not user:
        await MarketAdminUser.create(
            name="aqfake",
            phone="12300000000",
            email=config.FIRST_SUPERUSER,
            password=get_password_hash(config.FIRST_SUPERUSER_PASSWORD),
            scope1=SUPER_SCOPE,
            scope2=int(UserScope2.su),
        )
        print("!!! Created super super aqfake")
Exemple #11
0
async def add_admin(
        schema_in: AdminUserCreate,
        current_user: MarketAdminUser = Depends(require_super_scope_su),
):
    """添加管理员,需要总后台超管权限"""
    if current_user.scope1 != "aq" or current_user.scope2 != UserScope2.su:
        return CommonOut(errCode=-100, errMsg="添加失败,没有权限")

    marketadminuser = await MarketAdminUser.all()
    name_list = []
    phone_list = []
    email_list = []
    for i in marketadminuser:
        name_list.append(i.name)
        phone_list.append(i.phone)
        email_list.append(i.email)
    if name_list:
        if schema_in.name in name_list:
            return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")
    if phone_list:
        if schema_in.phone in phone_list:
            return CommonOut(errCode=-1, errMsg="添加失败,请检查手机号是否重复")
    if email_list:
        if schema_in.email in email_list:
            return CommonOut(errCode=-1, errMsg="添加失败,请检查邮箱是否重复")

    data = schema_in.dict()
    data["uuid"] = uuid.uuid1()
    data["password"] = get_password_hash(data["password"], data["uuid"].hex)
    try:
        await MarketAdminUser.create(**data)
        await MarketAdminUser.filter(name=schema_in.name
                                     ).update(scope2=UserScope2.simble)
    except Exception:
        logger.exception("create package failed: %s", schema_in.json())
        return CommonOut(errCode=-1, errMsg="添加失败,请检查名字是否重复")

    return CommonOut()
Exemple #12
0
async def register_user(user_in: UserCreate, response: Response):
    """
    Create new user.
    """
    # 验证验证码
    # await verify_code(user_in.vcode_id, user_in.vcode)
    await verify_auth_code(user_in.phone, user_in.email, user_in.sms_code)

    if not (user_in.phone or user_in.email):
        raise HTTPException(status_code=400, detail="Must specify phone/email")

    row = await MarketUser.select("id").where(MarketUser.name == user_in.name
                                              ).gino.all()
    if row:
        raise HTTPException(
            status_code=403,
            #detail="The user with this name already exists in the system.",
            detail="该用户名已存在,请直接登录!")
    if user_in.phone:
        row = await MarketUser.select("id").where(
            MarketUser.phone == user_in.phone).gino.all()
        if row:
            raise HTTPException(
                status_code=403,
                #detail="The user with this phone already exists in the system.",
                detail="该手机号已存在")
    if user_in.email:
        row = await MarketUser.select("id").where(
            MarketUser.email == user_in.email).gino.all()
        if row:
            raise HTTPException(
                status_code=403,
                #detail="The user with this email already exists in the system.",
                detail="该邮箱已存在")
    market = await StrategyMarket.get(int(config.MARKET_ID))
    if not market:
        raise HTTPException(status_code=500, detail="配置错误,请联系管理员!")
    user_data = user_in.dict()
    user_data["password"] = get_password_hash(user_in.password)
    user_data["market"] = market
    user_data["status"] = int(UserStatus.normal)
    #user = await MarketUser.create(**user_data)
    user = await MarketUser.create(
        name=user_in.name,
        phone=user_in.phone,
        email=user_in.email,
        uuid=uuid.uuid1().hex,
        password=get_password_hash(user_in.password),
        #sms_code = user_in.sms_code,
        broker_id=user_in.broker_id,
        #vcode_id = user_in.vcode_id,
        #vcode = user_in.vcode,
        market_id=int(market.id),
        status=int(UserStatus.normal),
    )

    access_token_expires = timedelta(
        minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    #print(user.uuid.hex,'uuid--------1222222222221111111111111')
    access_token = create_access_token(
        #data={"uuid": user.id}, expires_delta=access_token_expires
        data={"uuid": user.uuid.hex},
        expires_delta=access_token_expires)
    # response.headers[APIKEY_HEADER_NAME] = access_token
    response.set_cookie(key=APIKEY_HEADER_NAME, value=access_token)
    return UserToken(**user.__dict__["__values__"], token=access_token)