def box_oauth_finish(auth, **kwargs): """View called when the Oauth flow is completed. Adds a new BoxUserSettings record to the user and saves the user's access token and account info. """ user = auth.user node = Node.load(session.data.pop('box_auth_nid', None)) # Handle request cancellations from Box's API if request.args.get('error'): flash('Box authorization request cancelled.') if node: return redirect(node.web_url_for('node_setting')) return redirect(web_url_for('user_addons')) result = finish_auth() # If result is a redirect response, follow the redirect if isinstance(result, BaseResponse): return result client = BoxClient(CredentialsV2( result['access_token'], result['refresh_token'], settings.BOX_KEY, settings.BOX_SECRET, )) about = client.get_user_info() oauth_settings = BoxOAuthSettings.load(about['id']) if not oauth_settings: oauth_settings = BoxOAuthSettings(user_id=about['id'], username=about['name']) oauth_settings.save() oauth_settings.refresh_token = result['refresh_token'] oauth_settings.access_token = result['access_token'] oauth_settings.expires_at = datetime.utcfromtimestamp(time.time() + 3600) # Make sure user has box enabled user.add_addon('box') user.save() user_settings = user.get_addon('box') user_settings.oauth_settings = oauth_settings user_settings.save() flash('Successfully authorized Box', 'success') if node: # Automatically use newly-created auth if node.has_addon('box'): node_addon = node.get_addon('box') node_addon.set_user_auth(user_settings) node_addon.save() return redirect(node.web_url_for('node_setting')) return redirect(web_url_for('user_addons'))