Beispiel #1
0
def do_login():
    username = request.forms.username
    password = request.forms.password
    user = User.login(username, password)
    if not user:
        return {"error": "Invalid credentials."}

    create_session(user)
    return redirect("/")
Beispiel #2
0
async def play_trivia(message):
    question = trivia.get_question()
    embed = discord.Embed(color=theme_color, title=question.question)
    desc = ' '.join([
        '%s. %s\t' % (key, question.options[key]) for key in question.options
    ])
    embed.description = desc
    embed.set_footer(text='Powered by OpenTriviaDB')
    await client.send_message(message.channel, embed=embed)
    session.create_session(message.server.id,
                           message.channel, [str(message.author)],
                           trivia.get_callback(question))
Beispiel #3
0
    def test_create_session(self, mock_DB):
        from session import create_session
        db_instance = mock_DB.return_value
        mock_session = Mock()
        db_instance.getSession.return_value = mock_session
        create_session()
        mock_DB.assert_called_once_with('teresa teng', '123456', '192.168.1.1', 'test')
        util.get_value_from_ssm_parameter_store.assert_has_calls([call('/_username'), call('/rds/_password')])
        db_instance.getSession.assert_called_once()

        # restore mock
        util.get_value_from_ssm_parameter_store = original_get_value_from_ssm_parameter_store
        DB.get_rds_host = original_get_rds_host
Beispiel #4
0
def do_pull(args):
    """
    Call appropriate pull function based on arguments
    Default is to pull everything from the instance
    """
    session = create_session(path=config_path(), name=args.name)
    path = os.path.normpath(args.directory)

    if args.category:
        if args.library:
            library.pull(session=session,
                         path=path,
                         category=args.category,
                         name=args.library)
            return

        if args.operation_type:
            operation_type.pull(session=session,
                                path=path,
                                category=args.category,
                                name=args.operation_type)
            return

        category.pull(session=session, path=path, name=args.category)
        return

    if args.library or args.operation_type:
        logging.error(
            'To pull an operation type or library, you must enter a category')
        return

    instance.pull(session=session, path=path)
    return
Beispiel #5
0
 def __init__(self, config_file):
     self.config_file = config_file
     # parse config file
     self.session = session.create_session(config_file)
     # DB access
     # SLOW PART
     self.slow_answer = None
Beispiel #6
0
def do_create(args):
    session = create_session(path=config_path(), name=args.name)
    path = os.path.normpath(args.directory)

    if args.category:

        if args.operation_type:
            operation_type.create(session=session,
                                  path=path,
                                  category=args.category,
                                  name=args.operation_type)
            operation_type.pull(session=session,
                                path=path,
                                category=args.category,
                                name=args.operation_type)
            return

        if args.library:
            library.create(session=session,
                           path=path,
                           category=args.category,
                           name=args.library)
            library.pull(session=session,
                         path=path,
                         category=args.category,
                         name=args.library)
            return

        logging.error(
            "To create an operation type or library, you must enter a name.")
Beispiel #7
0
    def add_term_widget(self, cfg):
        layout = TermBoxLayout()

        ti = TabbedPanelHeader()
        ti.text = ' '.join([str(len(self.root_widget.term_panel.tab_list) + 1), 'Terminal'])
        ti.content = layout
        ti.size_hint = (1,1)

        self.root_widget.term_panel.add_widget(ti)

        session = create_session(cfg, self.create_terminal(cfg))

        term_widget = TermTextInput(session)
        term_widget.size_hint = (1, 1)
        term_widget.pos_hint = {'center_y':.5, 'center_x':.5}

        layout.add_widget(term_widget)
        layout.term_widget = term_widget

        ti.term_widget = term_widget
        ti.session = session

        ti.session.term_widget = term_widget
        ti.session.terminal.term_widget = term_widget

        Clock.unschedule(self.root_widget.term_panel._load_default_tab_content)
        self.switch_to_tab(ti)

        conn_str = cfg.get_conn_str()

        if conn_str in self.conn_history:
            self.conn_history.remove(conn_str)

        self.conn_history.insert(0, conn_str)
Beispiel #8
0
	def on_post(self, request, response):
		try:
			params = json.loads(request.stream.read())
		except json.JSONDecodeError:
			raise falcon.HTTPBadRequest()

		username = params.get("username")
		password = params.get("password")

		if not _validate_user(username):
			raise falcon.HTTPBadRequest(description="Invalid username")

		if not _validate_password(password):
			raise falcon.HTTPBadRequest(description="Invalid password")

		with sql() as db_session:
			user = db_session.query(models.User).filter((models.User.email==username) | (models.User.email==username+"@ravens.benedictine.edu")).first()
			if user is None:
				response.status = falcon.HTTP_NO_CONTENT
				return
			if _check_password(user, password):
				sess = session.create_session(user.student_id)
				response.media = {"token": sess.token, "success": 1}
			else:
				response.media = {"token": "", "success": 0}
Beispiel #9
0
    def _create_window(self, cfg):
        window = TermPygletWindow()
        session = create_session(cfg, self.create_terminal(cfg))
        session.on_session_stop = self._on_session_stop
        session.term_widget = window
        session.window = window
        session.terminal.term_widget = window
        window.session = session
        window.tab_width = session.get_tab_width()

        self._windows.append(window)
Beispiel #10
0
    def _create_window(self, cfg):
        window = TermPygletWindow()
        session = create_session(cfg, self.create_terminal(cfg))
        session.on_session_stop = self._on_session_stop
        session.term_widget = window
        session.window = window
        session.terminal.term_widget = window
        window.session = session
        window.tab_width = session.get_tab_width()

        self._windows.append(window)
Beispiel #11
0
    def post(self):
        '''Handles a request to prepare a session.'''
        # always respond in JSON format
        self.set_header('Content-Type', 'application/json')
        # get info about the user
        username = self.current_user
        
        # decode params
        args = json.loads(self.request.body)
        try:
            key = args['key']
        except KeyError:
            # no key given, abort
            log.warn('admin rejected user %s prep, missing key', username)
            raise tornado.web.HTTPError(400)
        # get collab flag
        collab = args.get('collab', True)
        cacheState = args.get('cacheState', False)
        try:
            # check if there is a session for this key already            
            sessionId = self.application.get_session_id(key, collab, cacheState)
        except KeyError:
            sessionId = None

        # allow container to dictate session access
        access = self._container.access
        sessionInfo = access.on_admin_request(username, key, collab)

        if sessionId is None:
            # create a new session if not started yet
            # if we made it here, user has permission to do so
            sess = session.create_session(
                collab,
                key=key,
                cacheState=cacheState,
                container=self._container,
                deadAfter=self._container.cowebIdleTimeout,
                exts=[bayeux.BayeuxAuthExt, bayeux.BayeuxAckExt]
            )
            # create a new session
            sess.start_session()
            sessionId = sess.sessionId

        # return session info
        resp = {
            'sessionurl': self.application.get_session_url(sessionId),
            'sessionid' : sessionId,
            'key': key,
            'collab': collab,
            'info': sessionInfo,
            'username' : username
        }
        self.write(resp)
Beispiel #12
0
def db_session():
    session = None
    try:
        session = create_session()
        yield session
        session.commit()
    except:
        if session:
            session.rollback()
        logger.exception('error occurs')
    finally:
        Session.remove()
def db_session():
    session = None
    try:
        session = create_session()
        yield session
        session.commit()
    except:
        if session:
            session.rollback()
        logger.exception('error occurs')
    finally:
        Session.remove()
Beispiel #14
0
    def _create_new_tab(self, win, view):
        win.tabview.add_item(view)

        cfg = view.model.cfg
        session = create_session(cfg, self.create_terminal(cfg))
        session.on_session_stop = self._on_session_stop
        session.term_widget = view
        session.window = win
        session.terminal.term_widget = view
        view.session = session
        view.tab_width = session.get_tab_width()

        self._session_task = Task(session.start, .1)
        #session.start()

        win.tabview.selected_index = len(win.tabview.items) - 1
Beispiel #15
0
    def _create_new_tab(self, win, view):
        win.tabview.add_item(view)

        cfg = view.model.cfg
        session = create_session(cfg, self.create_terminal(cfg))
        session.on_session_stop = self._on_session_stop
        session.term_widget = view
        session.window = win
        session.terminal.term_widget = view
        view.session = session
        view.tab_width = session.get_tab_width()

        self._session_task = Task(session.start, .1)
        #session.start()

        win.tabview.selected_index = len(win.tabview.items) - 1
Beispiel #16
0
def do_test(args):
    session = create_session(path=config_path(), name=args.name)
    path = os.path.normpath(args.directory)

    # have category, check for a library or operation type
    if args.category:
        category_path = create_named_path(path, args.category)
        if args.library:
            library.run_test(session=session,
                             path=create_named_path(category_path,
                                                    args.operation_type,
                                                    subdirectory="libraries"),
                             category=args.category,
                             name=args.library,
                             timeout=args.timeout)
            return

        if args.operation_type:
            operation_type.run_test(session=session,
                                    path=create_named_path(
                                        category_path,
                                        args.operation_type,
                                        subdirectory="operation_types"),
                                    category=args.category,
                                    name=args.operation_type,
                                    timeout=args.timeout)
            return

        category.run_tests(session=session,
                           path=category_path,
                           name=args.category,
                           timeout=args.timeout)
        return

    if args.library or args.operation_type:
        logging.error(
            "To test a single operation type or library, you must enter a category"
        )
        return

    instance.run_tests(session=session, path=path, timeout=args.timeout)
Beispiel #17
0
    def __init__(self, config_file):
        self.config_file = config_file
        # parse config file
        #print(self.config_file)
        self.session = session.create_session(config_file)
        # DB access
        # DAQ PART
        self.daq_answer = None
        self.daqfsm = Machine(model=self,
                              states=[
                                  'CREATED', 'INITIALISED', 'CONFIGURED',
                                  'RUNNING', 'CONFIGURED'
                              ],
                              initial='CREATED')
        self.daqfsm.add_transition('initialise',
                                   'CREATED',
                                   'INITIALISED',
                                   after='daq_initialising',
                                   conditions='isConfigured')
        self.daqfsm.add_transition('configure', ['INITIALISED', 'CONFIGURED'],
                                   'CONFIGURED',
                                   after='daq_configuring',
                                   conditions='isConfigured')
        self.daqfsm.add_transition('start',
                                   'CONFIGURED',
                                   'RUNNING',
                                   after='daq_starting',
                                   conditions='isConfigured')
        self.daqfsm.add_transition('stop',
                                   'RUNNING',
                                   'CONFIGURED',
                                   after='daq_stopping',
                                   conditions='isConfigured')
        self.daqfsm.add_transition('destroy',
                                   'CONFIGURED',
                                   'CREATED',
                                   after='daq_destroying',
                                   conditions='isConfigured')

        self.stored_state = self.getStoredState()
Beispiel #18
0
def do_push(args):
    session = create_session(path=config_path(), name=args.name)
    path = os.path.normpath(args.directory)

    if args.force and not args.operation_type:
        logging.warning(
            'Force Flag only operates with a single Operation Type')
        return
    # TODO: get category from the definition file
    if args.category:
        category_path = create_named_path(path, args.category)
        if args.library:
            library.push(session=session,
                         path=create_named_path(category_path,
                                                args.library,
                                                subdirectory='libraries'))
            return

        if args.operation_type:
            operation_type.push(session=session,
                                path=create_named_path(
                                    category_path,
                                    args.operation_type,
                                    subdirectory='operation_types'),
                                force=args.force)
            return

        category.push(session=session, path=category_path)
        return

    if args.library or args.operation_type:
        logging.error(
            'To push a single operation type or library, you must enter a category'
        )
        return

    instance.push(session=session, path=path)
Beispiel #19
0
def generate_session(email):
    user_secret = session.create_session(email, db)
    if user_secret is -1:
        return -1
    return user_secret
Beispiel #20
0
        self.api.add_route("/group_wishlist", endpoints.GroupWishlist())
        self.api.add_route("/wishlist", endpoints.StudentWishlist())
        self.api.add_route("/student", endpoints.Student())
        self.api.add_route("/myinfo", endpoints.MyInfo())
        self.api.add_route("/dorms", endpoints.Dorm())
        self.api.add_route("/rooms", endpoints.Room())
        self.api.add_route("/change-password", endpoints.Password())
        self.api.add_route("/login", endpoints.Login())
        self.api.add_route("/logout", endpoints.Logout())

    def _setup_sqlalchemy(self):
        sqlalchemy_init()


api = API()
application = api.api

session.create_session(2009578, "alex")
session.create_session(1, "denton")
session.create_session(2000000, "eli")
session.create_session(3, "michael")


def serve(host='localhost', port=8000):
    import waitress
    waitress.serve(api.api, host=host, port=port, ipv6=False)


if __name__ == '__main__':
    serve()
Beispiel #21
0
async def play_rps(message):
    session.create_session(message.server.id, message.channel,
                           [str(message.author)], rps.get_handler())
    await client.send_message(message.channel, '**Started match!**')
Beispiel #22
0
def create_new_session(user):
	return session.create_session(user)
# -*- coding: utf-8 -*-
"""
Created on Tue Sep  8 13:18:41 2020

@author: Vaibhav Deodhe
"""
import session
from bs4 import BeautifulSoup as bs
import csv
import re

session = session.create_session()


#Here we will check if article_link is valid or not
def check_validity(article_link):
    search = re.search("/page/", article_link)
    if search or (article_link == "#"):
        return False
    else:
        return True


def get_article_links():
    try:
        f = csv.writer(open("article_links.csv", "w", newline=''))
        headers = {
            "User-Agent":
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
        }
        for i in range(1, 187):
Beispiel #24
0
            self.cors_middleware.middleware, self.authentication_middleware
        ])

    def _setup_errors(self):
        self.api.add_error_handler(Exception, InternalServerError)

    def _setup_endpoints(self):
        # GET, DELETE, ###### DONE
        self.api.add_route("/group", groups.Group())
        self.api.add_route("/group/members", groups.GroupMembers())
        # GET, DELETE, PUT
        self.api.add_route("/group/invite", groups.GroupInvite())
        # GET, PUT, DELETE ###### Done
        self.api.add_route("/group_wishlist", group_wishlist.GroupWishlist())
        # GET, PUT, DELETE ###### Done
        self.api.add_route("/wishlist", student_wishlist.StudentWishlist())
        # GET ###### DONE
        self.api.add_route("/myinfo", student.MyInfo())
        # GET ###### almost DONE
        self.api.add_route("/dorms", dorms.Dorm())
        # GET ###### almost DONE
        self.api.add_route("/rooms", rooms.Room())


api = API()

session.create_session(0, "alex")
session.create_session(1, "denton")
session.create_session(2, "eli")
session.create_session(3, "michael")
Beispiel #25
0
#!C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe

import base
import os, cgi
import session
import authentication

params = cgi.FieldStorage()
if (os.environ["REQUEST_METHOD"].upper() == "POST"):
    username = params.getvalue("username")
    password = params.getvalue("password")
    success, user_id = authentication.authenticate(username, password)
    if success:
        session_id = session.create_session()
        session.add_to_session({"user_id": user_id}, session_id=session_id)
        print('Location: upload.py')

print("")
base.start_html()
print('''<form method="POST">
username <input type="text" name="username" />
password <input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>''')
if (os.environ["REQUEST_METHOD"].upper() == "POST" and not success):
    print("<div>Login Error</div>")
base.finish_html()
Beispiel #26
0
#!/usr/bin/env python

import list_ec2
import parse_ec2
import session

instances_list = list_ec2.list_instances()

choose_no = input('Choose an instance to terminate: ')
choose_instance = instances_list[choose_no-1]
choose_id = choose_instance['instance-id']

ec2_config = parse_ec2.get_config('ec2.json')

s = session.create_session(ec2_config['region'])

ec2 = s.client('ec2')
ec2.terminate_instances(InstanceIds=[choose_id])
Beispiel #27
0
 def __init__(self):
     session_object = session.create_session()
     self.driver = session_object.connect()