예제 #1
0
    def test_list_user_recommendation(self, mock_verify_id_token):
        """There must not be recommended users because anotehr users contacts contain my number."""
        mock_time = pendulum.datetime(2020, 5, 21, 12)
        pendulum.set_test_now(mock_time)

        # insert user_1
        mock_verify_id_token.return_value = dict(uid=mock_user_1["uid"])
        response_1 = create_user_1(self.app)
        self.assertEqual(response_1.status_code, 200)
        # insert user_2
        mock_verify_id_token.return_value = dict(uid=mock_user_2["uid"])
        response_2 = create_user_2(self.app)
        self.assertEqual(response_2.status_code, 200)

        User.objects(uid=mock_user_1["uid"]).update(available=True)
        User.objects(uid=mock_user_2["uid"]).update(available=True)

        response = self.app.get("/users/{user_id}/recommendation".format(
            user_id=response_1.get_json().get("_id")),
                                headers=dict(uid=mock_user_1["uid"]),
                                content_type="application/json")

        self.assertEqual(response.status_code, 500)
        recommendation = Recommendation.objects.first()
        self.assertEqual(len(recommendation.user_ids), 0)
예제 #2
0
def populateDB():
    """
		For testing and debugging purposes
	"""
    Config.load_config()
    task1 = Task(None, 1, "Make full maps",
                 "Map variables and create relations table with foreign keys",
                 None)
    task1.save()
    task2 = Task(None, 1, "Make coffee", "make coffee and drink it", None)
    task2.save()
    task3 = Task(None, 1, "Buy present", "buy present for april", None)
    task3.save()
    container1 = TasksContainer(None, 1, "todo")
    container1.add_task(task2, task3)
    container1.save()
    container2 = TasksContainer(None, 1, "testing")
    container2.add_task(task1)
    container2.save()
    container3 = TasksContainer.get_by_id(container1._id)
    container3.print_container()
    task3.detail = "Updated details"
    task3.save()
    container3._name = "Updated name"
    container3.save()
    user = User(None, 'admin', 'admin', '*****@*****.**', True)
    user.save()
예제 #3
0
    def post(self):
        """
        Sign-up API

        The body should be a JSON dictionary including the following attribute(s):
        - `username`: `str`
        - `real_name`: `str`
        - `password`: `str`
        - `id_card`: `str`
        - `phone_number`: `str`
        - `email`: `str`

        **return**: A JSON dictionary with values:
        - `code`: `int`, equals to 0 if sign-up is successful
        - `error`: `str`, shown if `code != 0`
        """
        session = DBSession()
        try:
            body = request.get_json()
            if session.query(User).filter(
                    User.username == body.get('username')).first() is not None:
                return jsonify(error='Username already exists', code=406)
            new_user = User(**body)
            new_user.hash_password()
            session.add(new_user)
            session.commit()
            return jsonify(code=0)
        except:
            session.rollback()
            return jsonify(code=10,
                           error='Unexpected error when creating user')
        finally:
            session.close()
예제 #4
0
    def test_user_images_approval(self, verify_id_token):

        uid = mock_user_1.get("uid")

        verify_id_token.return_value = dict(uid=uid)
        response_1 = create_user_1(self.app)

        user = response_1.get_json()

        # read file and send to server.
        file_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "testdata/nyan.png")

        with open(file_dir, "rb") as image:
            file = image.read()
            b = bytearray(file)

            response = self.app.post(
                "/users/{user_id}/user_images/{index}".format(
                    user_id=user["_id"], index=0),
                headers=dict(uid=uid),
                data=dict(user_image=(io.BytesIO(b), "test.jpg")),
                follow_redirects=False,
                content_type="multipart/form-data")
            self.assertEqual(response.status_code, 200)

            response = self.app.post(
                "/users/{user_id}/user_images/{index}".format(
                    user_id=user["_id"], index=1),
                headers=dict(uid=uid),
                data=dict(user_image=(io.BytesIO(b), "test.jpg")),
                follow_redirects=False,
                content_type="multipart/form-data")
            self.assertEqual(response.status_code, 200)

            response = self.app.post(
                "/users/{user_id}/user_images/{index}".format(
                    user_id=user["_id"], index=2),
                headers=dict(uid=uid),
                data=dict(user_image=(io.BytesIO(b), "test.jpg")),
                follow_redirects=False,
                content_type="multipart/form-data")
            self.assertEqual(response.status_code, 200)

        # retrieve it again and check
        user = User.objects(uid=uid).first()
        self.assertEqual(len(user.user_images), 0)
        self.assertEqual(len(user.user_images_temp), 3)

        response = self.app.put(
            "/users/{user_id}/status/approval".format(user_id=str(user.id)))

        user = User.objects(uid=uid).first()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(user.user_images), 3)
        self.assertEqual(len(user.user_images_temp), 3)

        for index, _ in enumerate(user.user_images):
            self.assertEqual(user.user_images[index],
                             user.user_images_temp[index])
예제 #5
0
    def test_user_from_dict(self):
        uid = "urYr3"
        secret = "1111"
        params_valid = dict()
        params_valid['uid'] = uid
        params_valid['name'] = "Mario"
        params_valid['icon'] = ""
        params_valid['secret'] = secret

        success_valid, user = User.from_dict(params=params_valid)
        assert success_valid, "failed to get User from dict"
        assert user.uid == uid
        assert user.secret == secret
        print "[test_user_from_dict] test case 0 finished"

        params_invalid_0 = dict()
        params_invalid_0['uid'] = uid
        params_invalid_0['name'] = "Mario"
        # params_invalid_0['secret'] = secret

        success_invalid_0, info = User.from_dict(params=params_invalid_0)
        assert not success_invalid_0, "expected KeyError, " + info
        print "[test_user_from_dict] test case 1 finished"

        params_invalid_1 = None

        success_invalid_1, info = User.from_dict(params=params_invalid_1)
        assert not success_invalid_0, info
        print "[test_user_from_dict] test case 2 finished"
예제 #6
0
파일: app.py 프로젝트: CleytonRR/pontoTel
 def post(self):
     """
            Cria um novo usuário
            ---
            parameters:
              - name: nome
                in: body
                type: string
                required: true
                default: { 'nome': 'any_name'}
            responses:
              201:
                description: Retorna um usuario baseado no nome
                schema:
                  id: User
                  properties:
                    message:
                      type: string
              400:
                description: Se ocorrer qualquer erro
     """
     try:
         dados = request.json
         user = User(name=dados['nome'])
         user.save()
         response = {
             'id': user.id,
             'nome': user.name,
         }
     except:
         response = {'message': 'erro verifique os campos'}
         return response, 400
     return response, 201
예제 #7
0
    def test_test(self):
        hojin_id = "5faa48e3181d410288943c88"
        hojin = User.objects(id=hojin_id).first()

        hojin.update(last_login_at=pendulum.now().int_timestamp)

        user = User.objects(id="5fa18ff392ccc8049e8766fd").first()
        print(user)
        nin_ids = user._get_nin_ids()
        users = User.objects(
            location__near=user.location["coordinates"],
            location__max_distance=5 * 1000,  # 5 km
            last_login_at__gte=pendulum.now().int_timestamp - (60 * 30),
            available=True,
            id__nin=nin_ids,
            sex="M").as_pymongo()

        ids = user._get_nin_ids()

        for _id in ids:
            if str(_id) == hojin_id:
                print(_id)

        for u in users:
            if str(u["_id"]) == hojin_id:
                print(u.to_json())
예제 #8
0
    def test_create_requests(self):
        import json
        user = User.objects(id="602ebbae11062b9a8edabb0a").first()
        requests = user.list_requests_to_me()
        start = pendulum.now().int_timestamp

        key = "user_from"

        _requests = []
        _ids = []

        for req in requests:
            req = req.to_mongo()
            subject_id = req.get(key, None)
            _ids.append(subject_id)
            _requests.append(req)

        users = User.objects(id__in=_ids).all()

        hash_index = dict()
        for user in users:
            _id = str(user.id)
            hash_index[_id] = user.to_mongo()

        for req in _requests:
            req[key] = hash_index[req.get(key)]

        end = pendulum.now().int_timestamp
        elapsed = end - start
        print(elapsed)
예제 #9
0
def login():
    user = User()

    login = request.form.get('login')
    password = request.form.get('password')

    user_data = user.query.filter( User.user_name == login ).first()
    if not user_data:
        return render_template(
                    'login.tmpl',
                    login='******',
                    nav_get_parents=nav_get_parents(),
                )

    if user.check_user_pass(user_id=user_data.id, password=password):
        render = render_template('login.tmpl', login=login, nav_get_parents=nav_get_parents(),)
        #resp = make_response(render)
        #resp.set_cookie('username', user_data.user_name)
        session['username'] = user_data.user_name
        session['user_id'] = user_data.id
        return redirect(request.referrer) or redirect(url_for('index'))
    else:
        return render_template(
                    'login.tmpl',
                    login='******',
                    nav_get_parents=nav_get_parents(),
                )
예제 #10
0
파일: bot.py 프로젝트: maddeer/bookshell
def command_handler(bot, update, user_data):
    global ANSWERS
    answer = ANSWERS[update.message.text][0]
    if update.message.text == '/save_my_book':
        genre_dict = get_genre_dict()
        genres = []
        for genre in user_data.get('genre'):
            genres.append(genre_dict[genre])
        user_data['genre'] = genres
        save_the_book(
            user_data.get('name'),
            User.get_id_by_telegram_name(update.message.chat.username),
            user_data.get('text_from_file'), user_data.get('description'),
            user_data.get('chapter_name'), user_data.get('genre'))
    elif update.message.text == '/choose_genres':
        genre_dict = get_genre_dict()
        for line in genre_dict.keys():
            answer += line
            answer += ', '
    elif update.message.text == '/by_author':
        authors_id_list = Author.get_authors_with_books()
        for author_id in authors_id_list:
            answer += ' ' + User.query.filter(
                User.id == author_id).first().user_name
    elif update.message.text == '/by_genre':
        for line in Genre.get_parents():
            answer += line.genre_name + ' '
    elif update.message.text == '/start':
        if User.get_id_by_telegram_name(update.message.chat.username) is None:
            answer = ANSWERS[update.message.text][2]
    update.message.reply_text(answer)
    return ANSWERS[update.message.text][1]
예제 #11
0
    def test_user_update_holder(self):
        # 1. create users
        user1 = User(uid="test0", name="test0", secret="1111")
        user2 = User(uid="test1", name="test1", secret="1111")

        # 2. imitate dialog
        # dialog_holders = DialogsHolders.get_instance()
        #
        # list_of_users = list()
        # list_of_users.append(user1.uid)
        # list_of_users.append(user2.uid)
        #
        # success, dialog = dialog_holders.create_dialog(list_of_users=list_of_users)

        # 3. prepare messages
        msg1 = Message(dialog_id="test", text="test text", from_id=user1.uid, time_stamp=-1)
        msg2 = Message(dialog_id="test", text="text test", from_id=user2.uid, time_stamp=-2)

        # 4. prepare update holders
        update_holder_u1 = UserUpdateHolder(user_id=user1.uid)
        update_holder_u2 = UserUpdateHolder(user_id=user2.uid)

        update_holder_u1.add(message=msg1, dialog_id="test")
        update_holder_u1.add(message=msg2, dialog_id="test")

        update_holder_u1_dict = update_holder_u1.get_as_dict()
        update_holder_u2_dict = update_holder_u2.get_as_dict()

        j_result = update_holder_u1.get_as_json()

        print "[test_user_update_holder] test cases finished"
        pass  # do not know how to automate validation -> seems to be OK
def list_users_close():
    """Endpoint for getting users."""
    uid = request.headers.get("uid", None)
    
    user_session = User.objects.get_or_404(uid=uid)
    
    users = User.objects(
        location__near=user_session.location["coordinates"],
        location__max_distance=5 * 1000  # 5 km
    ).all()
    
    user_ids = [user.id for user in users]
    
    random.seed(get_hash(uid) + 1)
    random.shuffle(user_ids)
    
    selected_users = User.objects(
        id__in=user_ids[:4]).all()
    
    converted = []
    for selected_user in selected_users[:4]:
        selected_user.uid = None
        converted.append(
            json.loads(selected_user.to_json(
                follow_reference=True, max_depth=1
            )))
    return Response(
        json.dumps(converted),
        mimetype="application/json")
def route_poke(user_id_to):
    uid = request.headers.get("uid", None)
    
    user_from = User.objects(uid=uid).get_or_404()
    
    user_to = User.objects(id=user_id_to).get_or_404()
    
    alert = alerts_blueprint.create_alert(
        user_from, user_to, push_type="POKE",
        message="{nick_name} 님이 당신을 찔렀습니다.".format(
            nick_name=user_from.nick_name))
    push_item = alert.records[-1]
    data: dict = alerts_blueprint.dictify_push_item(push_item)
    
    try:
        message = messaging.Message(
            data=data, token=user_to.r_token,
            apns=messaging.APNSConfig(),
            android=messaging.AndroidConfig(priority="high"),
            notification=messaging.Notification())
        messaging.send(message)
    except Exception as e:
        logging.exception(e)
    
    return Response(
        user_to.to_json(),
        mimetype="application/json")
예제 #14
0
파일: run.py 프로젝트: schopr9/flask-ubuntu
def user_new():
    """create new user"""
    raw_dict = request.get_json(force=True)
    try:
        user_schema.validate(raw_dict)
        user_dict = raw_dict['data']['attributes']
        user = User(user_dict['username'], user_dict['email'])
        user.add(user)
        query = User.query.filter_by(email=user_dict['email']).first()
        print query
        results = user_schema.dump(query).data
        print results
        return jsonify({"id": query.id})

    except ValidationError as err:

        resp = jsonify({"error": err.messages})
        resp.status_code = 403
        return resp

    except SQLAlchemyError as e:
        db.session.rollback()
        resp = jsonify({"error": str(e)})
        resp.status_code = 403
        return resp
예제 #15
0
def register(username, email):
    user = User(username, email)
    db.session.add(user)
    db.session.commit()
    saved_user_list = User.query.filter_by(username=user.get_username(),
                                           email=email).all()
    return saved_user_list[len(saved_user_list) - 1]
예제 #16
0
 def test_phone_query_performance(self):
     user = User.objects(uid=dldyddn0624_uid).first()
     start = pendulum.now().int_timestamp
     contact = Contact.objects(owner=user).first()
     phone_users = User.objects(phone__in=contact.phones).only("id").all()
     user_ids = set([str(user.id) for user in phone_users])
     end = pendulum.now().int_timestamp
     elapsed = end - start
     print(elapsed)
     self.assertEqual(elapsed < 1, True)
     self.assertEqual(len(user_ids), 505)
예제 #17
0
    def test_does_know_each_other(self):
        from model.models import Resource
        posts = Post.objects.all()
        for post in posts:
            if post.url is not None:
                post.resources.append(Resource(type="IMAGE", url=post.url))
                post.save()

        user1 = User.objects(id="6033ebb511062b6d1e495f1b").first()
        user2 = User.objects(id="6033eff011062b6d1e495f1f").first()
        result = user1.does_know_each_other(user2)
        print(result)
예제 #18
0
    def test_user_history_holder(self):
        #####
        # from previous test

        # 1. create users
        user1 = User(uid="uid_test0", name="name test0", secret="secr1111")
        user2 = User(uid="uid_test1", name="name test1", secret="secr1111")

        # 2. imitate dialog
        # dialog_holders = DialogsHolders.get_instance()
        #
        # list_of_users = list()
        # list_of_users.append(user1.uid)
        # list_of_users.append(user2.uid)
        #
        # success, dialog = dialog_holders.create_dialog(list_of_users=list_of_users)

        # 3. prepare messages
        msg1 = Message(dialog_id="did_test", text="test from_id=user1.uid", from_id=user1.uid, time_stamp=-1)
        msg2 = Message(dialog_id="did_test", text="text from_id=user2.uid", from_id=user2.uid, time_stamp=-2)
        msg3 = Message(dialog_id="did_test", text="text from_id=user2.uid 2", from_id=user2.uid, time_stamp=-3)

        # 4. prepare update holders
        update_holder_u1 = UserUpdateHolder(user_id=user1.uid)
        update_holder_u2 = UserUpdateHolder(user_id=user2.uid)

        update_holder_u1.add(message=msg1, dialog_id="did_test")
        update_holder_u1.add(message=msg2, dialog_id="did_test")
        update_holder_u1.add(message=msg3, dialog_id="did_test")

        update_holder_u1_dict = update_holder_u1.get_as_dict()
        update_holder_u2_dict = update_holder_u2.get_as_dict()

        j_result = update_holder_u1.get_as_json()

        #####
        # this test

        history_holder_u1 = UserHistoryHolder(user_id=user1.uid)
        history_holder_u2 = UserHistoryHolder(user_id=user2.uid)

        for did, dialog_update in update_holder_u1.storage.iteritems():
            history_holder_u1.on_add(dialog_update_list=dialog_update)

        for did, dialog_update in update_holder_u1.storage.iteritems():
            history_holder_u2.on_add(dialog_update_list=dialog_update)

        history_holder_u1_dict = history_holder_u1.to_dict()
        history_holder_u2_dict = history_holder_u2.to_dict()

        print "[test_user_history_holder] test cases finished"
        pass  # todo: automate validation
예제 #19
0
def signup():
    """."""
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username and password:
            user = User(name=username)
            user.password = generate_password_hash(password=password)
            user.save()
        return redirect(url_for('home'))
    return render_template('signup.html', error=error)
예제 #20
0
def route_list_all_favorite_users(post_id):
    uid = request.headers.get("uid", None)
    post = Post.objects.get_or_404(id=post_id)

    if post.author.uid != uid:
        abort(401)

    favorite_user_ids = post.favorite_user_ids
    users = User.objects(id__in=favorite_user_ids) \
        .exclude(*User.excludes()).as_pymongo()

    response = encode(list(users))
    return Response(response, mimetype="application/json")
예제 #21
0
def signIn():

    if current_user.is_authenticated:
        return redirect(url_for("index"))

    form = SignUpForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash("Congrats you successfully created your account, please login")
        return redirect(url_for("login"))

    return render_template("signIn.html", form=form)
예제 #22
0
def route_create_thumb_up(post_id, comment_id):
    uid = request.headers.get("uid", None)
    if not uid:
        abort(401)

    user = User.objects.get_or_404(uid=uid)
    post = Post.objects.get_or_404(id=post_id)
    comment = next(
        (comment
         for comment in post.comments if str(comment.id) == comment_id), None)

    if not comment:
        abort(404)

    comment.update(add_to_set__thumb_up_user_ids=user.id,
                   pull__thumb_down_user_ids=user.id)
    comment = Comment.objects.get_or_404(id=comment_id)

    if user.id == post.author.id:
        user_from = user
        user_to = User.get(id=comment.user_id)

        alarm = Alarm.create_alarm(
            user_from=user_from,
            user_to=user_to,
            event=Alarm.Event.COMMENT_THUMB_UP,
            post=post,
            comment=comment,
            message="{nickname} 님이 당신의 댓글을 좋아합니다.".format(
                nickname=user_from.nickname))
        alarm_record = alarm.records[-1]
        data = alarm_record.as_dict()
        message_service.push(data, user_to)

    return Response("", mimetype="application/json")
예제 #23
0
def profile(user_id=None):
    username = session.get('username')
    session_user_id = session.get('user_id')
    owner=False

    if not user_id:
        user_id = session_user_id

    edit = False

    user = User()
    user_data = user.query.filter( User.id == user_id ).first()

    if session_user_id == user_id:
        edit_raw = request.args.get('edit', 'False')
        if edit_raw.capitalize() == 'True':
            edit = True

        owner=True

        if request.form:
            update_profile(user_data=user_data, update_form=request.form)

    return render_template(
                'user_profile.tmpl',
                username=username,
                user_data=user_data,
                owner=owner,
                edit=edit,
                nav_get_parents=nav_get_parents(),
            )
예제 #24
0
 def get(self):
     userName=self.request.get('UserName')
     user=User.get_by_key_name('u'+userName)
     if user:
         self.render('templates/userinfo.html',{'user':user})
     else:
         self.response.out.write(u'查无此人')
예제 #25
0
def add_new_user(name, email, password):
    new_user = User(name=name,
                    email=email,
                    password=password,
                    time=datetime.datetime.now())
    db.session.add(new_user)
    db.session.commit()
예제 #26
0
 def test_update_image(self, verify_id_token):
     """Checks for an update of an image that already exists.."""
     # mock_user_1 has images.
     uid = mock_user_1.get("uid")
     image_index_to_update = 2
     
     # insert user
     response = self.app.post(
         "/users", data=json.dumps(mock_user_1),
         headers=dict(uid=mock_user_1["uid"]),
         content_type="application/json")
     response = self.app.put(
         "/users/profile", data=json.dumps(mock_user_1),
         headers=dict(uid=mock_user_1["uid"]),
         content_type="application/json")
     
     # read file and send to server.
     file_dir = os.path.join(
         os.path.dirname(os.path.abspath(__file__)),
         "testdata/nyan.png")
     
     with open(file_dir, "rb") as image:
         file = image.read()
         b = bytearray(file)
         response = self.app.post(
             "/users/user_images/{index}".format(
                 uid=uid, index=0),
             headers=dict(uid=uid),
             data=dict(file=(io.BytesIO(b), "test.jpg")),
             follow_redirects=False,
             content_type="multipart/form-data"
         )
         response = self.app.post(
             "/users/user_images/{index}".format(
                 uid=uid, index=1),
             headers=dict(uid=uid),
             data=dict(file=(io.BytesIO(b), "test.jpg")),
             follow_redirects=False,
             content_type="multipart/form-data"
         )
         response = self.app.post(
             "/users/user_images/{index}".format(
                 uid=uid, index=2),
             headers=dict(uid=uid),
             data=dict(file=(io.BytesIO(b), "test.jpg")),
             follow_redirects=False,
             content_type="multipart/form-data"
         )
     
     # retrieve it again and check
     user = User.objects(uid=uid).first()
     user_images_temp = user.user_images_temp
     
     updated_image_temp = user_images_temp[image_index_to_update]
     original_image = mock_user_1["user_images"][image_index_to_update]
     
     self.assertEqual(response.status_code, 200)
     self.assertNotEqual(original_image["url"], updated_image_temp["url"])
     self.assertEqual(user.available, False)
     self.assertEqual(user.status, 0)
예제 #27
0
    def test_update_user(self, verify_id_token):
        verify_id_token.return_value = dict(uid=mock_user_1["uid"])
        # insert user only with uid.
        create_user_1(self.app)

        updated_user = User.objects().first()

        self.assertEqual(updated_user["uid"], mock_user_1["uid"])
        self.assertEqual(updated_user["nickname"], mock_user_1["nickname"])
        self.assertEqual(updated_user["sex"], mock_user_1["sex"])
        self.assertEqual(updated_user["birthed_at"], mock_user_1["birthed_at"])
        self.assertEqual(updated_user["height"], mock_user_1["height"])
        self.assertEqual(updated_user["body_id"], mock_user_1["body_id"])
        self.assertEqual(updated_user["occupation"], mock_user_1["occupation"])
        self.assertEqual(updated_user["education"], mock_user_1["education"])
        self.assertEqual(updated_user["religion_id"],
                         mock_user_1["religion_id"])
        self.assertEqual(updated_user["drink_id"], mock_user_1["drink_id"])
        self.assertEqual(updated_user["smoking_id"], mock_user_1["smoking_id"])
        self.assertEqual(updated_user["blood_id"], mock_user_1["blood_id"])
        self.assertEqual(updated_user["device_token"],
                         'cPFFTaZTQ2ivAN-bAmxNI5:APA91bFsgmm')
        self.assertEqual(updated_user["introduction"],
                         mock_user_1["introduction"])
        self.assertEqual(updated_user["last_login_at"],
                         mock_user_1["last_login_at"])
        self.assertEqual(len(updated_user["charm_ids"]),
                         len(mock_user_1["charm_ids"]))
        self.assertEqual(len(updated_user["ideal_type_ids"]),
                         len(mock_user_1["ideal_type_ids"]))
        self.assertEqual(len(updated_user["interest_ids"]),
                         len(mock_user_1["interest_ids"]))
예제 #28
0
    def test_insert_image_pending(self, verify_id_token):
        """Checks for an insert of an new image.."""
        # mock_user_2 has no images.
        uid = mock_user_2.get("uid")
        index_to_test = 2

        # insert user
        verify_id_token.return_value = dict(uid=uid)
        response = create_user_2(self.app)
        self.assertEqual(response.status_code, 200)

        user = response.get_json()

        # read file and send to server.
        file_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "testdata/nyan.png")

        with open(file_dir, "rb") as image:
            file = image.read()
            b = bytearray(file)
            response = self.app.post(
                "/users/{user_id}/user_images/{index}".format(
                    user_id=user["_id"], index=index_to_test),
                data=dict(user_image=(io.BytesIO(b), "test.jpg")),
                headers=dict(uid=uid),
                follow_redirects=False,
                content_type="multipart/form-data")

        user = User.objects(uid=uid).get_or_404()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(user.user_images_temp), 1)
        self.assertEqual(user.user_images_temp[0].index, index_to_test)
        self.assertRegex(user.user_images_temp[0].url,
                         "https://storage.googleapis.com.*")
예제 #29
0
파일: API.py 프로젝트: evasyuk/pychatty
def on_add_user(params):  # it is a kind of registration
    """
    To create user provide 3 basic parameters

    - uid - unique id (email for instance)
    - name - user name
    - icon - user url icon (optional)
    - secret - password

    Cases to cover:
        400 missing params
        201 created
        400 failed to add new user

    :param params:
    :return:
    """
    correct, user = User.from_dict(params=params)

    if not correct:
        response = json.dumps({'error': user})
        return response, 400
    else:
        result, info = users_storage.add_user(user)

        if result:
            response = user.to_json()
            return response, 201
        else:
            response = json.dumps({'error': info})
            return response, 400
예제 #30
0
    def test_update_star_rating_score(self, mock_send, mock_verify_id_token):
        # insert user_1
        mock_verify_id_token.return_value = dict(uid=mock_user_1["uid"])
        response = create_user_1(self.app)

        self.assertEqual(response.status_code, 200)

        # insert user_2
        mock_verify_id_token.return_value = dict(uid=mock_user_2["uid"])
        response = create_user_2(self.app)

        self.assertEqual(response.status_code, 200)

        # user 1 rates score to user 2
        user_id = str(User.objects(uid=mock_user_2["uid"]).first().id)
        response = self.app.put("/users/{user_id}/score/{score}".format(
            user_id=user_id, score=5),
                                headers=dict(uid=mock_user_1["uid"]),
                                content_type="application/json")
        self.assertEqual(response.status_code, 200)

        rate = StarRating.objects.first()

        self.assertEqual(rate.user_from.uid, mock_user_1["uid"])
        self.assertEqual(rate.user_to.uid, mock_user_2["uid"])
        self.assertEqual(rate.score, 5)
예제 #31
0
 def test_create_requests2(self):
     user = User.objects(id="5fceb2824192080326d089fb").first()
     random_users = User.objects.aggregate([{'$sample': {'size': 10}}])
     for random_user in random_users:
         Request(user_from=random_user.get("_id"),
                 user_to=user.id,
                 requested_at=1602139074).save()
예제 #32
0
def route_payment_purchase_ios(user_id: str):
    user = User.get_verified_user(user_id, request)

    token = request.form.get("token", None)
    if not token:
        raise ValueError("Token not found ..")

    result = decode_receipt(token)

    if int(result.status) != 0:
        response = json.dumps(dict(result=Payment.Result.INVALID))
        return Response(response, mimetype="application/json")

    purchase = result.receipt.in_app[0]
    product_id = purchase.product_id
    transaction_id = purchase.transaction_id
    created_at = pendulum.now().int_timestamp
    purchase_date_ms = int(purchase.purchase_date_ms)
    amount = get_amount(of=product_id)

    print("=================================")
    print(product_id)
    print(transaction_id)
    print(purchase_date_ms)
    print("=================================")

    purchase_result = user.purchase(platform="IOS",
                                    order_id=transaction_id,
                                    product_id=product_id,
                                    amount=amount,
                                    created_at=created_at,
                                    purchase_time_ms=purchase_date_ms)

    response = json.dumps(dict(result=purchase_result))
    return Response(response, mimetype="application/json")
예제 #33
0
def account_settings():
    """Account Settings Page.

    allow admin to change profile.

    Methods:
        GET and POST

    Args:
        GET:
            none

        POST:
            username: string
            pass1   : password
            pass2   : password twice for validate
            signature: user profile signature
            email   : for get reply email notification

    Returns:
        GET:
            user object
        POST:
            none
    """
    user = UserModel.objects(name=current_user.name).first()
    if request.method == 'POST':
        username = request.form['username']
        pass1 = request.form['pass1']
        pass2 = request.form['pass2']
        signature = request.form['signature']
        email = request.form['email']
        avatar = request.form['avatar']

        if pass1 and pass2 and pass1 == pass2:
            user.password = generate_password_hash(password=pass1)

        if username:
            user.name = username

        if signature:
            user.signature = signature

        if email:
            user.email = email

        if avatar:
            user.avatar = avatar

        user.save()

        if pass1 or username:
            logout_user()
            flash(u"请重新登陆")
            return redirect(url_for("admin.index"))

        return redirect(url_for("admin.account_settings"))
    else:
        return render_template('admin/account/settings.html', user=user)
예제 #34
0
    def get_by_name(self, username):
        """Get user by username

        Args:
            username: string

        Return:
            user: user object
        """
        return User.objects(name=username).first()
예제 #35
0
def getNickName(id):
    name=memcache.get('nick'+str(id))
    if name:
        return name
    else:
        name=User.get_by_key_name('u'+str(id))
        if name:
            name=name.nickname
            memcache.set('nick'+str(id),name,3600)
            return name
        else:
            return ''
예제 #36
0
def home():
    """."""
    if request.method == "POST" and "project_name" in request.form:
        username = session['username']
        author = User.objects(name=username).first()

        project_name = request.form['project_name']
        current_project = Project(name=project_name)
        current_project.author = author
        current_project.save()

        return redirect(url_for('home'))
    else:
        try:
            username = session['username']
            author = User.objects(name=username).first()
            projects = Project.objects(author=author).order_by('-created_at')
        except:
            projects = []

        return render_template('home.html', projects=projects)
예제 #37
0
 def get(self):
     try:
         username=self.request.get('UserName') or ''
         friend=self.request.get('Friend') or ''
         if username and friend:
             user=User.get_by_key_name('u'+username)
             if friend in user.friends:
                 user.friends.remove(friend)
                 user.put()
             self.response.out.write('0')#成功了
     except Exception,e:
         logging.info(str(e))
         self.response.out.write('1')
예제 #38
0
    def get(self):
        username=self.request.get('UserName') or ''

        contentlist=[]
#        getMapList(contentlist,APPCODE+'-s1',APPCODE,'',APPCODE,'100',u'聊天',None,'1',replayType)
        if username:
            user=getorAddUser(username)
            userdic=user2dic(user)
            getMapList(contentlist,APPCODE+'-s1-'+username,APPCODE+'-s1','0',APPCODE,'101',json.dumps(userdic),None,'1',replayType)
            for uid in user.friends:
                u=User.get_by_key_name('u'+uid)
                userdic=user2dic(u)
                getMapList(contentlist,APPCODE+'-s1-'+uid,APPCODE+'-s1','1',APPCODE,'101',json.dumps(userdic),None,'1',replayType)
            for uid in user.stranger:
                u=User.get_by_key_name('u'+uid)
                userdic=user2dic(u)
                getMapList(contentlist,APPCODE+'-s1-'+uid,APPCODE+'-s1','2',APPCODE,'101',json.dumps(userdic),None,'1',replayType)
            xml,datas=infoallxmldic(contentlist)
            datas.setAttribute('type','infoall')
            datas.setAttribute('code',APPCODE)
            datas.setAttribute('timespan',str(10*60*1*60))
            infoAllGroup(self,datas,getMapList,infoallxmldic,xml,user)
            self.response.out.write(xml.toxml('utf-8'))
예제 #39
0
def login():
    """."""
    error = None
    if request.method == "POST" and "username" in request.form:
        username = request.form["username"]
        password = request.form["password"]
        user = User.objects(name=username).first()

        if user and check_password_hash(user.password, password):
            session['logged_in'] = True
            session['username'] = username
            flash('You were logged in')
            return redirect(url_for('home'))
    return render_template('login.html', error=error)
예제 #40
0
파일: tool.py 프로젝트: wangjian2254/moguim
def getNickName(uid):
    if uid[0] != "u":
        uid = uid[1:]
    name = memcache.get("nick" + str(uid))
    if "000" == id:
        return "蘑菇系统"
    if name:
        return name
    else:
        name = User.get_by_key_name("u" + str(uid))
        if name:
            name = name.nickname
            memcache.set("nick" + str(uid), name, 3600)
            return name
        else:
            return uid
예제 #41
0
def project_upload():
    """."""
    if request.method == 'POST':
        project_id = request.form['project_id']
        up_file = request.files['pdffile']
        current_project = Project.objects(pk=project_id)

        username = session['username']
        author = User.objects(name=username).first()
        if up_file:
            filename = (secure_filename(up_file.filename) +
                        str(int(time.time())))
            filename = filename.replace('.pdf', '') + '.pdf'
            pdf_em = PdfEm(
                name=filename,
                author=author
            )
            current_project.update_one(push__pdfs=pdf_em)
            up_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('project', project_id=project_id))
    return render_template('project.html')
예제 #42
0
파일: index.py 프로젝트: amyangfei/webtest
 def post(self):
     
     username = self.get_argument('username')
     email = self.get_argument('email')
     password1 = self.get_argument('password1')
     password2 = self.get_argument('password2')
     
     wrong_tips = [''] * 4
     zerotip = '这个字段是必填项'
     if len(username) == 0:
         wrong_tips[0] = zerotip
     else:
         user = self.session.query(User).filter_by(uname = username).first()
         if user:
             wrong_tips[0] = '称号已被注册'
     if len(email) == 0:
         wrong_tips[1] = zerotip
     else:
         user = self.session.query(User).filter_by(uemail = email).first()
         if user:
             wrong_tips[1] = '用户已经存在'
     if len(password1) == 0:
         wrong_tips[2] = zerotip
     elif len(password1) < 6:
         wrong_tips[2] = '确保该值不少于 6 个字符 (现在有 ' + str(len(password1)) + ' 个)'
     if len(password2) == 0:
         wrong_tips[3] = zerotip
     elif password2 != password1:
         wrong_tips[3] = '密码不匹配'
     
     status = 'error'
     if wrong_tips == ['']*4:
         status = 'success'
         encryptPwd = self.pwdEncrypt(email, password1)
         user = User()
         user.uname = username
         user.uemail = email
         user.upwd = encryptPwd
         user.uavatar = gravatar.getGravatarHash(email)
         user.ucreatedate = datetime.now()
         
         self.session.add(user)
         self.session.commit()
         self.set_current_user(user.uemail)
         
     self.write(escape.json_encode({'status':status, 'wrong_tips':wrong_tips}))
예제 #43
0
 def delete_user(self):
     """Delete User"""
     return User.objects().first().delete()
예제 #44
0
 def generate_user(self, username, password):
     """Generate User"""
     user = User(name=username)
     user.password = generate_password_hash(password=password)
     return user.save()
예제 #45
0
파일: tool.py 프로젝트: wangjian2254/moguim
def getorAddUser(uname):
    user = User.get_by_key_name("u" + uname)
    if not user:
        user = User(key_name="u" + uname)
        user.put()
    return user
예제 #46
0
파일: web.py 프로젝트: Hasimir/Bits-Books
def edit_profile():
    users = User.get().all()
    return debug_str(users)
예제 #47
0
    def post(self):
#        type=self.request.get('searchType')
        try:
            sendusername=self.request.get('UserName')
            logging.info("sendusername:"******"searchUname:"+username)
            nickname=self.request.get('nickname') or ''

            nickname=nickname.encode('utf-8')
            nickname=nickname.decode('utf-8')
            logging.info("nickname:"+nickname)
            minage=self.request.get('minage') or '0'
            logging.info("minage:"+str(minage))
            maxage=self.request.get('maxage') or '99'
            logging.info("maxage:"+str(maxage))
            sheng=self.request.get('sheng') or ''
            logging.info("sheng:"+sheng)
            if sheng:
                sheng=int(sheng)
            city=self.request.get('city') or ''
            logging.info("city:"+city)
            if city:
                city=int(city)
            sex=self.request.get('sex') or ''
            logging.info("sex:"+sex)
            userlist=[]

            if username:
                user=User.get_by_key_name('u'+username)
                if user and username!=sendusername:
                    userlist.append(user2dic(user))
            else:
                online=memcache.get('online') or []
#                logging.info(str(online))
                online=online[1:]
                online.reverse()
                my=User.get_by_key_name('u'+sendusername)
                for u in online:
                    if sendusername==u['username'] or u['username'] in my.friends:
                        continue
                    isuser=True
                    logging.info("isuser:"******"%Y-%m-%d").tm_year
                    else:
                        age=18
#                    logging.info(str(nickname and nickname not in u['nickname'])+'-1-'+u['nickname'])
                    if nickname and nickname not in u['nickname']:
                        isuser=False
                    logging.info("nickname-isuser:"******"age-isuser:"******"sheng-isuser:"******"city-isuser:"******"sex-isuser:"******"6--"+str(isuser))
                    if isuser:
                        userlist.append(u)
                        if len(userlist)>=20:
                            break
            self.response.out.write(json.dumps(userlist))
        except Exception,e:
            logging.info(str(e))
            self.response.out.write('1')
예제 #48
0
def getuser(m,uid):
    if not m.has_key(uid):
        m[uid]=User.get_by_key_name('u'+uid)
    return m[uid]
예제 #49
0
 def post(self):
     #u={'nickname':user.nickname,'birthday':user.birthday,'sheng':user.sheng,'city':user.city,'sex':user.sex}
     try:
         username=self.request.get('UserName') or ''
         if username:
             user=User.get_by_key_name('u'+username)
             if not user:
                 user=User(key_name='u'+username)
             user.nickname=self.request.get('nickname').encode('utf-8').decode('utf-8') or ''
             user.desc=self.request.get('desc').encode('utf-8').decode('utf-8') or ''
             user.birthday=self.request.get('birthday') or ''
             sheng=self.request.get('sheng') or ''
             if sheng:
                 user.sheng=int(sheng)
             city=self.request.get('city') or ''
             if city:
                 user.city=int(city)
             header=self.request.get('header') or 0
             if header:
                 user.header=int(header)
             sex=self.request.get('sex') or ''
             if sex.lower()=='True'.lower():
                 user.sex=True
             if sex.lower()=='False'.lower():
                 user.sex=False
             user.put()
             self.response.out.write(setting.WEBURL[7:]+'/InfoAll')
     except Exception,e:
         logging.info(str(e))
         self.response.out.write('1')
예제 #50
0
def build():
    user = User(name='admin')
    user.password = generate_password_hash(password='******')
    user.save()
    print "Default Admin add Success!"
    execute(deploy)