def user_roles_update(user_id): api = system_util.pillar_api() group_subscriber = Group.find_one({'where': "name=='subscriber'"}, api=api) external_subscriptions_server = app.config['EXTERNAL_SUBSCRIPTIONS_MANAGEMENT_SERVER'] # Fetch the user once outside the loop, because we only need to get the # subscription status once. user = User.me(api=api) r = requests.get(external_subscriptions_server, params={'blenderid': user.email}) if r.status_code != 200: log.warning("Error communicating with %s, code=%i, unable to check " "subscription status of user %s", external_subscriptions_server, r.status_code, user_id) return store_user = r.json() max_retry = 5 for retry_count in range(max_retry): # Update the user's role & groups for their subscription status. roles = set(user.roles or []) groups = set(user.groups or []) if store_user['cloud_access'] == 1: roles.add(u'subscriber') groups.add(group_subscriber._id) elif u'admin' not in roles: roles.discard(u'subscriber') groups.discard(group_subscriber._id) # Only send an API request when the user has actually changed if set(user.roles or []) == roles and set(user.groups or []) == groups: break user.roles = list(roles) user.groups = list(groups) try: user.update(api=api) except sdk_exceptions.PreconditionFailed: log.warning('User etag changed while updating roles, retrying.') else: # Successful update, so we can stop the loop. break # Fetch the user for the next iteration. if retry_count < max_retry - 1: user = User.me(api=api) else: log.warning('Tried %i times to update user %s, and failed each time. Giving up.', max_retry, user_id)
def load_user(userid): from application import system_util api = system_util.pillar_api(token=userid) try: user = User.me(api=api) except sdk_exceptions.ForbiddenAccess: return None if not user: return None login_user = UserClass(userid) login_user.email = user.email login_user.objectid = user._id login_user.username = user.username login_user.gravatar = gravatar(user.email) login_user.roles = user.roles login_user.groups = user.groups try: login_user.full_name = user.full_name except KeyError: pass return login_user