Exemple #1
0
def user_config_get():
    if request.method == 'GET':
        return UserController.serve_user_config_form()
    elif request.method == 'POST':
        return UserController.handle_user_config_form()
    else:
        raise CairisHTTPError(httplib.NOT_FOUND, message='Not found')
Exemple #2
0
def apilogin():
    auth = request.authorization
    if not auth or not auth.username:
        return make_response(
            'Username required!', 401,
            {'WWW-Authenticate': 'Basic realm="Username required!"'})

    if not auth.password:
        return make_response(
            'Password required!', 401,
            {'WWW-Authenticate': 'Basic realm="Password required!"'})

    if av.is_username_valid(auth.username) and av.is_password_valid(
            auth.password):
        uc = UserController()
        user = uc.getuser(username=auth.username)
        if user:
            if check_password_hash(user.password, auth.password):
                token = jwt.encode(
                    {
                        'username':
                        auth.username,
                        'exp':
                        datetime.datetime.utcnow() +
                        datetime.timedelta(minutes=60)
                    }, app.config['SECRET_KEY'])
                return jsonify({'token': token})

    return make_response('Invalid user or password!', 401,
                         {'WWW-Authenticate': 'Basic realm="Invalid user!"'})
Exemple #3
0
def object_store():
    global user_controller
    user_controller = UserController()
    names = user_controller.get_db_names()
    return render_template('object_store_devel.html',
                           db_names=names,
                           timestamps=user_controller.get_timestamps(),
                           no_of_obj=user_controller.get_no_objs())
def users(page_num):
    if not current_user.group == 'admin':
        abort(401)

    uc = UserController()
    users = uc.getusers()
    return render_template('users.html',
                           username=current_user.username,
                           users=users)
Exemple #5
0
    def createExpertSession(self, gname, fname, email, institution, product,
                            question, extId):

        print('\n[main] Acquiring auth token...\n')
        authorized_session = AuthController.AuthController(
            self.URL, self.COLLAB_KEY, self.COLLAB_SECRET, self.COLLAB_CERTS)
        authorized_session.setToken()
        print('\n[main] Returned token: ' + authorized_session.getToken() +
              '\n')

        user = User.User(gname, fname,
                         gname + " " + fname + "(" + institution + ")", extId,
                         email)

        print("User: "******"moderator")
        clientUrl = sessions.enrollUser(session_id, user.getUserJson(),
                                        "presenter")

        print("Client URL: " + clientUrl)
        print("SME URL: " + smeUrl)

        print("[main] Processing Complete")

        return ({'expert_url': smeUrl, 'client_url': clientUrl})
def adduser():
    if current_user.group != 'admin':
        abort(401)

    form = UsersForm()
    if form.validate_on_submit():
        uc = UserController()
        hashed_pw = generate_password_hash(form.password.data,
                                           method='pbkdf2:sha256:260000',
                                           salt_length=16)
        user_data = {
            'user': form.username.data,
            'group': form.group.data,
            'password': hashed_pw
        }
        uc.adduser(user_data)
        return redirect(url_for('users', page_num=1))

    return render_template('register.html', form=form)
def login():
    msg = None
    form = LoginForm()
    remember = False
    nexturl = request.args.get('next', None)
    if form.validate_on_submit():
        uc = UserController()
        user = uc.getuser(username=form.username.data)
        if user:
            if check_password_hash(user.password, form.password.data):
                if form.remember.data:
                    remember = True

                login_user(user, remember=remember)
                if nexturl:
                    return redirect(nexturl)

                return redirect(url_for('home'))
        msg = "Invalid username or password!"

    return render_template('login.html', form=form, msg=msg, nexturl=nexturl)
def save_project(request, id):
    data = request.json
    project = Project({
        "title": data["title"],
        "platforms": data["platforms"],
        "description": data["description"],
        "screenshot": data["screenshot"],
        "technologies": data["technologies"]
    })
    project.m.save()
    project = decode.decode_object_id(project)
    return UserController.add_project(id, project._id)
def reset():
    uid = request.args.get('uid', None)
    if current_user.group != 'admin':
        if current_user.id != int(uid):
            abort(401)

    form = UsersFormPassword()
    if form.validate_on_submit():
        hashed_pw = generate_password_hash(form.password.data,
                                           method='pbkdf2:sha256:260000',
                                           salt_length=16)
        uc = UserController()
        user_data = {'uid': int(form.uid.data), 'password': hashed_pw}
        uc.edituser(user_data, updatepw=True)

        if current_user.id == int(uid):
            return redirect(url_for('logout'))
        else:
            return redirect(url_for('users', page_num=1))

    form.uid.data = uid
    return render_template('resetpw.html', form=form)
Exemple #10
0
def user_info_component(controller: UserController, user_name: str):
    user = controller.get_by_username(user_name)

    return html.Div([
        html.Table([
            html.Thead(
                html.Tr([
                    html.Th("Attribute"),
                    html.Th("Value")
                ])
            ),
            html.Tbody([
                html.Tr([
                    html.Td("Profile Image"),
                    html.Td(
                        html.Img(
                            src=user.profile_image_url,
                            width=128,
                            height=128
                        )
                    )
                ]),
                html.Tr([
                    html.Td("Username"),
                    html.Td(user.user_name)
                ], className='bg-blue-200'),
                html.Tr([
                    html.Td("Name"),
                    html.Td(user.name)
                ]),
                html.Tr([
                    html.Td("Url"),
                    html.Td(html.A(user.url, href=user.url))
                ], className='bg-blue-200'),
                html.Tr([
                    html.Td("Followers"),
                    html.Td(user.followers)
                ]),
                html.Tr([
                    html.Td("Following"),
                    html.Td(user.following)
                ], className='bg-blue-200'),
                html.Tr([
                    html.Td("Likes"),
                    html.Td(user.likes)
                ]),
            ])
        ],
            className='table-auto')
    ], className='flex-col border-2 rounded-md border-blue-700 m-2 p-2')
def user(user_id):
    if not current_user.is_authenticated:
        abort(401)

    form = UsersFormEdit()
    uc = UserController()
    user = uc.getuser(uid=user_id)
    if not user:
        abort(404)

    if current_user.group != 'admin':
        if current_user.username != user.username:
            abort(401)

    if form.validate_on_submit():
        user_data = {}
        if form.delete.data == 'Y':
            user_data['uid'] = user.id
            uc.deleteuser(user_data)
            return redirect(url_for('users', page_num=1))
        else:
            user_data['username'] = form.username.data
            user_data['uid'] = user.id
            user_data['group'] = form.group.data
            uc.edituser(user_data)
            return redirect(url_for('users', page_num=1))

    form.username.data = user.username
    form.group.data = user.group
    delete = request.args.get('delete', None)
    if delete:
        form.delete.data = 'Y'
    else:
        form.delete.data = 'N'

    return render_template('user.html',
                           username=current_user.username,
                           form=form,
                           uid=user.id)
Exemple #12
0
#!/usr/bin/env python
from __future__ import print_function  # In python 2.7
from flask import Flask, render_template, request, jsonify
from gevent.pywsgi import WSGIServer
import sys
import json
from controllers import UserController

app = Flask(__name__)
app.config.from_pyfile('app.cfg')
queries_list = []
user_controller = UserController()


@app.route('/', methods=['GET', 'POST'])
@app.route('/query', methods=['GET', 'POST'])
def index():
    print("Rendering rs_live.html", file=sys.stderr)
    return render_template('rs_live.html')


@app.route('/store', methods=['GET', 'POST'])
def object_store():
    global user_controller
    user_controller = UserController()
    names = user_controller.get_db_names()
    return render_template('object_store_devel.html',
                           db_names=names,
                           timestamps=user_controller.get_timestamps(),
                           no_of_obj=user_controller.get_no_objs())
Exemple #13
0
def get_user_information(user_id):
    result = UserController.get_profile(user_id)
    if result:
        return make_response(jsonify(result))
    else:
        return abort(404)
Exemple #14
0
def authorization(code):
    UserController.auth(code)
Exemple #15
0
def get_user(id):
    res = UserController.get_user(id=id)
    if not res:
        raise exceptions.NotFound()
    return res
Exemple #16
0
def login():
    return UserController.login()
Exemple #17
0
def register():
    return UserController.register()
Exemple #18
0
def signin():
    return UserController.signin()
def load_user(user_id):
    uc = UserController()
    return uc.getuser(uid=int(user_id))
Exemple #20
0
def signup():
    return UserController.signup()
Exemple #21
0
def main(datadir,courses,users):

    COURSES = False
    USERS = False

    if not courses and not users:
        COURSES = True
        USERS = True
    else:
        if courses:
            COURSES = True
        if users:
            USERS = True

    preflight(datadir,COURSES,USERS)

    try:
        dictConfig(Config.logging)
        logger = logging.getLogger('main')
    except KeyError:
        print("Invalid configuration in Config.py: logging missing")
        sys.exit()

    logger.debug("datadir: " + datadir + ", COURSES: " + str(COURSES) + ", USERS: " + str(USERS))

    try:
        if Config.collab['verify_certs'] == 'True':
            VERIFY_CERTS = True
        else:
            VERIFY_CERTS = False
    except KeyError:
        errMsg = "Invalid configuration in Config.py: collab.verify_certs missing."
        logger.critical(errMsg)
        sys.exit()
    
    logger.info("Starting bulk creation process")

    try:
        authorized_session = AuthController.AuthController(Config.collab['collab_base_url'],Config.collab['collab_key'],Config.collab['collab_secret'],VERIFY_CERTS)
        authorized_session.setToken()
    except ValueError:
        errMsg = "Invalid configuration in Config.py: collab settings missing or incomplete"
        logger.critical(errMsg)
        sys.exit()

    ctxDict = {}
    usrDict = {}
    sesDict = {}

    try:
        ctxCtrl = ContextController.ContextController(Config.collab['collab_base_url'], authorized_session, VERIFY_CERTS)
        usrCtrl = UserController.UserController(Config.collab['collab_base_url'], authorized_session, VERIFY_CERTS)
        sesCtrl = SessionController.SessionController(Config.collab['collab_base_url'], authorized_session, VERIFY_CERTS)
    except KeyError:
        errMsg = "Invalid configuration in Config.py: collab settings missing or incomplete"
        logger.critical(errMsg)
        sys.exit()

    try:
        session_config = Config.session_settings
    except KeyError:
        errMsg = "Invalid configuration in Config.py: session settings missing"
        logger.critical(errMsg)
        sys.exit()

    try:
        teachercsv = open('output/teacherenrollments.csv', 'w', newline='')
        teacherwriter = csv.writer(teachercsv, delimiter=',', quotechar='"')
        teacherwriter.writerow([ 'TEACHERID', 'TEACHEREMAIL', 'COURSENAME', 'URL'])

        studentcsv = open('output/studentenrollments.csv', 'w', newline='')
        studentwriter = csv.writer(studentcsv, delimiter=',', quotechar='"')
        studentwriter.writerow([ 'COURSEID', 'TEACHERID', 'TEACHERNAME', 'STUDENTID', 'STUDENTNAME', 'STUDENTEMAIL', 'COURSENAME', 'URL'])

    except Exception as e:
        errMsg = "Error opening output file: " + str(e)
        logger.critical(errMsg)
        sys.exit()

    if COURSES:
        with open(datadir + '/course.csv', newline='') as csvfile:
                courses = csv.reader(csvfile, delimiter=',', quotechar='"')

                next(courses)

                for course in courses:

                    crsId = course[0]
                    crsName = course[1]
                    insId = course[2]
                    insName = course[3]
                    insEmail = course[4]

                    if insEmail is None or insEmail == "":
                        logger.error("Instructor <" + insName + "> email address is blank")
                        continue
                    elif validate_email(insEmail) == False:
                        logger.error("Instructor <" + insName + "> does not have a valid email address: <" + insEmail + ">")
                        continue

                    logger.debug(crsId + ',' + crsName + ',' + insId + ',' + insName + ',' + insEmail)
                    
                    try:
                        ctxId = ctxCtrl.getContext(crsName)

                        if ctxId['contextId'] is None:
                            ctx = Context.Context(crsName,crsName,crsName,crsId)
                            ctxres = ctxCtrl.createContext(ctx.getContextJson())

                            for k in ctxres:
                                result = k
                                break

                            if result == '200':
                                ctxId = { 'contextId' :  ctxres[result]}
                            else:
                                logger.error("Error creating context for course " + crsName + ", " + result + ": " + ctxres[result])
                                continue

                        logger.debug(ctxId['contextId'])

                        ctxDict[crsId] = {
                            "contextId" : ctxId['contextId'],
                            "teacherId" : insId
                        }
                    except Exception as e:
                        logger.error("Error creating Context: " + str(e))
                        continue

                    try:
                        ses = Session.Session(crsName, crsName, str(datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")), None, session_config)
                        sesres = sesCtrl.createSession(ses.getSessionJson())

                        logger.debug(ses.getSessionJson())

                        for k in sesres:
                            result = k
                            break

                        if result == '200':
                            ses.setId(sesres[result])
                            logger.info("Session: " + ses.getId() + ", CREATED, for course " + crsName)
                        else:
                            logger.error("Error creating session for course " + crsName + ", " + result + ": " + sesres[result])
                            continue
                        
                        sesDict[crsId] = ses
                    except Exception as e:
                        logger.error("Error creating Session: " + str(e))
                        continue

                    try:
                        if ctxCtrl.assignSessionToContext(ctxId['contextId'],ses.getId()) == False:
                            logger.error("Error assigning session to context for course " + crsName + ", session: " + ses.getId() + ", context: " + ctxId['contextId'])
                            continue
                    except Exception as e:
                        logger.error("Error assigning session to Context: " + str(e))
                        continue

                    try:
                        teacher = User.User(insName,insId,insEmail)

                        teacherres = usrCtrl.createUser(teacher.getUserJson())

                        for k in teacherres:
                            result = k
                            break

                        if result == '200':
                            teacher.setId(teacherres[result])
                        else:
                            logger.error("Error creating user " + insName + " for course " + crsName + ", " + result + ": " + teacherres[result])
                            continue

                        logger.debug(teacher.getUserJson())
                        usrDict[insId] = teacher
                    except Exception as e:
                        logger.error("Error creating user " + insName + " for course " + crsName + ": " + str(e))
                        continue

                    try:
                        urlres = sesCtrl.enrollUser(ses.getId(),teacher.getId(),'moderator')

                        for k in urlres:
                            result = k
                            break

                        if result == '200':
                            teacherUrl = urlres[result]
                        else:
                            logger.error("Error creating enrollment " + insName + " for course " + crsName + ", " + result + ": " + urlres[result])
                            continue
                    except Exception as e:
                        logger.error("Error creating enrollment " + insName + " for course " + crsName + ": " + str(e))
                        continue
                                    
                    try:
                        teacherwriter.writerow([ teacher.getExtId(), teacher.getEmail(), ses.getName(), teacherUrl])

                        logger.info("Session link: " + teacherUrl + " for User: "******" CREATED for course " + crsName)
                    except KeyError as ke:
                        logger.error("Error writing teacher enrollment information: " + str(ke))
                        continue

    if USERS:
        with open(datadir + '/student.csv', newline='') as csvfile:
                users = csv.reader(csvfile, delimiter=',', quotechar='|')

                next(users)

                for user in users:
                    logger.debug('Students: ' + str(user))

                    studentId = user[0]
                    studentName = user[1]
                    studentEmail = user[2]

                    if studentEmail is None or studentEmail == "":
                        logger.error("Student <" + studentName + "'s> is blank")
                        continue
                    elif validate_email(studentEmail) == False:
                        logger.error("Student <" + studentName + "> does not have a valid email address: <" + studentEmail + ">")
                        continue

                    try:
                        student = User.User(studentName,studentId,studentEmail)

                        studentres = usrCtrl.createUser(student.getUserJson())

                        for k in studentres:
                            result = k
                            break

                        if result == '200':
                            student.setId(studentres[result])
                            logger.info("Student: " + student.getId() + ", CREATED, for user " + student.getDisplayName())
                        else:
                            logger.error("Error creating user " + studentName + ", " + result + ": " + studentres[result])
                            continue

                        logger.debug(student.getUserJson())
                        usrDict[studentId] = student
                    except Exception as e:
                        logger.error("Error creating student " + studentName + ": " + str(e))
                        continue

        with open(datadir + '/enrollment.csv', newline='') as csvfile:
                enrollments = csv.reader(csvfile, delimiter=',', quotechar='|')

                next(enrollments)

                for enrollment in enrollments:
                    logger.debug('Enrollments: ' + str(enrollment))

                    courseId = enrollment[0]
                    studentId = enrollment[1]

                    try:
                        session = sesDict[courseId]
                    except KeyError:
                        logger.error("courseId " + courseId + " not found")
                        continue

                    try:
                        user = usrDict[studentId]
                    except KeyError:
                        logger.error("studentId " + studentId + " not found")
                        continue

                    try:
                        urlres = sesCtrl.enrollUser(session.getId(),user.getId(),'participant')

                        for k in urlres:
                            result = k
                            break

                        if result == '200':
                            studentUrl = urlres[result]
                        else:
                            logger.error("Error creating enrollment " + user.getDisplayName() + " for course " + session.getName() + ", " + result + ": " + urlres[result])
                            continue
                    except Exception as e:
                        logger.error("Error creating enrollment " + user.getDisplayName() + " for course " + session.getName() + ": " + str(e))
                        continue
              
                    try:
                        studentwriter.writerow([ courseId, ctxDict[courseId]['teacherId'], usrDict[ctxDict[courseId]['teacherId']].getDisplayName(), user.getExtId(), user.getDisplayName(), user.getEmail(), session.getName(), studentUrl])

                        logger.info("Session link: " + studentUrl + " for User: "******" CREATED for course " + session.getName())
                    except KeyError as ke:
                        logger.error("Error writing student enrollment information: " + str(ke))
                        continue

    logger.info("Bulk creation processing complete")
Exemple #22
0
def logout():
    return UserController.logout()
Exemple #23
0
def getUserLatestResult(user_code):
	return UserController.getUserLatestResult(user_code)
def user() :
	if request.method == "POST" :
		return UserController.update(request.form)
	return UserController.view()
Exemple #25
0
    # Fertilizer routes
    (Fertilizer.as_view(), '/api/fertilizers'),
    (Fertilizer.as_view(), '/api/fertilizers/<id:\w{32}>'),
    (Fertilizer.as_view(), '/api/fertilizers/<id:all>'),

    # Lab routes
    (Lab.as_view(), '/api/labs'),
    (Lab.as_view(), '/api/labs/<id:\w{32}>'),
    (Lab.as_view(), '/api/labs/<id:all>'),

    # Land routes
    (Land.as_view(), '/api/lands'),
    (Land.as_view(), '/api/lands/<id:\w{32}>'),
    (Land.as_view(), '/api/lands/<id:all>'),

    # Recomendation routes
    (Recomendation.as_view(), '/api/recomendation'),

    # User routes
    (User.as_view(), '/api/users'),
    (User.as_view(), '/api/users/<id:\w{32}>'),
    (User.as_view(), '/api/users/<id:all>'),

    # SignIn routes
    (SignIn.as_view(), '/api/sign-in'),

    # SignOut routes
    (SignOut.as_view(), '/api/sign-out'),
]