Beispiel #1
0
    def get(self, mode=""):
        google_user = users.get_current_user()

        if google_user is None:
            self.redirect(users.create_login_url("/login"))

        # last_access_timeを記録
        user = User.gql("WHERE user_id=:1 and service=:2", google_user.user_id(), "google").get()
        if user is None:
            user = User(
                user_id=google_user.user_id(),
                name=google_user.nickname(),
                mail=google_user.email(),
                service="google",
                access_token=None,
                google_user=google_user,
                post_key="control",
                last_access_time=datetime.datetime.now(),
            )
            user.put()

        session = Session(self.request, self.response)
        session.new(user)
        if mode == "mlogin":
            self.redirect("/mhome?xoauth_requestor_id=" + user.user_id)
            return
        self.redirect("/")
Beispiel #2
0
    def get(self, mode=""):
        google_user = users.get_current_user()

        if google_user is None:
            self.redirect(users.create_login_url('/login'))

        # last_access_timeを記録
        user = User.gql("WHERE user_id=:1 and service=:2",
                        google_user.user_id(), "google").get()
        if user is None:
            user = User(user_id=google_user.user_id(),
                        name=google_user.nickname(),
                        mail=google_user.email(),
                        service='google',
                        access_token=None,
                        google_user=google_user,
                        post_key='control',
                        last_access_time=datetime.datetime.now())
            user.put()

        session = Session(self.request, self.response)
        session.new(user)
        if mode == 'mlogin':
            self.redirect('/mhome?xoauth_requestor_id=' + user.user_id)
            return
        self.redirect('/')
Beispiel #3
0
    def get_bad_products(category: str, session: Session) -> List[Product]:
        """
        Get bad products from given category in user database.

        :param category: Category to filter on
        :param session: Session
        :return: List[Product]
        """
        stmt = """
        SELECT
            p.brands,
            '',
            p.id,
            p.nutriscore_grade,
            p.packaging_tags,
            p.product_name_fr,
            '',
            p.url
        FROM Product_Category_Association as pca
        INNER JOIN Products as p
            ON pca.product_id = p.id
        INNER JOIN Categories as c
            ON pca.category_id = c.id
        WHERE
            pca.category_id = (SELECT id FROM Categories WHERE name = %s)
        AND 'D' <= p.nutriscore_grade
        """

        products = session.select(stmt, (category, ))

        bad_products: List[Product] = choices(
            [Product(*args) for args in products], k=ITEM_DISPLAYED)

        return bad_products
Beispiel #4
0
    def insert_in_database(self, session: Session,
                           stores: List[Store]) -> None:
        """
        Method to put all stores in database.

        :param session: Session
        :param stores: list containing all stores on OpenFoodFacts
        :return: None
        """
        columns = sorted(stores[0].__dict__.keys())

        values = []

        for store in stores:
            values.append((str(uuid1()), store.name, store.url))

        stmt = session.prepare_insert_statement(self.table, columns)

        session.insert(stmt, values)
    def insert_in_database(self, categories: List[Category],
                           session: Session) -> None:
        """
        Put categories in user's database.

        :param categories: List containing all categories on OpenFoodFacts
        :param session: Session
        :return: None
        """
        columns = sorted(categories[0].__dict__.keys())

        values = []

        for category in categories:
            values.append(
                (str(uuid1()), category.name, category.off_id, category.url))

        stmt = session.prepare_insert_statement(self.table, columns)

        session.insert(stmt, values)
Beispiel #6
0
    def insert_products_in_database(self, products: List[Product],
                                    session: Session) -> None:
        """
        Insert products in user's database.

        :param products: List of products to insert in database
        :param session: Session
        :return: None
        """
        columns = sorted(products[0].__dict__.keys())

        category_association = []
        store_association = []

        values = []

        for product in products:
            product_id = str(uuid1())
            values.append(
                (product.brands, ', '.join(product.categories_tags),
                 product_id, product.nutriscore_grade,
                 ', '.join(product.packaging_tags)
                 if product.packaging_tags else None, product.product_name_fr,
                 ', '.join(product.stores_tags), product.url))
            for category in product.categories_tags:
                category_association.append((product_id, category))
            for store in product.stores_tags:
                store_association.append((product_id, store))

        stmt_category_association = """
        INSERT IGNORE INTO Product_Category_Association
        (product_id, category_id)
        VALUES (%s, (SELECT id FROM Categories WHERE off_id = %s))
        """

        stmt_store_association = """
        INSERT IGNORE INTO Product_Store_Association
        (product_id, store_id)
        VALUES (%s, (SELECT id FROM Stores WHERE name = %s))
        """

        stmt = session.prepare_insert_statement(self.table, columns)

        # Insert product values in Products
        session.insert(stmt, values)

        # Insert Product_Category_Association
        session.insert(stmt_category_association, category_association)

        # Insert Product_Store_Association
        session.insert(stmt_store_association, store_association)
Beispiel #7
0
def main():
    """
    Main method of the program
    """
    category_manager: CategoryManager = CategoryManager()
    product_manager: ProductManager = ProductManager()
    store_manager: StoreManager = StoreManager()
    session: Session = Session()

    try:
        session.connect()

        session = welcome(category_manager, product_manager, session,
                          store_manager)
    except Exception:
        session.close()
        raise

    session.close()
Beispiel #8
0
    def get_saved_products(session: Session) -> List:
        """
        Get all previously saved products.

        :param session: Session
        :return: List[Product]
        """
        stmt = """
        SELECT
            p.product_name_fr,
            p2.product_name_fr,
            rp.date
        FROM Registered_Products as rp
        INNER JOIN Products as p
            ON rp.product_tested = p.id
        INNER JOIN Products as p2
            ON rp.product_substitued = p2.id
        """

        return session.select(stmt)
Beispiel #9
0
def define_database(category_manager: CategoryManager,
                    product_manager: ProductManager, session: Session,
                    store_manager: StoreManager) -> Session:
    """
    Format user's database to host application's data.

    :param category_manager: CategoryManager
    :param product_manager: ProductManager
    :param session: Session
    :param store_manager: StoreManager
    :return: Session
    """
    global DATABASE  # pylint: disable=W0603
    while 1:
        database_name: str = input("Entrez le nom de la base de "
                                   "données: \n")
        if session.database_exists(database_name):
            database = Database(session, database_name)
            session.close()
            session = Session()
            database.session = session
            try:
                session.connect()
                database.populate(category_manager, product_manager,
                                  store_manager)
                DATABASE = database_name

                return session
            except Exception:
                session.close()
                raise
        else:
            print(f"\n"
                  f"Vous avez tapé {database_name} mais celle-ci "
                  f"n'est pas présente dans mysql. Merci de "
                  f"vérifier "
                  f"\n")
Beispiel #10
0
    def get_better_product(product: Product, session: Session) -> Product:
        """
        Get a better product in replacement.

        :param product: Product to replace
        :param session: Session
        :return: None
        """
        stmt = """
        SELECT
            p.brands,
            '',
            p.id,
            p.nutriscore_grade,
            p.packaging_tags,
            p.product_name_fr,
            s.name,
            p.url
        FROM  Products as p
        INNER JOIN Product_Category_Association as pca
            ON pca.product_id = p.id
        INNER JOIN Categories as c
            ON pca.category_id = c.id
        INNER JOIN Product_Store_Association as psa
            ON psa.product_id = p.id
        INNER JOIN Stores as s
            ON psa.store_id = s.id
        WHERE
            pca.category_id = (SELECT Category_id
                             FROM Product_Category_Association
                             WHERE Product_id = %s LIMIT 1)
        AND 'B' >= p.nutriscore_grade
        """

        products = session.select(stmt, (product.id, ))

        better_product = choice([Product(*args) for args in products])

        return better_product
Beispiel #11
0
    def get(self, action="", account="", param=""):
        verification_code = self.request.get("code")
        args = dict(client_id=settings.FACEBOOK_APP_ID,
                    redirect_uri=self.request.path_url)
        if verification_code:
            args["client_secret"] = settings.FACEBOOK_APP_SECRET
            args["code"] = verification_code
            response = cgi.parse_qs(
                urllib.urlopen(
                    "https://graph.facebook.com/oauth/access_token?" +
                    urllib.urlencode(args)).read())
            access_token = response["access_token"][-1]

            profile_res = unicode(
                urllib.urlopen("https://graph.facebook.com/me?" +
                               urllib.urlencode(dict(
                                   access_token=access_token))).read(),
                'utf-8')
            profile = simplejson.loads(profile_res)

            user = None
            is_not_login = False
            try:
                self.check_login()
                user = self.session.get_user()
            except utils.NotLoginError:
                is_not_login = True
                user = User.gql("WHERE user_id=:1 and service=:2",
                                str(profile["id"]), "facebook").get()
                if user is None:
                    user = User(user_id=str(profile["id"]),
                                name=str(profile["name"]),
                                mail=str(profile["email"]),
                                service='facebook',
                                access_token=access_token,
                                post_key='control',
                                last_access_time=datetime.datetime.now())
                    user.put()
                session = Session(self.request, self.response)
                session.new(user)

            account = Account(user_ref=user,
                              service="facebook",
                              account_name=str(profile["id"]),
                              display_name=str(profile["name"]),
                              account_info=profile_res,
                              scope=FACEBOOK_SCOPE,
                              access_token=access_token)
            account.put()

            #既に同じアカウントが登録されていたら削除します
            saved_accounts = Account.gql(
                "WHERE service = :1 and user_ref = :2 and account_name = :3",
                "facebook", user.key(), account.account_name)
            for saved_account in saved_accounts:
                if saved_account.key() != account.key():
                    saved_account.delete()

            if is_not_login:
                if action == 'mlogin':
                    self.redirect('/mhome?xoauth_requestor_id=' + user.user_id)
                    return
                self.redirect('/')
                return

            #ウィンドウを閉じます
            tmpl = os.path.join(os.path.dirname(__file__),
                                "../view/oauth_callback.html")
            return self.response.out.write(
                template.render(tmpl, {'account': account}))
        else:
            args["scope"] = FACEBOOK_SCOPE
            if action == 'oauth':
                args["display"] = 'popup'
            self.redirect("https://www.facebook.com/dialog/oauth?" +
                          #"https://graph.facebook.com/oauth/authorize?" +
                          urllib.urlencode(args))
            return
Beispiel #12
0
    def check_login(self):
#        if self.check_2lo_oauth():
#            return
        self.session = Session(self.request, self.response)
        if not self.session.is_login():
            raise NotLoginError()
Beispiel #13
0
class BaseHandler(webapp.RequestHandler):
    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)
        
        lang = request.get('lang')
        if lang:
            translation.activate(lang)
            return
        #main.pyでDBに保存された言語設定をクッキーに入れている。それを取得。Ajaxリクエスト時に使用
        lang = Cookies(self).get('lang')
        if not lang:
            #なければリクエストヘッダーから取得する
            self.request.COOKIES = Cookies(self)
            self.request.META = os.environ
            lang = translation.get_language_from_request(self.request)
        translation.activate(lang)
        
        self.is_ajax = self.request.headers.get("X-Requested-With") == "XMLHttpRequest"
        self.is_mobile = False
#        if not self.is_ajax:
#            mobile_useragents = r'iPhone|iPod|Android|dream|CUPCAKE|BlackBerry|webOS|incognito|webmate'
#            user_agent = self.request.headers["user-agent"]
#            self.is_mobile = re.search(mobile_useragents, user_agent) is not None
    
    def handle_exception(self, exception, debug_mode):
        if isinstance(exception, NotLoginError):
            if self.is_ajax:
                self.error(403)
                return self.response.out.write("notlogin")
            #
            self.request.COOKIES = Cookies(self)
            self.request.META = os.environ
            lang = translation.get_language_from_request(self.request)
            if self.is_mobile:
                view = '../view/m_index.html'
            elif lang == "ja":
                view = '../view/index.html'
            else:
                view = '../view/index-en.html'
            template_values = {
               'version' : controller.version,
               'production' : not controller.is_dev
            }
            tmpl = os.path.join(os.path.dirname(__file__), view)
            return self.response.out.write(template.render(tmpl, template_values))
        logging.exception(exception)
        self.error(500)
        if self.is_ajax:
            return self.response.out.write("error")
        tmpl = os.path.join(os.path.dirname(__file__), '../view/500.html')
        return self.response.out.write(template.render(tmpl, {}))
    
    def check_login(self):
#        if self.check_2lo_oauth():
#            return
        self.session = Session(self.request, self.response)
        if not self.session.is_login():
            raise NotLoginError()
    
    def check_2lo_oauth(self):
        auth_header = self.request.headers.get("Authorization")
        if not auth_header:
            return False
        
        self.is_ajax = True
        
        user_id = self.request.get('xoauth_requestor_id')
        if not user_id:
            raise NotLoginError()
        
        try:
            # Builder our request object.
            request = oauth2.Request.from_request(
                self.request.method, self.request.path_url, self.request.headers, None,
                self.request.query)
        except Exception, e:
            logging.warn("Could not parse request from method = %s,"
                "uri = %s, headers = %s, query = %s, exception = %s" % (
                self.request.method, self.request.path_url, self.request.headers,
                self.request.query, e))
            raise NotLoginError()
        
        # Fetch the token from Cassandra and build our Consumer object.
        if request is None or 'oauth_consumer_key' not in request:
            logging.warn("Request is missing oauth_consumer_key.")
            raise NotLoginError()
        
        try:
            # Verify the two-legged request.
            server = oauth2.Server()
            server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())
            server.verify_request(request, _get_consumer(request["oauth_consumer_key"]), None)
        except Exception, e:
            logging.warn("Could not verify signature (%s)." % e)
            raise NotLoginError()
Beispiel #14
0
 def check_login(self):
     #        if self.check_2lo_oauth():
     #            return
     self.session = Session(self.request, self.response)
     if not self.session.is_login():
         raise NotLoginError()
Beispiel #15
0
class BaseHandler(webapp.RequestHandler):
    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)

        lang = request.get('lang')
        if lang:
            translation.activate(lang)
            return
        #main.pyでDBに保存された言語設定をクッキーに入れている。それを取得。Ajaxリクエスト時に使用
        lang = Cookies(self).get('lang')
        if not lang:
            #なければリクエストヘッダーから取得する
            self.request.COOKIES = Cookies(self)
            self.request.META = os.environ
            lang = translation.get_language_from_request(self.request)
        translation.activate(lang)

        self.is_ajax = self.request.headers.get(
            "X-Requested-With") == "XMLHttpRequest"
        self.is_mobile = False


#        if not self.is_ajax:
#            mobile_useragents = r'iPhone|iPod|Android|dream|CUPCAKE|BlackBerry|webOS|incognito|webmate'
#            user_agent = self.request.headers["user-agent"]
#            self.is_mobile = re.search(mobile_useragents, user_agent) is not None

    def handle_exception(self, exception, debug_mode):
        if isinstance(exception, NotLoginError):
            if self.is_ajax:
                self.error(403)
                return self.response.out.write("notlogin")
            #
            self.request.COOKIES = Cookies(self)
            self.request.META = os.environ
            lang = translation.get_language_from_request(self.request)
            if self.is_mobile:
                view = '../view/m_index.html'
            elif lang == "ja":
                view = '../view/index.html'
            else:
                view = '../view/index-en.html'
            template_values = {
                'version': controller.version,
                'production': not controller.is_dev
            }
            tmpl = os.path.join(os.path.dirname(__file__), view)
            return self.response.out.write(
                template.render(tmpl, template_values))
        logging.exception(exception)
        self.error(500)
        if self.is_ajax:
            return self.response.out.write("error")
        tmpl = os.path.join(os.path.dirname(__file__), '../view/500.html')
        return self.response.out.write(template.render(tmpl, {}))

    def check_login(self):
        #        if self.check_2lo_oauth():
        #            return
        self.session = Session(self.request, self.response)
        if not self.session.is_login():
            raise NotLoginError()

    def check_2lo_oauth(self):
        auth_header = self.request.headers.get("Authorization")
        if not auth_header:
            return False

        self.is_ajax = True

        user_id = self.request.get('xoauth_requestor_id')
        if not user_id:
            raise NotLoginError()

        try:
            # Builder our request object.
            request = oauth2.Request.from_request(self.request.method,
                                                  self.request.path_url,
                                                  self.request.headers, None,
                                                  self.request.query)
        except Exception, e:
            logging.warn("Could not parse request from method = %s,"
                         "uri = %s, headers = %s, query = %s, exception = %s" %
                         (self.request.method, self.request.path_url,
                          self.request.headers, self.request.query, e))
            raise NotLoginError()

        # Fetch the token from Cassandra and build our Consumer object.
        if request is None or 'oauth_consumer_key' not in request:
            logging.warn("Request is missing oauth_consumer_key.")
            raise NotLoginError()

        try:
            # Verify the two-legged request.
            server = oauth2.Server()
            server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())
            server.verify_request(request,
                                  _get_consumer(request["oauth_consumer_key"]),
                                  None)
        except Exception, e:
            logging.warn("Could not verify signature (%s)." % e)
            raise NotLoginError()
Beispiel #16
0
 def get(self, action="", account="", param=""):
     verification_code = self.request.get("code")
     args = dict(client_id=settings.FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
     if verification_code:
         args["client_secret"] = settings.FACEBOOK_APP_SECRET
         args["code"] = verification_code
         response = cgi.parse_qs(urllib.urlopen(
             "https://graph.facebook.com/oauth/access_token?" +
             urllib.urlencode(args)).read())
         access_token = response["access_token"][-1]
         
         profile_res = unicode(urllib.urlopen(
             "https://graph.facebook.com/me?" +
             urllib.urlencode(dict(access_token=access_token))).read(),'utf-8')
         profile = simplejson.loads(profile_res)
         
         user = None
         is_not_login = False
         try:
             self.check_login()
             user = self.session.get_user()
         except utils.NotLoginError:
             is_not_login = True
             user = User.gql("WHERE user_id=:1 and service=:2", str(profile["id"]), "facebook").get()
             if user is None:
                 user = User(
                     user_id=str(profile["id"]),
                     name=str(profile["name"]),
                     mail=str(profile["email"]),
                     service='facebook',
                     access_token=access_token,
                     post_key='control',
                     last_access_time=datetime.datetime.now()
                 )
                 user.put()
             session = Session(self.request, self.response)
             session.new(user)
         
         account = Account(
             user_ref=user,
             service="facebook",
             account_name=str(profile["id"]),
             display_name=str(profile["name"]),
             account_info=profile_res,
             scope=FACEBOOK_SCOPE,
             access_token=access_token
             )
         account.put()
         
         #既に同じアカウントが登録されていたら削除します
         saved_accounts = Account.gql(
             "WHERE service = :1 and user_ref = :2 and account_name = :3",
             "facebook",
             user.key(),
             account.account_name)
         for saved_account in saved_accounts:
             if saved_account.key() != account.key():
                 saved_account.delete()
         
         if is_not_login:
             if action == 'mlogin':
                 self.redirect('/mhome?xoauth_requestor_id='+user.user_id)
                 return
             self.redirect('/')
             return
         
         #ウィンドウを閉じます
         tmpl = os.path.join(os.path.dirname(__file__), "../view/oauth_callback.html")
         return self.response.out.write(template.render(tmpl, {'account':account}))
     else:
         args["scope"] = FACEBOOK_SCOPE
         if action == 'oauth':
             args["display"] = 'popup'
         self.redirect(
             "https://www.facebook.com/dialog/oauth?" +
             #"https://graph.facebook.com/oauth/authorize?" +
             urllib.urlencode(args))
         return
Beispiel #17
0
# Single place for global scoped objects
# Provides a single DatabaseManager, and Creator.
# Also, the order of the imports is important, so don't try to
# neaten them up.


import os

_PATH = os.path.dirname(os.path.abspath(__file__))

from controller.database_manager import DatabaseManager
database_manager = DatabaseManager()

from controller.database_creator import DatabaseCreator
database_creator = DatabaseCreator()

from controller.test_db_creator import TestDatabaseCreator
test_database_creator = TestDatabaseCreator()

from controller.session import Session
session = Session()