Example #1
0
def mainPage(request):
    session = get_current_session()
    access_token_key = session['access_token_key']
    access_token_secret = session['access_token_secret']
    oauth_verifier = request.GET.get('oauth_verifier', '')
    get_absolute_path(request)
    if not access_token_key:
        #params['test'] = reverse('sinaweibo.views.login', args=[], kwargs={})#, current_app=context.current_app)        
        login_url = reverse('sinaweibo.views.login', args=[], kwargs={})
        #return shortcuts.render_to_response('test.html', params)
        return http.HttpResponseRedirect(login_url)
    else:
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.setToken(access_token_key, access_token_secret)
        api = API(auth)
        
        #myself = api.get_user(id=1894001933)
        #screen_name = myself. __getattribute__('screen_name')
        myweibo = []
        myweibo_obj = api.user_timeline(count=20, page=1)
        for weibo in myweibo_obj:
            myweibo.append({'text': weibo.text, 
                            'created_at': weibo.created_at, 
                            'retweeted_status': hasattr(weibo, 'retweeted_status') and weibo.retweeted_status or None,
                            'source': weibo.source})
        wrapper__at(myweibo)
        params = {}
        
        params['user'] = api.verify_credentials()
        params['result'] = myweibo
        template = get_template_uri(appContext, 'weibo.html')
        return shortcuts.render_to_response(template, params)
Example #2
0
def callback():
    '''用户成功登录授权后,会回调此方法,获取access_token,完成授权'''
    verifier = request.args.get('oauth_verifier', None)
    # 设置之前保存在session的request_token
    if 'oauth_request_token' in session:
        request_token = session['oauth_request_token']
        del session['oauth_request_token']
    else:
        return render_template('index.html')

    auth_client.set_request_token(request_token.key, request_token.secret)
    access_token = auth_client.get_access_token(verifier)
    at_key = access_token.key
    at_secret = access_token.secret
    #设定用户令牌密钥
    auth_client.setToken(at_key, at_secret)
    #绑定用户验证信息.
    api = API(auth_client)
    #获取微博信息
    weibo = api.verify_credentials()
    if weibo is False or weibo is None:
        flash(u'杯具啊,你木有开通微博吧(⊙﹏⊙)a', 'error')
        return render_template('index.html')

    #记录用户登录信息,更新用户微博资料
    User.login(weibo=weibo)
    Weibo.set(weibo=weibo, at_key=at_key, at_secret=at_secret)
    #设置session
    session['id'] = weibo.id
    session.permanent = True
    # 跳转回最初登录前的页面
    back_to_url = session.get('login_back_to_url', '/')
    return redirect(back_to_url)
Example #3
0
    def GET(self):
        access_token=session.get('access_token',None)
        if not access_token:
            auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET,web.ctx.get('homedomain')+'/callback')
            auth_url = auth.get_authorization_url()
            session.request_token=auth.request_token
            web.seeother(auth_url)
        else:
            auth =OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
            auth.access_token=access_token
            api=API(auth)
            user=api.verify_credentials()
            user_timeline=user.timeline(count=10)

            print "current user is ",user.screen_name
            hot_list=get_hot_list()
            for user_tweet in user_timeline:
                try:
                    hot_list.append(tuple([user_tweet.user.screen_name,
                                            user_tweet.mid,
                                            user_tweet.text,
                                            user_tweet.source,
                                            user_tweet.created_at,
                                            None,
                                            None]))
                except AttributeError:
                    #no retweet_statues
                    continue
            return render.index(user.screen_name,user.id,hot_list)
Example #4
0
def callback():
    '''用户成功登录授权后,会回调此方法,获取access_token,完成授权'''
    verifier = request.args.get('oauth_verifier', None)
    # 设置之前保存在session的request_token
    if 'oauth_request_token' in session:
        request_token = session['oauth_request_token']
        del session['oauth_request_token']
    else:
        return render_template('index.html')

    auth_client.set_request_token(request_token.key, request_token.secret)
    access_token = auth_client.get_access_token(verifier)
    at_key = access_token.key
    at_secret = access_token.secret
    #设定用户令牌密钥
    auth_client.setToken( at_key, at_secret )
    #绑定用户验证信息.
    api = API(auth_client)
    #获取微博信息
    weibo = api.verify_credentials()
    if weibo is False or weibo is None:
        flash(u'杯具啊,你木有开通微博吧(⊙﹏⊙)a', 'error')
        return render_template('index.html')

    #记录用户登录信息,更新用户微博资料
    User.login(weibo=weibo)
    Weibo.set(weibo=weibo, at_key=at_key, at_secret=at_secret)
    #设置session
    session['id'] = weibo.id
    session.permanent = True
    # 跳转回最初登录前的页面
    back_to_url = session.get('login_back_to_url', '/')
    return redirect(back_to_url)
Example #5
0
 def get_username(self):
     if self.username is None:
         api = API(self)
         user = api.verify_credentials()
         if user:
             self.username = user.screen_name
         else:
             raise WeibopError("Unable to get username, invalid oauth token!")
     return self.username
Example #6
0
 def get_username(self):
     if self.username is None:
         api = API(self)
         user = api.verify_credentials()
         if user:
             self.username = user.screen_name
         else:
             raise WeibopError("Unable to get username, invalid oauth token!")
     return self.username
Example #7
0
    def get(self):
        verifier = self.request.get('oauth_verifier')
        logging.info('verify id = %s' % verifier)
        
        signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
        
        # Get token - key and secret from memcache that we set on SinaOauthPhaseOne
        tokenstr = memcache.get("PK_"+self.request.get('id'))
        memcache.delete("PK_"+self.request.get('id'))
        token = oauth.OAuthToken.from_string(tokenstr)                
               
        consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                                   ACCESS_TOKEN_URL, AUTHORIZATION_URL)
        
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
                            consumer,
                            token=token, verifier=verifier,
                            http_url=client.access_token_url)
        oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
        
        # Finally get access_token after verifier is matched.
        access_token = client.fetch_access_token(oauth_request)
        logging.info('Sina Authorized access_token = %s' % access_token)
        
        # Set cookie into browser in case for further use.
        self.response.headers.add_header('Set-Cookie',
                                         'oauth_key=' + access_token.key + cookie)
        self.response.headers.add_header('Set-Cookie',
                                         'oauth_secret=' + access_token.secret + cookie)
        
        # Call Sina weibopy API auth.OAuthHandler() and set access_token to
        # fetch access_resource aka:user resource.
        auth_access_resource = OAuthHandler(
                                    consumer_key=CONSUMER_KEY,
                                    consumer_secret=CONSUMER_SECRET)
        auth_access_resource.set_access_token(access_token.key,
                                              access_token.secret)
        
        # API() inherits auth_access_resource return.
        api = API(auth_access_resource)
        
        # I call api.verify_credentials instead of use auth.OAuthHandler.get_username
        username = api.verify_credentials()
 
        if username:
            self.username = username.screen_name
            self.response.headers.add_header('Set-Cookie',
                                             'sina_username='******'Sina username: %s' % self.username)
        else:
            logging.info('NO SINA USER')

        
        self.redirect('/')
Example #8
0
    def get(self):
        verifier = self.request.get('oauth_verifier')
        logging.info('verify id = %s' % verifier)

        signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()

        # Get token - key and secret from memcache that we set on SinaOauthPhaseOne
        tokenstr = memcache.get("PK_" + self.request.get('id'))
        memcache.delete("PK_" + self.request.get('id'))
        token = oauth.OAuthToken.from_string(tokenstr)

        consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                                   ACCESS_TOKEN_URL, AUTHORIZATION_URL)

        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            consumer,
            token=token,
            verifier=verifier,
            http_url=client.access_token_url)
        oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)

        # Finally get access_token after verifier is matched.
        access_token = client.fetch_access_token(oauth_request)
        logging.info('Sina Authorized access_token = %s' % access_token)

        # Set cookie into browser in case for further use.
        self.response.headers.add_header(
            'Set-Cookie', 'oauth_key=' + access_token.key + cookie)
        self.response.headers.add_header(
            'Set-Cookie', 'oauth_secret=' + access_token.secret + cookie)

        # Call Sina weibopy API auth.OAuthHandler() and set access_token to
        # fetch access_resource aka:user resource.
        auth_access_resource = OAuthHandler(consumer_key=CONSUMER_KEY,
                                            consumer_secret=CONSUMER_SECRET)
        auth_access_resource.set_access_token(access_token.key,
                                              access_token.secret)

        # API() inherits auth_access_resource return.
        api = API(auth_access_resource)

        # I call api.verify_credentials instead of use auth.OAuthHandler.get_username
        username = api.verify_credentials()

        if username:
            self.username = username.screen_name
            self.response.headers.add_header(
                'Set-Cookie', 'sina_username='******'Sina username: %s' % self.username)
        else:
            logging.info('NO SINA USER')

        self.redirect('/')
Example #9
0
    def GET(self):
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            user = api.verify_credentials()
            fan = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.followers(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))

                else:
                    next_cursor = 0
                    for line in timeline:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))

            friend = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.friends(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))
                else:
                    next_cursor = 0
                    for line in timeline:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))
            #获取我的粉丝中还不是我的关注对象
            fanNotAttention = list(set(fan).difference(set(friend)))
            nu = len(fanNotAttention)
            if nu == 0:
                return render_template('noattentionok.html', nu=nu)
            else:
                return render_template('noattention.html',
                                       nu=nu,
                                       fanNotAttention=fanNotAttention)

        except:
            info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..."
            return render_template('error.html', info=info.decode('utf-8'))
Example #10
0
class SinaClient:
    def __init__(self, key, secret):
        self.auth=OAuthHandler(key,secret)

    def get_auth_url(self):
        return self.auth.get_authorization_url()

    def set_access_token(self,token):
        key,secret=token.split('|')
        self.auth.setToken(key,secret)
        self.api=API(self.auth)

    def get_access_token(self):
        token=self.auth.access_token
        return token.key+'|'+token.secret

    def set_request_token(self,token):
        key,secret=token.split('|')
        self.auth.request_token=oauth.OAuthToken(key,secret)

    def get_request_token(self):
        token=self.auth.request_token
        return token.key+'|'+token.secret

    def set_verifier(self,verifier):
        self.auth.get_access_token(verifier)
        self.api=API(self.auth)

    def send_msg(self,msg,coord=None):
        lat,long=self.get_lat_long(coord)
        msg=msg.encode('utf-8')
        status=self.api.update_status(status=msg,lat=lat,long=long)
        return status

    def send_pic(self,msg,pic,coord=None):
        lat,long=self.get_lat_long(coord)
        msg=msg.encode('utf-8')
        status=self.api.upload(pic,status=msg,lat=lat,long=long)
        
        return status

    def get_timeline(self):
        return self.request(SINA_USER_TIMELINE_URL)

    def get_lat_long(self,coord):
        if not coord:
          return (None,None)

        return map(lambda x:str(x),coord)

    def get_user(self):
        return self.api.verify_credentials()
Example #11
0
def do_auth():
    auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)
    auth_url = auth.get_authorization_url()
    request_token_key = auth.request_token.key
    request_token_secret = auth.request_token.secret
    auth.set_request_token(request_token_key, request_token_secret)
    webbrowser.open(auth_url)
    verifier = input("Verifier: ").strip()
    access_token = auth.get_access_token(verifier)
    ATK = access_token.key
    ATS = access_token.secret
    auth.setAccessToken(ATK, ATS)
    api = API(auth)
    user = api.verify_credentials()
    logging("[AUTH]: We are uing API from account: [uid = %s, name = %s]" % (user.id, user.screen_name))
    return api
Example #12
0
 def GET(self):
     access_token=session.get('access_token',None)
     if not access_token:
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET,web.ctx.get('homedomain')+'/callback')
         #获得新浪微博的认证url地址
         auth_url = auth.get_authorization_url()
         logger.debug("认证地址为:%s"%auth_url)
         #在session中保存request_token,用于在新浪微博认证通过后换取access_token
         session.request_token=auth.request_token
         web.seeother(auth_url)
     else:
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
         auth.access_token=access_token
         api=API(auth)
         user=api.verify_credentials()
         friends=api.friends()
         return render_template('index.html',friends=friends,user=user)
Example #13
0
def do_auth():
    auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)
    auth_url = auth.get_authorization_url()
    request_token_key = auth.request_token.key
    request_token_secret = auth.request_token.secret
    auth.set_request_token(request_token_key, request_token_secret)
    webbrowser.open(auth_url)
    verifier = input("Verifier: ").strip()
    access_token = auth.get_access_token(verifier)
    ATK = access_token.key
    ATS = access_token.secret
    auth.setAccessToken(ATK, ATS)
    api = API(auth)
    user = api.verify_credentials()
    logging("[AUTH]: We are uing API from account: [uid = %s, name = %s]" %
            (user.id, user.screen_name))
    return api
Example #14
0
def oauth_callback(request):
    oauth_verifier = request.REQUEST.get('oauth_verifier', None)
    request_token = request.session.get('oauth_sina_request_token', None)
    auth = OAuthHandler(settings.SINA_CONSUMER_KEY,
                        settings.SINA_CONSUMER_SECRET)
    auth.request_token = request_token
    access_token = auth.get_access_token(oauth_verifier)
    logger.debug("authorized")
    request.session['oauth_sina'] = auth

    api = API(auth)
    data = api.verify_credentials()

    from django.contrib.auth import authenticate, login as django_login

    user = authenticate(sinaweiboid=data.id)
    if user is None:
        #  query = SinaWeibo.objects.filter(weiboid = data.id)
        #  if (len(query) ==  0):

        user = User()
        user.username = "******" + data.name
        user.backend = 'sinaweibo'
        user.save()

        sina_weibo = SinaWeibo()
        sina_weibo.weiboid = data.id
        sina_weibo.name = data.name
        sina_weibo.access_token = auth.access_token.key
        sina_weibo.access_secret = auth.access_token.secret
        sina_weibo.user = user
        sina_weibo.save()

        user = authenticate(sinaweiboid=data.id)
        assert user != None


#  else:
#    sina_weibo = query[0]
#    user = sina_weibo.user
#    user.backend = 'sinaweibo'

    django_login(request, user)

    return HttpResponseRedirect("/")
Example #15
0
 def GET(self):
     access_token = session.get('access_token', None)
     if not access_token:
         """ 
          key.py中放置了开发者的信息 
          """
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET,
                             web.ctx.get('homedomain') + '/callback')
         #获取授权url
         auth_url = auth.get_authorization_url()
         session.request_token = auth.request_token
         web.seeother(auth_url)
     else:
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
         auth.access_token = access_token
         api = API(auth)
         user = api.verify_credentials()
         return render_template('index.html', user=user)
Example #16
0
    def api_verify(*args, **kwargs):
        if g.api:
            return func(*args, **kwargs)
        else:
            if g.weibo:
                if g.weibo.at_key and g.weibo.at_secret:
                    auth_client.setToken(g.weibo.at_key, g.weibo.at_secret)
                    api = API(auth_client)
                    weibo = api.verify_credentials()
                    if weibo:
                        g.api = api
                        return func(*args, **kwargs)

        if 'id' in session:
            del session['id']
            session.permanent = False
        g.user = None
        g.weibo = None
        return render_template('errors/need_api.html')
Example #17
0
 def api_verify(*args, **kwargs):
     if g.api:
         return func(*args, **kwargs)
     else:
         if g.weibo:
             if g.weibo.at_key and g.weibo.at_secret:
                 auth_client.setToken(g.weibo.at_key, g.weibo.at_secret)
                 api =  API(auth_client)
                 weibo = api.verify_credentials()
                 if weibo:
                     g.api = api
                     return func(*args, **kwargs)
  
     if 'id' in session:
         del session['id']
         session.permanent = False
     g.user = None
     g.weibo = None
     return render_template('errors/need_api.html')
Example #18
0
access_token = auth.get_access_token( verifier );
atKey = access_token.key;
atSecret = access_token.secret;
#   终于,我们获取到了用户令牌密钥atKey和atSecret,接下来的所有步骤都需要用这两个参数来验证用户的身份。

# 三、获取用户信息
from weibopy.error import WeibopError;

#设定用户令牌密钥.
auth.setToken( atKey, atSecret );
#绑定用户验证信息.
api = API(auth);

#获取用户信息.
try:
  user = api.verify_credentials();
except WeibopError, e:
  return e.reason;  

#用户ID
userid = user.id;
#用户昵称.
username = user.screen_name.encode('utf-8');
# 四、发布微博消息
from weibopy.error import WeibopError;

#设定用户令牌密钥.
auth.setToken( atKey, atSecret );
#绑定用户验证信息.
api = API(auth);
Example #19
0
class Setag(threading.Thread):
    """ 
这个线程主要是用来搜索用户tag,如果满足tag要求就写入数据库中, 
    """
    def authorization(self):
        """ 
        开发者认证 
        """
        auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
        auth.setToken(key.TOKEN, key.TOKEN_SECRET)
        self.api = API(auth)
        self.cursor = cursor

    def adduser(self, uid):
        """ 
        遍历uid用户的tag,满足条件加入数据库 
        """
        try:
            fan = self.api.followers_ids(uid)
            fanuid = fan.ids
            for id in fanuid:
                tags = self.api.tags(id)
                tt = []
                for t in tags:
                    tagid = t.__getattribute__('id')
                    value = t.__getattribute__(tagid)
                    tt.append(value.encode('utf-8'))
                """ 
                获取用户tag与要求标签的交集 
                """
                common = set(tt).intersection(set(systag))
                if len(common) == 0:
                    continue
                else:
                    for t in common:
                        """ 
                        获取tag对应的tagid 
                        """
                        tagindex = tagdict[t]
                        try:
                            self.cursor.execute(
                                "insert into taginfo(uid,tagid) values(%d,%d)"
                                % (int(id), int(tagindex)))
                            conn.commit()
                        except:
                            continue
        except:
            time.sleep(120)
            pass
        finally:
            time.sleep(60)
            """ 
            将uid用户的第一个粉丝uid传给adduser 
            """
            return self.adduser(fanuid[0])

    def run(self):
        self.authorization()
        me = self.api.verify_credentials()
        """ 
        将我自己的uid给adduser 
        """
        self.adduser(me.id)