Ejemplo n.º 1
0
 def test_authenticate_wrong_email(self):
     """
     authenticate method must raise exception on wrong email
     """
     self.create_user()
     with self.assertRaises(Exception):
         User.authenticate('wrong_email', 'password')
Ejemplo n.º 2
0
def add_one():
    # 1
    user = User(open_id='test_open_id', nickname='test_nickname')
    user.save()

    # 2
    User.objects.create(open_id='test_open_id2', nickname='test_nickname2')
Ejemplo n.º 3
0
def __authorize_by_code(request):
    post_data = request.body.decode('utf-8')
    post_data = json.loads(post_data)
    print(post_data)
    code = post_data.get('code').strip()
    app_id = post_data.get("appId").strip()
    nick_name = post_data.get("nickName").strip()

    response = {}
    if not code or not app_id:
        response['message'] = "authoreized failed, need entire authorization data. "
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response, safe=False)

    data = c2s(app_id,code)
    openid = data.get('openid')
    if not openid:
        response = wrap_json_response(code=ReturnCode.FAILED, message="auth failed")
        return JsonResponse(data=response, safe=False)

    request.session['openid'] = openid
    request.session['is_authorized'] = True

    if not User.objects.filter(openid=openid):
        new_user = User(openid=openid, nickname=nick_name)
        new_user.save()

    response = wrap_json_response(code=ReturnCode.SUCCESS, message="auth success")
    return JsonResponse(data=response, safe=False)
    pass
Ejemplo n.º 4
0
    def delete_user_success(self, jwt_header):
        header = {'HTTP_AUTHORIZATION': jwt_header}
        response = self.client.delete(reverse('user'), **header)
        self.assertContains(response, 'ok', status_code=200)

        with self.assertRaises(Exception):
            User.get_current_user(jwt_header)
Ejemplo n.º 5
0
def __authorize_by_code(request):
    post_data = request.body.decode('utf-8')
    post_data = json.loads(post_data)
    code = post_data.get('code').strip()
    app_id = post_data.get('appId').strip()
    nickname = post_data.get('nickname').strip()

    response_data = {}
    if not code or not app_id:
        response_data[
            'message'] = 'authorized failed, need entire authorization data.'
        response_data['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response_data, safe=False)

    data = c2s(app_id, code)
    openid = data.get('openid')
    print('get openid:', openid)

    if not openid:
        response = CommonResponseMixin.wrap_json_response(
            code=ReturnCode.FAILED, message='auth failed')
        return JsonResponse(data=response, safe=False)
    request.session['open_id'] = openid
    request.session['is_authorized'] = True

    if not User.objects.filter(open_id=openid):
        new_user = User(open_id=openid, nickname=nickname)
        print('new_user:open_id:%s, nickname:%s' % (openid, nickname))
        new_user.save()
    response = CommonResponseMixin.wrap_json_response(code=ReturnCode.SUCCESS,
                                                      message='auth succeess')
    return JsonResponse(data=response, safe=False)
Ejemplo n.º 6
0
def get_author(request):
    post_data = request.body.decode('utf-8')
    post_data = json.loads(post_data)
    code = post_data.get('code').strip()
    appid = post_data.get('appid').strip()
    nickName = post_data.get('nickName').strip()
    response = {}
    if not code or not appid:
        response['message'] = 'authorize failed'
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response, safe=False)
    data = auth.c2s(appid, code)
    openid = data.get('openid')
    if not openid:
        response['message'] = 'authorize failed'
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response, safe=False)
    request.session['open_id'] = openid
    request.session['is_authorized'] = True
    if not User.objects.filter(openid=openid):
        user = User(openid=openid, nickname=nickName)
        user.save()
    response = CommonResponseMixin.wrap_json_response(code=ReturnCode.SUCCESS,
                                                      message='success auth')
    return JsonResponse(data=response, safe=False)
Ejemplo n.º 7
0
 def test_get_current_user_no_redis_entity(self):
     """
     get_current_user must raise error if no redis entity for user
     """
     user = self.create_user()
     encoded_jwt, timestamp = self.make_jwt(user)
     decoded_jwt = encoded_jwt.decode('utf-8')
     with self.assertRaises(Exception):
         User.get_current_user(decoded_jwt)
Ejemplo n.º 8
0
def add_one():
    '''
    添加用户,添加用户时openid不能重复
    :return:
    '''
    # 添加用户 法1
    user = User(openid='test_open_id', nickname='test_nickname')
    user.save()
    # 添加用户 法2
    User.objects.create(openid='test_lyq_id2', nickname='test_nickname')
Ejemplo n.º 9
0
 def test_get_user_from_request_without_header(self):
     """
     get_user_from_request must raise Exception on no Authorization header
     """
     user = self.create_user()
     encoded_jwt, timestamp = self.make_jwt(user)
     request = HttpRequest()
     User.redis_connection.database[encoded_jwt] = timestamp
     with self.assertRaises(Exception):
         User.get_user_from_request(request)
Ejemplo n.º 10
0
 def test_get_current_user_with_old_timestamp(self):
     """
     get_current_user must raise error if timestamp is timed out
     """
     user = self.create_user()
     encoded_jwt, timestamp = self.make_jwt(user)
     decoded_jwt = encoded_jwt.decode('utf-8')
     User.redis_connection.database[encoded_jwt] = timestamp - User.JWT_TIMEOUT - 1
     with self.assertRaises(Exception):
         User.get_current_user(decoded_jwt)
Ejemplo n.º 11
0
def __authorize_by_code(request):
    '''
    使用wx.login获取到的临时code发送到微信提供的code2session接口授权
    :param request:
    :return:
    '''
    post_data = request.body.decode(
        'utf-8')  # 接收冲微信小程序传过来的信息(code,appid,nickname)
    post_data = json.loads(post_data)
    code = post_data.get('code').strip()
    appid = post_data.get('appId').strip()
    nickname = post_data.get('nickname').strip()
    print('post 信息:', code)
    print(appid)
    print(nickname)

    response = {}
    if not code or not appid:
        response['message'] = '信息不完整'
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        print('信息不完整')
        return JsonResponse(data=response, safe=False)
    data = c2s(appid, code)
    print('data:', data)
    openid = data.get('openid')
    # print('openid:',openid)
    session_key = data.get('session_key')
    print('session_key:', session_key)

    if not openid:
        response = ResponseMixin.json_response(code=ReturnCode.FAILED,
                                               message='auth failed')
        return JsonResponse(data=response, safe=False)

    # 使用session中间件标记了两个数据
    request.session['openid'] = openid  # 获取的opeid
    request.session['is_authorize'] = True  # 是否已经认证,如果已经认证则需要判断用户是否在数据库中
    print('openid:', openid)
    print('nickname:', nickname)
    print(type(nickname))
    openid = json.dumps(openid)
    openid = json.loads(openid)

    print('!!!!!!!!!!', openid)
    # 如果重数据库中查询不到,则说明其不在数据库中,需要将此用户保存下来
    if not User.objects.filter(openid=openid):
        new_user = User(openid=openid, nickname=nickname)  # 新建用户
        print('openid:', openid)
        print('nickname:', nickname)
        new_user.save()  # 保存用户信息

    response = ResponseMixin.json_response(code=ReturnCode.SUCCESS,
                                           message='auth success')
    return JsonResponse(data=response, safe=False)
Ejemplo n.º 12
0
    def post(self, request, *args, **kwargs):
        username = request.data['username']
        email = request.data['email']
        password = request.data['password']
        allow_send_email = request.data['allow_send_email']

        user = User(username=username,
                    email=email,
                    password=password,
                    allow_send_email=allow_send_email)
        user.save()

        return Response(status=status.HTTP_200_OK)
Ejemplo n.º 13
0
def oauth_callback(provider):
    oauth = OAuthSignIn.get_provider(provider)
    social_id, username, email = oauth.callback()
    if social_id is None:
        return jsonify({'error': 'Auth error'}), 401
    user_social = User_social.query.filter_by(social_id=social_id).first()
    if not user_social:
        token = str(uuid.uuid4())
        hash_password = generate_password_hash(username, method='sha256')
        create_user = User(username=username,
                           password=hash_password,
                           token=token)
        db.session.add(create_user)
        db.session.flush()
        id = create_user.id

        user_social = User_social(social_id=social_id, id_user=id)
        db.session.add(user_social)

        db.session.commit()
    get_user = User.query.filter(User.id == user_social.id_user).one()
    token = jwt.encode(
        {
            'public_id': get_user.token,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
        }, current_app.config['SECRET_KEY'])
    res = make_response({
        'id': get_user.id,
        'have_personal_area': get_user.have_personal_area,
        'token': token.decode('UTF-8')
    })
    return res
Ejemplo n.º 14
0
def add_batch():
    new_user_list = []
    for i in range(10):
        open_id = ranstr(32)
        nickname = ranstr(10)
        user = User(open_id=open_id, nickname=nickname)
        new_user_list.append(user)
    User.objects.bulk_create(new_user_list)
Ejemplo n.º 15
0
 def test_authenticate(self):
     """
     authenticate method must return user and jwt and store jwt in redis
     """
     expected_user = self.create_user()
     user, encoded_jwt = User.authenticate('email', 'password')
     expected_jwt = list(User.redis_connection.database.keys())[0]
     self.assertEqual(expected_user.email, user.email, 'Wrong user returned')
     self.assertEqual(expected_jwt, encoded_jwt.encode('utf-8'), 'Wrong jwt returned')
Ejemplo n.º 16
0
 def test_get_current_user(self):
     """
     get_current_user must return authenticated user by jwt
     """
     user = self.create_user()
     encoded_jwt, timestamp = self.make_jwt(user)
     decoded_jwt = encoded_jwt.decode('utf-8')
     User.redis_connection.database[encoded_jwt] = timestamp
     authenticated_user = User.get_current_user(decoded_jwt)
     self.assertEqual(user.email, authenticated_user.email, 'Wrong user returned')
Ejemplo n.º 17
0
def __authorize_by_code(request):
    """
    使用wx.login()得到的临时code获得微信提供的code2session接口授权
    :param request:
    :return:
    """
    post_data = request.body.decode('utf-8')
    post_data = json.loads(post_data)
    code = post_data.get('code')
    app_id = post_data.get('appId')
    nickname = post_data.get('nickname')

    response = {}
    if not code or not app_id:
        response['message'] = '参数不完整'
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response, safe=False)
    data = code2session(appid=app_id, code=code)
    openid = data.get('openid')
    print('openid is ' + openid)

    if not openid:
        response = wrap_json_response(code=ReturnCode.FAILED,
                                      message='auth failed!')
        return JsonResponse(data=response, safe=False)

    # openid存在
    request.session['openid'] = openid
    request.session['is_authorized'] = True  # 是否已经认证

    # 如果成功认证,判断该用户是否在数据库中
    if not User.objects.filter(open_id=openid):  # 如果不在,将用户保存到数据库
        new_user = User(open_id=openid, nickname=nickname)
        new_user.save()
        response = wrap_json_response(code=ReturnCode.SUCCESS,
                                      message='auth success')
        print('auth is not in tables')
        return JsonResponse(data=response, safe=False)

    print('auth is in tables')
    response = wrap_json_response(code=ReturnCode.SUCCESS,
                                  message='auth success')
    return JsonResponse(data=response, safe=False)
Ejemplo n.º 18
0
    def test_other_user_auth(self):
        self._create_user()
        _, jwt_header = User.authenticate(self.EMAIL, self.PASSWORD)

        post_user = self._create_user(email='alternative_email')
        post, name, text = self._create_post_name_text(post_user)
        post.status = Post.ACTIVE
        post.save()

        self.update_post_wrong_user(post.pk, jwt_header)
        self.delete_post_wrong_user(post.pk, jwt_header)
Ejemplo n.º 19
0
    def test_post_live_cycle(self):
        self._create_user()
        _, jwt_header = User.authenticate(self.EMAIL, self.PASSWORD)

        post_pk = self.create_post_success(jwt_header).pk
        self.get_post_success(post_pk)

        self.update_post_success(post_pk, jwt_header)
        self.get_post_success(post_pk)

        self.delete_post_success(post_pk, jwt_header)
        self.get_post_error(post_pk)
Ejemplo n.º 20
0
    def check_post_reachable(self, post, request):
        if post.status == Post.DELETED:
            raise Exception('Post not found')

        if post.status != Post.ACTIVE:
            user = None
            try:
                user = User.get_user_from_request(request)
            except:
                pass
            if not user or not user.pk == post.author.pk:
                raise Exception('Post not found')
Ejemplo n.º 21
0
 def wrapper(request: HttpRequest, *args, **kwargs):
     try:
         user = User.get_user_from_request(request)
         if not user:
             raise Exception('User not found')
         return func(request, user, *args, **kwargs)
     except Exception as error:
         return JsonResponse({
             'status': 'error',
             'message': str(error)
         },
                             status=403)
Ejemplo n.º 22
0
 def generate_fake_user_data(cls, count):
     new_user_list = []
     for i in range(count):
         open_id = ranstr(32)
         nickname = ranstr(10)
         new_user = User(open_id=open_id, nickname=nickname)
         new_user_list.append(new_user)
         if i % 10000 == 0:
             print('created %d items.' % i)
             User.objects.bulk_create(new_user_list)
             new_user_list = []
     pass
Ejemplo n.º 23
0
 def test_get_user_from_request(self):
     """
     get_user_from_request must return authenticated user from request
     """
     user = self.create_user()
     encoded_jwt, timestamp = self.make_jwt(user)
     decoded_jwt = encoded_jwt.decode('utf-8')
     request = HttpRequest()
     request.META = {'HTTP_AUTHORIZATION': decoded_jwt}
     User.redis_connection.database[encoded_jwt] = timestamp
     authenticated_user = User.get_user_from_request(request)
     self.assertEqual(user.email, authenticated_user.email, 'Wrong user returned')
Ejemplo n.º 24
0
 def create_new_user(self, body):
     user = User(first_name=body['first_name'],
                 last_name=body['last_name'],
                 email=body['email'],
                 username=body['email'])
     user.set_password(body['password'])
     user.save()
Ejemplo n.º 25
0
 def create_user(self):
     user = User(first_name='first_name',
                 last_name='last_name',
                 email='email',
                 username='******')
     user.set_password('password')
     user.save()
     return user
Ejemplo n.º 26
0
 def post(self, request, *args, **kwargs):
     try:
         body = self.process_body(request, [
             'email',
             'password',
         ])
         user, encoded_jwt = User.authenticate(body['email'],
                                               body['password'])
         return self.respond_success_json({
             'jwt': encoded_jwt,
             'user': user.serialize()
         })
     except Exception as error:
         return self.respond_error_json(error, status=403)
Ejemplo n.º 27
0
 def _create_user(self, email=None):
     email = email if email else self.EMAIL
     user = User(first_name='first_name',
                 last_name='last_name',
                 email=email,
                 username=email)
     user.set_password(self.PASSWORD)
     user.save()
     return user
Ejemplo n.º 28
0
def __authorize_by_code(request):
    """
    使用wx.login拿到的临时code到微信提供的code2session接口授权
    """
    post_data = request.body.decode('utf-8')
    post_data = json.loads(post_data)
    code = post_data.get('code').strip()
    app_id = post_data.get('appId').strip()
    nickname = post_data.get('nickname').strip()

    response = {}
    if not code or not app_id:
        response['message'] = '认证不完整,需要完整数据'
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response, safe=False)

    # 将app_id和code拼凑成url,去微信接口服务做认证,返回值是认证结果
    data = c2s(app_id, code)
    openid = data.get('openid')
    print('get openid:',openid)
    if not openid:
        # 如果openid不存在,返回认证失败的接口信息
        response = CommonResponseMixin.wrap_json_response(code=ReturnCode.SUCCESS, message='auth failed')
        return JsonResponse(data=response, safe=False)

    # open_id存在就做进一步开发,利用session中间件标记两个数据
    request.session['open_id'] = openid
    request.session['is_authorized'] = True

    if not User.objects.filter(open_id=openid):
        # 如果数据库中查不到这个open_id就保存
        new_user = User(open_id=openid, nickname=nickname)
        print('new user: open_id: %s, nickname: %s' %(openid, nickname))
        new_user.save()

    response = CommonResponseMixin.wrap_json_response(code=ReturnCode.SUCCESS, message='auth success')
    return JsonResponse(data=response, safe=False)
Ejemplo n.º 29
0
def add_batch():
    '''
    批量添加用户
    :return:
    '''
    new_user_list = []
    # 用于向列表中添加数据
    for i in range(10):
        openid = ranstr(32)
        nickname = ranstr(10)
        user = User(openid=openid, nickname=nickname)
        new_user_list.append(user)

    # 批量添加数据,(将列表中的数据批量添加到数据库中)
    User.objects.bulk_create(new_user_list)
Ejemplo n.º 30
0
 def generate_fake_user_data(cls, count):
     all_app = App.objects.all()
     new_user_list = []
     for i in range(count):
         open_id = ranstr(32)
         nickname = ranstr(10)
         new_user = User(open_id=open_id, nickname=nickname)
         new_user_list.append(new_user)
         if i % 1000 == 0:
             print('created %d items.' % i)
             User.objects.bulk_create(new_user_list)
             new_user_list = []
     all_user = User.objects.all()
     for user in all_user:
         user.menu.set(
             random.sample(list(all_app),
                           random.randint(1, all_app.count())))
         user.save()