def get_admin_communities(context: Context): if not context.user_is_logged_in and context.user_is_admin(): return [] user = UserProfile.objects.get(pk=context.user_id) admin_groups = user.communityadmingroup_set.all() communities = [ag.community for ag in admin_groups] return communities, None
def graph_actions_completed_by_team( self, context: Context, args) -> Tuple[Graph, MassEnergizeAPIError]: try: team_id = args.get('team_id', None) if not team_id: return None, CustomMassenergizeError("Missing team_id field") team: Team = Team.objects.get(id=team_id) if not team: return None, InvalidResourceError() if not context.is_sandbox and not context.user_is_admin(): if not team.is_published: return None, CustomMassenergizeError( "Content Not Available Yet") users = get_team_users(team) completed_action_rels = [] for user in users: completed_action_rels.extend( user.useractionrel_set.filter(status="DONE").all()) categories = TagCollection.objects.get( name="Category").tag_set.order_by("name").all() prefetch_related_objects(completed_action_rels, "action__tags") data = [] for category in categories: data.append({ "id": category.id, "name": category.name, "value": len( list( filter( lambda action_rel: category in action_rel. action.tags.all(), completed_action_rels))) }) res = { "data": data, "title": "Actions Completed By Members Of Team", "team": team.info() } return res, None except Exception as e: capture_message(str(e), level="error") return None, CustomMassenergizeError(e)
def graph_actions_completed(self, context: Context, args) -> (Graph, MassEnergizeAPIError): try: subdomain = args.get('subdomain', None) community_id = args.get('community_id', None) if not community_id and not subdomain: return None, CustomMassenergizeError( "Missing community_id or subdomain field") community: Community = Community.objects.get( Q(pk=community_id) | Q(subdomain=subdomain)) if not community: return None, InvalidResourceError() if context.is_prod and not context.user_is_admin(): if not community.is_published: return None, CustomMassenergizeError( "Content Available Yet") graph = Graph.objects.prefetch_related('data').select_related( 'community').filter( community=community, title="Number of Actions Completed by Category").first() if not graph: graph = Graph.objects.create( community=community, title="Number of Actions Completed") graph.save() category, ok = TagCollection.objects.get_or_create(name="Category") for t in category.tag_set.all(): d = Data.objects.filter(tag=t, community=community).first() if not d: d = Data.objects.create(tag=t, community=community, name=f"{t.name}", value=0) if not d.pk: d.save() if d.name != t.name: d.name = t.name d.save() graph.data.add(d) graph.save() res = graph.full_json() res['community'] = community.info() return res, None except Exception as e: import traceback traceback.print_exc() return None, CustomMassenergizeError(e)
def process_view(self, request, view_func, *view_args, **view_kwargs): try: #extract JWT auth token id_token, err = self._get_auth_token(request) if err: return err # add a context: (this will contain all info about this user's session info) ctx = Context() #set request body ctx.set_request_body(request) if id_token: decoded_token = jwt.decode(id_token, SECRET_KEY, algorithm='HS256') # at this point the user has an active session ctx.set_user_credentials(decoded_token) request.context = ctx #TODO: enforce all requests accessing resources are always logged in first except Exception as e: return CustomMassenergizeError(e)
def members(self, context: Context, args) -> (Team, MassEnergizeAPIError): try: if not context.user_is_admin(): return None, NotAuthorizedError() team_id = args.get('team_id', None) if not team_id: return [], CustomMassenergizeError( 'Please provide a valid team_id') members = TeamMember.objects.filter(is_deleted=False, team__id=team_id) return members, None except Exception: return None, InvalidResourceError()
def delete_user(self, context: Context, user_id) -> Tuple[dict, MassEnergizeAPIError]: try: if not user_id: return None, InvalidResourceError() # check to make sure the one deleting is an admin if not context.user_is_admin(): # if they are not an admin make sure they can only delete themselves if context.user_id != user_id: return None, NotAuthorizedError() users = UserProfile.objects.filter(id=user_id) users.update(is_deleted=True) return users.first(), None except Exception as e: capture_message(str(e), level="error") return None, CustomMassenergizeError(e)
def update_user(self, context: Context, args) -> Tuple[dict, MassEnergizeAPIError]: try: user_id = args.get('id', None) email = args.get('email', None) if not self._has_access(context, user_id, email): return None, CustomMassenergizeError("permission_denied") if context.user_is_logged_in and ((context.user_id == user_id) or (context.user_is_admin())): users = UserProfile.objects.filter(id=user_id) if not users: return None, InvalidResourceError() profile_picture = args.pop("profile_picture", None) users.update(**args) user = users.first() if profile_picture: if profile_picture == "reset": user.profile_picture = None user.save() else: pic = Media() pic.name = f'{user.full_name} profpic' pic.file = profile_picture pic.media_type = 'image' pic.save() user.profile_picture = pic user.save() return user, None else: return None, CustomMassenergizeError('permission_denied') except Exception as e: capture_message(str(e), level="error") return None, CustomMassenergizeError(e)
def process_view(self, request, view_func, *view_args, **view_kwargs): try: # add a context: (this will contain all info about # the request body, this user's session info, etc) ctx = Context() #set request body ctx.set_request_body(request) path = self._get_clean_path(request) #extract JWT auth token token = request.COOKIES.get('token', None) if token: decoded_token, err = self._get_decoded_token(token) if err: err.delete_cookie('token') return err # at this point the user has an active session ctx.set_user_credentials(decoded_token) if ctx.user_is_admin() and ctx.is_admin_site: # Extend work time when working on the Admin portal so work is not lost MAX_AGE = 24 * 60 * 60 # one day response = MassenergizeResponse(None) # BHN: I'm not sure why the cookie needs to be deleted first # but set_cookie doesn't keep it from expiring as I expected response.delete_cookie("token") response.set_cookie("token", value=token, max_age=MAX_AGE, samesite='Strict') request.context = ctx except Exception as e: capture_message(str(e), level="error") return CustomMassenergizeError(e)
def get_team_info(self, context: Context, team_id) -> (dict, MassEnergizeAPIError): try: team = Team.objects.filter(id=team_id).first() if not team: return None, InvalidResourceError() userOnTeam = False if context.user_id: # None for anonymous usage user = UserProfile.objects.get(id=context.user_id) userOnTeam = TeamMember.objects.filter(team=team, user=user).exists() #TODO: untested if not team.is_published and not (context.user_is_admin() or userOnTeam): return None, CustomMassenergizeError( "Cannot access team until it is approved") return team, None except Exception as e: capture_message(str(e), level="error") return None, CustomMassenergizeError(e)
def _has_access(self, context: Context, user_id=None, email=None): """ Checks to make sure if the user has access to the user profile they want to access """ if (not user_id and not email): return False if not context.user_is_logged_in: return False if context.user_is_admin(): # TODO: update this to only super admins. Do specific checks for # community admins to make sure user is in their community first return True if user_id and (context.user_id == user_id): return True if email and (context.user_email == email): return True return False
def update_user(self, context: Context, user_id, args) -> (dict, MassEnergizeAPIError): try: email = args.get('email', None) # user_id = args.get('user_id', None) if not self._has_access(context, user_id, email): return None, CustomMassenergizeError("permission_denied") if context.user_is_logged_in and ((context.user_id == user_id) or (context.user_is_admin())): user = UserProfile.objects.filter(id=user_id) if not user: return None, InvalidResourceError() user.update(**args) return user.first(), None else: return None, CustomMassenergizeError('permission_denied') except Exception as e: capture_message(str(e), level="error") return None, CustomMassenergizeError(e)
def get_community_info(self, context: Context, args) -> (dict, MassEnergizeAPIError): try: subdomain = args.get('subdomain', None) community_id = args.get('id', None) if not community_id and not subdomain: return None, CustomMassenergizeError( "Missing community_id or subdomain field") community: Community = Community.objects.select_related( 'logo', 'goal').filter(Q(pk=community_id) | Q(subdomain=subdomain)).first() if not community: return None, InvalidResourceError() if context.is_prod and not community.is_published and not context.user_is_admin( ): return None, InvalidResourceError() return community, None except Exception as e: return None, CustomMassenergizeError(e)