def create_project(current_user: User): # fix to retrieve collaborators collabs = request.form.getlist('collaborators[]') data = request.form.to_dict( ) # form data is used instead request.json so files can be uploaded if not data: # no data given return jsonify({'message': 'Missing data to create project'}), 400 data['collaborator_ids'] = collabs # check if file is uploaded if 'cover' in request.files and request.files['cover'] != '': file = request.files['cover'] if allowed_file(file.filename): data['filename'] = save_file(file) if current_user is not None: data['owner_id'] = str(current_user.id) # load and validate result = project_schema.load(data) if len(result.errors) > 0: return jsonify({'errors': result.errors}), 422 new_project = Project(**result.data) new_project.save() return jsonify({ 'message': "Project created!", 'project': project_schema.dump(new_project).data })
def get_or_create(session, hexsha, project_id): try: ci_commit = (session.query(CiCommit).filter( CiCommit.project_id == project_id, CiCommit.hexsha.startswith(hexsha), ).one()) except MultipleResultsFound: print( f'!!!!!!!!!!!!! Multiple results for commit {hexsha} @{project_id}' ) ci_commit = (session.query(CiCommit).filter( CiCommit.project_id == project_id, CiCommit.hexsha.startswith(hexsha), ).first()) except NoResultFound: try: from backend.models import Project project = Project.get_or_create(session=session, id=project_id) try: commit = project.repo.commit(hexsha) except Exception as e: error = f'[ERROR] Could not create a commit for {hexsha}. {e}' print(error) raise (ValueError, error) ci_commit = CiCommit(commit, project=project) session.add(ci_commit) session.commit() except ValueError: error = f'[ERROR] ValueError: could not create a commit for {hexsha}' print(error) raise (ValueError, error) if not ci_commit.data: ci_commit.data = {} return ci_commit
def create_project(): user_id = auth.check_token(request.headers.get('session')) if not user_id: return "Unauthorized request: Bad session token", 401 user = User.find_id(user_id) if not user: return "User not found", 404 project = Project() event_id = request.json.get('event') if not event_id: return "Event is required", 400 event = Event.find_event(event_id) if not event: return "Event not found", 404 if not (event in user.events or event.id in user.events): return "User not attending event", 400 teammate_email = request.json.get('teammate') # A team is required if not teammate_email: return "Teammate email is required", 400 teammate = User.objects(email=teammate_email).first() if not teammate: return "Teammate not found", 404 if not (event in teammate.events or event.id in teammate.events): return "Teammate not registered for event", 400 project.name = request.json.get('name') project.description = request.json.get('description') project.image = request.json.get('image') project.event = event project.team = [] project.team.append(user) project.team.append(teammate) project.save() if not project.id: return 'Error creating project', 500 return project.select_related(max_depth=1).to_json()
def get_all(): projects = [] query = {} for key, obj in request.args.iteritems(): query[key] = ObjectId(obj) for project in Project.objects(**query).select_related(max_depth=1): projects.append(project.to_dict()) return json.dumps(projects), 200, jsonType
def register_project(request, project_id=1): args = {} args.update(csrf(request)) if request.POST: project_name = request.POST.get('project_name') description = request.POST.get('description') skills = request.POST.get('skills') num_members = request.POST.get('num_members') user = User.objects.filter(id=request.user.id)[0] proj = Project(project_name = project_name, description = description, skills = skills, publication_date = timezone.now(), max_people = int(num_members)) proj.creator = user proj.save() return render_to_response('index.html', args, context_instance=RequestContext(request))
def get_all_projects(): # TODO: find out how to filter and sort with mongoengine q = Project.objects() if 'country_id' in request.args: q.filter(country__country_code=request.args['country_id']) if 'sort' in request.args: q.order_by(request.args['sort']) # parse them through a schema which converts is to a dict result = project_schema.dump(q.all(), many=True) return jsonify({'projects': result.data }) # convert dict to json and return that to client
def search(): user_query = User.objects.all() project_query = Project.objects.all() if 'q' in request.args: q = request.args['q'] user_query = User.objects(username__icontains=q).all() project_query = Project.objects(title__icontains=q).all() return jsonify({ 'projects': project_schema.dump(project_query.all(), many=True).data, 'users': user_schema.dump(user_query, many=True).data })
def delete_project(current_user: User, project_id): project = Project.objects(pk=project_id) # check if user is an admin if not current_user.admin: # if not filter by the projects only from this user project = project.filter(owner=current_user.id) project = project.first() if project is None: return jsonify({'message': 'No project found!'}), 404 project.delete() return jsonify({'message': 'Project deleted!'})
def remove_project(project_id): session_id = auth.check_token(request.headers.get('session')) if not session_id: return "Unauthorized request: Bad session token", 401 user_sess = User.find_id(session_id) if not user_sess: return "Session token not found", 404 project = Project.find_id(project_id) if not project: return "Project not found", 404 if not (user_sess in project.team or user_sess.type == "organizer"): return "Unauthorized request: You don't have permission for this action", 401 project.delete() return 'Project deleted'
def get_event_projects(event_id): event = Event.find_event(event_id) if not event: return "Event not found", 404 projects = [] query = {} for key, obj in request.args.iteritems(): query[key] = ObjectId(obj) query['name__exists'] = True query['event'] = event.id for project in Project.objects(**query).only( 'name', 'image', 'description', 'team', 'prize').select_related(max_depth=1): projects.append(project.to_dict()) return json.dumps(projects), 200, jsonType
def remove_teammate(project_id): project = Project.find_id(project_id) if not project: return "Project not found", 404 teammate_email = request.json.get('teammate') # A team is required if not teammate_email: return "Teammate email is required", 400 teammate = User.objects(email=teammate_email).first() if not teammate: teammate = user.find_id(teammate_email) if not teammate or not teammate in project.team: return "Teammate not found", 404 project.team.remove(teammate) project.save() return project.to_json()
def create_project(): identity = get_jwt_identity() request_user = User.query.filter_by(username=identity["username"]).first() is_admin = True if request_user.role.role == "admin" else False if is_admin == False: return jsonify(message="Unauthorized access!"), 401 if not request.is_json: return jsonify(message="Missing JSON in request"), 400 name = request.json.get("name", None) if not name: return ( jsonify(message="Please provide a project name!", type="PROJECT_NAME_MISSING"), 400, ) api_key = generate_api_key() try: project = Project(name=name, api_key=api_key, creator_user_id=request_user.id) db.session.add(project) db.session.commit() db.session.refresh(project) except Exception as e: if type(e) == sa.exc.IntegrityError: app.logger.info(f"Project {name} already exists!") return ( jsonify(message="Project already exists!", type="DUPLICATE_PROJECT"), 409, ) app.logger.error("Error creating project") app.logger.error(e) return jsonify(message="Error creating project!"), 500 return jsonify(project_id=project.id, message="Project has been created!"), 201
def update_project(project_id): session_id = auth.check_token(request.headers.get('session')) if not session_id: return "Unauthorized request: Bad session token", 401 user_sess = User.find_id(session_id) if not user_sess: return "Session token not found", 404 project = Project.find_id(project_id) if not project: return "Project not found", 404 for key, value in request.get_json().items(): if not key.startswith('_'): # Some security setattr(project, key, value) project.save() return project.to_json()
def update_project(current_user: User, project_id): q = Project.objects(pk=project_id) # check if user is an admin if not current_user.admin: # if not filter by the projects only from this user q = q.filter(owner=current_user.id) project = q.first() if project is None: return jsonify({'message': 'No project found!'}), 404 data = request.form.to_dict( ) # form data is used instead request.json so files can be uploaded if not data: # no data given return jsonify({'message': 'Missing data to update project'}), 400 if 'cover' in request.files and request.files['cover'] != '': # TODO: cleanup old file first # project.delete_cover() # a file is uploaded file = request.files['cover'] if allowed_file(file.filename): data['filename'] = save_file(file) # load and validate result = project_schema.load(data, partial=True) if len(result.errors) > 0: return jsonify({'errors': result.errors}), 422 for attr, value in result.data.items(): setattr(project, attr, value) project.save() return jsonify({ 'message': "Project updated!", 'project': project_schema.dump(project).data })
def add_teammate(project_id): project = Project.find_id(project_id) if not project: return "Project not found", 404 teammate_email = request.json.get('teammate') # A team is required if not teammate_email: return "Teammate email is required", 400 teammate = User.objects(email=teammate_email).first() if not teammate: return "Teammate not found", 404 if not project.event in teammate.events: return "Teammate not registered for event", 400 if len(project.team) >= 5: return "Your team is full. Max team size is 5 people.", 400 project.team.append(teammate) project.save() return project.select_related(max_depth=1).to_json()
def populate(): print('populating countries') for country in countries: Country(**country).save() # populate users print('populating users') for user in users: User(**user).save() # populate projects print('populating projects') for project in projects: owner = User.objects(public_id=project['owner']).first() country = Country.objects(country_code=project['country']).first() collaborators = [] for collab in project['collaborators']: collaborators.append(User.objects(public_id=collab).first()) del project['owner'] del project['country'] del project['collaborators'] p = Project(**project) p.owner = owner p.collaborators += collaborators p.country = country p.save() print('populating donations') for donation in donations: project = Project.objects(title=donation['project']).first() donator = User.objects(public_id=donation['donator']).first() del donation['project'] del donation['donator'] d = Donation(**donation) d.project = project d.donator = donator d.save()
def get_or_create(session, hexsha, project_id, data=None): try: ci_commit = (session.query(CiCommit).filter( CiCommit.project_id == project_id, CiCommit.hexsha.startswith(hexsha), ).one()) except NoResultFound: # FIXME: if not cimplete hash. fallback git... ? or raise error? (then docs: ask full 32 hash..) or symetrics if hexsha.strtswith(query) try: from backend.models import Project project = Project.get_or_create(session=session, id=project_id) if data and data.get('qaboard_config'): is_initialization = not project.data or 'qatools_config' not in data reference_branch = data["qaboard_config"]['project'].get( 'reference_branch', 'master') is_reference = data.get( "commit_branch") == reference_branch if is_initialization or is_reference: # FIXME: We put in Project.data.git the content of # https://docs.gitlab.com/ee/user/project/integrations/webhooks.html#push-events # FIXME: We should really have Project.data.gitlab/github/... if "git" not in project.data: project.data["git"] = {} if "path_with_namespace" not in project.data[ "git"] and "name" in data["qaboard_config"].get( "project", {} ): # FIXME: it really should be Project.root # FIXME: Doesn't support updates for now... again should have .id: int, name: str, root: str... project.data["git"]["path_with_namespace"] = data[ "qaboard_config"]["project"]["name"] project.data.update( {'qatools_config': data['qaboard_config']}) if "qaboard_metrics" in data: project.data.update( {'qatools_metrics': data["qaboard_metrics"]}) flag_modified(project, "data") else: # For backward-compatibility we fallback to reading the data from the commit itself # But in regular use QA-Board doesn't require read rights on repositories try: git_commit = project.repo.commit(hexsha) except Exception as e: error = f'[ERROR] Could not find information on commit {hexsha}. {e}' print(error) raise ValueError(error) ci_commit = CiCommit( hexsha, project=project, commit_type='git', # we don't use anything else parents=data["commit_parents"] if (data and "commit_parents" in data) else [c.hexsha for c in git_commit.parents], message=data["commit_message"] if (data and "commit_message" in data) else git_commit.message, committer_name=data["commit_committer_name"] if (data and "commit_committer_name" in data) else git_commit.committer.name, authored_datetime=data["commit_authored_datetime"] if (data and "commit_authored_datetime" in data) else git_commit.authored_datetime, # commits belong to many branches, so this is a guess branch=data["commit_branch"] if (data and "commit_branch" in data) else find_branch( hexsha, project.repo), ) if data and data.get('qaboard_config'): ci_commit.data.update( {'qatools_config': data['qaboard_config']}) if "qaboard_metrics" in data: ci_commit.data.update( {'qatools_metrics': data['qaboard_metrics']}) flag_modified(ci_commit, "data") session.add(ci_commit) session.commit() except ValueError: error = f'[ERROR] ValueError: could not create a commit for {hexsha}' print(error) raise ValueError(error) if not ci_commit.data: ci_commit.data = {} return ci_commit
def get_user_projects(user_id): user = user_schema.dump(find_user_or_404(user_id)).data projects = Project.objects(owner=user['id']) result = project_schema.dump(projects.all(), many=True) return jsonify({'projects': result.data})
def find_project(project_id): project = Project.find_id(project_id) if not project: return "Project not found", 404 return project.to_json()