Ejemplo n.º 1
0
def projects():
    """ projects page """
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    r = requests.get(build_url('api/projects')).json()
    projects = r.get('projects')
    for project in projects:
        contributors = []
        for user_id in project.get("contributors"):
            r = requests.get(build_url(f"api/users/{str(user_id)}")).json()
            user_obj = ''
            if r.get('Status') == 'OK':
                user_obj = r.get('user')
                contributors.append(user_obj)
        project["contributors"] = contributors
        tech_list = []
        for tech_id in project.get("tech"):
            r = requests.get(build_url(f"api/tech/{str(tech_id)}")).json()
            tech_obj = ''
            if r.get('Status') == 'OK':
                tech_obj = r.get('tech')
                tech_list.append(tech_obj)
        project["tech"] = tech_list
    return render_template('projects.html', projects=projects, data=data)
Ejemplo n.º 2
0
def display_user_with_projects(request, user):
    from models.auth import Auth
    current_user = Auth.get_current_user()

    full_view = request.full_view
    tech_list = []
    if user and user.get('tech'):
        for tech_id in user.get("tech"):
            r = requests.get(build_url(f"api/tech/{str(tech_id)}")).json()
            tech_obj = ''
            if r.get('Status') == 'OK':
                tech_obj = r.get('tech')
                tech_list.append(tech_obj)
        user["tech"] = tech_list
    proj_list = []
    if user.get('projects'):
        for proj_id in user.get("projects"):
            r = requests.get(build_url(f"api/projects/{str(proj_id)}")).json()
            proj_obj = ''
            if r.get('Status') == 'OK':
                proj_obj = r.get('project')
                proj_list.append(proj_obj)
        user["projects"] = proj_list
    if current_user and current_user.get('id') == user.get('id'):
        current_user = user
    else:
        current_user = None
    data = {'user': user, 'current_user': current_user, 'full_view': full_view}
    return data
Ejemplo n.º 3
0
def edit_project():
    data, current_user = set_data_and_current_user()
    data["api_url"] = build_url('api/')
    data["roles"] = ['role1', 'role2', 'role3', 'role4']
    r = requests.get(build_url('api/projects')).json()
    projects = r.get('projects')
    return render_template('edit_project.html', data=data, projects=projects)
Ejemplo n.º 4
0
def projects():
    """ projects page """
    data, current_user = set_data_and_current_user()
    r = requests.get(build_url('api/projects')).json()
    projects = r.get('projects')
    for project in projects:
        contributors = []
        if project.get('contributors'):
            for user_id in project.get("contributors"):
                r = requests.get(build_url(f"api/users/{str(user_id)}")).json()
                user_obj = ''
                if r.get('Status') == 'OK':
                    user_obj = r.get('user')
                    contributors.append(user_obj)
            project["contributors"] = contributors
        tech_list = []
        if project.get('tech'):
            for tech_id in project.get("tech"):
                r = requests.get(build_url(f"api/tech/{str(tech_id)}")).json()
                tech_obj = ''
                if r.get('Status') == 'OK':
                    tech_obj = r.get('tech')
                    tech_list.append(tech_obj)
            project["tech"] = tech_list
    return render_template('gallery.html', projects=projects, data=data)
Ejemplo n.º 5
0
def express_interest(project_id):
    data, current_user = set_data_and_current_user()    
    response = requests.put(build_url(f'api/projects/{project_id}'), data={'interested': current_user.get("id")}).json()
    if not response.get('status') == 'OK':
        r = requests.get(build_url('api/projects')).json()
        projects = r.get('projects')
        data['msg'] = 'request failed'
        return render_template('dashboard.html', data=data, projects=projects)
    return redirect(url_for('dash.dashboard'))
Ejemplo n.º 6
0
def submit_project():
    data, current_user = set_data_and_current_user()
    r = requests.post(build_url("api/projects"), data=request.form).json()
    if r.get('status') == 'error':
        data['msg'] = 'Failed to create new project.'
        return render_template('submit_project.html', data=data)
    project_id = r.get('project').get('id')
    response = requests.put(build_url(f'api/projects/{project_id}'),
                            data={
                                'interested': current_user.get("id")
                            }).json()
    return redirect(url_for('dash.dashboard'))
Ejemplo n.º 7
0
def search():
    ''' search projects '''
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    query = str(request.form.get('searchBar')).lower()
    r = requests.get(build_url('api/projects')).json()
    projects = r.get('projects')
    matches = []
    for project in projects:
        if query == project.get('name').lower() or query in project.get(
                'name').lower():
            matches.append(project)
            continue
        if project not in matches:
            for user in project.get('users'):
                if query == user.lower() or query in user.lower():
                    matches.append(project)
                    break
            if project not in matches:
                for tech in project.get('technologies'):
                    if query == tech.lower() or query in tech.lower():
                        matches.append(project)
                        break
    msg = None
    if len(matches) == 0:
        matches = projects
        msg = f'{query} not found'
    # pub_data, auth_data, my_auth_data, my_role_auth_data
    return render_template('projects.html',
                           projects=matches,
                           msg=msg,
                           data=data)
def index():
    data = {}
    r = requests.get(build_url('api/products')).json()
    if not r.get('status') == 'OK':
        data['msg'] = 'API error'
    data['products'] = r.get('products')
    return render_template('store.html', data=data)
Ejemplo n.º 9
0
def link_database(
    scheme,
    database_host,
    port='',
    username='',
    password='',
    database_name='',
    variable_name='DATABASE_URL'
):
    """
    Create a link with a database by setting an environment variable
    The variable will be "DATABASE_URL" by default
    """

    database_url = build_url(
        scheme=scheme,
        domain=database_host,
        port=port,
        username=username,
        password=password,
        path=database_name
    )

    update_property_in_json_file(
        env_file_path, variable_name, database_url
    )

    # Relation changed - re-run update target
    update_target()

    # Reset wsgi relation settings
    wsgi_relation()
Ejemplo n.º 10
0
def get(endpoint, parameters={}):
    """
    Query the Insights API (admin.insights.ubuntu.com) using the cache
    """

    return feeds.cached_request(
        helpers.build_url(API_URL, endpoint, parameters))
Ejemplo n.º 11
0
def assign_roles():
    data, current_user = set_data_and_current_user()
    data["api_url"] = build_url('api/')
    data["roles"] = ['Role1', 'Role2', 'Role3', 'Role4']
    r = requests.get(build_url('api/projects')).json()
    projects, active = r.get("projects"), None
    r = requests.get(build_url('api/users')).json()
    data["users"] = r.get('users')
    for project in projects:
        if project["active"]:
            active = project
            break

    if "127.0.0.1" in data["api_url"]:
        active = projects[0]

    return render_template('assign_roles.html', data=data, project=active)
Ejemplo n.º 12
0
def project_by_id(id):
    r = requests.get(build_url('api/projects')).json()
    if r.get('status') == 'error':
        return jsonify({'status': 'error', 'project': {}}), 400
    projects = r.get('projects')
    for project in projects:
        if project.get("id") == id:
            return jsonify({'status': 'OK', 'project': project}), 200
    return jsonify({'status': 'error', 'project': {}}), 400
Ejemplo n.º 13
0
def tech_by_id(id):
    r = requests.get(build_url('api/tech')).json()
    if r.get('status') == 'error':
        return jsonify({'Status': 'error', 'tech': {}}), 400
    techs = r.get('tech')
    for item in techs:
        if item.get("id") == id:
            return jsonify({'Status': 'OK', 'tech': item}), 200
    return jsonify({'Status': 'error', 'tech': {}}), 400
Ejemplo n.º 14
0
def modify_project(id):
    data, current_user = set_data_and_current_user()
    r = requests.put(build_url(f"api/projects/{id}"), data=request.form).json()
    print(r)
    if r.get('status') == 'error':
        data['error'] = f'PUT api/projects/{id} failed'
        print('ERROR')
        return render_template('error.html', data=data)
    return redirect(url_for('dash.dashboard'))
Ejemplo n.º 15
0
def users():
    """ users page """
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    r = requests.get(build_url('api/users')).json()
    users = r.get('users')
    for user in users:
        tech_list = []
        if user.get('tech'):
            for tech_id in user.get("tech"):
                r = requests.get(build_url(f"api/tech/{str(tech_id)}")).json()
                tech_obj = ''
                if r.get('Status') == 'OK':
                    tech_obj = r.get('tech')
                    tech_list.append(tech_obj)
            user["tech"] = tech_list
    return render_template('users.html', users=users, data=data)
Ejemplo n.º 16
0
def project_by_name(name):
    r = requests.get(build_url('api/projects')).json()
    if r.get('status') == 'error':
        return jsonify({'status': 'error', 'projects': {}}), 400
    projects = r.get('projects')
    for item in projects:
        if item.name == name:
            return jsonify({'status': 'OK', 'projects': item}), 200
    return jsonify({'status': 'error', 'projects': {}}), 400
Ejemplo n.º 17
0
 def get_current_user(cls):
     """ make request to api for current user based on request.current_user """
     from models.users import User
     from flask import request
     import requests
     from helpers import build_url
     id = request.current_user if request.current_user else ''
     response = requests.get(build_url(f'api/users/{id}')).json()
     if response.get('user'):
         return response.get('user')
     return None
Ejemplo n.º 18
0
def user_profile(id):
    """ profile page """
    from models.auth import Auth
    if not id == request.current_user:
        r = requests.get(build_url(f"api/users/{str(id)}")).json()
        user = r.get('user')
    else:
        user = Auth.get_current_user()
    data = display_user_with_projects(request, user)
    if request.method == 'GET':
        return render_template('profile.html', data=data)
    # UPDATE users profile
    if request.method == 'POST':
        response = requests.put(build_url(f'api/users/{id}'),
                                data=request.form).json()
        if response.get('status') == 'error':
            data['msg'] = response.get('message')
            return render_template('profile.html', data=data)
        # do the update here
        return redirect(url_for('landing.user_profile', id=id))
Ejemplo n.º 19
0
def start_session(r):
    response = requests.post(build_url('api/sessions'), data=r.form).json()
    print(r.form)
    print(response)
    if not response or response.get('status') == 'error':
        data = {'msg': response.get('message')}
        return render_template('login.html', data=data)
    user = response.get('user')
    print(user)
    data = display_user_with_projects(r, user)
    data['msg'] = response.get('message')
    data['current_user'] = data.get('user')
    res = make_response(render_template('profile.html', data=data))
    res.set_cookie('session', response.get('id'))
    return res
Ejemplo n.º 20
0
def dashboard():
    from datetime import datetime
    data, current_user = set_data_and_current_user()
    projects = requests.get(build_url('api/projects')).json().get('projects')
    data['projects'] = projects
    data = trigger_current_project(data)
    if data.get('load_buttons'):
        projects_list = []
        for project_dict in projects:
            print(project_dict.get('participant_count'), '*****')
            data, project_dict = fill_and_count_participants(data, project_dict)
            projects_list.append(project_dict)
            if project_dict.get('active'):
                if not project_dict.get('contributors'):
                    project_dict['contributors'] = project_dict['participants']
                data['current_project'] = project_dict
        data['projects'] = projects_list
            
    if current_user.get('staff'):
        r = requests.get(build_url(f"api/users")).json()
        if not r.get('status') == 'OK':
            data['msg'] = 'api/users encountered an error'
        data['users'] = r.get('users')
    return render_template('dashboard.html', data=data)
Ejemplo n.º 21
0
def fill_and_count_participants(data, project_dict):
    count = 0
    for user_id in project_dict.get('interested'):
        project_dict['participants'] = []
        if user_id:
            r = requests.get(build_url(f'api/users/{user_id}')).json()
            if not r.get('status') == 'OK':
                    data['msg'] = 'api/users/<id> encountered an error'
            else:
                if 'user' in r and 'password' in r['user']:
                    del r['user']['password']                
                project_dict['participants'].append(r.get('user'))
                count += 1
    project_dict['participant_count'] = count
    return data, project_dict
Ejemplo n.º 22
0
def webservice_relation():
    """
    Create "WEBSERVICE_URL" environment variable from relation
    """

    log('Function: webservice_relation')
    http_protocol = relation_get('http_protocol') or 'http'
    address = relation_get('private-address')
    hostname = relation_get('hostname') or address

    # If hostname is IP address or FQDN, use it
    # otherwise use private_address
    ip_regex = re.compile(
        (
            r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)"
            r"{3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
        )
    )
    hostname_regex = re.compile(
        (
            r"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+"
            r"([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"
        )
    )

    if hostname_regex.match(hostname) or ip_regex.match(hostname):
        domain = hostname
    else:
        domain = address

    webservice_url = build_url(
        scheme=http_protocol,
        domain=domain,
        port=relation_get("port")
    )

    update_property_in_json_file(
        env_file_path, 'WEBSERVICE_URL', webservice_url
    )

    # Relation changed - re-run update target
    update_target()

    # Reset wsgi relation settings
    wsgi_relation()
Ejemplo n.º 23
0
def register():
    """ about us page """
    # post request to api/users to create new one
    response = requests.post(build_url('api/users'), data=request.form).json()
    if response.get('status') == 'error':
        data = {'msg': response.get('message')}
        return render_template('login.html', data=data)
    print('user created')
    return start_session(request)
    # post to api/sessions
    # using user id from that, get user from /users
    # data dict with current_user = user
    # make response for profile.html with data
    # set cookie on response
    # return response
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    return render_template('login.html', data=data)
Ejemplo n.º 24
0
 def test_get_project_by_name(self):
     r = requests.get(build_url('/api/projects/name/cheese')).json()
     self.assertEqual(r.get('status'), 'OK')
Ejemplo n.º 25
0
def delete_account(id):
    response = requests.delete(build_url(f'api/users/{id}')).json()
    data = {'msg': response.get('message')}
    res = make_response(render_template('login.html', data=data))
    res.set_cookie('session', '')
    return res
Ejemplo n.º 26
0
def login_or_authenticate():
    if request.method == 'POST':
        f = request.form
        email, password = f.get('email'), f.get('password')

        response = {'status': 'error', 'message': 'incomplete form'}

        # verify user completed the form
        if not email or not password:
            return jsonify(response), 400

        # verify user exists with that email
        user_dict_list = User.get_by_attr('email', email)
        if not user_dict_list or len(user_dict_list) == 0:
            response['message'] = 'email not found'
            return jsonify(response), 400
        user_dict = user_dict_list[0].to_dict()

        # verify password is correct
        user = User(**user_dict)
        if not user.validate_password(password):
            response['message'] = 'incorrect password'
            return jsonify(response), 400
        del user_dict['password']

        # create a session
        session = Session(**{'user_id': user.id})
        sess_id = session.id
        del session

        return jsonify({
            'status': 'OK',
            'message': 'login successful',
            'user': user_dict,
            'id': sess_id
        }), 200
    if request.method == 'PUT':
        from datetime import datetime
        import requests
        from helpers import build_url
        # get session id passed in a cookie
        cookie = request.cookies.get('session')
        session_dict = Session.sessions.get(cookie)
        if session_dict:
            created_at = Session.sessions[cookie].get('created_at')
        # check if it matches existing session, and ensure not expired
        if not session_dict or Session.expired(cookie, created_at):
            if session_dict:
                session_obj = Session(**session_dict)
                session_obj.delete()
                del Session.sessions[cookie]
            # return error message if invalid or expired
            return jsonify({
                'status': 'error',
                'message': 'session invalid or expired'
            }), 404
        else:
            # update timestamp of session
            session_dict['created_at'] = datetime.utcnow()
            session_obj = Session(**session_dict)
            response = requests.get(
                build_url(f'/api/users/{session_obj.user_id}')).json()
            user = response.get('user')
            session_obj.delete()
            return jsonify({
                'status': 'OK',
                'message': 'session updated',
                'user': user
            }), 200
Ejemplo n.º 27
0
 def test_get_all_projects_status(self):
     r = requests.get(build_url('/api/projects')).json()
     self.assertEqual(r.get('status'), 'OK')