def post(self, request): data = request.DATA try: username = data["username"] password = data["password"] except KeyError as e: return Response({"error": "Invalid object."}, status=status.HTTP_400_BAD_REQUEST, exception=True) #todo: validate username and password user = User.objects.create_user(username = username, password = password) new_user = AppUser(user = user, app = request.app) try: new_user.full_clean() except ValidationError as e: return Response(e.message_dict, status=status.HTTP_400_BAD_REQUEST) new_user.save() user = authenticate(username=username, password=password) login(request, user) request.session.save() return Response({settings.SESSION_COOKIE_NAME : request.session.session_key, "id" : user.id }, status=status.HTTP_201_CREATED)
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(), })
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()
def post(self, request): try: #todo: update first_name, last_name and other attributes stream = StringIO.StringIO(request.body) data = JSONParser().parse(stream) username = data["username"] password = data["password"] except Exception as e: self.logger.error("Unable to decode object. Error: %s"%str(e)) return Response({"detail": "Invalid object."}, status=status.HTTP_400_BAD_REQUEST, exception=True) app = request.META['app'] #todo: validate username and password user = User.objects.create_user(username = username, password = password) new_user = AppUser(user = user, app = app) try: new_user.full_clean() except ValidationError as e: return Response(e.message_dict, status=status.HTTP_400_BAD_REQUEST) new_user.save() user = authenticate(username=data["username"], password=data["password"]) login(request, user) request.session.save() return Response({settings.SESSION_COOKIE_NAME : request.session.session_key, "id" : user.id }, status=status.HTTP_201_CREATED)
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
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
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)
def user_context(request): try: username = request.session['username'] channel_logo = request.session['channel_logo'] company_logo = request.session['company_logo'] app_user = AppUser.get(username) fullname = app_user.user.get_full_name() site = Site.objects.get_current() except KeyError: channel_logo = "/static/images/logo-blue-transparent.png" company_logo = "/static/dimages/tilde.png" fullname = '' site = Site.objects.get() try: ga_code = ga_codes[site.name] except KeyError: ga_code = ga_codes['default'] context = { 'session': request.session, 'path': request.path, 'version': VERSION_STAMP, 'fullname': fullname, 'channel_logo': channel_logo, 'company_logo': company_logo, 'site': site.name, 'ga_code': ga_code, } callingframe = sys._getframe(1) logger.info( '\n----\n%r context %s\n--------', callingframe.f_code.co_name, context) return context
def user_context(request): try: username = request.session['username'] channel_logo = request.session['channel_logo'] company_logo = request.session['company_logo'] app_user = AppUser.get(username) fullname = app_user.user.get_full_name() site = Site.objects.get_current() except KeyError: channel_logo = "/static/images/logo-blue-transparent.png" company_logo = "/static/dimages/tilde.png" fullname = '' site = Site.objects.get() try: ga_code = ga_codes[site.name] except KeyError: ga_code = ga_codes['default'] context = { 'session': request.session, 'path': request.path, 'version': VERSION_STAMP, 'fullname': fullname, 'channel_logo': channel_logo, 'company_logo': company_logo, 'site': site.name, 'ga_code': ga_code, } callingframe = sys._getframe(1) logger.info('\n----\n%r context %s\n--------', callingframe.f_code.co_name, context) return context
def testInitNewUser(self): users.get_current_user = mock.MagicMock(return_value=self.new_app_user) self.assertEqual(self.new_app_user, InitUser('new token').user) new_app_user_ndb = AppUser.query( AppUser.user == users.get_current_user()).fetch()[0] self.assertTrue(new_app_user_ndb) self.assertEqual('new token', new_app_user_ndb.refresh_token)
def test_add_user(self): count = AppUser.query.count() res = self.client.post('/api/v1/user/add', data=dict(email='*****@*****.**', username='******', password='******')) self.assertEqual(len(AppUser.get_all()), count + 1)
def check_token(**kwargs): try: g.user_id = AppUser.verify_auth_token(request.headers.get('x-access-token')) except ValueError as err: print(err.args) abort(403) return func(**kwargs)
def test_user_pw(self): res = self.client.post('/api/v1/user/add', data=dict(email='*****@*****.**', username='******', password='******')) user = AppUser.get_by_id(json.loads(res.get_data()).get('id')) self.assertTrue(user.check_password('xxxx'))
def get(self): user = users.get_current_user() products = [] if user: url_linktext = 'Logout' # Función propia de la clase USER de App Engine url = users.create_logout_url(self.request.uri) # get_or_insert es una solución para obtener o crear un registro en caso de que # ya se encontrara guardado o no, respectivamente app_user = AppUser.get_or_insert(user.user_id(), identity=user.user_id(), email=user.email()) keys = [ndb.Key(Product, int(k)) for k in app_user.products] if keys: products = ndb.get_multi(keys) products = filter(None, products) else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' template = JINJA_ENVIRONMENT.get_template(VIEWS['index']) # A la función "render" se le pasa un diccionario de parámetros que se van a utilizar en la vista. # Estos parámetros vienen identificados por {{ }} self.response.write( template.render({'user': user, 'url': url, 'url_linktext': url_linktext, 'products': products}))
def test_user_pw_fail(self): res = self.client.post('/api/v1/user/add', data=dict(email='*****@*****.**', username='******', password='******')) print json.loads(res.get_data()).get('id') id = json.loads(res.get_data()).get('id') user = AppUser.get_by_id(id) self.assertFalse(user.check_password('xsssxxx'))
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
def get(self): user = users.get_current_user() products = Product.query().order(Product.name) if user: app_user = AppUser.get_or_insert(get_user_key(user), identity=user.user_id(), email=user.email()) else: return self.redirect(URLS['index']) template = JINJA_ENVIRONMENT.get_template(VIEWS['products']) self.response.write(template.render({'products': products, 'user': app_user}))
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 })
def RevokeOldCredentials(): """Revoke old credentials. Find all users in the datastore with refresh tokens older than 30 days and revokes them. """ users_with_expired_tokens = AppUser.query( AppUser.date_acquired <= datetime.datetime.now() - datetime.timedelta(30)).fetch() for expired_user in users_with_expired_tokens: expired_user.refresh_token = None ndb.put_multi(users_with_expired_tokens)
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
def generate_report_xlsx(self, project_id, report_type): project = Project.get(Project.id == project_id) total_probes = len([p for p in project.project_stacks]) project_users = AppUser.select().join(ProjectUser).where(ProjectUser.project == project) project_info = project.title.split('_') report = {} total_iteration = 0 for iteration, project_stack in enumerate(project.project_stacks): stack = {} stack_images = StackImage.select().where(StackImage.stack == project_stack.stack.id) for stack_image in stack_images: users = {} for user in project_users: markers = Marker.select().where( Marker.app_user == user.id, Marker.stack_image == stack_image.id, Marker.project_stack == project_stack.id ) user_markers = [m.serialized for m in markers] if user_markers: users[user.email] = user_markers stack[stack_image.image.name] = users report[project_stack.stack.title] = stack self.update_state(state='PROGRESS', meta={ 'current': iteration, 'total': total_probes, 'projectId': project_id, 'reportType': report_type }) total_iteration += 1 return { 'current': total_iteration, 'total': total_probes, 'status': 'Task complete', 'projectId': project_id, 'report': report, 'reportType': report_type }
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()
def post(self): user = users.get_current_user() action = self.request.POST.get('action') # En la vista de productos, se envía un campo oculto llamado 'action' # Este campo puede tener tres valores distintos: # - 'create': se crea un nuevo producto aleatoriamente y se añade al listado principal de productos. # - 'buy': el usuario compra un nuevo producto. # - 'delete': se elimina un producto del listado principal. if action == 'create': product = Product(name='p' + str(random.randint(NAME_VALUES[0], NAME_VALUES[1])), cost=random.randint(PRICE_VALUES[0], PRICE_VALUES[1])) product.put() elif user: product = Product.get_by_id(int(self.request.POST.get('id'))) app_user = AppUser.get_or_insert(get_user_key(user), identity=user.user_id(), email=user.email()) if action == 'buy': app_user.add_product(product) elif action == 'delete': app_user.remove_product(product) ndb.Key(Product, product.key.id()).delete() self.redirect(URLS['products'])
def test_user_pw_fail(self): res = self.client.post('/api/v1/user/add',data=dict(email='*****@*****.**',username='******',password='******')) user = AppUser.get_by_id(2) self.assertFalse(user.check_password('xsssxxx'))
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
def test_add_user(self): count = AppUser.query.count() res = self.client.post('/api/v1/user/add',data=dict(email='*****@*****.**',username='******',password='******')) self.assertEqual(len(AppUser.get_all()),count+1)
def get_project_report(project_id): users = User.select().join(ProjectUser).where(ProjectUser.project == project_id) return jsonify({ 'users': [u.serialized for u in users] })
def test_get_user_posts(self): user = AppUser.get_all()[0] res = self.client.post('/api/v1/user/{0}/posts'.format(user.id)) posts = json.loads(res.get_data()) self.assertEqual(posts,map(lambda x: x.to_json(),user.posts.all()))
def test_user_pw_fail(self): res = self.client.post('/api/v1/user/add',data=dict(email='*****@*****.**',username='******',password='******')) print json.loads(res.get_data()).get('id') id = json.loads(res.get_data()).get('id') user = AppUser.get_by_id(id) self.assertFalse(user.check_password('xsssxxx'))
def test_user_pw(self): res = self.client.post('/api/v1/user/add',data=dict(email='*****@*****.**',username='******',password='******')) user = AppUser.get_by_id(json.loads(res.get_data()).get('id')) self.assertTrue(user.check_password('xxxx'))
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()
def test_get_user_posts(self): user = AppUser.get_all()[0] res = self.client.post('/api/v1/user/{0}/posts'.format(user.id)) posts = json.loads(res.get_data()) self.assertEqual(posts, map(lambda x: x.to_json(), user.posts.all()))
def get_user_key(user): return str(AppUser.query(AppUser.identity == user.user_id()).get().key.id())
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', }