def view(self): """Handle creating and/or logging in the user and updating their :py:class:`~.Pilot`\s and :py:class:`~.Group`\s. """ resp = self.oauth.authorized_response() # Check that the response was successful # Yeah, an exception as a return value. I don't know either. if isinstance(resp, OAuthException): flash(u"Login failed: {} ({})".format(resp.type, resp.message), u'error') return redirect(url_for('login.login')) # Handle other kinds of errors elif resp is None: reason = ensure_unicode(request.args.get('error', u'Unknown error')) if reason == u'access_denied': reason = u'Access denied' flash(u"Login failed: {}".format(reason), u'error') return redirect(url_for('login.login')) # Check CSRF token csrf_token = request.args['state'] if not csrf.validate_csrf(csrf_token, time_limit=True): flash(u"CSRF validation failed. Please try logging in again.", u'error') return redirect(url_for('login.login')) token = {'access_token': resp['access_token']} # Get the User object for this user, creating one if needed user = self.get_user(token) if user is not None: # Apply site-wide admin flag user.admin = self.is_admin(user) # Login the user, so current_user will work self.login_user(user) else: flash(u"Login failed.", u'error') return redirect(url_for('login.login')) # Add new Pilots current_pilots = self.get_pilots(token) for pilot in current_pilots: pilot.user = user # Remove old pilots user_pilots = set(user.pilots) for pilot in user_pilots: if pilot not in current_pilots: pilot.user = None db.session.commit() # Add new groups current_groups = self.get_groups(token) for group in current_groups: user.groups.add(group) # Remove old groups user_groups = set(user.groups) for group in user_groups: if group not in current_groups and group in user.groups: user.groups.remove(group) # Save all changes db.session.commit() return redirect(url_for('index'))
def validate_csrf_data(self, data): if not validate_csrf(data, self.SECRET_KEY, self.TIME_LIMIT): return False cache_value = cache.get(data) cache.delete(data) if cache_value is not None: if cache_value == 0: return True return cache_value == g.user.id return False
def validate_csrf_data(self, data): if not validate_csrf(data, self.SECRET_KEY, self.TIME_LIMIT): return False key = "csrf_%s" % data cache_value = cache.get(key) cache.delete(key) if cache_value is not None: if cache_value == 0: return True return cache_value == g.user.id return False
def validate_csrf_data(self, data): if current_app.debug: return True if not validate_csrf(data, self.SECRET_KEY, self.TIME_LIMIT): return False cache_value = cache.get(data) cache.delete(data) if cache_value is not None: if cache_value == 0: return True return cache_value == g.user.id return False
def process_authenticate_callback(callback_uri): code = request.args.get('code') state = request.args.get('state') error = request.args.get('error') error_desc = request.args.get('error_description', '') if error: return {'error': 'Facebook auth canceled or failed with error: {}, ' 'description: {}'.format(error, error_desc)} if not validate_csrf(state): return {'error': 'csrf token mismatch in Facebook callback.'} r = requests.get('https://graph.facebook.com/oauth/access_token', params={ 'client_id': current_app.config['FACEBOOK_CLIENT_ID'], 'client_secret': current_app.config['FACEBOOK_CLIENT_SECRET'], 'redirect_uri': callback_uri, 'code': code, 'scope': PERMISSION_SCOPES, }) if r.status_code // 100 != 2: error_obj = r.json() error = error_obj.get('error') error_desc = error_obj.get('error_description') return {'error': 'Error ({}) requesting access token: {}, ' 'description: {}' .format(r.status_code, error, error_desc)} payload = parse_qs(r.text) current_app.logger.debug('auth responses from Facebook %s', payload) access_token = payload['access_token'][0] r = requests.get('https://graph.facebook.com/v2.5/me', params={ 'access_token': access_token, 'fields': 'id,name,picture', }) if r.status_code // 100 != 2: error_obj = r.json() error = error_obj.get('error') error_desc = error_obj.get('error_description') return {'error': 'Error ({}) requesting authed user info: {}, ' 'description: {}' .format(r.status_code, error, error_desc)} user_info = r.json() current_app.logger.debug('authed user info from Facebook %s', user_info) return { 'token': access_token, 'user_id': user_info.get('id'), 'username': user_info.get('name'), 'user_info': user_info, }
def __init__(self): self.request_args = RequestArgs(formdata=request.args) self.request_data = RequestArgs(formdata=MultiDict(request.get_json())) self.response_data = dict() if not self.request_args.validate(): abort(400) if request.method in ['DELETE']: if not validate_csrf(self.request_data.csrfToken.data): abort(400) self.response_data.update(csrfToken=generate_csrf())
def process_authenticate_callback(redirect_uri): code = request.args.get('code') error = request.args.get('error') if error: return {'error': 'Blogger authorization canceled or ' 'failed with error: {}' .format(error)} if not validate_csrf(request.args.get('state')): return {'error': 'csrf token mismatch in blogger callback.'} r = requests.post(API_TOKEN_URL, data={ 'code': code, 'client_id': current_app.config['GOOGLE_CLIENT_ID'], 'client_secret': current_app.config['GOOGLE_CLIENT_SECRET'], 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code', }) if util.check_request_failed(r): return {'error': 'failed to validate access token'} current_app.logger.info('Got Blogger access token response: %s', r.text) payload = r.json() access_token = payload.get('access_token') expires_in = payload.get('expires_in') refresh_token = payload.get('refresh_token') if expires_in: expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(expires_in)) else: expiry = None current_app.logger.info( 'Got Blogger access token: %s. expiry: %s. refresh token: %s', access_token, expiry, refresh_token) r = requests.get(API_SELF_URL, headers={ 'Authorization': 'Bearer ' + access_token, }) if util.check_request_failed(r): return {'error': 'failed to fetch {}'.format(API_SELF_URL)} payload = r.json() username = user_id = payload.get('id') account = Account.lookup_by_user_id(SERVICE_NAME, user_id) if account: # update the saved tokens account.token = access_token account.expiry = expiry if refresh_token: account.refresh_token = refresh_token db.session.commit() return { 'user_id': user_id, 'username': username, 'user_info': payload, 'token': access_token, 'refresh': refresh_token, 'expiry': expiry, }
def __init__(self): BaseView.__init__(self) if not validate_csrf(self.request_args.csrfToken.data): abort(400)
def __init__(self): EditPost.__init__(self) if not validate_csrf(self.request_args.csrfToken.data): abort(400)
def process_authenticate_callback(callback_uri): # ignore the callback uri because wp only lets us define one client_id = current_app.config['WORDPRESS_CLIENT_ID'] client_secret = current_app.config['WORDPRESS_CLIENT_SECRET'] redirect_uri = url_for('wordpress.callback', _external=True), code = request.args.get('code') error = request.args.get('error') error_desc = request.args.get('error_description') csrf, purpose = request.args.get('state', '').split('|', 1) if error: return {'error': 'Wordpress authorization canceled or failed with ' 'error: {}, and description: {}' .format(error, error_desc)} if not validate_csrf(csrf): return {'error': 'csrf token mismatch in wordpress callback.'} r = requests.post(API_TOKEN_URL, data={ 'client_id': client_id, 'redirect_uri': redirect_uri, 'client_secret': client_secret, 'code': code, 'grant_type': 'authorization_code', }) if r.status_code // 100 != 2: error_obj = r.json() return { 'error': 'Error ({}) requesting access token: {}, description: {}' .format(r.status_code, error_obj.get('error'), error_obj.get('error_description'))} payload = r.json() current_app.logger.info('WordPress token endpoint repsonse: %r', payload) access_token = payload.get('access_token') blog_url = payload.get('blog_url') blog_id = str(payload.get('blog_id')) r = requests.get(API_ME_URL, headers={ 'Authorization': 'Bearer ' + access_token}) current_app.logger.info('User info response %s', r) if r.status_code // 100 != 2: error_obj = r.json() return {'error': 'Error fetching user info: {}, description: {}' .format(error_obj.get('error'), error_obj.get('error_description'))} user_info = r.json() user_id = str(user_info.get('ID')) username = user_info.get('username') return { 'token': access_token, 'blog_id': blog_id, 'blog_url': blog_url, 'user_id': user_id, 'username': username, 'user_info': user_info, }