예제 #1
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        self.existing_app_user = users.User('*****@*****.**')
        AppUser(user=self.existing_app_user, email='*****@*****.**').put()
        self.new_app_user = users.User('*****@*****.**')

        AppUser.date_acquired._auto_now = False  # override for testing purposes

        self.old_user = users.User('*****@*****.**')
        AppUser(user=self.old_user,
                email='*****@*****.**',
                refresh_token='should not exist',
                date_acquired=datetime.datetime(2000, 1, 1)).put()

        AppUser.date_acquired._auto_now = True

        self.recent_user = users.User('*****@*****.**')
        AppUser(user=self.recent_user,
                email='*****@*****.**',
                refresh_token='should exist').put()

        app_credential = AppCredential(client_id='1', client_secret='secret')
        app_credential.put()
예제 #2
0
def register():
    """
    This view allows a user to register for the site.

    This will create a new User in Stormpath, and then log the user into their
    new account immediately (no email verification required).
    """
    if request.method == 'GET':
        if user.is_authenticated():
            return redirect(url_for('index'))

        return render_template('register.html')

    try:
        _user = stormpath_manager.application.accounts.create({
            'username':
            request.form.get('username'),
            'email':
            request.form.get('email'),
            'password':
            request.form.get('password'),
            'given_name':
            request.form.get('first_name'),
            'surname':
            request.form.get('last_name')
        })
        _user.__class__ = User

        app_user = AppUser(_user.get_id())
        db.session.add(app_user)
        db.session.commit()

    except StormpathError, err:
        return render_template('register.html', error=err.message)
예제 #3
0
def InitUser(refresh_token=None):
  """Initialize application user.

  Retrieve existing user credentials from datastore or add new user.
  If a refresh token is specified, it replaces the old refresh token and the
  date_acquired is updated as well.

  Args:
    refresh_token: str A new refresh token received from the auth flow.
                   Defaults to None.

  Returns:
    AppUser instance of the application user.
  """

  result = AppUser.query(
      AppUser.user == users.get_current_user()).fetch(limit=1)

  if result:
    # app_user exists
    app_user = result[0]
    if not app_user.refresh_token:
      # update refresh_token if provided in the arguments
      app_user.refresh_token = refresh_token
      app_user.date_acquired = datetime.datetime.now()
  else:
    app_user = AppUser(
        user=users.get_current_user(),
        email=users.get_current_user().email(),
        refresh_token=refresh_token)

  app_user.put()
  return app_user
예제 #4
0
 def __subscribe_add_user(self):
     #关注获取用户信息
     openid = self.from_user
     user_info = self.appitem.get_user_info(openid)
     user = self.__get_user()
     if not user:
         user = AppUser(openid=openid)
         user.save()
     try:
         user.nickname = user_info.get('nickname')
         user.sex = user_info.get('sex')
         user.language = user_info.get('language')
         user.city = user_info.get('city')
         user.province = user_info.get('province')
         user.country = user_info.get('country')
         user.headimgurl = user_info.get('headimgurl')
         user.unionid = user_info.get('unionid')
         user.save()
     except:
         pass
     if not self.appitem.app_users.filter(openid=openid).exists():
         self.appitem.app_users.add(user)
     else:
         user.is_guanzhu = True
         user.unionid = user_info.get('unionid')
         user.save()
예제 #5
0
def create_recipe():
    data = request.get_json()
    recipe = data.get("recipe")
    owner = data.get("owner")

    user = AppUser.query.filter(AppUser.name == owner).first()

    if user is None:
        user = AppUser(name=owner)
        try:
            user.insert()
        except:
            abort(422)

    title = recipe.get("recipeTitle")
    ingredients = json.dumps(recipe.get("ingredients", ""))
    instructions = recipe.get("instructions")
    recipe = Recipe(title=title, ingredients=ingredients, instructions=instructions, owner_id=user.id)

    try:
        recipe.insert()
    except:
        abort(422)

    return jsonify({
        "success": True,
        "recipe": recipe.long(),
    })
예제 #6
0
def createUser(login_session):
    print "inside createUser function"
    newUser = AppUser(name=login_session['username'],
                      email=login_session['email'],
                      picture=login_session['picture'])
    session.add(newUser)
    session.commit()
    print "returning user..."
    user = session.query(AppUser).filter_by(email=login_session['email']).one()
    print user.id
    return user.id
예제 #7
0
    def testAppUser(self, ident='123', email='*****@*****.**', is_admin='0'):
        print ' --- App users tests --- '
        assert not users.get_current_user()

        self.testbed.setup_env(USER_EMAIL=email,
                               USER_ID=ident,
                               USER_IS_ADMIN=is_admin,
                               overwrite=True)

        user = users.get_current_user()

        assert user.email() == email
        assert user.user_id() == ident

        app_user = AppUser(identity=user.user_id(), email=user.email())
        assert app_user.identity == user.user_id()
        assert app_user.email == user.email()

        app_user_key = app_user.put().urlsafe()

        retrieved_app_user = get_entity_memcache(app_user_key)
        assert retrieved_app_user is not None
        assert retrieved_app_user.identity == user.user_id()
        assert retrieved_app_user.email == user.email()

        product1 = Product(name='product1', cost=1)
        product2 = Product(name='product2', cost=2)
        product3 = Product(name='product3', cost=3)
        product1_key = product1.put().urlsafe()
        product2_key = product2.put().urlsafe()
        product3_key = product3.put().urlsafe()

        retrieved_product1 = get_entity_memcache(product1_key)
        retrieved_product2 = get_entity_memcache(product2_key)
        retrieved_product3 = get_entity_memcache(product3_key)

        app_user.add_product(retrieved_product1)
        app_user.add_product(retrieved_product2)
        app_user.add_product(retrieved_product3)

        assert len(app_user.products) > 0
        assert len(app_user.products) == 3

        app_user.remove_product(retrieved_product1)
        assert len(app_user.products) > 0
        assert len(app_user.products) == 2

        app_user.remove_product(retrieved_product2)
        app_user.remove_product(retrieved_product3)

        assert len(app_user.products) == 0
예제 #8
0
def get_app_user(db, team_id: int, slack_user_id: str, slack_user_name: str):
    assert isinstance(team_id, int)
    assert isinstance(slack_user_id, str)
    assert isinstance(slack_user_name, str)
    app_user = db.query(AppUser).filter(
        AppUser.team_id == team_id,
        AppUser.slack_user_id == slack_user_id).first()
    if app_user:
        app_user.slack_user_name = slack_user_name
    else:
        app_user = AppUser(team_id=team_id,
                           slack_user_id=slack_user_id,
                           slack_user_name=slack_user_name)
        db.add(app_user)
        db.flush()
    return app_user
예제 #9
0
def register_user(request):
    user_exist = False
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            name = request.POST['username']
            current_site = get_current_site(request)
            print current_site
            try:
                user_exist = User.objects.get(username=name)
                print "USER EXIST ---------", user_exist
            except ObjectDoesNotExist:
                password = request.POST['password1']
                user = User.objects.create_user(name,
                                                name,
                                                password,
                                                is_active=False)
                key = ''.join(
                    random.choice(string.digits + string.letters)
                    for _ in range(10))
                app_user = AppUser(user=user,
                                   key_expires=timezone.now() +
                                   datetime.timedelta(minutes=3),
                                   activation_key=key)
                app_user.save()
                # activation_key = key, to = ['*****@*****.**'])
                Thread(target=mail.registration_mail,
                       kwargs={
                           'host': current_site.domain,
                           'activation_key': key,
                           'to': ['*****@*****.**']
                       }).start()
                # mail.registration_mail(activation_key=key, to=['*****@*****.**'])
                print 'mail sent success --------'
                return HttpResponseRedirect(reverse('login'))
    else:
        form = RegistrationForm()
    return render(request, 'login/register.html', {
        'form': form,
        'user_exist': user_exist
    })
예제 #10
0
def bootstrapTestDB(db):
    """
        Takes an created SQLAlchemy db and bootstraps the tables
        with dummy data
    """
    books_copy, authors_copy = deepcopy(books), deepcopy(authors)

    # load authors
    for author_data in authors:
        db.session.add(Author.author_from_dict(**author_data))
    db.session.commit()

    # load genres
    for book_data in books_copy:
        for genre in book_data['genres']:
            g = Genre.query.filter_by(name=genre).first()
            if not g:
                db.session.add(Genre(genre))
                db.session.flush()
    db.session.commit()

    # load books
    for book_data in books_copy:
        book_data['genres'] = [
            Genre.query.filter_by(name=genre_item).first()
            for genre_item in book_data['genres']
        ]
        book_data['author'] = Author.query.filter_by(
            name=book_data['author']).first()
        db.session.add(Book.book_from_dict(**book_data))
    # commit the changes
    db.session.commit()

    #load users
    for author_data in authors_copy:
        author = Author.query.filter_by(name=author_data['name']).first()
        db.session.add(
            AppUser(stormpathUserHash(author_data['user_href']),
                    author_data['user_href'], author))
    db.session.commit()
예제 #11
0
  def setUp(self):
    self.testbed = testbed.Testbed()
    self.testbed.activate()
    self.testbed.init_datastore_v3_stub()
    self.testbed.init_memcache_stub()

    app_credential = AppCredential(client_id='1', client_secret='secret')
    app_credential.put()

    self.new_app_user = users.User('*****@*****.**')
    self.existing_app_user = users.User('*****@*****.**')
    AppUser(user=self.existing_app_user, email='*****@*****.**',
            refresh_token='blah').put()

    # mocking webapp2 request object
    class RequestMock(object):

      def redirect(self, uri):
        return uri

    self.request_mock = RequestMock()

    # mocking handler
    @oauth2required
    def homepage_mock(request):
      return '/'
    self.homepage_mock = homepage_mock

    # helper class for mocking retry decorator
    class TestObject(object):

      def __init__(test_self):
        test_self.fails_remaining = 2

      @retry(NotImplementedError)
      def instant_success_func(test_self):
        return 'success'

      @retry(NotImplementedError)
      def eventual_success_func(test_self):
        if test_self.fails_remaining > 0:
          test_self.fails_remaining -= 1
          raise NotImplementedError()
        return 'success'

      @retry(NotImplementedError)
      def failure_func(test_self):
        raise NotImplementedError()

    self.test_obj = TestObject()
    logging.warning = mock.MagicMock(side_effect=logging.warning)

    # simulating a line item object
    self.suds_obj = suds.sudsobject.Object()
    self.suds_obj.goal = suds.sudsobject.Object()
    self.suds_obj.goal.units = 10000
    self.suds_obj.goal.goalType = 'LIFETIME'
    self.suds_obj.goal.unitType = 'IMPRESSIONS'
    self.suds_obj.orderId = 987654321
    self.suds_obj.endDateTime = suds.sudsobject.Object()
    self.suds_obj.endDateTime.date = suds.sudsobject.Object()
    self.suds_obj.endDateTime.date.year = 2015
    self.suds_obj.endDateTime.date.day = 31
    self.suds_obj.endDateTime.date.month = 12
    self.suds_obj.endDateTime.timeZoneID = 'America/New_York'
    self.suds_obj.endDateTime.second = 0
    self.suds_obj.endDateTime.hour = 23
    self.suds_obj.endDateTime.minute = 59
    self.suds_obj.reserveAtCreation = False

    def create_suds_test_obj(id_):
      obj = suds.sudsobject.Object()
      obj.id = id_
      obj.type = 'PIXEL'
      return obj
    self.suds_obj.creativePlaceholders = [
        create_suds_test_obj(0),
        create_suds_test_obj(1),
        create_suds_test_obj(2),
    ]

    self.unpacked_suds_obj = {
        'goal': {
            'units': 10000,
            'goalType': 'LIFETIME',
            'unitType': 'IMPRESSIONS',
        },
        'orderId': 987654321,
        'endDateTime': {
            'date': {
                'year': 2015,
                'day': 31,
                'month': 12,
            },
            'timeZoneID': 'America/New_York',
            'second': 0,
            'hour': 23,
            'minute': 59,
        },
        'reserveAtCreation': False,
        'creativePlaceholders': [
            {
                'id': 0,
                'type': 'PIXEL',
            },
            {
                'id': 1,
                'type': 'PIXEL',
            },
            {
                'id': 2,
                'type': 'PIXEL',
            },
        ],
    }

    # simulating a row object from PQLService
    self.cols = ['id', 'browsername']
    self.row_obj = suds.sudsobject.Object()
    self.row_obj.values = [
        suds.sudsobject.Object(),
        suds.sudsobject.Object(),
    ]
    self.row_obj.values[0].value = '123456'
    self.row_obj.values[1].value = 'Test Browser'
    self.unpacked_row_obj = {
        'id': '123456',
        'browsername': 'Test Browser',
    }