Esempio n. 1
0
def get_mentor_by_uid():
    uid = g.uid
    if request.method == 'GET':
        try:
            user = Users.select(Users.mentor_id).where(Users.uid == uid).get()
            return {'mentors': Mentor.select().where(Mentor.id == user.mentor_id).dicts().get()}
        except DoesNotExist:
            return {'mentors': []}
    elif request.method == 'PUT':
        mentor_data = request.json
        try:
            user = Users.select(Users.mentor_id).where(Users.uid == uid).get()
            Mentor.select().where(Mentor.id == user.mentor_id).dicts().get()
            exists = True
        except DoesNotExist:
            exists = False

        try:
            if exists:
                updated = Mentor.update(mentor_data).where(Mentor.id == user.mentor_id).execute()
                updated_user = Users.update(mentor_id=updated).where(Users.uid == uid).execute()
            else:
                updated = Mentor.insert(mentor_data).execute()
                updated_user = Users.insert(uid=uid, mentor_id=updated, is_manager=False, is_admin=False).execute()
        except Exception as e:
            return f'Failed with error: {e}', 409
        return 'Success' if updated else 'Non updated'
Esempio n. 2
0
    def test_mentor_to_group(self):
        m = Mentor(name='Snoke')

        g1 = Group(name='Solo')
        g2 = Group(name='Generals')

        s1 = Student(name='Ray')
        s2 = Student(name='Kylo')
        s3 = Student(name='Hux')


        db.session.add(m)
        db.session.add(g1)
        db.session.add(g2)
        db.session.add(s1)
        db.session.add(s2)
        db.session.add(s3)
        db.session.commit()

        g1.add_student(s1)
        g1.add_student(s2)
        g2.add_student(s3)

        m.add_group(g1)
        m.add_group(g2)
        
        assert g1.mentor.name == 'Snoke'
        assert m.has_group(g2)
Esempio n. 3
0
def mentors():
    if request.method == 'GET':
        return {'mentors': [mentor_dict for mentor_dict in Mentor.select().dicts()]}
    mentor_data = request.form
    if request.method == 'POST':
        try:
            Mentor.insert(mentor_data).execute()
            return 'Success'
        except IntegrityError:
            return 'Mentor exists (email)', 409
Esempio n. 4
0
    def get_user_info(username):

        # check permissions:
        if not has_scope("get:userinfo"):
            abort(403)

        # First, check to see if user is a Coder
        # If so, return relevant information for profile on front end
        coder = Coder.get_by_name(username)
        if coder:
            if coder.mentor:
                mentor = coder.mentor.username
            else:
                mentor = None

            if coder.snippets:
                snippets = [snippet.to_dict() for snippet in coder.snippets]
            else:
                snippets = []

            return jsonify({
                "success": True,
                "user_id": coder.id,
                "usertype": "Coder",
                "mentor": mentor,
                "snippets": snippets
            })

        # If not a coder, then check to see if user is a Mentor
        # If so, return relevant information for profile on front end
        mentor = Mentor.get_by_name(username)
        if mentor:
            coders = []
            if mentor.coders:
                coder_objs = mentor.coders
                for coder in coder_objs:
                    coders.append({
                        "username":
                        coder.username,
                        "id":
                        coder.id,
                        "snippets": [
                            snippet.to_dict() for snippet in coder.snippets
                            if snippet.needs_review
                        ]
                    })

            else:
                coders = []

            return jsonify({
                "success": True,
                "user_id": mentor.id,
                "usertype": "Mentor",
                "coders": coders
            })

        # If neither a coder nor a mentor is found, return 404 error
        abort(404)
Esempio n. 5
0
def updateUsers(env):
    db = configure(env)

    from models import base
    from models import User, Mentor, Appointment, Project

    Session = sessionmaker(db)
    session = Session()

    #   Updating data relevant for Sensei application proper functionality like:
    #   1.  User projects completed / resubmmitted
    #   2.  User inactivity
    try:
        users = session.query(User)
        print("starting...")
        for user in users:
            if (datetime.datetime.utcnow() -
                    user.last_seen) > automaticDeactivationTime:
                user.active = False
            if user.active == True:
                id42user = getattr(user, 'id_user42')
                userProjects = Api42.userProjects(id42user)
                if not userProjects:
                    continue
                for p in userProjects:
                    project = session.query(Project).filter(
                        Project.id_project42 == p['id_project42']).first()
                    if project:
                        mentor = session.query(Mentor).filter(
                            Mentor.id_user42 == id42user,
                            Mentor.id_project42 == p['id_project42']).first()
                        if not mentor:
                            mentor = Mentor(id_project42=p['id_project42'],
                                            id_user42=id42user,
                                            finalmark=p['finalmark'])
                            session.add(mentor)
                        print(type(projectMinScore))
                        if mentor.finalmark >= int(projectMinScore):
                            mentor.abletomentor = True
        session.commit()
    except Exception as inst:
        print(inst.args)
        session.rollback()
    finally:
        session.close()
Esempio n. 6
0
def apply_for_mentorship():
    if request.method == "POST":
        user_info = github.get("/user", access_token=g.user.github_access_token)
        print("Userinfo", user_info["login"])
        m = Mentor.get_or_none(username=user_info["login"])
        if m:
            flash(f"You have already applied for mentorship."
                  f" Your Status is {m.status}"
                  f"{f' and Reason is {m.status_reason}.' if m.status == 'rejected' else '.'}")
        else:
            print("M is ", m)
            m = Mentor(username=user_info["login"], status="pending",
                       profile_link=user_info["html_url"], status_reason="")
            m.save()
            flash("Submitted Successfully. It takes approximately 1 week to process"
                  " application. If you want to check your application status later"
                  " then click the same apply_mentor button")
    return render_template("apply_mentor.html", nav=nav)
def load_mentors(raw_mentors_json):
    loaded_mentors: [Mentor] = []
    loaded_team_mentors: [TeamMentors] = []
    for mentor in raw_mentors_json:
        mntr = Mentor(name=mentor["name"])
        loaded_mentors.append(mntr)
        for mentored_team in mentor['teams']:
            tm_name = mentored_team['name']
            loaded_team_mentors.append(
                TeamMentors(team_name=tm_name, mentor_name=mntr.name))

    return loaded_mentors, loaded_team_mentors
Esempio n. 8
0
    def signup_user():

        # get body of request; if nothing included, abort with 400
        body = request.get_json()
        if not body:
            abort(400)

        # set attributes for new User based on body input
        username = body.get('username', None)
        usertype = body.get('usertype', None)
        email = body.get('email', None)
        password = body.get('password', None)

        # proceed only if both required fields are provided
        if username and usertype:

            # First, check to see if username is already being used in local bd, and abort with 409 (conflict) if so
            if Mentor.exists(username) or Coder.exists(username):
                abort(409)

        # Then, try to add new user to auth0 database:
            url = f'https://{AUTH0_DOMAIN}/dbconnections/signup'

            post_object = {
                "client_id": AUTH0_CLIENT_ID,
                "email": email,
                "password": password,
                "connection": AUTH0_CONNECTION,
                "username": username,
                "user_metadata": {
                    "role": usertype.title()
                }
            }

            auth0_response = requests.post(url, json=post_object)

            # If there was a problem with auth0 process, abort:
            if hasattr(auth0_response, 'error'):
                abort(401)

            # Finally, if auth0 signup orcess successful,
            # insert user into local database:

            # instantiate a new object for the new user
            if usertype == 'mentor':
                user = Mentor(username=username)
            if usertype == 'coder':
                user = Coder(username=username)

            # try to add the new user to the applicable table in the database
            try:
                user.insert()
            except:
                abort(500)

        # if required fields weren't provided in the request, abort with 400
        else:
            abort(400)

        return jsonify({"success": "True", "user_id": user.id})
Esempio n. 9
0
def search(query):
    result = "["
    solutions_by_user = Solution.select().where(Solution.username.contains(query))
    mentors = Mentor.select().where(
        (Mentor.username.contains(query)) &
        (Mentor.status == "accepted"))
    for solution in solutions_by_user:
        result += "{" + f"'solution_url': '{solution.url}'," \
            f"'username': '******'" + "}"

    for mentor in mentors:
        result += "{" + f"'username': '******'," \
            f"'profile_url': '{mentor.profile_link}'" + "}"
    result += "]"
    return json.dumps(result)
    def inner(*args, **kwargs):
        from models import EmailLog, Mentor, Applicant
        subject = args[3]
        content = args[1][:144]
        mode = [i for i in modes if modes[i] == subject][0]
        recipient_email = args[2]
        if mode == 'mentor':
            mentor = Mentor.get(Mentor.email == recipient_email)
            recipient_name = mentor.first_name + " " + mentor.last_name
        else:
            applicant = Applicant.get(Applicant.email == recipient_email)
            recipient_name = applicant.first_name + " " + applicant.last_name

        timestamp = datetime.datetime.now()

        ret = func(*args, **kwargs)

        if ret is None:
            EmailLog.create(subject=subject, content=content, mode=mode, timestamp=timestamp,
                            recipient_name=recipient_name, recipient_email=recipient_email, status=True)
        else:
            EmailLog.create(subject=subject, content=content, mode=mode, timestamp=timestamp,
                            recipient_name=recipient_name, recipient_email=recipient_email, status=False)
	def mutate(cls, _, args, context, info):
		query = Mentors.get_query(context)
		mentor = query.filter(MentorModel.email == args.get('email')).first()

		if mentor is None:
			mentor = MentorModel(email=args.get('email'), 
		                     timestamp=args.get('ts'),
		                     role=args.get('role'),
		                     availability=args.get('availability'),
		                     org_level=args.get('org_level'),
		                     org=args.get('org'),
		                     expertise=args.get('expertise'),
		                     outside_org=args.get('outside_org'),
		                     requests=args.get('requests'),
		                     identify_as=args.get('identify_as'),
		                     fullname=args.get('full_name'),
		                     manager_email=args.get('manager_email'),
		                     #Sent_Wecome_Email__date_=args.get('welcome_email_date'),
		                     #Sent_Manager_Approval_Email__date_=args.get('manager_approval_email_date'),
		                     #Manager_Approved__date_=args.get('manager_approved_date'),
		                     #Mentee_Limit=args.get('mentee_limit'),
		                     #Gender=args.get('gender'),
		                     )
			db_session.add(mentor)
		else:
			mentor.timestamp=args.get('ts')
			mentor.role=args.get('role')
			mentor.availability=args.get('availability')
			mentor.org_level=args.get('org_level')
			mentor.org=args.get('org')
			mentor.expertise=args.get('expertise')
			mentor.outside_org=args.get('outside_org')
			mentor.requests=args.get('requests')
			mentor.identify_as=args.get('identify_as')
			mentor.fullname=args.get('full_name')
			mentor.manager_email=args.get('manager_email')

		db_session.commit()
		
		# on successful commit, compute ranking and update or overwrite in rankings table
		rankings = MentorLearnerRankingsModel(mentor=args.get('email'), 
		                     learner='testlearner2',
		                     ranking=NaiveRanker.rank_learners(args.get('email')))
		db_session.add(rankings)
		db_session.commit()
		
		ok = True
		return createOrUpdateMentor(mentor=mentor, rankings=rankings, ok=ok)