Exemple #1
0
def login():
    error = None
    if request.method == 'POST':
        user = controls.get_user_info(request.form['username'])
        if len(user) <= 0:
            error = 'Invalid username'
        elif request.form['password'] != user['password']:
            error = 'Invalid password' 
        else:
            session['logged_in'] = True
            session['username'] = request.form['username']
            session['first_name'] = user['first_name']
            session['last_name'] = user['last_name']
            # CHECK IF THIS HAS BEEN SET YET
            if user['shard_id'] is not None and len(user['shard_id']) > 0: 
                session['shard_id'] = user['shard_id']
            if user['auth_token'] is not None and len(user['auth_token']) > 0:
                session['auth_token'] = user['auth_token']
            if user['is_admin'] is not None and user['is_admin'] > 0:
                session['admin'] = True
            flash('Successfully Logged In')
            return redirect(url_for('index'))
    else:
        if session.get('logged_in'):
            return redirect(url_for('index'))
    return render_template('login.html', error=error)
Exemple #2
0
def login():
    error = None
    if request.method == 'POST':
        user = controls.get_user_info(request.form['username'])
        if len(user) <= 0:
            error = 'Invalid username'
        elif request.form['password'] != user['password']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            session['username'] = request.form['username']
            session['first_name'] = user['first_name']
            session['last_name'] = user['last_name']
            # CHECK IF THIS HAS BEEN SET YET
            if user['shard_id'] is not None and len(user['shard_id']) > 0:
                session['shard_id'] = user['shard_id']
            if user['auth_token'] is not None and len(user['auth_token']) > 0:
                session['auth_token'] = user['auth_token']
            if user['is_admin'] is not None and user['is_admin'] > 0:
                session['admin'] = True
            flash('Successfully Logged In')
            return redirect(url_for('index'))
    else:
        if session.get('logged_in'):
            return redirect(url_for('index'))
    return render_template('login.html', error=error)
Exemple #3
0
def course_info_route():
    course_token = request.args.get('course_token')
    course_owner = request.args.get('owner')
    course_id = Course.get_course_id(course_token, EXPIRY_INTERVAL * 2)
    if not all((course_id, course_owner, len(course_owner) > 0)):
        return error_response('Invalid course specified')
    course = db.session.query(Course).filter_by(id=long(course_id)).first()
    if course is None:
        return error_response('No course with that ID exists')
    course_detail = {
        'paper_name':
        course.name,
        'paper_code':
        course_token,
        'icon':
        course.logo_location,
        'duration':
        course.duration_in_minutes,
        'instructor':
        course.lecturer_in_charge,
        'departments':
        jsonify_departments(course.departments),
        'randomize':
        course.randomize_questions,
        'owner':
        course_owner,
        'reply_to':
        url_for('auth.post_secure_sesd_route', _external=True),
        'url':
        url_for('auth.get_paper_route',
                url=coursify(course.id, course.quiz_filename),
                _external=True)
    }
    return success_response(course_detail)
Exemple #4
0
def settings():
    if request.method == 'GET':
        # GET USER INFO FOR SETTINGS
        user = controls.get_user_info(session.get('username'))
        if not user:
            return redirect(url_for('logout'))
        authorized_users = controls.get_authorized_users()
        lead = controls.get_lead(session.get('username'))
        if len(lead) == 0:
            lead={'first_name':'', 'last_name':'', 'username':''}
        else:
            lead=lead[0]
        return render_template('settings.html', authorized_users = authorized_users, lead=lead['username'], user=user)   
    elif request.method== 'POST':
        # UPDATE USER INFO WITH: ALL VALUES FROM THE FORM
        lead_id = request.form['lead'] if request.form['lead'] != 'None' else None
        payload ={'first_name':request.form['first_name'],
                  'last_name':request.form['last_name'],
                  'lead_id':lead_id}
        if request.form['password'] != '':
            payload['password']=request.form['password']
        if 'auth' in request.form:
            payload['authorized']=0
            payload['auth_token']=None
            session.pop('shard_id')
            session.pop('auth_token')
            session['authorized'] = 0
        payload['use_email'] = request.form['use_email']
        #payload['use_email'] = 1 if 'use_email' in request.form else 0
        controls.update_user(session.get('username'), **payload)
        flash('Settings Updated Successfully')
        session['first_name'] = request.form['first_name']
        session['last_name'] = request.form['last_name']
        return redirect(url_for('settings', lead=lead_id))
Exemple #5
0
def get_endpoint_route():
    endpoints = {
        'result': url_for('auth.get_result_route', _external=True),
        'ranking': url_for('auth.most_ranked_courses_route', _external=True),
        'course_info': url_for('auth.course_info_route', _external=True)
    }
    return success_response(endpoints)
Exemple #6
0
def admin_signup_route():
    links = Links()
    links.tuq_on_pc = url_for('web.tuq_on_pc_route', _external=True)
    links.admin_reg = url_for('web.admin_signup_route', _external=True)
    links.index_url = url_for('web.index_page_route', _external=True)
    form = AdminRequestForm()
    if form.validate_on_submit():
        submission_info = {
            'username': form.username.data,
            'fullname': form.full_name.data,
            'address': form.address.data,
            'email': form.email.data,
            'nationality': form.nationality.data,
            'alias': form.display_name.data,
            'mobile': form.phone_number.data,
            'password': form.password.data
        }
        json_writer = MyJSONObjectWriter()
        json.dump(submission_info,
                  json_writer,
                  skipkeys=True,
                  indent=2,
                  separators=(',', ': '))
        data_string = json_writer.get_buffer()

        data_cache.hset('tuq:admin_requests', form.username.data, data_string)
        session['name'] = form.full_name.data
        return redirect(url_for('web.submission_made_route', _external=True))
    else:
        return render_template('admin_register.html', form=form, links=links)
Exemple #7
0
def tuq_on_pc_route():
    get_route_link = url_for('main.main_route', _external=True)
    links = Links()
    links.tuq_on_pc = url_for('web.tuq_on_pc_route', _external=True)
    links.admin_reg = url_for('web.admin_signup_route', _external=True)
    links.index_url = url_for('web.index_page_route', _external=True)
    return render_template('tuq_on_pc.html',
                           main_link=get_route_link,
                           links=links)
Exemple #8
0
def submission_made_route():
    fullname = session.get('name', None)
    if fullname is None:
        return redirect(url_for('web.index_page_route', _external=True))
    session.pop('name')
    message = 'Thank you for using Tuq services, {}'.format(fullname)
    links = Links()
    links.tuq_on_pc = url_for('web.tuq_on_pc_route', _external=True)
    links.admin_reg = url_for('web.admin_signup_route', _external=True)
    links.index_url = url_for('web.index_page_route', _external=True)
    return render_template('submission.html', links=links, message=message)
Exemple #9
0
def admin():
    """used to administrate the users of the system"""
    if request.method == 'GET':
        # SELECT ALL USERS, ADMIN_USERS, AND LEAD ID
        users = controls.get_users_info()
        # GET LEAD FIRST / LAST BASED ON lead_id
        for user in users:
            # RETURNS A JSON ObJECT OF USERNAME, FIRST AND LAST
            lead = controls.get_lead(user['username'])
            if len(lead) > 0:
                user['lead_first'] = lead['first_name']
                user['lead_last'] = lead['last_name']
        return render_template('admin.html', users=users)
    elif request.method == 'POST':
        users = request.form.getlist('user')
        action = request.form['action']
        for user in users:
            if action == 'delete':
                controls.delete_user(user)
            elif action == 'admin':
                controls.update_user(user, is_admin=1)
            elif action == 'noadmin':
                controls.update_user(user, is_admin=0)
            elif action == 'auth':
                controls.update_user(user,
                                     auth_token=None,
                                     shard_id=None,
                                     authorized=0)
                session['authorized'] = 0
                session.pop('auth_token')
                session.pop('shard_id')
            elif action == 'pwd':
                controls.update_user(user, password='******')
        return redirect(url_for('admin'))
Exemple #10
0
def auth_start():
    """Makes a request to Evernote for the request token then redirects the
    user to Evernote to authorize the application using the request token.

    After authorizing, the user will be redirected back to auth_finish()."""
    #CHECK SHARD INFO
    client = get_oauth_client()

    # Make the request for the temporary credentials (Request Token)
    callback_ip = "%s:%d" %(app.config.get('IP'), app.config.get('PORT'))
    callback_url = 'http://%s%s' % (callback_ip, url_for('auth_finish'))
    request_url = '%s?oauth_callback=%s' % (app.config['EN_REQUEST_TOKEN_URL'],
        urllib.quote(callback_url, safe=":/"))

    resp, content = client.request(request_url, 'GET')

    if resp['status'] != '200':
        raise Exception('Invalid response %s.' % resp['status'])

    request_token = dict(urlparse.parse_qsl(content))

    # Save the request token information for later
    session['oauth_token'] = request_token['oauth_token']
    session['oauth_token_secret'] = request_token['oauth_token_secret']

    # Redirect the user to the Evernote authorization URL
    return redirect('%s?oauth_token=%s' % (app.config['EN_AUTHORIZE_URL'],
        urllib.quote(session['oauth_token'])))
Exemple #11
0
def add_repository_route():
    try:
        data = request.get_json()
        if data is None:
            return error_response('Invalid data')
        repository_name = data.get('repository_name')
        if repository_name is None or len(repository_name) == 0:
            return error_response('Invalid repository name supplied')
        for repo in current_user.repositories:
            if repo.repo_name == repository_name:
                return error_response(
                    'Repository with that name already exist in your account')
        repository = Repository(repo_name=repository_name)
        current_user.repositories.append(repository)

        safe_makedir(UPLOAD_DIR, current_user.username, repository_name)

        db.session.add(repository)
        db.session.add(current_user)
        db.session.commit()
        url = '{url}{username}/{repo}{ext}'.format(
            url=url_for('auth.auth_route', _external=True),
            username=current_user.username,
            repo=repository.repo_name,
            ext=EXT)
        return success_response(url)
    except BadRequest:
        return error_response('Bad request')
    except Exception as e:
        print(e)
        return error_response(
            'Unable to add repository, check the data and try again')
Exemple #12
0
def admin():
    """used to administrate the users of the system"""
    if request.method == 'GET':
        # SELECT ALL USERS, ADMIN_USERS, AND LEAD ID
        users = controls.get_users_info()
        # GET LEAD FIRST / LAST BASED ON lead_id
        for user in users:
            # RETURNS A JSON ObJECT OF USERNAME, FIRST AND LAST 
            lead = controls.get_lead(user['username'])
            if len(lead) > 0:
                user['lead_first'] = lead['first_name']
                user['lead_last'] = lead['last_name']
        return render_template('admin.html', users=users)
    elif request.method == 'POST':
        users = request.form.getlist('user')
        action = request.form['action']
        for user in users:
            if action == 'delete':
                controls.delete_user(user)
            elif action == 'admin':
                controls.update_user(user, is_admin=1)
            elif action == 'noadmin':
                controls.update_user(user, is_admin=0)
            elif action == 'auth':
                controls.update_user(user, auth_token=None, shard_id=None, authorized=0)
                session['authorized'] = 0
                session.pop('auth_token')
                session.pop('shard_id')
            elif action == 'pwd':
                controls.update_user(user, password='******')
        return redirect(url_for('admin'))
Exemple #13
0
def auth_start():
    """Makes a request to Evernote for the request token then redirects the
    user to Evernote to authorize the application using the request token.

    After authorizing, the user will be redirected back to auth_finish()."""
    #CHECK SHARD INFO
    client = get_oauth_client()

    # Make the request for the temporary credentials (Request Token)
    callback_ip = "%s:%d" % (app.config.get('IP'), app.config.get('PORT'))
    callback_url = 'http://%s%s' % (callback_ip, url_for('auth_finish'))
    request_url = '%s?oauth_callback=%s' % (app.config['EN_REQUEST_TOKEN_URL'],
                                            urllib.quote(callback_url,
                                                         safe=":/"))

    resp, content = client.request(request_url, 'GET')

    if resp['status'] != '200':
        raise Exception('Invalid response %s.' % resp['status'])

    request_token = dict(urlparse.parse_qsl(content))

    # Save the request token information for later
    session['oauth_token'] = request_token['oauth_token']
    session['oauth_token_secret'] = request_token['oauth_token_secret']

    # Redirect the user to the Evernote authorization URL
    return redirect(
        '%s?oauth_token=%s' %
        (app.config['EN_AUTHORIZE_URL'], urllib.quote(session['oauth_token'])))
Exemple #14
0
def login_route():
    try:
        data = request.get_json()
        if data is None:
            return respond_back(ERROR, 'Invalid request sent')
        username = data.get('username', None)
        password = data.get('password', None)

        student = db.session.query(User).filter_by(username=username).first()
        if student is None:
            return jsonify({'status': ERROR, 'detail': 'Invalid login detail'})
        if not student.verify_password(password):
            return jsonify({
                'status': ERROR,
                'detail': 'Invalid username or password'
            })
        login_user(student, False)
        return jsonify({
            'status':
            SUCCESS,
            'detail':
            current_user.fullname,
            'dp_link':
            current_user.display_picture,
            'endpoints':
            url_for('auth.get_endpoint_route', _external=True)
        })
    except BadRequest:
        return error_response('Invalid login request received.')
Exemple #15
0
def get_paper_route():
    data = get_data(60*60, request.args.get('url', None))
    if data is None:
        return invalid_url_error()
    fileid = data.get('id')
    random_number = randint(1, 300000)  # just a random number.
    return redirect(url_for('auth.get_question_route', file_id=fileid, path_generator=str(random_number), _external=True))
Exemple #16
0
def get_repositories_route():
    repositories = [{'name': repository.repo_name,
                     'url': '{url}{username}/{repo}{ext}'.format(url=
                                                                 url_for('auth.auth_route', _external=True),
                                                                 username=current_user.username,
                                                                 repo=repository.repo_name, ext=EXT),
                     'courses': [course.name for course in repository.courses]} for repository in
                    current_user.repositories]
    return jsonify({'status': 1, 'repositories': repositories, 'detail': 'Successful'})
Exemple #17
0
def settings():
    if request.method == 'GET':
        # GET USER INFO FOR SETTINGS
        user = controls.get_user_info(session.get('username'))
        if not user:
            return redirect(url_for('logout'))
        authorized_users = controls.get_authorized_users()
        lead = controls.get_lead(session.get('username'))
        if len(lead) == 0:
            lead = {'first_name': '', 'last_name': '', 'username': ''}
        else:
            lead = lead[0]
        return render_template('settings.html',
                               authorized_users=authorized_users,
                               lead=lead['username'],
                               user=user)
    elif request.method == 'POST':
        # UPDATE USER INFO WITH: ALL VALUES FROM THE FORM
        lead_id = request.form[
            'lead'] if request.form['lead'] != 'None' else None
        payload = {
            'first_name': request.form['first_name'],
            'last_name': request.form['last_name'],
            'lead_id': lead_id
        }
        if request.form['password'] != '':
            payload['password'] = request.form['password']
        if 'auth' in request.form:
            payload['authorized'] = 0
            payload['auth_token'] = None
            session.pop('shard_id')
            session.pop('auth_token')
            session['authorized'] = 0
        payload['use_email'] = request.form['use_email']
        #payload['use_email'] = 1 if 'use_email' in request.form else 0
        controls.update_user(session.get('username'), **payload)
        flash('Settings Updated Successfully')
        session['first_name'] = request.form['first_name']
        session['last_name'] = request.form['last_name']
        return redirect(url_for('settings', lead=lead_id))
Exemple #18
0
def admin_signup_route():
    form = AdminRequestForm()
    if form.validate_on_submit():
        submission_info = {'username': form.username.data, 'fullname': form.full_name.data,
                           'address': form.address.data, 'email': form.email.data,
                           'nationality': form.nationality.data, 'alias': form.display_name.data,
                           'mobile': form.phone_number.data, 'password': form.password.data }
        json_writer = MyJSONObjectWriter()
        json.dump(submission_info,json_writer, skipkeys=True, indent=2, separators=(',', ': '))
        data_string = json_writer.get_buffer()

        data_cache.hset('tuq:admin_requests', form.username.data, data_string)
        flash('Thank you for using Tuq services, {}'.format(form.full_name.data))
        return redirect(url_for('main.submission_made_route', _external=True))
    else:
        return render_template('admin_register.html', form=form)
Exemple #19
0
def upload():
    # THIS USES THE NEW_NOTE CALL, so going to move that to en_lib
    if request.method=='POST':
        upload_file = request.files['file']
        if upload_file and lib.allowed_file(upload_file.filename, app.config['ALLOWED_EXTENSIONS']):
            filename = upload_file.filename
            content = upload_file.stream.getvalue()
            # CHECK IF THIS NOTE WAS EXPORTED BY THE DESKTOP CLIENT AND IF SO STRIP OUT COMPONENTS
            pattern = re.compile('(.*?!\[CDATA\[)(.*?<\/en-note>)(.*?\]\]><\/content>.*)', re.DOTALL)
            m = pattern.search(content)
            if m is not None and len(m.group(2)) > 0:
                content = m.group(2) 
            flash(new_note(content=content, title=upload_file.filename))
            with open(os.path.join(app.config['UPLOADED_FILE_DEST'], filename), 'w') as f:
                f.write(content)
        return redirect(url_for('index'))
    else:
        return render_template('upload.html') 
Exemple #20
0
def register_user():
    """Create a user in the database"""
    error = None
    # REST CALLS
    authorized_users = controls.get_authorized_users()
    if request.method == 'POST':
        if len(request.form['username'].strip()) <= 0:
            error = 'Username cannot be blank'
        else:
            if controls.user_exists(request.form['username'].strip()):
                error = 'Username already exists'
            elif len(request.form['password'].strip()) <= 0:
                error = 'Password cannot be blank'
            elif not  lib.valid_email(request.form['email_address']):
                error='Invalid Email Address'
            else:
                if request.form['lead'] == 'None':
                    lead = None
                else:
                    lead = request.form['lead']
                if request.form['use_email'] == 'True':
                    use_email = 1
                else:
                    use_email = 0
                controls.create_user(request.form['username'], 
                                     request.form['password'],
                                     request.form['first_name'],
                                     request.form['last_name'],
                                     request.form['email_address'],
                                     lead,
                                     use_email)
                flash("New User was successfully registered")
                session['logged_in'] = True
                session['first_name'] = request.form['first_name']
                session['last_name'] = request.form['last_name']
                session['username'] = request.form['username']
                return redirect(url_for('login'))
    return render_template('register.html', 
                           error=error, 
                           authorized_users=authorized_users)
Exemple #21
0
def configure(guid_list=None):
    if request.method=='POST':
        guid_list = request.form.getlist('notebook')
        controls.update_user(session.get('username'), notebook_ids=','.join(guid_list))
        return redirect(url_for('configure'))
    else:    
        # CHECK IF THIS NEEDS SHARD/AUTH
        notebook_list=get_notebook_list(session.get('auth_token'), session.get('shard_id'))
        if guid_list is None:
            # CHECK AND SEE IF USER HAS SELECTED NOTEBOOKS
            guid_list = controls.get_notebook_ids(session.get('username'))
            if len(guid_list) == 1:
                guid_list = guid_list[0]['ids'].split(',')
            else:
                guid_list = None
        if guid_list is not None:
            for notebook in notebook_list:
                for guid in guid_list:
                    if guid == notebook['guid']:
                        notebook['selected'] = True
                        break    
    return render_template('configure.html', notebooks=notebook_list)
Exemple #22
0
def upload():
    # THIS USES THE NEW_NOTE CALL, so going to move that to en_lib
    if request.method == 'POST':
        upload_file = request.files['file']
        if upload_file and lib.allowed_file(upload_file.filename,
                                            app.config['ALLOWED_EXTENSIONS']):
            filename = upload_file.filename
            content = upload_file.stream.getvalue()
            # CHECK IF THIS NOTE WAS EXPORTED BY THE DESKTOP CLIENT AND IF SO STRIP OUT COMPONENTS
            pattern = re.compile(
                '(.*?!\[CDATA\[)(.*?<\/en-note>)(.*?\]\]><\/content>.*)',
                re.DOTALL)
            m = pattern.search(content)
            if m is not None and len(m.group(2)) > 0:
                content = m.group(2)
            flash(new_note(content=content, title=upload_file.filename))
            with open(os.path.join(app.config['UPLOADED_FILE_DEST'], filename),
                      'w') as f:
                f.write(content)
        return redirect(url_for('index'))
    else:
        return render_template('upload.html')
Exemple #23
0
def register_user():
    """Create a user in the database"""
    error = None
    # REST CALLS
    authorized_users = controls.get_authorized_users()
    if request.method == 'POST':
        if len(request.form['username'].strip()) <= 0:
            error = 'Username cannot be blank'
        else:
            if controls.user_exists(request.form['username'].strip()):
                error = 'Username already exists'
            elif len(request.form['password'].strip()) <= 0:
                error = 'Password cannot be blank'
            elif not lib.valid_email(request.form['email_address']):
                error = 'Invalid Email Address'
            else:
                if request.form['lead'] == 'None':
                    lead = None
                else:
                    lead = request.form['lead']
                if request.form['use_email'] == 'True':
                    use_email = 1
                else:
                    use_email = 0
                controls.create_user(request.form['username'],
                                     request.form['password'],
                                     request.form['first_name'],
                                     request.form['last_name'],
                                     request.form['email_address'], lead,
                                     use_email)
                flash("New User was successfully registered")
                session['logged_in'] = True
                session['first_name'] = request.form['first_name']
                session['last_name'] = request.form['last_name']
                session['username'] = request.form['username']
                return redirect(url_for('login'))
    return render_template('register.html',
                           error=error,
                           authorized_users=authorized_users)
Exemple #24
0
def auth_finish():
    """After the user has authorized this application on Evernote's website,
    they will be redirected back to this URL to finish the process."""

    oauth_verifier = request.args.get('oauth_verifier', '')

    token = oauth.Token(session['oauth_token'], 
                        session['oauth_token_secret'])
    token.set_verifier(oauth_verifier)

#    client = get_oauth_client()
    client = get_oauth_client(token)

    # Retrieve the token credentials (Access Token) from Evernote
    resp, content = client.request(app.config['EN_ACCESS_TOKEN_URL'], 'POST')

    if resp['status'] != '200':
        raise Exception('Invalid response %s.' % resp['status'])

    access_token = dict(urlparse.parse_qsl(content))
    authToken = access_token['oauth_token']
    
    # MAY NEED SHARD/AUTH
    userStore = get_userstore()
    user = userStore.getUser(authToken)

    # Save the users information to so we can make requests later
    session['shard_id'] = user.shardId
    session['auth_token'] = authToken
    
    # INSERT THE SESSION AND LINK TO THE USERID
    controls.update_user(session.get('username'),
                         auth_token=session.get('auth_token'), 
                         shard_id=session.get('shard_id'),
                         authorized=1)
    flash("Evernote Test Session Authorized!!")
    return redirect(url_for('index'))
Exemple #25
0
def auth_finish():
    """After the user has authorized this application on Evernote's website,
    they will be redirected back to this URL to finish the process."""

    oauth_verifier = request.args.get('oauth_verifier', '')

    token = oauth.Token(session['oauth_token'], session['oauth_token_secret'])
    token.set_verifier(oauth_verifier)

    #    client = get_oauth_client()
    client = get_oauth_client(token)

    # Retrieve the token credentials (Access Token) from Evernote
    resp, content = client.request(app.config['EN_ACCESS_TOKEN_URL'], 'POST')

    if resp['status'] != '200':
        raise Exception('Invalid response %s.' % resp['status'])

    access_token = dict(urlparse.parse_qsl(content))
    authToken = access_token['oauth_token']

    # MAY NEED SHARD/AUTH
    userStore = get_userstore()
    user = userStore.getUser(authToken)

    # Save the users information to so we can make requests later
    session['shard_id'] = user.shardId
    session['auth_token'] = authToken

    # INSERT THE SESSION AND LINK TO THE USERID
    controls.update_user(session.get('username'),
                         auth_token=session.get('auth_token'),
                         shard_id=session.get('shard_id'),
                         authorized=1)
    flash("Evernote Test Session Authorized!!")
    return redirect(url_for('index'))
Exemple #26
0
def configure(guid_list=None):
    if request.method == 'POST':
        guid_list = request.form.getlist('notebook')
        controls.update_user(session.get('username'),
                             notebook_ids=','.join(guid_list))
        return redirect(url_for('configure'))
    else:
        # CHECK IF THIS NEEDS SHARD/AUTH
        notebook_list = get_notebook_list(session.get('auth_token'),
                                          session.get('shard_id'))
        if guid_list is None:
            # CHECK AND SEE IF USER HAS SELECTED NOTEBOOKS
            guid_list = controls.get_notebook_ids(session.get('username'))
            if len(guid_list) == 1:
                guid_list = guid_list[0]['ids'].split(',')
            else:
                guid_list = None
        if guid_list is not None:
            for notebook in notebook_list:
                for guid in guid_list:
                    if guid == notebook['guid']:
                        notebook['selected'] = True
                        break
    return render_template('configure.html', notebooks=notebook_list)
Exemple #27
0
def index_page_route():
    links = Links()
    links.tuq_on_pc = url_for('web.tuq_on_pc_route', _external=True)
    links.admin_reg = url_for('web.admin_signup_route', _external=True)
    links.index_url = url_for('web.index_page_route', _external=True)
    return render_template('index.html', links=links)
Exemple #28
0
def get_endpoint_route():
    endpoints = { 'result': url_for( 'auth.get_result_route', _external=True ) }
    return respond_back(SUCCESS, endpoints)
Exemple #29
0
def index():
    error_list = None
    # CHECK IF THE USER IS LOGGED IN, OTHERWISE REDIRECT
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    # GET THE USER INFO, REDIRECT IF NOTHING IS RETURNED
    user = controls.get_user_info(session.get('username'))
    if not user:
        redirect(url_for('logout'))
    authorized_users = controls.get_authorized_users()
    # RETURNS A JSON ObJECT OF USERNAME, FIRST AND LAST
    lead = controls.get_lead(session.get('username'))
    if len(lead) == 0:
        lead = {'username': '', 'first_name': '', 'last_name': ''}
    else:
        lead = lead[0]
    notebooks = []
    if session.get('auth_token'):
        # CHECK AND SEE IF USER HAS SELECTED NOTEBOOKS
        if user['notebook_ids'] is not None and len(user['notebook_ids']) > 0:
            guid_list = user['notebook_ids'].split(',')
            flash("Getting Notebooks and Notes")
            notebooks = get_notebooks(session.get('auth_token'),
                                      session.get('shard_id'), guid_list)
        else:
            return redirect(url_for('configure', guid_list=None))
    # POST REQUESTS
    if request.method == 'POST':
        error_list = []
        note_list = request.form.getlist('note')
        # GET THE NOTE CONTENT FOR EACH NOTES GUID
        for value in note_list:
            try:
                title, guid = value.split(':')
                note = get_note(session.get('auth_token'),
                                session.get('shard_id'), guid)
            except Exception as e:
                error = "Error retrieving note using guid %s" % e
                return render_template('main.html', error=error)
            # ATTEMPT TO PARSE THE NOTE INTO A ENXML OBJECT
            # GET DOCTYPE FROM NOTE CONTENT
            rg = re.compile('(<!DOCTYPE .*?>)')
            m = rg.search(note)
            try:
                # CREATE EN OBJECT INITILIZING WITH NOTE AND DOCTYPE
                en = EN(note, doctype=m.group(1))
                # BREAK OUT TABLES
                en.break_out_tables()
                try:
                    en.set_activity_type('O')
                    en.set_activity_type('I')
                except:
                    error_list.append(
                        "Using an old Template, update your template in the future"
                    )
                    error_list.append(
                        "Unable to set Issues and Activities within the note")
                flash(
                    update_note(session.get('auth_token'),
                                session.get('shard_id'),
                                en.tostring(),
                                guid=guid,
                                title=title))
                # IF EMAIL IS SET
                if user['use_email'] == 1:
                    lib.send_email(en, app.config['EMAIL_SERVER'],
                                   user['email_address'])
                    flash("Note sent as email to %s" % user['email_address'])
                # IF LEAD IS SET
                if request.form['lead'] != 'None':
                    # GET LEAD AUTH_TOKEN
                    lead = controls.get_user_info(request.form['lead'])
                    flash(
                        new_note(shard_id=lead['shard_id'],
                                 content=en.tostring(),
                                 title=title,
                                 auth_token=lead['auth_token']))
                    flash("Sent note to lead: %s" % request.form['lead'])
                    controls.set_lead(session.get('username'),
                                      request.form['lead'])
                # CHANGE THE USERS LEAD ID TO THAT USED
                else:
                    controls.delete_lead(session.get('username'))
                    lead = {'username': '', 'first_name': '', 'last_name': ''}
                flash("Bug Time: %s" % en.times['B'])
                flash("Setup Time: %s" % en.times['S'])
                flash("Test Time: %s" % en.times['T'])
                flash("Session Length: %s" % en.session_length)
                en.export_xml(app.config['UPLOADED_FILE_DEST'],
                              "%s.xml" % title)
            except Exception as e:
                error_list.append(
                    "ERROR parsing out data from note %s. Exception: [%s]" %
                    (title, e))
    return render_template('main.html',
                           notebooks=notebooks,
                           error=error_list,
                           authorized_users=authorized_users,
                           lead=lead)
Exemple #30
0
def logout():
    for key in session.keys():
        session.pop(key, None)
    flash('You were logged out')
    return redirect(url_for('index'))
Exemple #31
0
def logout():
    for key in session.keys():
        session.pop(key, None)
    flash('You were logged out')
    return redirect(url_for('index'))
Exemple #32
0
def index():
    error_list = None
    # CHECK IF THE USER IS LOGGED IN, OTHERWISE REDIRECT
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    # GET THE USER INFO, REDIRECT IF NOTHING IS RETURNED
    user = controls.get_user_info(session.get('username'))
    if not user:
        redirect(url_for('logout'))
    authorized_users = controls.get_authorized_users()
    # RETURNS A JSON ObJECT OF USERNAME, FIRST AND LAST 
    lead = controls.get_lead(session.get('username'))
    if len(lead) == 0:
        lead = {'username':'', 'first_name':'', 'last_name':''}
    else:
        lead = lead[0]
    notebooks = []
    if session.get('auth_token'):
        # CHECK AND SEE IF USER HAS SELECTED NOTEBOOKS
        if user['notebook_ids'] is not None and len(user['notebook_ids']) > 0:
            guid_list = user['notebook_ids'].split(',')
            flash("Getting Notebooks and Notes")
            notebooks = get_notebooks(session.get('auth_token'), 
                                      session.get('shard_id'),
                                      guid_list) 
        else:
            return redirect(url_for('configure', guid_list=None))         
    # POST REQUESTS
    if request.method=='POST':
        error_list = []
        note_list = request.form.getlist('note')
        # GET THE NOTE CONTENT FOR EACH NOTES GUID
        for value in note_list:
            try:
                title, guid = value.split(':')
                note = get_note(session.get('auth_token'), 
                                session.get('shard_id'),
                                guid)
            except Exception as e:
                error = "Error retrieving note using guid %s" %e
                return render_template('main.html', 
                                       error=error)
            # ATTEMPT TO PARSE THE NOTE INTO A ENXML OBJECT
            # GET DOCTYPE FROM NOTE CONTENT
            rg = re.compile('(<!DOCTYPE .*?>)')
            m = rg.search(note)
            try:
                # CREATE EN OBJECT INITILIZING WITH NOTE AND DOCTYPE
                en = EN(note, doctype=m.group(1))
                # BREAK OUT TABLES
                en.break_out_tables()
                try:
                    en.set_activity_type('O')
                    en.set_activity_type('I')
                except:
                    error_list.append("Using an old Template, update your template in the future")
                    error_list.append("Unable to set Issues and Activities within the note")
                flash(update_note(session.get('auth_token'),
                                  session.get('shard_id'),
                                  en.tostring(), 
                                  guid=guid, 
                                  title=title))
                # IF EMAIL IS SET
                if user['use_email'] == 1:
                    lib.send_email(en, app.config['EMAIL_SERVER'], user['email_address'])
                    flash("Note sent as email to %s" %user['email_address'])
                # IF LEAD IS SET
                if request.form['lead'] != 'None':
                    # GET LEAD AUTH_TOKEN
                    lead = controls.get_user_info(request.form['lead'])
                    flash(new_note(shard_id=lead['shard_id'],
                                   content=en.tostring(), 
                                   title=title, 
                                   auth_token=lead['auth_token']))
                    flash("Sent note to lead: %s" %request.form['lead'])
                    controls.set_lead(session.get('username'), request.form['lead'])
                # CHANGE THE USERS LEAD ID TO THAT USED
                else: 
                    controls.delete_lead(session.get('username'))
                    lead = {'username':'', 'first_name':'', 'last_name':''}
                flash("Bug Time: %s" %en.times['B'])
                flash("Setup Time: %s" %en.times['S'])
                flash("Test Time: %s" %en.times['T'])
                flash("Session Length: %s" %en.session_length)
                en.export_xml(app.config['UPLOADED_FILE_DEST'], "%s.xml" %title)
            except Exception as e:
                error_list.append("ERROR parsing out data from note %s. Exception: [%s]" %(title, e))
    return render_template('main.html',
                            notebooks=notebooks, 
                            error=error_list,
                            authorized_users=authorized_users,
                            lead=lead) 
Exemple #33
0
def main_route():
    endpoints = {
        'login_to': url_for('main.login_route', _external=True),
        'add_user': url_for('main.signup_route', _external=True),
        'add_repository': url_for('auth.add_repository_route', _external=True),
        'add_course': url_for('auth.admin_add_course_route', _external=True),
        'get_repositories': url_for('auth.get_repositories_route',
                                    _external=True),
        'get_courses': url_for('auth.get_courses_route', _external=True),
        'upload_image': url_for('auth.upload_image_route', _external=True),
        'upload_file': url_for('auth.upload_file_route', _external=True),
        'delete_repo': url_for('auth.delete_repository_route', _external=True),
        'delete_course': url_for('auth.delete_course_route', _external=True),
        'edit_course': url_for('auth.edit_course_route', _external=True),
        'list_partakers': url_for('auth.list_partakers_route', _external=True),
        'delete_score': url_for('auth.delete_exam_info_route', _external=True)
    }
    return jsonify({'status': SUCCESS, 'endpoints': endpoints})