Exemple #1
0
def confirm_email(token):
    s = URLSafeTimedSerializer(app.config['SECRET_KEY'])
    email = s.loads(token, salt='email-confirm', max_age=3600)
    UserService.confirm_customer(email, token)

    form = forms.CustomerLogin()
    return render_template("login.html", conf=True, form=form)
Exemple #2
0
def admin_campaigns(customer_id):
    vf = AdminViewFuncs(customer_id)
    if vf.ValidView():
        account_form = forms.AccountForm()

        if request.method == 'POST' and account_form.validate_on_submit():
            UserService.update_id(facebook_id=account_form.facebook_id.data,
                                  google_id=account_form.google_id.data,
                                  twitter_id=account_form.twitter_id.data,
                                  customer_id=customer_id)

        page = AdminViewModel(session['permissions'],
                              'campaigns',
                              admin=session['admin'],
                              user=customer_id,
                              view="campaigns")
        return render_template('layouts/admin_layout.html',
                               view="campaigns",
                               owner=session['owner_logged_in'],
                               admin=session['admin_logged_in'],
                               manager=session['manager_logged_in'],
                               page=page,
                               customer_id=customer_id,
                               account_form=account_form)
    else:
        return 'You do not have permission to view this client.'
Exemple #3
0
def login_post(service: UserService):
    username = request.json.get('username')
    password = request.json.get('password')

    user = service.find_one_by(username=username)
    if user is None:
        raise UserLoginFailed()

    service.verify_password(user, password)

    response = jsonify(user.to_dict())
    set_new_tokens(response, username)

    return response
Exemple #4
0
def customer_login():
    if 'logged_in' in session and session.get('logged_in') == True:
        return redirect(url_for("home"))
    else:
        form = forms.CustomerLogin()

        if ViewFuncs.ValidSubmission(form=form, method=request.method):
            loginResult, action = UserService.customer_login(
                form.email.data, form.password.data)
            return UserService.routeLogin(loginResult, action, form=form)

        elif request.method == 'GET':
            session['logged_in'] = False

        return render_template('login.html', form=form)
Exemple #5
0
def get_user_service():
    global user_service
    if user_service:
        return user_service
    else:
        user_service = UserService()
        return user_service
Exemple #6
0
def temperature():
    user_id = session["user_id"]
    devices = UserService().get_by_user_id_and_type(user_id=user_id,
                                                    device_type="temperature")
    return render_template("temperature.html",
                           user_id=user_id,
                           devices=devices)
def configure_services(binder):
    user_validator = UserValidator()
    user_service = UserService(user_validator)
    binder.bind(UserService, to=user_service, scope=singleton)

    area_validator = AreaValidator()
    area_service = AreaService(area_validator)
    binder.bind(AreaService, to=area_service, scope=singleton)

    socket_server = SocketIO(cors_allowed_origins='*')
    binder.bind(SocketIO, to=socket_server, scope=singleton)

    notification_service = NotificationService(socket_server)
    binder.bind(NotificationService, to=notification_service, scope=singleton)

    area_service.emitter.on(AreaServiceEvents.AREA_ADDED, notification_service.notify_area_add)
    area_service.emitter.on(AreaServiceEvents.AREA_UPDATED, notification_service.notify_area_update)
    area_service.emitter.on(AreaServiceEvents.AREA_DELETED, notification_service.notify_area_delete)

    def notification_service_on_authentication_try_link(sid: str, username: str):
        user = user_service.find_one_by(username=username)
        if not user:
            notification_service.notify_authenticate_error(sid)
            return

        notification_service.authenticate_link_notify(sid, user)

    notification_service.emitter.on(NotificationServiceEvents.AUTHENTICATE_TRY_LINK,
                                    notification_service_on_authentication_try_link)
 def meta(self):
     query = 'SELECT tactic_id, title, description, image, category FROM tactics WHERE tactic_id = ?'
     tup = (self.tag_id, )
     data, cursor = db.execute(query, True, tup)
     data = cursor.fetchall()
     columns = ['tactic_id', 'title', 'description', 'image', 'category']
     data = UserService.parseCursor(data, columns)
     return data
Exemple #9
0
def register_post(service: UserService):
    username = request.json.get('username')
    password = request.json.get('password')
    first_name = request.json.get('first_name')
    last_name = request.json.get('last_name')

    user = service.add(username, password, first_name, last_name)
    return jsonify(user.to_dict())
 def get(self) -> dict:
     query = f"""exec fetch_notifications @customer_id = {self.customer_id}"""
     data, cursor = db.execute(query, True, ())
     data = cursor.fetchall()
     columns = [
         'message_string', 'task_title', 'insight_body', 'message_from'
     ]
     return_data = UserService.parseCursor(data, columns)
     return return_data
 def get_tests(self):
     query = """SELECT * FROM get_tests(?)"""
     data, cursor = db.execute(query, True, (self.customer_id,))
     data = cursor.fetchall()
     columns = [
         'views', 'conversion', 'variant', 'best_worst_binary', 'hypothesis'
     ]
     return_data = UserService.parseCursor(data, columns)
     return return_data
class RatingService:
    def __init__(self):
        self.database = database
        self.product = ProductService()
        self.user = UserService()

    def addRating(self, user_id, rating, product_id):
        if self.productAndUserExist(user_id, product_id):
            logger.info(
                "Adding rating for user: {}, product: {}, rating: {}".format(
                    user_id, product_id, rating))
            saved_record = self.database.addRating(user_id, rating, product_id)
            return saved_record
        else:
            logger.error("Product/User does not exist.")
            return None

    def productAndUserExist(self, user_id, product_id):
        product = self.database.getProduct(product_id)
        user = self.database.getUser(user_id)
        if product is not None and user is not None:
            return True
        else:
            return False

    def getRatingsDetailsForProduct(self, params):
        response = {}
        product_id = params['productId']
        response['averageRating'] = self.database.getAverageRating(product_id)
        response['totalRatings'] = self.database.getRatingsCount(product_id)
        response['productDetails'] = self.product.getProductById(product_id)
        if 'userId' in params:
            response['userDetails'] = self.user.getUserById(params['userId'])
            response[
                'loggedInUserRating'] = self.database.getProductRatingForUser(
                    product_id, params['userId'])

        if response['loggedInUserRating'] is None:
            response['loggedInUserRating'] = 0

        ratings = self.database.getRatings(product_id)
        response['ratingsBreakdown'] = self.computeRatingsBreakdown(ratings)
        return response

    def removeRating(self, params):
        return self.database.removeRating(params['userId'],
                                          params['productId'])

    @staticmethod
    def computeRatingsBreakdown(ratings):
        c = Counter(ratings)
        ratings_percentages = dict(
            (i, round(c[i] / len(ratings) * 100, 1)) for i in ratings)
        for i in range(1, 5):
            if i not in ratings_percentages:
                ratings_percentages[i] = 0
        return ratings_percentages
Exemple #13
0
    def get(self):
        print('invoked')
        query = "exec get_tactics @customer_id = ?"
        data, cursor = db.execute(query, True, (self.customer_id, ))
        data = cursor.fetchall()
        columns = ['title', 'description', 'tactic_id']
        returned = UserService.parseCursor(data, columns)

        return returned
Exemple #14
0
def setup_authentication(app):
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = '/login'
    user_service = UserService()

    @login_manager.user_loader
    def load_user(userId):
        user = user_service.get_user(user_id=userId)
        return user
Exemple #15
0
def new():
    form = forms.CreateCustomer()
    if ViewFuncs.ValidSubmission(form=form, method=request.method):
        result = UserService.CreateCustomer(form.email.data,
                                            form.password.data,
                                            form=form,
                                            app=app)
        if result:
            # return redirect(url_for('"splash", next_step="begin"'))
            login = UserService.customer_login(form.email.data,
                                               form.password.data)
            if login:
                return redirect(url_for('begin'))
        else:
            error = "something went wrong."
            return render_template('new.html', form=form, error=error)
    elif request.method == 'GET':
        session['logged_in'] = False
    return render_template('new.html', form=form)
Exemple #16
0
def add_secondary_user():
    req = request.get_json()
    UserService.CreateSecondaryUser(req.get('first_name'),
                                    req.get('last_name'), req.get('email'),
                                    req.get('password'), session['user'])

    email = EmailService()
    email.send_email_reset(req.get('email'), reset=False)

    return 'hi'
Exemple #17
0
def register_user():

    payload = request.get_json()
    user = UserService.register_user(email=payload['username'],
                                     password=payload['password'])

    if not user:
        return 'Email already used', status.HTTP_409_CONFLICT
    else:
        return jsonify(user), status.HTTP_200_OK
Exemple #18
0
def success():
    # get plan id
    email = session['email'] if session['logged_in'] else request.args.get(
        'email')
    customer_id = session['stripe_id'] if session[
        'logged_in'] else request.args.get('stripe_id')
    payments = PaymentsService(session['email'],
                               customer_id=session['stripe_id'])
    gchat = GoogleChatService()
    plans = payments.get_plan()
    for plan in plans:
        gchat.new_customer(email=session['email'], customer_type=plan)
        # update db with plan id
        UserService.update_plan(session['user'], plan)

    UserService.init_profile_after_purchase(UserService.now(), session['user'])

    # redirect to home
    return redirect(url_for('home', view='campaigns'))
def audience():
    form = forms.Audience()
    service = IntakeService(session['user'], 'audience',
                            session['onboarding_complete'])

    if 'view_id' not in request.args:
        view_id = service.get_persona()
        return redirect(url_for('audience', view_id=view_id, splash=False))

    if ViewFuncs.ValidSubmission(form=form, method=request.method):
        if request.form['submit_button'] != 'skip':
            service.audience(form.data, request.args.get('view_id'))
        else:
            service.skip(40)

        if request.form['submit_button'] == '+ save and add another audience':
            next_id = service.get_persona()
            return redirect(url_for('audience', view_id=next_id, splash=False))
        else:
            if not session['onboarding_complete']:
                ts = time.time()
                st = datetime.datetime.fromtimestamp(ts).strftime(
                    '%Y-%m-%d %H:%M:%S')
                UserService.init_profile(st, session['user'])
                google = GoogleChatService()
                google.onboarding_complete(email=session['email'])
                session['onboarding_complete'] = True
                intro = True
            else:
                intro = False

            return redirect(url_for('home', view='campaigns', intro=intro))

    return ViewFuncs.view_page(
        user=session['user'],
        user_name=session['user_name'],
        form=form,
        view_page='audience',
        next_page='product',
        coming_home=request.args.get('home'),
        splash=request.args.get('splash'),
        onboarding_complete=session['onboarding_complete'])
Exemple #20
0
def user_resource():

    if request.method == 'GET':
        user_id = flask_jwt.current_identity.id
        user = UserService.get_user_by_id(user_id=user_id)

        if not user:
            return 'User does not exist', status.HTTP_404_NOT_FOUND
        else:
            return jsonify(user), status.HTTP_200_OK

    if request.method == 'PUT':
        payload = request.get_json()
        user_id = flask_jwt.current_identity.id
        user = UserService.update_user(user_id, payload['age'], payload['bio'],
                                       payload['firstName'],
                                       payload['lastName'],
                                       payload['interests'])

        if not user:
            return 'User does not exist', status.HTTP_404_NOT_FOUND
        else:
            return jsonify(user), status.HTTP_200_OK
Exemple #21
0
    def is_time_period_available(user_id, user_given_start_date, user_given_end_date):
        def time_periods_overlap(ftpsd, ftped, stpsd, stped):
            return stpsd <= ftpsd <= stped or stpsd <= ftped <= stped \
                   or stpsd <= ftpsd <= stped or stpsd <= ftped <= stped

        if user_given_end_date <= user_given_start_date:
            return False

        busytimes = UserService.get_user_busy_times(user_id)

        return list(
            filter((lambda busytime: time_periods_overlap(
                user_given_start_date, user_given_end_date, busytime.start, busytime.end)), busytimes)
        ) == []
	def GetData(self):
		if self.table == 'audience':
			params = ('persona_name', 'audience_id', self.table, self.user)
		elif self.table == 'product_list':
			params = ('name', 'p_id', self.table, self.user)
		
		query = "SELECT %s, %s FROM %s WHERE customer_id = %s" % params
		data, cursor = db.execute(query, True, ())
		data = cursor.fetchall()

		column_list = ['name', 'id']
		data = UserService.parseCursor(data, column_list)

		return data
	def __init__(self, id, user_name, title=None):
		stage_1 = ['competitors', 'company', 'audience', 'product', 'product_2', 'salescycle']
		stage_2 = ['goals']
		stage_3 = ['history', 'platforms', 'past']
		stage_4 = ['creative']
		custom = ['salescycle', 'history', 'platforms']
		self.id = id
		self.title = title
		self.name = user_name

		if self.title in stage_1:
			self.stage = 1
		elif self.title in stage_2:
			self.stage = 2
		elif self.title in stage_3:
			self.stage = 3
		elif self.title in stage_4:
			self.stage = 4
		else:
			self.stage = 0

		def get_copy(self):
			query = """

					SELECT * FROM dbo.everything as e
					WHERE
					e.page_title = '%s'

					and
					(
						NOT EXISTS (select * from should_show(e.relevant_tags, %s))
						OR
						e.relevant_tags IS null
					)

					ORDER BY e.order_on_page
 

					""" % (self.title, self.id)

			data, cursor = db.execute(query, True, ())
			data = data.fetchall()
			cursor.close()
			return data

		columns = ['q_id', 'page_id', 'page_title', 'page_h1', 'page_p', 'label', 'why_asking_binary', 'why_label', 'what_binary', 'what_label', 'required_binary', 'label_p', 'horizontal_separator_binary', 'container_binary', 'answer_type', 'placeholder', 'a_format', 'html_name', 'route', 'tiles_name_h6', 'tiles_name_p', 'icon_file_path', 'sub_name', 'relevant_tags', 'order_on_page', 'q_group']
		if self.title not in custom:
			self.questions = UserService.parseCursor(get_copy(self), columns)
		else:
			self.questions = None
    def get_customers(self, conditional=None):
        query = """
                    SELECT * FROM customer_list
                """

        if conditional != None:
            query += conditional

        data, cursor = db.execute(query, True, ())
        data = cursor.fetchall()
        cursor.close()

        columns = [
            'name', 'email', 'company_name', 'customer_id', 'mgr', 'admin_id'
        ]

        if len(data) > 0:
            return_data = UserService.parseCursor(data, columns)
        else:
            null_list = [('no customers assigned yet', '', '', '', '', '')]
            return_data = UserService.parseCursor(null_list, columns)

        return return_data
Exemple #25
0
class UserController(BaseController):
    
    def __init__(self, app):
        super().__init__(app)
        self.user_service = UserService()
        self.app = app

    def routes_setup(self):
        self.app.add_url_rule('/users', 'users_index', self.index, methods=['GET'])

    def index(self):
        return self.response_success({"msg": self.user_service.r})

    def get_by_id(self):
        post_count = self.user_service.get_by_id(1)
        return jsonify({"posts": post_count})
Exemple #26
0
    def events_by_availability_filter_builder(user_id):
        def time_periods_overlap(ftpsd, ftped, stpsd, stped):
            return stpsd <= ftpsd <= stped or stpsd <= ftped <= stped \
                   or stpsd <= ftpsd <= stped or stpsd <= ftped <= stped

        busytimes = UserService.get_user_busy_times(user_id)

        if not busytimes:
            return lambda busytime: True

        return lambda event: reduce(
            (lambda x, y: x and y),
            map(
                (lambda busytime: not time_periods_overlap(
                    event.busytime.start, event.busytime.end, busytime.start, busytime.end)),
                busytimes
            )
        )
Exemple #27
0
    def post(self, user_id, device_id=None):
        request_data = request.json

        user = UserService().get_by_id(resource_id=user_id)

        if device_id:
            device = self.resource_service.update(device_id, request_data)
        else:
            device = self.resource_service.create(request_data)
        user.update(add_to_set__devices=device, upsert=True)
        user.save()

        return response_handler.success(response_data=device.to_json())
    def get_google(self, user='******'):
        query = """SELECT * FROM customer_ads_display(?)"""
        data, cursor = db.execute(query, True, (self.customer_id,))
        data = cursor.fetchall()
        columns = [
            'agg_ctr',
            'agg_cost',
            'best_ctr',
            'worst_ctr',
            'best_headline_1',
            'best_headline_2',
            'best_description',
            'worst_headline_1',
            'worst_headline_2',
            'worst_description'
        ]
        return_data = UserService.parseCursor(data, columns)

        return return_data
    def events_by_interests_filter_builder(user_id):
        def intersection(list1, list2):
            return [element for element in list1 if element in list2]

        def interests_in_event(event):
            event_interests = [
                interest.label for user in event.users
                for interest in user.interests
            ]
            event_interests = list(set(event_interests))  # Removing duplicates

            return event_interests

        user_interests = [
            interest.label
            for interest in UserService.get_user_by_id(user_id).interests
        ]

        return lambda event: intersection(interests_in_event(event),
                                          user_interests) is not []
def begin():
    form = forms.Profile()
    service = IntakeService(session['user'], 'begin',
                            session['onboarding_complete'])

    if ViewFuncs.ValidSubmission(form=form, method=request.method):
        if request.form['submit_button'] != 'skip':
            service.begin(form.data)
            if session['onboarding_complete'] == False:
                payments = PaymentsService(session['email'])
                stripe_id = payments.create_customer()

                session['stripe_id'] = stripe_id
                UserService.UpdateStripeId(session['email'],
                                           session['stripe_id'])

                gchat = GoogleChatService()
                gchat.onboarding_started(email=session['email'])

                stripe_info = PaymentsService(session['email'],
                                              customer_id=session['stripe_id'])
                stripe_info.modify(company_name=form.company_name.data)

        else:
            service.skip(10)

        if session['onboarding_complete'] == True:
            return redirect(url_for('home', view='profile'))
        else:
            return redirect(url_for('competitors'))

    return ViewFuncs.view_page(
        user=session['user'],
        user_name=session['user_name'],
        form=form,
        view_page='profile',
        next_page='competitors',
        coming_home=request.args.get('home'),
        splash=request.args.get('splash'),
        onboarding_complete=session['onboarding_complete'],
        onboarding=True if session['onboarding_complete'] == False else False)