def invitation_register(id):

    form = RegistrationForm(request.form)

    db_session = weblab_api.db.Session()

    invitation = weblab_api.db.get_invitation(db_session, id)

    if invitation is None:
        error_message = "Invitation does not exist"
        return render_template("webclient/error.html",error_message=error_message)

    # Save the group_name for later
    group_name = invitation.group.name

    can_accept, why = invitation.can_accept()

    db_session.close()

    if not can_accept:

        if why == "expired":
            error_message =  "Invitation has expired"
            return render_template("webclient/error.html",error_message=error_message)

        elif why == "limit":
            error_message = "Too many people have used this invitation already"
            return render_template("webclient/error.html", error_message=error_message)

        else:
            error_message = "Cannot accept invitation: " + why
            return render_template("webclient/error.html", error_message=error_message)

    if request.method == "GET":

        # Render the registration form.
        return render_template("webclient/registration_form.html", form=form)

    # If this was a POST then we must try to create the user.
    elif request.method == "POST" and form.validate():

        login = form.login.data
        password = form.password.data
        full_name = form.full_name.data
        email = form.email.data

        user = weblab_api.db.get_user(login)
        if user is not None:
            flash(gettext('User exists already'))
            return render_template("webclient/registration_form.html", form=form)

        weblab_api.db.create_db_user(login, full_name, email, password, 'student')

        weblab_api.db.accept_invitation(login, invitation.unique_id, group_name, True)

        flash(gettext('Registration done and invitation accepted'))

        return redirect(url_for(".login", _external=True, _scheme=request.scheme))
    else:
        return render_template("webclient/registration_form.html", form=form)
Example #2
0
def handle_login_POST():
    """
    Carries out an actual log in.
    :return:
    """

    # If this is a POST it is a login request.
    #
    username = request.values.get("username")
    password = request.values.get("password")

    # We may or may not have a 'next' field. If we do, we make sure that the URL is safe.
    try:
        session_id = weblab_api.api.login(username, password)
    except InvalidCredentialsError:
        flash(gettext("Invalid username or password"), category="error")
        # _scheme is a workaround. See comment in other redirect.
        return redirect(url_for(".login", _external=True, _scheme=request.scheme))
    except:
        traceback.print_exc()
        flash(gettext("There was an unexpected error while logging in."), 500)
        return weblab_api.make_response(gettext("There was an unexpected error while logging in."), 500)
    else:
        # TODO: Find proper way to do this.
        # This currently redirects to HTTP even if being called from HTTPS. Tried _external as a workaround but didn't work.
        # More info: https://github.com/mitsuhiko/flask/issues/773
        # For now we force the scheme from the request.
        return weblab_api.make_response(redirect(get_next_url()))
Example #3
0
def lab(category_name, experiment_name):
    """
    Renders a specific laboratory.
    """
    federated_reservation_id = session.get('reservation_id')
    federated_mode = federated_reservation_id is not None
    if federated_mode:
        back_url = session.get('back_url')
    else:
        back_url = None

    experiment = None
    if federated_mode:
        finished = request.args.get('finished', 'false').lower() == 'true'
        if finished:
            return render_template("webclient/error.html", error_level='info', error_message = gettext("You have finished using this experiment."), federated_mode = True, back_url = back_url)
            
        weblab_api.ctx.reservation_id = federated_reservation_id
        # Now obtain the current experiment
        try:
            experiment = _get_experiment_data(weblab_api.api.get_reservation_experiment_info())
            reservation_status = weblab_api.api.get_reservation_status()
        except SessionNotFoundError:
            session.pop('reservation_id', None)
            session.pop('back_url', None)
            federated_mode = False

            # Check if the user has a valid session (it may happen that this comes from an old reservation_id)
            try:
                experiment_list = weblab_api.api.list_experiments(experiment_name, category_name)
            except SessionNotFoundError:
                return render_template("webclient/error.html", error_message = gettext("Your use has finished."), federated_mode = True, back_url = back_url)
        else:
            if experiment is not None and reservation_status is not None and experiment['type'] == 'redirect':
                if reservation_status.status == Reservation.CONFIRMED:
                    local_url = reservation_status.url
                    if local_url is not None:
                        return redirect(local_url.replace("TIME_REMAINING", unicode(local_url.time)))

    if experiment is None:
        try:
            experiment_list = weblab_api.api.list_experiments(experiment_name, category_name)
        except SessionNotFoundError:
            flash(gettext("You are not logged in"), 'danger')
            return redirect(url_for('.login', next=request.url))

        for exp_allowed in experiment_list:
            if exp_allowed.experiment.name == experiment_name and exp_allowed.experiment.category.name == category_name:
                experiment = _get_experiment(exp_allowed)

        if experiment is None:
            # TODO: check what to do in case there is no session_id (e.g., federated mode)
            if weblab_api.db.check_experiment_exists(experiment_name, category_name):
                flash(gettext("You don't have permission on this laboratory"), 'danger')
            else:
                flash(gettext("Experiment does not exist"), 'danger')
            return redirect(url_for('.labs'))

    return render_template("webclient/lab.html", experiment=experiment, federated_mode = federated_mode, back_url = back_url, federated_reservation_id = federated_reservation_id)
Example #4
0
def to_human(seconds):
    if seconds < 60:
        return gettext("%(num)s sec", num="%.2f" % seconds)
    elif seconds < 3600:
        return gettext("%(min)s min %(sec)s sec", min=(int(seconds) / 60), sec=(int(seconds) % 60))
    elif seconds < 24 * 3600:
        return gettext("%(hours)s hour %(min)s min", hours=(int(seconds) / 3600), min=(int(seconds) % 3600 / 60))
    else:
        return gettext("%(days)s days", days = (int(seconds) / (3600 * 24)))
Example #5
0
 def wrapped(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except WebError as e:
         return weblab_api.make_response(gettext(e.args[0]), 500)
     except Exception:
         if current_app.debug:
             raise
         traceback.print_exc()
         return weblab_api.make_response(gettext("Error processing request"), 500)
Example #6
0
def lab(category_name, experiment_name):
    """
    Renders a specific laboratory.
    """
    federated_reservation_id = session.get('reservation_id')
    federated_mode = federated_reservation_id is not None
    if federated_mode:
        back_url = session.get('back_url')
    else:
        back_url = None

    experiment = None
    if federated_mode:
        weblab_api.ctx.reservation_id = federated_reservation_id
        # Now obtain the current experiment
        try:
            experiment = _get_experiment_data(weblab_api.api.get_reservation_experiment_info())
            reservation_status = weblab_api.api.get_reservation_status()
        except SessionNotFoundError:
            session.pop('reservation_id', None)
            session.pop('back_url', None)
            federated_mode = False

            # Check if the user has a valid session (it may happen that this comes from an old reservation_id)
            try:
                experiment_list = weblab_api.api.list_experiments(experiment_name, category_name)
            except SessionNotFoundError:
                return render_template("webclient/error.html", error_message = gettext("The reservation you used has expired."), federated_mode = True, back_url = back_url)
        else:
            if experiment is not None and reservation_status is not None and experiment['type'] == 'redirect':
                if reservation_status.status == Reservation.CONFIRMED:
                    local_url = reservation_status.url
                    if local_url is not None:
                        return redirect(local_url.replace("TIME_REMAINING", unicode(local_url.time)))

    if experiment is None:
        try:
            experiment_list = weblab_api.api.list_experiments(experiment_name, category_name)
        except SessionNotFoundError:
            flash(gettext("You are not logged in"), 'danger')
            return redirect(url_for('.login', next=request.url))

        for exp_allowed in experiment_list:
            if exp_allowed.experiment.name == experiment_name and exp_allowed.experiment.category.name == category_name:
                experiment = _get_experiment(exp_allowed)

        if experiment is None:
            # TODO: check what to do in case there is no session_id (e.g., federated mode)
            if weblab_api.db.check_experiment_exists(experiment_name, category_name):
                flash(gettext("You don't have permission on this laboratory"), 'danger')
            else:
                flash(gettext("Experiment does not exist"), 'danger')
            return redirect(url_for('.labs'))

    return render_template("webclient/lab.html", experiment=experiment, federated_mode = federated_mode, back_url = back_url, federated_reservation_id = federated_reservation_id)
Example #7
0
 def wrapped(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except WebError as e:
         return weblab_api.make_response(gettext(e.args[0]), 500)
     except Exception:
         if current_app.debug:
             raise
         traceback.print_exc()
         return weblab_api.make_response(
             gettext("Error processing request"), 500)
Example #8
0
def federated():
    redirecting = session.pop('federated_redirecting', None)
    widget = request.args.get('widget')
    reservation_id = request.args.get('reservation_id')
    reservation_tokens = reservation_id.split(';')
    back_url = request.args.get('back_url')
    if len(reservation_tokens) == 1:
        reservation_id = reservation_tokens[0]
    else:
        reservation_id = reservation_tokens[0]
        reservation_id_plus_route = reservation_tokens[1]
        # The second argument is the session identifier plus a route. 
        # Here we analyze whether this message was intended for this server or for any other with a different route.
        # To do this, we check the route, and if it's different, we return a redirection to the same URL but setting a cookie with the required URL
        # However, if we were already redirecting, then there is a problem (e.g., not using an existing route), and a message is displayed.
        if '.' in reservation_id_plus_route:
            route = reservation_id_plus_route.split('.', 1)[1]
            if route != weblab_api.ctx.route:
                if redirecting:
                    return render_template("webclient/error.html", error_message = gettext("Invalid federated URL: you're attempting to use a route not used in this WebLab-Deusto instance"), federated_mode = True, title = gettext("Error"), back_url = back_url)

                session['federated_redirecting'] = "true"
                response = redirect(request.url)
                now = datetime.datetime.now()
                response.set_cookie('weblabsessionid', reservation_id_plus_route, expires = now + datetime.timedelta(days = 100), path = weblab_api.ctx.location)
                return response

    weblab_api.ctx.reservation_id = reservation_id
    try:
        experiment = weblab_api.api.get_reservation_experiment_info()
    except SessionNotFoundError:
        return render_template("webclient/error.html", error_message = gettext("The provided reservation identifier is not valid or has expired."), federated_mode = True, back_url = back_url)
    except:
        traceback.print_exc()
        return render_template("webclient/error.html", error_message = gettext("Unexpected error on the server side while trying to get the reservation information."), federated_mode = True, back_url = back_url)

    session['reservation_id'] = reservation_id
    session['back_url'] = request.args.get('back_url')
    kwargs = {}
    if request.args.get('locale'):
        session['locale'] = request.args.get('locale')
        kwargs = dict(locale=request.args.get('locale'))
    response = redirect(url_for('.lab', experiment_name=experiment.name, category_name=experiment.category.name, **kwargs))
    reservation_id_plus_route = '%s.%s' % (reservation_id, weblab_api.ctx.route)
    weblab_api.fill_session_cookie(response, reservation_id_plus_route, reservation_id)
    return response
Example #9
0
 def wrapped(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except WebError as e:
         return weblab_api.jsonify(error=True, message=e.args[0])
     except Exception:
         if current_app.debug:
             raise
         traceback.print_exc()
         return weblab_api.jsonify(error=True, message=gettext("Error processing request"))
Example #10
0
 def wrapped(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except WebError as e:
         return weblab_api.jsonify(error=True, message=e.args[0])
     except Exception:
         if current_app.debug:
             raise
         traceback.print_exc()
         return weblab_api.jsonify(
             error=True, message=gettext("Error processing request"))
Example #11
0
def demo_lab(category_name, experiment_name):
    try:
        experiment_list = weblab_api.api.list_experiments(experiment_name, category_name)
    except SessionNotFoundError:
        g.next_url = url_for('.lab', category_name = category_name, experiment_name = experiment_name)
        return demo()
    except:
        flash(gettext("Error processing request"), 'danger')
        return redirect(url_for('.labs'))
    else: # User is logged in and has permissions
        return redirect(url_for('.lab', category_name = category_name, experiment_name = experiment_name))
Example #12
0
def login_service():
    contents = request.get_json(force=True, silent=True)
    if contents == False or not isinstance(contents, dict):
        return weblab_api.jsonify(error = True, message = "Error reading username and password")

    username = contents.get('username', '')
    password = contents.get('password', '')

    try:
        session_id = weblab_api.api.login(username, password)
    except InvalidCredentialsError:
        return weblab_api.jsonify(error = True, message = gettext("Invalid username or password"))

    return weblab_api.jsonify(error = False, redirect = get_next_url())
Example #13
0
def gefx(session, condition):
    links, _ = generate_links(session, condition)
    if not links:
        return gettext("This groups does not have any detected plagiarism")

    G = nx.DiGraph()
    
    for source_node in links:
        for target_node in set(links[source_node]):
            weight = links[source_node].count(target_node)
            G.add_edge(source_node, target_node, weight=weight)

    out_degrees = G.out_degree()
    in_degrees = G.in_degree()

    for name in G.nodes():
         G.node[name]['out_degree'] = out_degrees[name]
         G.node[name]['in_degree'] = in_degrees[name]

    G_undirected = G.to_undirected();
    partitions = best_partition(G_undirected)
    colors = {}
    for member, c in partitions.items():
        if not colors.has_key(c):
            r = random.randrange(64,192)
            g = random.randrange(64,192)
            b = random.randrange(64,192)
            colors[c] = (r, g, b)
        G.node[member]["viz"] = {
            'color': { 
              'r': colors[c][0],
              'g': colors[c][1],
              'b': colors[c][2],
            },
            'size': 5 * G.node[member]['out_degree']
        }

    output = StringIO()
    nx.write_gexf(G, output)
    return Response(output.getvalue(), mimetype='text/xml')
Example #14
0
    def index(self):
        login = get_app_instance(self).get_user_information().login
        user = self._session.query(model.DbUser).filter_by(login = login).one()
        
        facebook_auth_obj = self._session.query(model.DbAuth).filter_by(name = 'FACEBOOK').first()
        facebook_id = ''

        change_password = True
        password_auth = None
        facebook_auth = None

        for user_auth in user.auths:
            if user_auth.auth.auth_type.name.lower() == 'facebook':
                facebook_id = user_auth.configuration
                facebook_auth = user_auth
            if 'ldap' in user_auth.auth.auth_type.name.lower():
                change_password = False
            if user_auth.auth.auth_type.name.lower() == 'db':
                password_auth = user_auth


        if len(request.form):
            form = ProfileEditForm(request.form)
        else:
            form = ProfileEditForm()
            form.full_name.data = user.full_name
            form.login.data     = user.login
            form.email.data     = user.email
            form.facebook.data  = facebook_id

        user_permissions = get_app_instance(self).get_permissions()
        
        change_profile = True
        for permission in user_permissions:
            if permission.name == permissions.CANT_CHANGE_PROFILE:
                change_password = False
                change_profile  = False

        if change_profile and form.validate_on_submit():

            errors = []

            if change_password and password_auth is not None and form.password.data:
                if len(form.password.data) < 6:
                    errors.append(gettext("Error: too short password"))
                else:
                    password_auth.configuration = password2sha(form.password.data)

            user.email = form.email.data
            
            if form.facebook.data:
                if facebook_auth is None:
                    if facebook_auth_obj is not None:
                        new_auth = model.DbUserAuth(user, facebook_auth_obj, form.facebook.data)
                        self._session.add(new_auth)
                else:
                    facebook_auth.configuration = form.facebook.data
            else:
                if facebook_auth is not None:
                    self._session.delete(facebook_auth)

            self._session.commit()

            if errors:
                for error in errors:
                    flash(error)
            else:
                flash(gettext("Saved"))

        return self.render("profile/profile-edit.html", form=form, change_password=change_password, change_profile=change_profile, facebook_available=facebook_auth_obj is not None)
def invitation(id):

    db_session = weblab_api.db.Session()

    invitation = weblab_api.db.get_invitation(db_session, id)
    if invitation is None:
        error_message = "Invitation does not exist"
        return render_template("webclient/error.html",
                               error_message=error_message)

    # Get the group name for later.
    group = invitation.group

    can_accept, why = invitation.can_accept()

    db_session.close()

    if not can_accept:

        if why == "expired":
            error_message = "Invitation has expired"
            return render_template("webclient/error.html",
                                   error_message=error_message)

        elif why == "limit":
            error_message = "Too many people have used this invitation already"
            return render_template("webclient/error.html",
                                   error_message=error_message)

        else:
            error_message = "Cannot accept invitation: " + why
            return render_template("webclient/error.html",
                                   error_message=error_message)

    login = None
    collective = False
    in_group = False
    try:
        weblab_api.api.check_user_session()
        user_session = True
        login = weblab_api.current_user.login
        login_url = None
        user = weblab_api.db.get_user_by_name(login)
        collective = user.role.name == 'federated' or user.login == 'demo'
        in_group = weblab_api.db.user_in_group(login, group)

    except SessionNotFoundError:
        login_url = url_for('.login',
                            next=url_for('.invitation',
                                         id=id,
                                         _external=True,
                                         scheme=request.scheme),
                            _external=True,
                            scheme=request.scheme)
        user_session = False

    if request.method == "GET":

        return render_template("webclient/invitation.html",
                               id=id,
                               user_session=user_session,
                               login_url=login_url,
                               group_name=group.name,
                               collective=collective,
                               in_group=in_group)

    elif request.method == "POST":

        # Accept the invitation. This can only be done (from here) if we have a logged-in account to add the group to.
        if login is None:
            # We have no valid session. We redirect back to the invitation screen.
            flash('error', gettext('You are not logged in'))
            return redirect(url_for(".invitation", id=id))
        if collective:
            flash('error', gettext('You are logged with a collective account'))
            return redirect(url_for(".invitation", id=id))
        if in_group:
            flash(gettext('You are already in this group'))
            return redirect(url_for('.labs'))

        weblab_api.db.accept_invitation(login, invitation.unique_id,
                                        group.name, False)

        flash(gettext('Invitation accepted'))

        return redirect(url_for(".labs"))
def invitation_register(id):

    form = RegistrationForm(request.form)

    db_session = weblab_api.db.Session()

    invitation = weblab_api.db.get_invitation(db_session, id)

    if invitation is None:
        error_message = "Invitation does not exist"
        return render_template("webclient/error.html",
                               error_message=error_message)

    # Save the group_name for later
    group_name = invitation.group.name

    can_accept, why = invitation.can_accept()

    db_session.close()

    if not can_accept:

        if why == "expired":
            error_message = "Invitation has expired"
            return render_template("webclient/error.html",
                                   error_message=error_message)

        elif why == "limit":
            error_message = "Too many people have used this invitation already"
            return render_template("webclient/error.html",
                                   error_message=error_message)

        else:
            error_message = "Cannot accept invitation: " + why
            return render_template("webclient/error.html",
                                   error_message=error_message)

    if request.method == "GET":

        # Render the registration form.
        return render_template("webclient/registration_form.html", form=form)

    # If this was a POST then we must try to create the user.
    elif request.method == "POST" and form.validate():

        login = form.login.data
        password = form.password.data
        full_name = form.full_name.data
        email = form.email.data

        user = weblab_api.db.get_user(login)
        if user is not None:
            flash(gettext('User exists already'))
            return render_template("webclient/registration_form.html",
                                   form=form)

        weblab_api.db.create_db_user(login, full_name, email, password,
                                     'student')

        weblab_api.db.accept_invitation(login, invitation.unique_id,
                                        group_name, True)

        flash(gettext('Registration done and invitation accepted'))

        return redirect(
            url_for(".login", _external=True, _scheme=request.scheme))
    else:
        return render_template("webclient/registration_form.html", form=form)
Example #17
0
 def search_placeholder(self):
     return gettext("Search")
Example #18
0
    def index(self):
        login = get_app_instance(self).get_user_information().login
        user = self._session.query(model.DbUser).filter_by(login=login).one()

        facebook_auth_obj = self._session.query(
            model.DbAuth).filter_by(name='FACEBOOK').first()
        facebook_id = ''

        change_password = True
        password_auth = None
        facebook_auth = None

        for user_auth in user.auths:
            if user_auth.auth.auth_type.name.lower() == 'facebook':
                facebook_id = user_auth.configuration
                facebook_auth = user_auth
            if 'ldap' in user_auth.auth.auth_type.name.lower():
                change_password = False
            if user_auth.auth.auth_type.name.lower() == 'db':
                password_auth = user_auth

        if len(request.form):
            form = ProfileEditForm(request.form)
        else:
            form = ProfileEditForm()
            form.full_name.data = user.full_name
            form.login.data = user.login
            form.email.data = user.email
            form.facebook.data = facebook_id

        user_permissions = get_app_instance(self).get_permissions()

        change_profile = True
        for permission in user_permissions:
            if permission.name == permissions.CANT_CHANGE_PROFILE:
                change_password = False
                change_profile = False

        if change_profile and form.validate_on_submit():

            errors = []

            if change_password and password_auth is not None and form.password.data:
                if len(form.password.data) < 6:
                    errors.append(gettext("Error: too short password"))
                else:
                    password_auth.configuration = password2sha(
                        form.password.data)

            user.email = form.email.data

            if form.facebook.data:
                if facebook_auth is None:
                    if facebook_auth_obj is not None:
                        new_auth = model.DbUserAuth(user, facebook_auth_obj,
                                                    form.facebook.data)
                        self._session.add(new_auth)
                else:
                    facebook_auth.configuration = form.facebook.data
            else:
                if facebook_auth is not None:
                    self._session.delete(facebook_auth)

            self._session.commit()

            if errors:
                for error in errors:
                    flash(error)
            else:
                flash(gettext("Saved"))

        return self.render("profile/profile-edit.html",
                           form=form,
                           change_password=change_password,
                           change_profile=change_profile,
                           facebook_available=facebook_auth_obj is not None)
Example #19
0
 def search_placeholder(self):
     return gettext("Search")
Example #20
0
def invitation(id):

    db_session = weblab_api.db.Session()

    invitation = weblab_api.db.get_invitation(db_session, id)
    if invitation is None:
        error_message = "Invitation does not exist"
        return render_template("webclient/error.html",error_message=error_message)

    # Get the group name for later.
    group = invitation.group

    can_accept, why = invitation.can_accept()

    db_session.close()

    if not can_accept:

        if why == "expired":
            error_message =  "Invitation has expired"
            return render_template("webclient/error.html",error_message=error_message)

        elif why == "limit":
            error_message = "Too many people have used this invitation already"
            return render_template("webclient/error.html", error_message=error_message)

        else:
            error_message = "Cannot accept invitation: " + why
            return render_template("webclient/error.html", error_message=error_message)

    login = None
    collective = False
    in_group = False
    try:
        weblab_api.api.check_user_session()
        user_session = True
        login = weblab_api.current_user.login
        login_url = None
        user = weblab_api.db.get_user_by_name(login)
        collective = user.role.name == 'federated' or user.login == 'demo'
        in_group = weblab_api.db.user_in_group(login,group)

    except SessionNotFoundError:
        login_url = url_for('.login', next=url_for('.invitation',id=id, _external=True, scheme=request.scheme),
                            _external=True, scheme=request.scheme)
        user_session = False

    if request.method == "GET":

        return render_template("webclient/invitation.html",
                               id=id,
                               user_session = user_session,
                               login_url = login_url,
                               group_name = group.name,
                               collective = collective,
                               in_group = in_group)

    elif request.method == "POST":

        # Accept the invitation. This can only be done (from here) if we have a logged-in account to add the group to.
        if login is None:
            # We have no valid session. We redirect back to the invitation screen.
            flash('error', gettext('You are not logged in'))
            return redirect(url_for(".invitation", id=id))
        if collective:
            flash('error', gettext('You are logged with a collective account'))
            return redirect(url_for(".invitation", id=id))
        if in_group:
            flash(gettext('You are already in this group'))
            return redirect(url_for('.labs'))

        weblab_api.db.accept_invitation(login, invitation.unique_id, group.name, False)

        flash(gettext('Invitation accepted'))

        return redirect(url_for(".labs"))