示例#1
0
文件: views.py 项目: arunanm/daily3
def authorize():
    error = request.args.get('error')
    code = request.args.get('code')
    state = request.args.get('state')
    #TODO: Handle state here
    if error:
        flash(error, 'error')
        #TODO: Handle error here
        return redirect(url_for('home'))
    if not code:
        #TODO: No code received, something went wrong
        return redirect(url_for('home'))
    else:
        reddit = get_reddit()
        access_info = reddit.get_access_information(code)
        praw_user = reddit.get_me()
        user = User.get_by_id(praw_user.name)
        if not user:
            user = User(
                id=praw_user.name,
                username=praw_user.name,
                created_reddit=datetime.fromtimestamp(praw_user.created)
                )
        user.access_token = access_info['access_token']
        user.refresh_token = access_info['refresh_token']
        user.put()
        session['user'] = user.username
        return redirect(url_for('home'))
示例#2
0
	def current_user(self):
		if not hasattr(self, "_current_user"):
			self._current_user = None
			cookie = facebook.get_user_from_cookie(
				self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
			if cookie:
				# Store a local instance of the user data so we don't need
				# a round-trip to Facebook on every request
				user = User.get_by_key_name(cookie["uid"])
				if not user:
					graph = facebook.GraphAPI(cookie["access_token"])
					profile = graph.get_object("me")
					# Change the user type's key to be a unique key (maybe openid)
					user = User(key_name=str(profile["id"]),
					#user = User(key_name=str(api.users.get_current_user().email()),
								guser=api.users.get_current_user(),
								fbid=str(profile["id"]),
								name=profile["name"],
								profile_url=profile["link"],
								access_token=cookie["access_token"])
					user.put()
				elif user.access_token != cookie["access_token"]:
					user.access_token = cookie["access_token"]
					user.put()
				self._current_user = user
		return self._current_user
示例#3
0
 def current_user(self):
     if self.session.get("user"):
         return self.session.get("user")
     else:
         cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                FACEBOOK_APP_ID,
                                                FACEBOOK_APP_SECRET)
         
         if cookie:
             user = User.get_by_key_name(cookie["uid"])
             if not user:
                 graph = facebook.GraphAPI(cookie["access_token"])
                 profile = graph.get_object("me")
                 user = User(
                     key_name = str(profile["id"]),
                     id = str(profile["id"]),
                     name = profile["name"],
                     profile_url = profile["link"],
                     access_token = cookie["access_token"]
                 )
                 user.put()
             elif user.access_token != cookie["access_token"]:
                 user.access_token = cookie["access_token"]
                 user.put()
         
             self.session["user"] = dict(
                 name = user.name,
                 profile_url = user.profile_url,
                 id = user.id,
                 access_token = user.access_token
             )
             return self.session.get("user")
     return None
示例#4
0
    def current_user(self):
        """
        :returns object: User object or None
        """
        if not hasattr(self, "_current_user"):
            logging.info("not hasattr")
            self._current_user = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies,
                self.app.config.get("FACEBOOK_APP_ID", ""),
                self.app.config.get("FACEBOOK_APP_SECRET", ""))
            logging.info(str(self.request.cookies))
            if cookie:
                logging.info("if cookie")
                # Store a local instance of the user data so we don't need
                # a round-trip to Facebook on every request
                user = User.get_by_key_name(cookie["uid"])
                if not user:
                    logging.info("if not user")
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    user = User(key_name=str(profile["id"]),
                                id=str(profile["id"]),
                                name=profile["name"],
                                profile_url=profile["link"],
                                access_token=cookie["access_token"])
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    logging.info("elif user.access_token")
                    user.access_token = cookie["access_token"]
                    user.put()
                self._current_user = user
#             else:
#                 return None
        return self._current_user
示例#5
0
def handle_redirect():
    payload = {
        'grant_type': 'authorization_code',
        'code': request.args['code'],
        'client_id': client_id,
        'client_secret': client_secret,
        'redirect_uri': 'http://127.0.0.1:5000/auth_redirect',
    }
    response = requests.post(base_accounts_url + '/oauth/token',
                             data=payload).json()
    h = {"Freelancer-OAuth-V1": response["access_token"]}
    url = base_url + "/api/users/0.1/self/"
    details = requests.get(url, headers=h).json()
    session['Authorization'] = response['access_token']
    session['name'] = details['result']['username']
    user = User.query.filter_by(name=session["name"]).first()
    if not user:
        user = User(details['result']['username'], details["result"]['email'],
                    response['access_token'], response['refresh_token'])
        db.session.add(user)
    else:
        user.access_token = response['access_token']
        user.refresh_token = response['refresh_token']
    db.session.commit()
    return render_template("user.html", user=user)
示例#6
0
    def get(self):
        # XXX FIXME ignore state for now since we're going to rely on
        # GitHub to track users
        code = self.request.get('code')
        result = github_api.access_token_from_code(code)
        access_token = result['access_token']

        result = github_api.user(access_token)

        user = User.get_by_id(result['id'])
        if user is None:
            user = User(id=result['id'])

        user.access_token = access_token
        user.github_user = result

        user_key = user.put()
        session_token = db.create_uuid()
        session = Session(id=session_token)
        session.user = user_key
        session.put()

        expires = datetime.datetime.now() + datetime.timedelta(days=20 *
                                                               365.25)

        self.response.set_cookie('session_token',
                                 session_token,
                                 httponly=False,
                                 overwrite=True,
                                 expires=expires)
        self.redirect('/team')
示例#7
0
def authorize():
    error = request.args.get('error')
    code = request.args.get('code')
    state = request.args.get('state')
    #TODO: Handle state here
    if error:
        flash(error, 'error')
        #TODO: Handle error here
        return redirect(url_for('home'))
    if not code:
        #TODO: No code received, something went wrong
        return redirect(url_for('home'))
    else:
        reddit = get_reddit()
        access_info = reddit.get_access_information(code)
        praw_user = reddit.get_me()
        user = User.get_by_id(praw_user.name)
        if not user:
            user = User(id=praw_user.name,
                        username=praw_user.name,
                        created_reddit=datetime.fromtimestamp(
                            praw_user.created))
        user.access_token = access_info['access_token']
        user.refresh_token = access_info['refresh_token']
        user.put()
        session['user'] = user.username
        return redirect(url_for('home'))
示例#8
0
 def current_user(self):
     try:
         """Returns the active user, or None if the user has not logged in."""
         if not hasattr(self, "_current_user"):
             self._current_user = None
             cookie = facebook.get_user_from_cookie(
                 self.request.cookies, self.get_config('facebook', 'app_id'), self.get_config('facebook', 'app_secret'))
             if cookie:
                 # Store a local instance of the user data so we don't need
                 # a round-trip to Facebook on every request
                 user = User.get_by_key_name(cookie["uid"])
                 if not user:
                     graph = facebook.GraphAPI(cookie["access_token"])
                     profile = graph.get_object("me")
                     user = User(key_name=str(profile["id"]),
                                 id=str(profile["id"]),
                                 name=profile["name"],
                                 email=profile["email"],
                                 profile_url=profile["link"],
                                 access_token=cookie["access_token"])
                     user.put()
                     try:
                       name =  user.name.split()
                       fname = name[0]
                       lname = name[len(name)-1]
                       deferred.defer(export_email_mailchimp,{'email':user.email,"fname":fname,"lname":lname})
                     except:
                       pass
                 elif user.access_token != cookie["access_token"]:
                     user.access_token = cookie["access_token"]
                     user.put()
                 self._current_user = user
         return self._current_user
     except:
         self._current_user = None
示例#9
0
 def add_user(self, valid_domains, user_info, token):
     if (valid_domains != '*'
             and user_info.get('hd') not in valid_domains.split(',')):
         raise Exception('Invalid email domain')
     user = User.query.filter_by(sub=user_info['sub']).first()
     if user is None:
         user = User(sub=user_info['sub'],
                     email=user_info['email'],
                     name=user_info['name'],
                     allocated_team_id=self.allocate_team().id,
                     token_type=token['token_type'],
                     access_token=token['access_token'],
                     refresh_token=token.get('refresh_token'),
                     expires_at=(int(datetime.utcnow().timestamp()) +
                                 token['expires_in']))
     else:
         user.token_type = token['token_type']
         user.access_token = token['access_token']
         user.expires_at = (int(datetime.utcnow().timestamp()) +
                            token['expires_in'])
         if token.get('refresh_token'):
             user.refresh_token = token['refresh_token']
     db.session.add(user)
     db.session.commit()
     return user
示例#10
0
def get_current_user():
    """Set g.user to the currently logged in user.

    Called before each request, get_current_user sets the global g.user
    variable to the currently logged in user.  A currently logged in user is
    determined by seeing if it exists in Flask's session dictionary.

    If it is the first time the user is logging into this application it will
    create the user and insert it into the database.  If the user is not logged
    in, None will be set to g.user.
    """

    # Set the user in the session dictionary as a global g.user and bail out
    # of this function early.
    if session.get('user'):
        g.user = session.get('user')
        return

    # Attempt to get the short term access token for the current user.
    result = get_user_from_cookie(cookies=request.cookies,
                                  app_id=FB_APP_ID,
                                  app_secret=FB_APP_SECRET)

    # If there is no result, we assume the user is not logged in.
    if result:
        # Check to see if this user is already in our database.
        user = User.query.filter(User.id == result['uid']).first()

        if not user:
            # Not an existing user so get info
            graph = GraphAPI(result['access_token'])
            extended_token = graph.extend_access_token(
                app_id=FB_APP_ID, app_secret=FB_APP_SECRET)
            access_token = extended_token[
                'access_token'] if extended_token else result['access_token']

            profile = graph.get_object('me')
            if 'link' not in profile:
                profile['link'] = ""

            # Create the user and insert it into the database
            user = User(id=str(profile['id']),
                        name=profile['name'],
                        profile_url=profile['link'],
                        access_token=access_token)
            db.session.add(user)
        elif user.access_token != result['access_token']:
            # If an existing user, update the access token
            user.access_token = result['access_token']

        # Add the user to the current session
        session['user'] = dict(name=user.name,
                               profile_url=user.profile_url,
                               id=user.id,
                               access_token=user.access_token)

    # Commit changes to the database and set the user as a global g.user
    db.session.commit()
    g.user = session.get('user', None)
示例#11
0
def get_current_user():
    """Set g.user to the currently logged in user.

    Called before each request, get_current_user sets the global g.user
    variable to the currently logged in user.  A currently logged in user is
    determined by seeing if it exists in Flask's session dictionary.

    If it is the first time the user is logging into this application it will
    create the user and insert it into the database.  If the user is not logged
    in, None will be set to g.user.
    """
    # A/B test value
    g.ab = _ab()

    # Set the user in the session dictionary as a global g.user and bail out
    # of this function early.
    if session.get('user'):
        user = session.get('user')
        user = User.query.filter(User.id == user['id']).first()
        g.user = user
        return



    # Attempt to get the short term access token for the current user.
    result = get_user_from_cookie(cookies=request.cookies, app_id=app.config['FB_APP_ID'],
                                  app_secret=app.config['FB_SECRET'])

    # If there is no result, we assume the user is not logged in.
    if result:
        # Check to see if this user is already in our database.
        user = User.query.filter(User.id == result['uid']).first()

        if not user:
            # Not an existing user so get info
            graph = GraphAPI(result['access_token'])
            profile = graph.get_object('me')

            # Create the user and insert it into the database
            user = User(id=str(profile['id']), name=profile['name'],
                        profile_url=profile['link'],
                        access_token=result['access_token'])
            db.session.add(user)
        elif user.access_token != result['access_token']:
            # If an existing user, update the access token
            user.access_token = result['access_token']

        # Add the user to the current session
        session['user'] = dict(name=user.name, profile_url=user.profile_url,
                               id=user.id, access_token=user.access_token,
                               admin=user.admin)

        # Commit changes to the database and set the user as a global g.user
        db.session.commit()
        g.user = session.get('user', None)
    else:
        g.user = None
示例#12
0
def save_token(token, user=None):
    if not user:
        user = User()
    user.access_token = token.get("access_token")
    user.refresh_token = token.get("refresh_token")
    try:
        user.expires = datetime.datetime.now() +\
                datetime.timedelta(seconds=token.get("expires_in"))
    except (TypeError, ValueError) as e:
        print "Error converting expries_in value"
    user.save()
    return user
示例#13
0
    def current_user(self):
        if "user" not in self.session:
            cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                   FACEBOOK_APP_ID,
                                                   FACEBOOK_APP_SECRET)
            if cookie:
                # Store a local instance of the user data so we don't need
                # a round-trip to Facebook on every request
                graph = facebook.GraphAPI(cookie["access_token"])
                profile = graph.get_object("me?fields=email,id,name")
                user = User.get_by_id(
                    str(profile["id"]),
                    parent=user_utils.get_parent_key_from_facebookID(
                        str(profile["id"])))
                if not user:
                    user = User(
                        parent=user_utils.get_parent_key_from_facebookID(
                            str(profile["id"])),
                        id=str(profile["id"]))
                    user.name = profile["name"]
                    user.nickname = profile["name"]
                    user.access_token = cookie["access_token"]
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()

                self.session["user"] = dict(
                    id=str(profile["id"]),
                    name=profile["name"],
                    access_token=cookie["access_token"])

                return self.session.get("user")
            else:
                return None
        return self.session.get("user")
示例#14
0
def __create_user__(access_token, refresh_token):
    app.logger.error("access: %s refresh: %s", access_token, refresh_token)
    if access_token and refresh_token:
        r = __spibot__.get_user_info(access_token)
        if r:
            username = r['id']
            name = r['display_name']
            u = User.query.filter_by(spotify_id=username).first()
            if (u is None):
                u = User(username, access_token, refresh_token)
            else:
                u.access_token = access_token
            db.session.add(u)
            db.session.commit()
            return (jsonify("success!"))
    return (jsonify("error adding new user"))
示例#15
0
    def current_user(self):
        if self.session.get("user"):
            # User is logged in
            return self.session.get("user")
        else:
            # Either used just logged in or just saw the first page
            # We'll see here
            cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                   FACEBOOK_APP_ID,
                                                   FACEBOOK_APP_SECRET)
            if cookie:
                # Okay so user logged in.
                # Now, check to see if existing user
                user = User.get_by_key_name(cookie["uid"])

                if not user:
                    # Not an existing user so get user info
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    email_verified = False
                    verification_code = generate_verification_code()
                    user = User(
                        key_name=str(profile["id"]),
                        id=str(profile["id"]),
                        name=profile["name"],
                        profile_url=profile["link"],
                        access_token=cookie["access_token"],
                        email_verified = email_verified,
                        verification_code = verification_code,
                    )
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                # User is now logged in
                self.session["user"] = dict(
                    name=user.name,
                    profile_url=user.profile_url,
                    id=user.id,
                    access_token=user.access_token,
                    email_verified = user.email_verified,
                    verification_code = user.verification_code,
                    #is_part_of_rangoli = self.is_part_of_group(cookie, RANGOLI_GROUP_ID)
                    is_part_of_rangoli = True
                )
                return self.session.get("user")
        return None
示例#16
0
def authorized():
    resp = google.authorized_response()

    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )

    if isinstance(resp, OAuthException):
        return 'Access denied: %s' % resp.message

    session['user_token'] = (resp['access_token'], '')
    me           = google.get('userinfo')
    access_token = resp['access_token']
    name         = me.data['name']
    picture      = me.data['picture']

    # Check if user already exists on database
    user = db_session.query(User).filter_by(access_token=access_token).first()
    if user is None:

    	user = User(access_token, name, picture)

        db_session.add(user)

    # store access token into database
    user.access_token = access_token
    db_session.commit()

    # store user data on session
    session['user_id'] = user.id
    session['user_token'] = user.access_token
    session['user_name'] = user.name
    session['user_picture'] = user.picture

    flash('You\'re logged in!', 'success')
    return redirect(url_for('index'))
示例#17
0
def authenticate():
    # Check for errors in authentication
    error = request.args.get('error')

    if error:
        flash(error)
        return redirect(url_for('login'))

    # Validate state to prevent XSRF
    state = request.args.get('state')

    if not is_valid_state(state):
        abort(403)

    # Get access token with provided single-use code
    code = request.args.get('code')
    access_token = get_token(code)

    # Get username with access token
    username = get_username(access_token)

    # Get User object (if exists)
    user = User.query.filter_by(username = username).first()

    # If not, create user
    if user is None:
        user = User(username = username)
        db.session.add(user)

    # Save new access token
    user.access_token = access_token
    db.session.commit()

    # Login user with User object
    login_user(user)

    return redirect(request.args.get('next') or url_for('index'))
示例#18
0
def authorized(token):
    """ callback for github auth """
    url = "https://api.github.com/user?access_token=" + str(token)
    req = requests.get(url)
    github_username = req.json()['login']

    redirect_to = request.args.get('next') or url_for('index')
    if token is None:
        return redirect(redirect_to)

    user = db_session.query(User)\
        .filter_by(github_username=github_username).first()
    if user is None:
        user = User(github_username=github_username)
        db_session.add(user)

    user.access_token = token
    db_session.commit()

    session['user_id'] = user.id
    session['access_token'] = user.access_token
    session['username'] = user.github_username

    return redirect(url_for('index'))
示例#19
0
def index():
    if not 'facebook' in session:
        access_token = get_token()
        if access_token is not None:
            session['facebook'] = access_token
    else:
        access_token = session['facebook']

    channel_url = url_for('get_channel', _external=True)
    channel_url = channel_url.replace('http:', '').replace('https:', '')

    if access_token:
        me = fb_call('me', args={'access_token': access_token})
        fb_app = fb_call(FB_APP_ID, args={'access_token': access_token})

        url = request.url
	
        # creates user in database
        user = db.session.query(User).get(me['id'])
        if not user:
            newUser = User(me['name'], me['email'], me['id'])
            db.session.add(newUser)
            newUser.access_token = access_token
            db.session.commit()
            user = db.session.query(User).get(me['id'])
	else:
		user.access_token = access_token
		db.session.commit()
		user = db.session.query(User).get(me['id'])
        session['user'] = user

        # get google service
        if 'google_cred' in session and util.ensure_cred(session['google_cred']):
            google_service = util.get_google_serv(session['google_cred'])
        else:
            return redirect(util.get_google_code())
	   
        calendar_list = google_service.calendarList().list().execute()

        # set default calendar if not set
        if not user.default_calendar:
            primary = google_service.calendars().get(calendarId='primary').execute()
            user.default_calendar = primary['id']
            db.session.commit()
            session['user'] = user
        
        # get calendars
        calendar_list = google_service.calendarList().list().execute()

        # get events
        events = fb_call('me/events', args={'access_token': session['facebook']})
        for event in events['data']:
            event['details'] = fb_call(str(event['id']),
                args={'access_token': access_token})
            db_event = db.session.query(Event).get(event['id'])
            event['in_db'] = False
            if db_event:
                event['in_db'] = True

        return render_template(
            'index.html', app_id=FB_APP_ID, token=access_token, app=fb_app,
            me=me, name=FB_APP_NAME, events=events,
            calendar_list=calendar_list, default_calendar=session['user'].default_calendar)
    else:
        return render_template('login.html', app_id=FB_APP_ID, token=access_token, url=request.url, channel_url=channel_url, name=FB_APP_NAME)
示例#20
0
def analyze(username):
    user_q = User.query.filter_by(nickname = username).first()
    with_access_token = False
    if user_q != None:
        #print user_q.access_token
        data = search(username, user_q.access_token)
        #print user_q.access_token
        with_access_token = True
    else:
        new_user = User(nickname = username, scanned = False)
        db.session.add(new_user)
        db.session.commit()
        data = search(username, access_token)
        with_access_token = False
    user_q = User.query.filter_by(nickname = username).first()
    print data
    if data and user_q.scanned == False:
        #print 'OK_1'
        #print type(new_user)
        if with_access_token:
            new_user = User.query.filter_by(nickname = username).first()
            new_user.name = data[0][1]
            new_user.user_id = data[0][0]
            new_user.website = data[0][2]
            new_user.media_counts = data[0][3]
            new_user.likes_counts = data[0][4]
            new_user.follows_counts = data[0][5]
            new_user.followed_by_counts = data[0][6]
            new_user.profile_photo = data[0][7]
            new_user.bio = data[0][8]
            new_user.scanned = True
            db.session.commit()
            #new_user = User(name = data[0][1], user_id = data[0][0], website = data[0][2],
            #            media_counts = data[0][3], likes_counts = data[0][4], follows_counts = data[0][5],
            #            followed_by_counts = data[0][6], profile_photo = data[0][7], bio = data[0][8])
        else:
            new_user = User.query.filter_by(nickname = username).first()
            new_user.name = data[0][1]
            new_user.user_id = data[0][0]
            new_user.website = data[0][2]
            new_user.media_counts = data[0][3]
            new_user.likes_counts = data[0][4]
            new_user.follows_counts = data[0][5]
            new_user.followed_by_counts = data[0][6]
            new_user.profile_photo = data[0][7]
            new_user.bio = data[0][8]
            new_user.access_token = ""
            new_user.scanned = True
            #new_user = User(name = data[0][1], nickname = username, user_id = data[0][0], website = data[0][2],
            #            media_counts = data[0][3], likes_counts = data[0][4], follows_counts = data[0][5],
            #            followed_by_counts = data[0][6], profile_photo = data[0][7], bio = data[0][8], scanned = True)
            db.session.commit()
        #print 'OK'
        #print type(new_user)
        for obj in data[1]:
            image = UserImages(images = unicode(obj[0]), quantity = obj[1], author = new_user)
            db.session.add(image)
        for obj in data[2]:
            video = UserVideos(videos = unicode(obj), author = new_user)
            db.session.add(video)
        for obj in data[3]:
            caption = UserCaptions(captions = unicode(obj[0]), quantity = obj[1], author = new_user)
            db.session.add(caption)
        for obj in data[4]:
            hashtag = UserHashtags(hashtags = unicode(obj[0]), quantity = obj[1], author = new_user)
            db.session.add(hashtag)
        for obj in data[5]:
            location = UserLocations(locations = unicode(obj[0]), quantity = obj[1] , author = new_user)
            db.session.add(location)
        for obj in data[6]:
            comment = UserComments(comments = unicode(obj), author = new_user)
            db.session.add(comment)
        for obj in data[7]:
            user = UserLiked(name = unicode(obj[0]), quantity = obj[1], author = new_user)
            db.session.add(user)
        for obj in data[8]:
            user = LikesOfUsers(name = unicode(obj[0]), quantity = obj[1], author = new_user)
            db.session.add(user)
        for obj in data[9]:
            user = CommentRating(name = unicode(obj[0]), quantity = obj[1], author = new_user)
            db.session.add(user)
        for obj in data[10]:
            user = UserFilters(name = unicode(obj[0]), quantity = obj[1], author = new_user)
            db.session.add(user)
        db.session.commit()
        return render_template('successful_adding.html')
    else:
        return render_template('user_not_exist.html', username = username)
示例#21
0
    def current_user(self):
        if self.session.get("user"):
            # User is logged in
            logging.info("User is logged in.")
            return self.session.get("user")
        else:
            logging.info("Check if user is logged in to Facebook.")
            # Either used just logged in or just saw the first page
            # We'll see here
            try:
              cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                     FACEBOOK_APP_ID,
                                                     FACEBOOK_APP_SECRET)
            except HTTPError as err:
              logging.error(err.code)
              logging.error(err.reason)
              return None
              
            if cookie:
                # Okay so user logged in.
                # Now, check to see if existing user
                user = User.get_by_key_name(cookie["uid"])
                logging.info("Cookie found, user is logged in.")
                if not user:
                    logging.info('New app user')
                    graph = facebook.GraphAPI(version=2.1,access_token=cookie["access_token"])

                    # also get long live access token for approved off-line access
                    offline_token_full = graph.extend_access_token(app_id=FACEBOOK_APP_ID,app_secret=FACEBOOK_APP_SECRET)
                    offline_token = offline_token_full["access_token"]
                    #logging.info('old token expires %s', cookie['expires'])
                    #logging.info('new token expires %s', offline_token_full['expires'])

                    profile = graph.get_object("me")
                    user = User(
                        key_name=str(profile["id"]),
                        id=str(profile["id"]),
                        name=profile["name"],
                        profile_url=profile["link"],
                        access_token=cookie["access_token"],
                        offline_token=offline_token,
                        offline_token_created=datetime.utcnow(),
                    )
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    logging.info('Existing app user with new access token')

                    # Facebook will only extend the expiration time once per day
                    # @see https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal
                    if user.offline_token_created.date() < datetime.utcnow().date(): 
                      graph = facebook.GraphAPI(version=2.1,access_token=cookie["access_token"])
                      user.offline_token = graph.extend_access_token(app_id=FACEBOOK_APP_ID,app_secret=FACEBOOK_APP_SECRET)['access_token']
                      user.offline_token_created = datetime.utcnow()
                      user.offline_token_expires = (datetime.utcnow() + timedelta(0,int(cookie["expires"])))

                    user.access_token = cookie["access_token"]
                    user.put()

                # User is now logged in
                self.session["user"] = dict(
                    name=user.name,
                    profile_url=user.profile_url,
                    id=user.id,
                    access_token=user.offline_token,
                )
                return self.session.get("user")
        logging.info("No user logged in.")
        return None
示例#22
0
    def current_user(self):
        if settings.DEBUG:


            # Since we can't test real FB user on localhost
            # I made a fake account
            user = User.get_by_key_name('100000145269859')
            if not user:
                user = User(
                    key_name='100000145269859',
                    id='100000145269859',
                    username='******',
                    name='Eka Putra',
                    profile_url='https://facebook.com/ekaputra07',
                    is_admin=True,
                    access_token='AAAH4xJelaP7vErxcrgPn7VZCdFfmUReP6ZC29tYHui5OO',
                )
                user.put()

            self.session['user'] = dict(
                username=user.username,
                name=user.name,
                profile_url=user.profile_url,
                id=user.id,
                access_token=user.access_token,
                is_admin=user.is_admin,
            )
            return self.session.get('user');


        else:
            if self.session.get("user"):
                # User is logged in
                return self.session.get("user")
            else:
                # Either used just logged in or just saw the first page
                # We'll see here
                cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                   settings.FACEBOOK_APP_ID,
                                                   settings.FACEBOOK_APP_SECRET
                                                   )
                if cookie:
                    # Okay so user logged in.
                    # Now, check to see if existing user
                    user = User.get_by_key_name(cookie["uid"])
                    if not user:
                        # Not an existing user so get user info
                        graph = facebook.GraphAPI(cookie["access_token"])
                        profile = graph.get_object("me")

                        username = profile.get('username', 'user%s' % str(profile['id'])[-4:])
                        user = User(
                            key_name=str(profile['id']),
                            id=str(profile['id']),
                            username=username,
                            name=profile['name'],
                            profile_url=profile['link'],
                            access_token=cookie['access_token']
                        )
                        user.put()
                    elif user.access_token != cookie['access_token']:
                        user.access_token = cookie['access_token']
                        user.put()
                    # User is now logged in
                    self.session['user'] = dict(
                        username=user.username,
                        name=user.name,
                        profile_url=user.profile_url,
                        id=user.id,
                        access_token=user.access_token,
                        is_admin=user.is_admin,
                    )
                    return self.session.get("user")
            return None
示例#23
0
def callback():
    url = 'https://my.mlh.io/oauth/token'
    body = {
        'client_id': settings.MLH_APPLICATION_ID,
        'client_secret': settings.MLH_SECRET,
        'code': request.args.get('code'),
        'grant_type': 'authorization_code',
        'redirect_uri': helpers.mlh_callback_url()
    }
    resp = requests.post(url, params=body)
    try:
        json = resp.json()
    except Exception as e:
        g.log = g.log.bind(error=e, response=resp)
        g.log.error('Error Decoding JSON')
        flash('MyMLH had an error, please sign up here.', 'error')
        return redirect(url_for('sign-up'))

    if resp.status_code == 401:  # MLH sent expired token
        redirect_url = helpers.mlh_oauth_url()

        g.log = g.log.bind(auth_code=request.args.get('code'),
                           http_status=resp.status_code,
                           resp=resp.text,
                           redirect_url=redirect_url,
                           request_url=resp.url)
        g.log.error('Got expired auth code, redirecting: ')
        flash('MyMLH had an error, please sign up here.', 'error')
        return redirect(url_for('sign-up'))

    if 'access_token' in json:
        access_token = json['access_token']
    else:  # This is VERY bad, we should never hit this error
        g.log = g.log.bind(auth_code=request.args.get('code'),
                           http_status=resp.status_code,
                           resp=resp.text,
                           body=body)
        g.log.error('URGENT: FAILED BOTH MLH AUTH CODE CHECKS')
        flash('MyMLH had an error, please sign up here.', 'error')
        return redirect(url_for('sign-up'))

    user = User.query.filter_by(access_token=access_token).first()
    if user is None:  # create the user
        try:
            user_info = helpers.get_mlh_user_data(access_token)
            user_info['type'] = 'MLH'
            user_info['access_token'] = access_token
            g.log = g.log.bind(email=user_info['data']['email'])
            user = User.query.filter_by(
                email=user_info['data']['email']).first()
            if user is None:
                if settings.REGISTRATION_CLOSED and not settings.PUZZLES_OPEN:
                    flash('Registration has closed', 'error')
                    return redirect(url_for('login'))
                if settings.REGISTRATION_OPENED:
                    g.log.info('Creating a new user from MLH info')
                    user = User(user_info)
                else:
                    flash('Registration is currently closed', 'error')
                    return redirect(url_for('landing'))
            else:
                user.access_token = access_token
                g.log = g.log.bind(email=user_info['data']['email'])
                g.log.info('added mlh access token for user')
            DB.session.add(user)
            DB.session.commit()
            login_user(user, remember=True)
            if user.confirmed:
                return redirect(url_for('dashboard'))
            elif user.type == 'local':
                # user didn't confirm email but signed up locally
                return redirect(url_for('complete-registration'))

            # don't send another email if they come back way later to add an mlh login
            batch.send_confirmation_email(user)
            flash(
                'You have created your {0} account. We sent you a verification email. You need to verify your email before we can accept you to {0}'
                .format(settings.HACKATHON_NAME), 'warning')
            g.log.info('Successfully created user')
            return redirect(url_for('complete-mlh-registration'))
        except IntegrityError:
            # a unique value already exists this should never happen
            DB.session.rollback()
            flash('A fatal error occurred. Please contact us for help',
                  'error')
            return redirect(url_for('landing'))
        except Exception as e:
            g.log.error('{}: {}'.format(type(e), e))
            g.log.error('Unable to create the user')
            flash('A fatal error occurred. Please contact us for help',
                  'error')
            return redirect(url_for('landing'))
    login_user(user, remember=True)
    return redirect(url_for('dashboard'))
    def get(self):
        if self.request.get('code'):
            url = 'https://api.instagram.com/oauth/access_token'
            post = 'client_id=&client_secret=&redirect_uri=http://instadaily.appspot.com/auth/&grant_type=authorization_code&code=%s' % self.request.get(
                'code')
            try:
                result = urlfetch.fetch(url=url, payload=str(post), method=urlfetch.POST)
            except urlfetch.DownloadError:
                logging.error('User could not connect with Instagram auth')
                return self.response.out.write('We could not connect to Instagram. Please try again soon.')

            if result.status_code == 200:
                res = json.loads(result.content)

                md5 = hashlib.md5()
                md5.update('%s%s' % (res['access_token'], SECRET))
                token = md5.hexdigest()

                if User.all().filter('instagram_id =', res['user']['id']).count() == 0:
                    user = User()
                    user.token = token
                    user.access_token = res['access_token']  # instagram's one
                    user.name = res['user']['username']
                    user.instagram_id = res['user']['id']
                    user.full_name = res['user']['full_name']
                    user.pic = res['user']['profile_picture']
                    user.photos = 0
                    user.vote_like = 0
                    user.vote_dislike = 0
                    try:
                        user.last_subject_id = Subject().get_current().key().id()
                    except AttributeError:
                        logging.error('cannot find current subject!!!')
                        user.last_subject_id = 0
                    user.last_subject_points = 0
                    user.put()

                else:
                    user = User.all().filter('instagram_id =', res['user']['id']).get()
                    user.token = token
                    user.access_token = res['access_token']  # instagram's one
                    user.pic = res['user']['profile_picture']
                    user.full_name = res['user']['full_name']
                    user.put()

                # put data to remote server
                url = 'http://www.instadailyapp.com/auth/'

                # fill in with data
                user_dict = user.to_dict()
                user_dict['token'] = user.token
                user_dict['access_token'] = user.access_token
                user_dict['full_name'] = ''
                user_dict['vote_like'] = user.vote_like
                user_dict['vote_dislike'] = user.vote_dislike

                post = 'user=%s' % json.dumps(user_dict)
                try:
                    result = urlfetch.fetch(url=url, payload=str(post), method=urlfetch.POST)
                except urlfetch.DownloadError:
                    logging.error('Remote server failed!')

                if result.status_code != 200:
                    logging.error('Remote server failed with %s!' % result.status_code)

                template = """
				<html><head><style type="text/css">body { color: #ffffff; }</style></head>
				<body>%s</body></html>
				""" % json.dumps({
                    'status': 'ok',
                    'user': user.to_dict(),
                    'token': token
                })

                self.response.out.write(template)
            else:
                logging.warning('failed to receive token. response: %s' % result.content)
                self.response.out.write('failed to receive token: %s' % result.content)
        elif self.request.get('error'):
            # Access Denied
            self.redirect(
                'http://instagram.com/oauth/authorize/?client_id=&redirect_uri=http://instadaily.appspot.com/auth/&response_type=code&scope=comments+likes&display=touch')
        else:
            logging.info('unknown request')
            self.response.out.write('unknown request')