Example #1
0
    def fetch_mentions(self):
        url = "http://api.twitter.com/1/statuses/mentions.json?count=50"

        session = cherrypy.engine.publish('bind-session').pop()
        newest = Mention.newest(session)
        if newest:
            url += "&since_id=%d" % newest.tweet_id
        for user in User.all_(session):
            content = self.bus.publish("oauth-request", url, user.oauth_token,
                                       user.oauth_token_secret).pop()
            tweets = json.loads(content)
            if newest:
                cherrypy.log("Retrieved %d tweets since %s" %
                             (len(tweets), newest.date))
            else:
                cherrypy.log("Retrieved %d tweets" % (len(tweets), ))
            for tweet in tweets:
                user = tweet.get('user')
                if user:
                    session.add(
                        Mention(username=user['name'],
                                user_id=user['id'],
                                tweet=tweet['text'],
                                tweet_id=tweet['id'],
                                lang=self.guess_language(tweet['text']),
                                date=parse(tweet['created_at'])))

        cherrypy.engine.publish('commit-session')
Example #2
0
    def fetch_mentions(self):
        url = "http://api.twitter.com/1/statuses/mentions.json?count=50"
        
        session = cherrypy.engine.publish('bind-session').pop()
        newest = Mention.newest(session)
        if newest:
            url += "&since_id=%d" % newest.tweet_id
        for user in User.all_(session):
            content = self.bus.publish("oauth-request", url,
                                       user.oauth_token,
                                       user.oauth_token_secret).pop()
            tweets = json.loads(content)
            if newest: cherrypy.log("Retrieved %d tweets since %s" % (len(tweets), newest.date))
            else: cherrypy.log("Retrieved %d tweets" % (len(tweets), ))
            for tweet in tweets:
                user = tweet.get('user')
                if user:
                    session.add(Mention(username=user['name'],
                                        user_id=user['id'],
                                        tweet=tweet['text'],
                                        tweet_id=tweet['id'],
                                        lang=self.guess_language(tweet['text']),
                                        date=parse(tweet['created_at'])))

        cherrypy.engine.publish('commit-session')
Example #3
0
    def change(self, **params):
        engine = cherrypy.engine
        if cherrypy.session.get('auth', False):
            user = cherrypy.session['user']
            oldpasswd = cherrypy.request.params.get('oldpassword')
            newpasswd = cherrypy.request.params.get('newpassword')

            try:
                user.change_password(oldpasswd, newpasswd)

                return {'ok': True}
            except InvalidCredentials:
                return {'ok': False, 'error': 'Current password invalid.'}
            except UserModelException:
                return {
                    'ok':
                    False,
                    'error':
                    'Unknown system error.  Contact your Systems Administrator.'
                }

        elif cherrypy.session.get('token', False):
            cherrypy.session['user'] = User(cherrypy.session['username'])
            newpassword = cherrypy.request.params.get('newpassword')

            try:
                cherrypy.session['user'].set_password(newpassword)
                return {'ok': True}
            except UserModelException:
                return {
                    'ok': False,
                    'error': 'Unable to change your password. Try again later.'
                }
Example #4
0
    def _fetch(self):
        if 'user_id' not in cherrypy.session:
            raise cherrypy.HTTPRedirect("/login")

        uid = cherrypy.session['user_id'].decode('utf-8')
        user = User.get_by_uid(cherrypy.request.db, uid)
        if not user:
            raise cherrypy.HTTPRedirect("/login/")

        cherrypy.request.user = user
Example #5
0
    def _fetch(self):
        if 'user_id' not in cherrypy.session:
            raise cherrypy.HTTPRedirect("/login")

        uid = cherrypy.session['user_id'].decode('utf-8')
        user = User.get_by_uid(cherrypy.request.db, uid)
        if not user:
            raise cherrypy.HTTPRedirect("/login/")

        cherrypy.request.user = user
Example #6
0
 def POST(self, email, password):
     exists = userExists(email)
     if exists is None:
         salt = create_salt()
         hashed_password = hash_password(salt, password)
         newUser = User(email=email,
                        salt=salt,
                        password_hash=hashed_password)
         add(newUser)
     else:
         raise cherrypy.HTTPError(409, 'E-Mail already exists')
Example #7
0
    def success(self, *args, **kwargs):
        engine = cherrypy.engine
        content = engine.publish("oauth-request", Login.access_token_url,
                                 cherrypy.session['request_token']['oauth_token'],
                                 cherrypy.session['request_token']['oauth_token_secret']).pop()

        access_token = dict(cgi.parse_qsl(content))
        cherrypy.session['user_id'] = uid = access_token['user_id']
        db = cherrypy.request.db
        user = User.get_by_uid(db, uid.decode('utf-8'))
        if not user:
            user = User(name=access_token['screen_name'],
                        user_id=int(uid),
                        oauth_token=access_token['oauth_token'],
                        oauth_token_secret=access_token['oauth_token_secret'])
            db.add(user)
        else:
            user.oauth_token = access_token['oauth_token']
            user.oauth_token_secret = access_token['oauth_token_secret']
        
        raise cherrypy.HTTPRedirect("/")
Example #8
0
    def success(self, *args, **kwargs):
        engine = cherrypy.engine
        content = engine.publish(
            "oauth-request", Login.access_token_url,
            cherrypy.session['request_token']['oauth_token'],
            cherrypy.session['request_token']['oauth_token_secret']).pop()

        access_token = dict(cgi.parse_qsl(content))
        cherrypy.session['user_id'] = uid = access_token['user_id']
        db = cherrypy.request.db
        user = User.get_by_uid(db, uid.decode('utf-8'))
        if not user:
            user = User(name=access_token['screen_name'],
                        user_id=int(uid),
                        oauth_token=access_token['oauth_token'],
                        oauth_token_secret=access_token['oauth_token_secret'])
            db.add(user)
        else:
            user.oauth_token = access_token['oauth_token']
            user.oauth_token_secret = access_token['oauth_token_secret']

        raise cherrypy.HTTPRedirect("/")
Example #9
0
    def login(self, username=None, password=None):
        if username is None or password is None:
            raise cherrypy.HTTPError(400, 'Bad Request')

        try:
            cherrypy.session['user'] = User(username)
            cherrypy.session['auth'] = cherrypy.session['user'].authenticate(
                password)
            return {'ok': cherrypy.session['user'].auth}
        except (InvalidUser, InvalidCredentials):
            return {'ok': False, 'error': 'Invalid credentials.  Try again.'}
        except UserModelException:
            return {'ok': False}
Example #10
0
File: main.py Project: j0hn/snipptr
def before_request():
    """
    Ran before any HTTP request.
    Connects the database.
    """

    g.db = database
    g.db.connect()

    try:
        g.user = [x for x in User.select().where(id=session["user_id"])].pop()
    except:
        g.user = None
Example #11
0
    def _fetch(self, require_auth, require_admin=False):
        user = None
        username = cherrypy.session.get("_cp_username", None)

        if username:
            user = User.get(cherrypy.request.db, username)

        if require_auth and user is None and require_admin is not None:
            raise cherrypy.HTTPRedirect("/user/login")           

        cherrypy.request.user = user

        if require_admin and user.is_admin is False:
            raise cherrypy.HTTPError("403 Forbidden", "You are not allowed to access this resource.")
Example #12
0
def login():
    if g.user:  # Allready logged in
        return redirect(url_for("index"))

    error = None
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")

        try:
            user = [x for x in User.select().where(username=username, password=password)].pop()
            session["user_id"] = user.id
            return redirect(url_for("index"))
        except Exception, e:
            print e
            error = "Invalid username or password"
Example #13
0
    def _send_email(cls):
        """
        Check the email type and send the requested email using
        the email plugin.
        """
        if not hasattr(cherrypy.request, "email_address"):
            return

        if not hasattr(cherrypy.request, "email_type"):
            return

        cherrypy.request.user = User.get_by_email(cherrypy.request.email_address)

        if "mail" in cherrypy.request.user:
            if cherrypy.request.email_type == "password":
                cherrypy.engine.publish("email-send-reset", cherrypy.request.user)
            if cherrypy.request.email_type == "username":
                cherrypy.engine.publish("email-send-username", cherrypy.request.user)
Example #14
0
    def _send_email(cls):
        """
        Check the email type and send the requested email using
        the email plugin.
        """
        if not hasattr(cherrypy.request, 'email_address'):
            return

        if not hasattr(cherrypy.request, 'email_type'):
            return

        cherrypy.request.user = User.get_by_email(
            cherrypy.request.email_address)

        if 'mail' in cherrypy.request.user:
            if cherrypy.request.email_type == 'password':
                cherrypy.engine.publish('email-send-reset',
                                        cherrypy.request.user)
            if cherrypy.request.email_type == 'username':
                cherrypy.engine.publish('email-send-username',
                                        cherrypy.request.user)