Example #1
0
def update_cookie_login(user_id, new_series_id=False):
    params = {'user_id': user_id, 'logintoken': generate_salt()}
    if new_series_id:
        params['seriesid'] = generate_salt()

    for k, v in params.iteritems():
        web.setcookie(k, v, 9999999)  # a really long time

    del params['user_id']
    database.get_db().update('users',
                             where='id = $user_id',
                             vars={'user_id': user_id},
                             **params)
Example #2
0
 def POST(self, pin_id):
     form = self.get_form()
     if form.validates():
         web.header('Content-Type', 'application/json')
         sess = session.get_session()
         auth.force_login(sess)
         db = database.get_db()
         price = form.d.price or None
         pin_utils.update_base_pin_information(db, pin_id, sess.user_id,
                                               form.d.title,
                                               form.d.description,
                                               form.d.link, form.d.tags,
                                               price, form.d.product_url,
                                               form.d.price_range)
         categories = [int(c) for c in form.d.categories.split(',')]
         pin_utils.update_pin_into_categories(db, pin_id, categories)
         if form.d.imageurl:
             try:
                 image_filename, _ = urllib.urlretrieve(form.d.imageurl)
                 pin_utils.update_pin_images(db, pin_id, sess.user_id,
                                             image_filename)
             except Exception as e:
                 logger.error(
                     'Could not save the image for pin: {} from URL: {}'.
                     format(pin_id, form.d.imageurl),
                     exc_info=True)
                 return json.dumps({'status': str(e)})
         return json.dumps({'status': 'ok'})
     else:
         return web.notfound()
Example #3
0
 def GET(self, category_id):
     db = database.get_db()
     results = db.where(table='categories', id=category_id)
     for row in results:
         category = row
     subcategories = db.where(table='categories', parent=category_id)
     results = db.query(
         '''select root.id, root.name, child.id as child_id, child.name as child_name, child.is_default_sub_category
                                 from categories root left join categories child on root.id=child.parent
                                 where root.parent is NULL
                                     and root.id <> $id
                                 order by root.name, child.name
                                 ''',
         vars={'id': category_id})
     self.others = []
     current_category_id = None
     for row in results:
         root_id = row.id
         if not current_category_id or root_id != current_category_id:
             current_category_id = root_id
             self.others.append((root_id, row.name))
         if row.child_id:
             self.others.append(
                 (row.child_id, '{} - {}'.format(row.name, row.child_name)))
     form = self.get_form()
     msg = web.input(msg=None)['msg']
     return template.admin.category_delete(category, subcategories, form,
                                           msg)
Example #4
0
def username_exists(username):
    result = database.get_db().select('users',
                                      what='1',
                                      where='username=$username',
                                      vars={'username': username.lower()},
                                      limit=1)
    return bool(result)
Example #5
0
def email_exists(email):
    result = database.get_db().select('users',
                                      what='1',
                                      where='email=$email',
                                      vars={'email': email.lower()},
                                      limit=1)
    return bool(result)
Example #6
0
 def POST(self):
     sess = session.get_session()
     auth.force_login(sess)
     form = self._form()
     if form.validates():
         pin_id_list = list(set([int(x) for x in form.d.ids.split(',')]))
         pins_to_delte = ','.join(str(x) for x in pin_id_list)
         category_id_list = [int(x) for x in form.d.categories.split(',')]
         values_to_insert = [{
             'pin_id': pin_id,
             'category_id': category_id
         } for pin_id, category_id in itertools.product(
             pin_id_list, category_id_list)]
         db = database.get_db()
         transaction = db.transaction()
         try:
             db.delete(table='pins_categories',
                       where='pin_id in ({})'.format(pins_to_delte))
             db.multiple_insert(tablename='pins_categories',
                                values=values_to_insert)
             transaction.commit()
             return json.dumps({'status': 'ok'})
         except Exception:
             logger.error('Failed to update categories', exc_info=True)
             transaction.rollback()
             return json.dumps({'status': 'error'})
     else:
         return json.dumps({'status': 'error'})
Example #7
0
def ltpl(*params):
    sess = session.get_session()
    if auth.logged_in(sess):
        logintoken = convert_to_logintoken(sess.user_id)
        # Getting profile of a given user
        profile_url = "/api/profile/userinfo/info"
        profile_owner_context = {
            "csid_from_client": "1",
            "id": sess.user_id,
            "logintoken": logintoken}
        user = api_request(profile_url, data=profile_owner_context)\
            .get("data", [])

        if len(user) == 0:
            return u"Profile was not found"
        user = pin_utils.dotdict(user)

        db = database.get_db()

        acti_needed = user.activation
        notif_count = db.select('notifs', what='count(*)', where='user_id = $id', vars={'id': sess.user_id})
        # all_albums = list(db.select('albums', where="user_id=%s" % (sess.user_id), order='id'))
        all_albums = []
        boards = list(db.where(table='boards', order='name', user_id=sess.user_id))
        categories_to_select = list(cached_models.get_categories_with_children(db))
        return tpl('layout', tpl(*params), cached_models.get_categories(), boards, all_albums, user, acti_needed, notif_count[0].count, csrf_token,categories_to_select )
    return tpl('layout', tpl(*params), cached_models.get_categories())
Example #8
0
 def POST(self):
     form = self._email_form()
     if form.validates():
         user_email = form['email'].value
         sess = session.get_session()
         user_id = sess['tw_user_id']
         db = database.get_db()
         if user_id:
             db.update(tables='users',
                       where='id=$user_id',
                       vars={'user_id': user_id},
                       email=user_email)
         else:
             values = {
                 'name': sess['tw_name'],
                 'username': sess['tw_username'],
                 'twitter': sess['tw_twitter'],
                 'login_source': auth.LOGIN_SOURCE_TWITTER,
                 'email': user_email,
             }
             user_id = db.insert(tablename='users', **values)
         auth.login_user(session.get_session(), user_id)
         web.seeother(url='/register/after-signup', absolute=True)
     else:
         return template.ltpl('register/twitter/email',
                              form,
                              msg=_('Please provide an email'))
Example #9
0
 def GET(self):
     db = database.get_db()
     sess = session.get_session()
     results = db.where('users', what='username', id=sess.user_id)
     for row in results:
         username = row.username
     return template.ltpl('recover_password/complete', username)
Example #10
0
    def GET(self, allusers=None):
        auth.login()

        params = web.input(page=1, sort='users.name', dir='asc', query='')
        page = int(params.page) - 1
        sort = params.sort
        direction = params.dir
        search_query = params.query

        if search_query:
            where = """ and (
            users.email ilike '%%{query}%%' or
            users.name ilike '%%{query}%%' or
            users.about ilike '%%{query}%%')""".format(query=search_query)
        else:
            where = ''
        query = USERS_QUERY.format(where=where,
                                  sort=sort,
                                  dir=direction,
                                  offset=page * self.page_size,
                                  limit=self.page_size)
            
        db = database.get_db()
        results = db.query(query)
        results = self.fix_creation_date(results)
        return web.template.frender('t/admin/search_results.html')(results)
Example #11
0
 def DELETE(self, pin_id):
     db = database.get_db()
     pin = db.where(table='pins', id=pin_id)[0]
     pin_utils.delete_pin_from_db(db=db,
                                  pin_id=pin_id,
                                  user_id=pin.user_id)
     return 'ok'
Example #12
0
 def POST(self):
     form = self.UsernameForm()
     if form.validates():
         username_or_email = form.d.username
         self.db = database.get_db()
         results_username = self.db.where(table='users',
                                          username=username_or_email)
         for row in results_username:
             self.user = row
             break
         else:
             results_email = self.db.where(table='users',
                                           email=username_or_email)
             for row in results_email:
                 self.user = row
                 break
             else:
                 return web.seeother('?msg={}'.format(
                     _('It looks like you entered invalid information. Please try again.'
                       )),
                                     absolute=False)
         self.generate_a_temporary_password_change_token()
         self.send_email_to_user()
         return web.seeother('/recover_password_sent/')
     else:
         return web.seeother('?msg={}'.format(
             _('Enter your username or email address')),
                             absolute=False)
Example #13
0
 def GET(self):
     db = database.get_db()
     results = db.query(
         '''select root.id, root.name, child.id as child_id, child.name as child_name, child.is_default_sub_category
                                 from categories root left join categories child on root.id=child.parent
                                 where root.parent is NULL
                                 order by root.position desc, root.name, child.name
                                 ''')
     category_list = []
     last_root_category = None
     for row in results:
         if not last_root_category or last_root_category['id'] != row.id:
             last_root_category = {
                 'id': row.id,
                 'name': row.name,
                 'subcategories': list()
             }
             category_list.append(last_root_category)
         if row.child_id:
             last_root_category['subcategories'].append({
                 'id':
                 row.child_id,
                 'name':
                 row.child_name,
                 'default':
                 row.is_default_sub_category
             })
     return template.admin.list_categories(category_list)
Example #14
0
 def POST(self, user_id, token_id, token):
     user_id = int(user_id)
     token_id = int(token_id)
     form = self.PwdResetForm()
     if form.validates():
         sess = session.get_session()
         if sess['pwdrecov_token_id'] != token_id or sess[
                 'pwdrecov_user_id'] != user_id or sess[
                     'pwdrecov_token'] != token:
             message = _(
                 'Sorry! We cannot verify that this user requested a password reset. Please try to reset your passord again.'
             )
             return web.seeother(
                 url='/recover_password?msg={}'.format(message),
                 absolute=True)
         password = form.d.pwd1
         auth.chage_user_password(user_id, password)
         db = database.get_db()
         db.update(tables='password_change_tokens',
                   where='id=$id',
                   vars={'id': token_id},
                   used=True,
                   used_on=datetime.datetime.now())
         auth.login_user(sess, user_id)
         self.send_email()
         return web.seeother('/recover_password_complete/')
     else:
         return template.ltpl('recover_password/change_pwd_form', form)
Example #15
0
 def GET(self, pin_id=None):
     sess = session.get_session()
     auth.force_login(sess)
     db = database.get_db()
     results = db.query('''select pins.*
                         from pins
                         where pins.id=$id and user_id=$user_id''',
                        vars={
                            'id': pin_id,
                            'user_id': sess.user_id
                        })
     for row in results:
         web.header('Content-Type', 'application/json')
         row.price = str(row.price)
         row.price_range_repr = '$' * row.price_range if row.price_range < 5 else '$$$$+'
         results = db.select(
             tables=['categories', 'pins_categories'],
             where=
             'categories.id = pins_categories.category_id and pins_categories.pin_id=$id',
             vars={'id': pin_id})
         row['categories'] = [{
             'id': catrow.id,
             'name': catrow.name
         } for catrow in results]
         results = db.where(table='tags', pin_id=pin_id)
         tags = [r.tags for r in results]
         row['tags'] = tags
         return json.dumps(row)
     raise web.notfound()
Example #16
0
 def grab_and_insert_profile_picture(self):
     sess = session.get_session()
     db = database.get_db()
     album_id = db.insert(tablename='albums',
                          name=_('Profile Pictures'),
                          user_id=self.user_id)
     photo_id = db.insert(tablename='photos', album_id=album_id)
     picture_url = 'https://graph.facebook.com/{0}/picture'.format(
         sess.fb_profile['username'])
     picture_filename = 'static/pics/{0}.png'.format(photo_id)
     try:
         filename, headers = urllib.urlretrieve(url=picture_url)
         if filename.endswith('.png'):
             os.renames(old=filename, new=picture_filename)
         else:
             img = Image.open(filename)
             img.save(picture_filename)
             os.unlink(filename)
         img = Image.open(picture_filename)
         width, height = img.size
         ratio = 80.0 / float(width)
         width = 80
         height *= ratio
         img.thumbnail((width, height), Image.ANTIALIAS)
         picture_thumb_filename = 'static/pics/userthumb{0}.png'.format(
             photo_id)
         img.save(picture_thumb_filename)
         db.update(tables='users',
                   where='id=$id',
                   vars={'id': self.user_id},
                   pic=photo_id)
     except:
         # no problem, we can live without the profile picture
         logger.info('Could not obtain faceboog profile picture',
                     exc_info=True)
Example #17
0
 def POST(self, category_id):
     self.category_id = category_id
     self.web_input = web.input(name=None, number_of_sub_categories=None)
     name = self.web_input['name']
     slug = self.web_input['slug']
     position = int(self.web_input.get('position', 0))
     self.number_of_sub_categories = self.web_input[
         'number_of_sub_categories']
     if name and slug:
         self.db = database.get_db()
         transaction = self.db.transaction()
         try:
             self.db.update(tables='categories',
                            where='id=$id',
                            vars={'id': category_id},
                            name=name,
                            slug=slug,
                            position=position)
             if self.number_of_sub_categories:
                 self.save_sub_categories()
             transaction.commit()
             web.seeother(url='/admin/categories', absolute=True)
         except Exception as e:
             transaction.rollback()
             logger.error('Cannot update category {}'.format(category_id),
                          exc_info=True)
             try:
                 error = urllib.urlencode(('message', str(e)))
             except:
                 error = 'message=Cannot update category'
             web.seeother(url='?{}'.format(error), absolute=False)
     else:
         web.seeother(url='', absolute=False)
Example #18
0
    def get_user_from_db(self):
        '''
        Obtains the user_id from the database and return if exists, else returns false.

        Looks if the google nickname is in the DB. If the profile does not have a nickname,
        look if the email is in the DB.
        '''
        try:
            db = database.get_db()
            if 'nickname' in self.profile:
                query_result = db.select(tables='users', where="gplus=$username and login_source=$login_source",
                                           vars={'username': self.profile['nickname'].lower(),
                                                 'login_source': auth.LOGIN_SOURCE_GOOGLE})
            elif 'emails' in self.profile:
                email = self.profile['emails'][0]['value']
                query_result = db.select(tables='users', where="email=$email",
                                           vars={'email': email.lower()})
            else:
                return False
            for row in query_result:
                self.user_id = row['id']
                self.username = row['username']
                return self.user_id
            return False
        except:
            logger.error('Cannot obtain user from the DB. User id: %s', self.user_id, exc_info=True)
            return False
Example #19
0
 def POST(self, pin_id):
     db = database.get_db()
     pin = db.where(table='pins', id=pin_id)[0]
     data = web.input(image_file={})
     pin_utils.update_base_pin_information(db,
                                           pin_id=pin_id,
                                           user_id=pin.user_id,
                                           title=data.title,
                                           description=data.description,
                                           link=data.link,
                                           tags=data.tags,
                                           price=data.price,
                                           product_url=data.product_url,
                                           price_range=data.price_range,
                                           board_id=pin.board_id)
     categories = [int(v) for k, v in data.items() if k.startswith('category')]
     pin_utils.update_pin_into_categories(db=db,
                                          pin_id=pin_id,
                                          category_id_list=categories)
     if data.image_url:
         filename, _ = urllib.urlretrieve(data.image_url)
         pin_utils.update_pin_images(db=db,
                                     pin_id=pin_id,
                                     user_id=pin.user_id,
                                     image_filename=filename)
     return web.seeother('{}'.format(pin_id))
Example #20
0
 def GET(self):
     data = web.input(page=1, dir='desc', sort='pins.timestamp')
     sess = session.get_session()
     reset_offset = sess.get('search_reset_offset', False)
     if reset_offset:
         self.page = 0
         sess['search_reset_offset'] = False
     else:
         self.page = int(data.page) - 1
     self.sort = data.sort
     self.sort_direction = data.dir
     
     where_clause = build_where(self)
     db = database.get_db()
     results = db.query('''select 
                         pins.*,
                         case when users.username is null then '---' else users.username end as username
                     from pins 
                         left join users on pins.user_id=users.id
                     where {where_clause}
                     order by {sort_ord} {sort_dir}
                     limit {limit} offset {offset}
                     '''.format(where_clause=' and '.join(where_clause), sort_ord=self.sort, sort_dir=self.sort_direction, limit=PAGE_SIZE, offset=(PAGE_SIZE * self.page)))
     pins = []
     for row in results:
         pins.append(row)
     if pins:
         return web.template.frender('t/admin/pin_search_list.html')(pins, date)
     else:
         return web.template.frender('t/admin/pin_search_list.html')([], date)
Example #21
0
    def GET(self, category_id):
        '''
        Searches or returns all pins in this category_id.

        The results are paginated using offset and limit
        '''
        db = database.get_db()
        search_terms = web.input(search_terms=None)['search_terms']
        try:
            search_limit = int(web.input(limit='10')['limit'])
        except ValueError:
            search_limit = 10
        else:
            if search_limit > 50: search_limit = 50
            if search_limit < 5: search_limit = 5
        try:
            search_offset = int(web.input(offset='0')['offset'])
        except ValueError:
            search_offset = 0
        else:
            if search_offset < 0: search_offset = 0
        if search_terms:
            search_terms = "%{}%".format(search_terms.lower())
            pins = db.select(
                tables=['pins', 'pins_categories'],
                order='name',
                where=
                'pins.id=pins_categories.pin_id and pins_categories.category_id=$category_id'
                ' and (lower(name) like $search or lower(description) like $search)'
                ' and id not in (select pin_id from cool_pins where category_id=$category_id)',
                vars={
                    'category_id': category_id,
                    'search': search_terms
                },
                limit=search_limit,
                offset=search_offset)
        else:
            pins = db.select(
                tables='pins',
                order='name',
                where=
                'pins.id=pins_categories.pin_id and pins_categories.category_id=$category_id'
                ' and id not in (select pin_id from cool_pins where category_id=$category_id)',
                vars={
                    'category_id': category_id,
                    'search': search_terms
                },
                limit=search_limit,
                offset=search_offset)
        list_of_pins = []
        for p in pins:
            list_of_pins.append(dict(p))
        web.header('Content-Type', 'application/json')
        return json.dumps({
            'limit': search_limit,
            'offset': search_offset,
            'list_of_pins': list_of_pins,
            'search_terms': search_terms
        })
Example #22
0
 def POST(self):
     data = web.input(ids='')
     ids = [int(x) for x in data.ids.split(',')]
     db = database.get_db()
     for pin_id in ids:
         pin = db.where(table='pins', what='id, user_id', id=pin_id)[0]
         pin_utils.delete_pin_from_db(db, pin_id, pin.user_id)
     return 'ok'
Example #23
0
File: api.py Project: kissarat/pin
def convert_to_logintoken(id):
    '''
    Returns logintoken of user by id.
    '''
    user = database.get_db().select('users', {"id": id}, where="id=$id")
    if len(user) > 0:
        return user.list()[0]['logintoken']
    else:
        return None
Example #24
0
def chage_user_password(user_id, password):
    pw_hash = str(hash(password))
    pw_salt = generate_salt()
    pw_hash = str(hash(pw_hash + pw_salt))

    return database.get_db().update('users',
                                    where='id=$id',
                                    vars={'id': user_id},
                                    pw_hash=pw_hash,
                                    pw_salt=pw_salt)
Example #25
0
def create_user(email, password, **params):
    pw_hash = str(hash(password))
    pw_salt = generate_salt()
    pw_hash = str(hash(pw_hash + pw_salt))

    return database.get_db().insert('users',
                                    email=email.lower(),
                                    pw_hash=pw_hash,
                                    pw_salt=pw_salt,
                                    **params)
Example #26
0
 def GET(self, pin_id):
     db = database.get_db()
     query_results = db.where(table='pins', id=pin_id)
     pin = None
     for p in query_results:
         pin = dict(p)
         pin['price'] = str(pin['price'])
     if pin:
         web.header('Content-Type', 'application/json')
         return json.dumps(pin)
Example #27
0
 def username_already_exists(self, username):
     '''
     Test if the username already exists in the DB
     '''
     db = database.get_db()
     query_result = db.select(tables='users',
                              where="username=$username",
                              vars={'username': username.lower()})
     for _ in query_result:
         return True
     return False
Example #28
0
 def DELETE(self, pin_id):
     sess = session.get_session()
     category = sess['category']
     db = database.get_db()
     db.delete(table='pins_categories',
               where='pin_id=$pinid and category_id=$catid',
               vars={
                   'pinid': pin_id,
                   'catid': category
               })
     return 'ok'
Example #29
0
 def email_already_exists(self, email):
     '''
     Test if the email already exists in the DB
     '''
     db = database.get_db()
     query_result = db.select(tables='users',
                              where="email=$email",
                              vars={'email': email.lower()})
     for _ in query_result:
         return True
     return False
Example #30
0
File: api.py Project: kissarat/pin
def convert_to_id(logintoken):
    '''
    Returns id of user by logintoken.
    '''
    user = database.get_db().select('users', {"logintoken": logintoken},
                                    where="logintoken=$logintoken")

    if len(user) > 0:
        return user.list()[0]['id']
    else:
        return None