Example #1
0
 def test_validate_verify(self):
     user_id = str(1)
     code_type = str(4)
     verify_delta = timedelta(hours=48)
     v = Verify.add(user_id, code_type, verify_delta)
     v = Verify.validate(user_id, v.code, code_type)
     assert v is not None
Example #2
0
 def test_get_verify_by_code(self):
     user_id = str(1)
     code_type = str(4)
     verify_delta = timedelta(hours=48)
     v = Verify.add(user_id, code_type, verify_delta)
     verify_code = v.code
     oldv = v
     v = Verify.gets_by_code(verify_code)[0]
     self.assertTrue(v)
     self.assertEqual(v.id, oldv.id)
     self.assertEqual(v.user_id, oldv.user_id)
     self.assertEqual(v.type, oldv.type)
     self.assertEqual(v.verify_time, oldv.verify_time)
Example #3
0
def reset_mobile_user_password():
    '''
    /j/account/reset_mobile_user_password
    '''
    # 校验手机号是否对应已存在的用户
    mobile = request.form.get('mobile')
    user = Account.get_by_alias(mobile)
    if not user:
        return jsonify(r=False, error=u'该手机号尚未注册好规划')

    # 校验验证码是否正确
    code = request.form.get('code')
    try:
        v = Verify.validate(user.id_, code, VERIFY_CODE_TYPE.FORGOT_PASSWORD_MOBILE)
        v.delete()
    except VerifyCodeException as e:
        return jsonify(r=False, error=unicode(e))

    # 校验密码是否合法一致
    new_password = request.form.get('new_password')
    confirmed_password = request.form.get('confirmed_password')

    try:
        reset_password(user, new_password, confirmed_password)
    except PasswordValidationError as e:
        return jsonify(r=False, error=unicode(e))
    else:
        return jsonify(r=True)
Example #4
0
def reset_for_mail_user(user_id, code):
    error = ''
    user = Account.get(user_id)
    if not user:
        return redirect(url_for('.reset_failed'))

    try:
        # 当post时才删除验证码
        v = Verify.validate(user.id_, code,
                            VERIFY_CODE_TYPE.FORGOT_PASSWORD_EMAIL)
        if request.method == 'POST':
            v.delete()
    except VerifyCodeException as e:
        return redirect(url_for('.reset_failed'))

    if request.method == 'POST':
        # 校验密码是否合法一致
        new_password = request.form.get('new-password')
        confirmed_password = request.form.get('confirmed-password')

        try:
            reset_password(user, new_password, confirmed_password)
        except PasswordValidationError as e:
            error = unicode(e)
        else:
            return redirect(url_for('.reset_success'))
    return render_template('accounts/reset_mail_user_password.html',
                           error=error)
Example #5
0
 def validate_verify_code(self, field):
     user = Account.get_by_alias(self.mobile.data)
     if user:
         try:
             v = Verify.validate(user.id_, field.data, VERIFY_CODE_TYPE.REG_MOBILE)
             v.delete()
         except VerifyCodeException as e:
             raise validators.ValidationError(unicode(e))
Example #6
0
 def test_delete_verify(self):
     user_id = str(1)
     code_type = str(4)
     verify_delta = timedelta(hours=48)
     v = Verify.add(user_id, code_type, verify_delta)
     v.delete()
     v = v.get(v.id)
     self.assertFalse(v)
Example #7
0
 def test_add_verify(self):
     user_id = str(1)
     code_type = str(4)
     verify_delta = timedelta(hours=48)
     v = Verify.add(user_id, code_type, verify_delta)
     self.assertTrue(v)
     self.assertEqual(user_id, v.user_id)
     self.assertEqual(code_type, v.type)
Example #8
0
def send_reset_password_mail(user):
    if user.email.strip().endswith(INSECURE_EMAIL_DOMAINS):
        raise InsecureEmailError()

    v = Verify.add(user.id, VERIFY_CODE_TYPE.FORGOT_PASSWORD_EMAIL)
    mail_template_args = {
        'name': user.name,
        'uid': user.id,
        'url': url_for(
            'accounts.password.reset_for_mail_user', user_id=user.id_,
            code=v.code, _external=True, _scheme='https')
    }
    mail = Mail.create(user.email, reset_password_mail, **mail_template_args)
    mail.send()
Example #9
0
def reset_password_sms_verify():
    """重置密码(验证短信验证码)

    要使用本接口, 客户端必须有权以 ``user_info`` 作为 scope.

    :request: :class:`.ResetPasswordSmsVerifySchema`
    :response: :class:`.IdentityVoucherSchema`

    :reqheader X-Client-ID: OAuth 2.0 Client ID
    :reqheader X-Client-Secret: OAuth 2.0 Client Secret
    :status 403: 验证码错误或账号不存在
    :status 200: 验证通过
    """
    reset_password_sms_verify_schema = ResetPasswordSmsVerifySchema(
        strict=True)
    identity_voucher_schema = IdentityVoucherSchema(strict=True)

    result = reset_password_sms_verify_schema.load(
        request.get_json(force=True))
    user = Account.get_by_alias(result.data['mobile_phone'])
    if not user:
        abort(403, u'账号不存在')
    try:
        v = Verify.validate(user.id_, result.data['sms_code'],
                            VERIFY_CODE_TYPE.FORGOT_PASSWORD_MOBILE)
        v.delete()
        identity = Identity.get(user.id_)
        confirmed_code = VerifyVoucher(user.id_)
        confirmed_code.voucher = ''.join(random.sample(string.digits, 6))
        data = {
            'confirmed_code': confirmed_code.voucher,
            'uid': user.id_,
            'masked_name': identity
        }
        return jsonify(success=True,
                       data=identity_voucher_schema.dump(data).data)
    except VerifyCodeException as e:
        abort(403, unicode(e))
Example #10
0
    def create(cls, mobile, sms_kind, user_id=None, **sms_args):
        """为已注册用户发送短信"""
        assert isinstance(sms_kind, ShortMessageKind)

        if validate_phone(mobile) != errors.err_ok:
            raise ValueError(u'invalid mobile %s' % mobile)

        if sms_kind.need_verify:
            if not (user_id and Account.get(user_id)):
                raise ValueError(u'unable to verify user %s' % user_id)
            v = Verify.add(user_id, sms_kind.verify_type,
                           sms_kind.verify_delta)
            sms_args.update(verify_code=v.code)

        sms = cls(uuid4().hex)
        # simply check formatting
        sms_kind.content.format(**sms_args)
        sms.update_props_items({
            u'receiver_mobile': mobile,
            u'sms_kind_id': sms_kind.id_,
            u'sms_args': sms_args
        })
        return sms
Example #11
0
def register_verify():
    """注册新用户(验证短信验证码)

    要使用本接口, 客户端必须有权以 ``user_info`` 作为 scope.

    :request: :class:`.RegisterVerifySchema`
    :response: :class:`.UserSchema`

    :reqheader X-Client-ID: OAuth 2.0 Client ID
    :reqheader X-Client-Secret: OAuth 2.0 Client Secret
    :status 403: 注册被拒
    :status 200: 注册成功
    """
    register_verify_schema = RegisterVerifySchema(strict=True)
    user_schema = UserSchema(strict=True)

    result = register_verify_schema.load(request.get_json(force=True))
    user = Account.get_by_alias(result.data['mobile_phone'])
    if not user:
        return jsonify(success=False,
                       messages={'mobile_phone': ['该手机号与验证码不符,请确认后重试']}), 403

    try:
        v = Verify.validate(user.id_, result.data['sms_code'],
                            VERIFY_CODE_TYPE.REG_MOBILE)
        v.delete()
    except VerifyCodeException as e:
        return jsonify(success=False, messages={'sms_code': [unicode(e)]}), 403

    error_tuple = confirm_register(user.id_)
    if error_tuple != errors.err_ok:
        return jsonify(success=False,
                       messages={'mobile_phone': ['用户状态异常,请联系客服']}), 403
    initial_new_user(user.id_, result.data['password'])
    events['register_success'].send(request, user_id=user.id_)

    return jsonify(success=True, data=user_schema.dump(user).data)
Example #12
0
def verify_bind(user_id, code):
    try:
        v = Verify.validate(user_id, code, VERIFY_CODE_TYPE.BIND_MOBILE)
        v.delete()
    except VerifyCodeException as e:
        raise BindError(unicode(e))