コード例 #1
0
def check_jwt_token():
    jwt_token = get_jwt_token()

    if jwt_token:
        try:
            payload = jwt.decode(
                jwt_token, plexpy.CONFIG.JWT_SECRET, leeway=timedelta(seconds=10), algorithms=[JWT_ALGORITHM]
            )
        except (jwt.DecodeError, jwt.ExpiredSignatureError):
            return None

        if not Users().get_user_login(jwt_token=jwt_token):
            return None

        return payload
コード例 #2
0
ファイル: composite.py プロジェクト: 5g-media/CNO
def test3():
    filename_tree = "../DataComposite/linear_structure.txt"
    loops = False
    t = ServicesTree(loops, filename_tree)
    #n = Network("../Networks/isno_30_4")
    n = Network("../Networks/isno_5_2")
    u = Users(n)
    u.generate_users(len(t), target_alu=0.25, target_delay=0.8)
    u.write_demands("../DataComposite/isno_5_2-t2-users.txt")
    u.write_user_topo("../DataComposite/isno_5_2-t2-user_topo.txt")
    #u.write_demands("../DataComposite/isno_30_4-t1-users.txt")
    #u.write_user_topo("../DataComposite/isno_30_4-t1-user_topo.txt")
    s = Servers(t, n)
    s.generate_servers()
    s.write_servers("../DataComposite/isno_5_2-t2-costs.txt")
コード例 #3
0
ファイル: server.py プロジェクト: may-kumar/Dixit
    def __init__(self, *args, **kwargs):
        """Initializes the users, games, chat log, and cards."""
        self.users = Users()
        self.games = {}
        self.chat_log = ChatLog()

        # Specifies where to find all the card images for each set.
        self.card_sets = [
            CardSet(name, find_cards(folder), enabled)
            for name, (folder, enabled) in kwargs['card_sets'].items()
        ]
        self.admin_password = kwargs['admin_password']
        self.admin_enable = kwargs['admin_enable']

        super(Application, self).__init__(*args, **kwargs)
コード例 #4
0
 def login(self, email, password):
     """
     Login user to Producteev.
     """
     response = self.__request(
                     'users/login',
                     email=email,
                     password=password)
     self.token = response['login']['token']
     self.users = Users(self)
     self.tasks = Tasks(self)
     self.dashboards = Dashboards(self)
     self.labels = Labels(self)
     self.activities = Activities(self)
     self.subtasks = Subtasks(self)
コード例 #5
0
def test_users_database():
    from users import Users
    users = Users()
    users.load_from_db(complete_profile=False)
    admin_users = users.get_user_by_name_and_role(user_name='',
                                                  user_role='admin_users',
                                                  find_one=False)
    print("Original Users List")
    for user in admin_users:
        print("Key:", user.key)
        print("Nombre:", user.display_name)
        print("Email:", user.email)
        print("Rol:", user.user_role)
        print("Imagen", user.image)
        print(user.get_data())
コード例 #6
0
ファイル: composite.py プロジェクト: 5g-media/CNO
def test5():
    filename_tree = "../DataComposite/tree_syn_structure.txt"
    loops = False
    t = ServicesTree(loops, filename_tree)
    n = Network("../Networks/geant.txt", "sndlib")

    s = Servers(t, n, "../DataComposite/geant-tree-syn-costs.txt")
    u = Users(n, "../DataComposite/geant-tree-syn-users.txt",
              "../DataComposite/geant-tree-syn-user_topo.txt")

    cs = CompositeServices(n, t, s, u, opt_cong=False, congestion_cost=False)

    #print(cs)

    print(cs.min_cost())
    print(cs.minimum_first_hop())
コード例 #7
0
ファイル: system_setup.py プロジェクト: k0da/kiwi-1
    def setup_groups(self):
        """
            add groups for configured users
        """
        system_users = Users(self.root_dir)

        for users in self.xml_state.get_users():
            if not system_users.group_exists(users.group_name):
                options = []
                if users.group_id:
                    options.append('-g')
                    options.append(users.group_id)
                log.info('Adding group %s', users.group_name)
                system_users.group_add(
                    users.group_name, options
                )
コード例 #8
0
ファイル: composite.py プロジェクト: 5g-media/CNO
def test1():
    from composite_heuristic import CompositeHeuristic
    n = Network("../Networks/isno_5_2")
    filename_tree = "../DataComposite/linear_structure.txt"
    loops = False
    t = ServicesTree(loops, filename_tree)
    s = Servers(t, n, "../DataComposite/isno_5_2-costs.txt")
    u = Users(n, "../DataComposite/isno_5_2-users-v2.txt",
              "../DataComposite/isno_5_2-user_topo.txt")

    cs = CompositeServices(n, t, s, u, opt_cong=True, congestion_cost=True)
    #print(cs)

    hcs = CompositeHeuristic(cs)
    order = list(range(len(cs.users)))
    sol = hcs.heuristic(order)
    cs.of_normalized_penalty(sol, printcomps=True)
コード例 #9
0
def main():
    try:
        serverInfo = MCLIENT.server_info()
        logger.info("Connected to Mongo Server: %s." % serverInfo)
    except:
        logger.error("Could not connect to the Mongo Server.")
        raise
    updater = Updater(AUTHTOKEN)
    logger.info("Passed Auth")
    dp = updater.dispatcher

    game_state = Games(dp, MDB, logger=logger)
    user_state = Users(dp, MDB, logger=logger)

    updater.start_polling()
    logger.info("Starting polling")
    updater.idle()
コード例 #10
0
ファイル: works.py プロジェクト: coolboyweizi/op2dgraph
    def __init__(self, work_id, status, created, user_id):

        self.work_id = work_id
        self.user_id = user_id
        self.user = Users(user_id)  # 对应的user的xid
        self.work = Dgraph(work_id)  # 对应的xid

        if self.work.get_uid()['status'] < 0:  # 不存在则创建
            data = {
                "xid": work_id,
                "type.work": "",
                "work.status": status,
                "work.created_at": "T".join(created.split(" "))
            }
            self.work.add(data)

        self.uid = self.work.get_uid()['data']
コード例 #11
0
def register():
    if request.method == 'GET':
        id = None
        if "user" in session:
            id = session["user"]
        return render_template('register.html', user=Users.loadUserId(id))
    elif request.method == 'POST':
        values = (None, request.form['username'], request.form['mail'],
                  hashlib.sha1((request.form['password'] +
                                "babami").encode('utf-8')).hexdigest(),
                  request.form['birthday'])
        user = Users(*values).create()
        if user:
            user = Users.loadUserMail(user.mail)
            session["user"] = user.id
            return redirect('/')
        return redirect('/register')
コード例 #12
0
def users():
    dsn = app.config['dsn']
    page = Users(dsn)
    if session['admin']:
        if request.method == 'GET':
            return page.show_users()
        elif 'Add' in request.form:
            username = request.form['UserName']
            password = request.form['Password']
            type = request.form['UserType']
            if username and password and type:
                return page.add_user_from_table(username, password, type)
            else:
                flash("You need to enter all the fields")
                return page.show_users()
        elif 'Delete' in request.form:
            id = request.form.get('select', '')
            if id:
                return page.delete_user(id)
            else:
                flash(
                    "You need to select the user you want to delete using the radio buttons!"
                )
                return page.show_users()
        elif 'Update' in request.form:
            id = request.form.get('select', '')
            username = request.form['UserName']
            password = request.form['Password']
            type = request.form['UserType']
            if username and password and type and id:
                return page.update_user(username, password, type, id)
            else:
                if not id:
                    flash(
                        "You need to select the user you want to update using the radio buttons!"
                    )
                if not username or not password or not type:
                    flash("You need to enter all the fields")
                return page.show_users()
        elif 'Reset' in request.form:
            return page.reset_table()

    else:
        flash("Only admins can access that page!")
        return redirect(url_for('home'))
コード例 #13
0
 def __init__(self,
              config=None,
              algorithm='HS256',
              user_fields=[],
              whitelist=[]):
     self.config = config
     self.loop = asyncio.get_event_loop()
     self.JWT_SECRET = self.config.token_secret
     self.JWT_ALGORITHM = algorithm
     self.JWT_EXP_DELTA_SECONDS = self.config.token_expires
     self.whitelist = whitelist
     self.instance_id = str(uuid.uuid1())
     self.refresh_tokens = self.loop.run_until_complete(
         FileUtils.get_data_from_file(self.config.data_directory,
                                      'refresh_tokens'))
     self.users = Users(user_fields,
                        self.config.user_directory,
                        config=config)
コード例 #14
0
def execute(cfg):
    users = Users(cfg).run()
    base.storage('users', users)
    time.sleep(5)

    groups = Groups(cfg).run()
    base.storage('groups', groups)
    time.sleep(5)

    members = GroupsMembers(cfg, users, groups).run()
    base.storage('groups-members', members)
    time.sleep(10)

    projects = Projects(cfg, users['target'], groups['target']).run()
    base.storage('projects', projects)

    time.sleep(10)
    Repositories(cfg, projects['source']).run()
コード例 #15
0
ファイル: main.py プロジェクト: hcylus/gitlab-migrator
def execute(cfg):
    # cachepath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'cache')

    users = Users(cfg).run()
    #with open(cachepath + '/users.json','r') as f:
    #	users = json.load(f)

    groups = Groups(cfg).run()
    #with open( cachepath + '/groups.json','r') as f:
    #	groups = json.load(f)

    members = GroupsMembers(cfg, users, groups).run()

    projects = Projects(cfg, users, groups).run()
    # with open( cachepath + '/projects.json','r') as f:
    # 	projects = json.load(f)

    Repositories(cfg, projects).run()
コード例 #16
0
    def sendSummary(self, user=None):
        '''Given a User Object, or None for all,
           Send Summary Email to user(s).
        '''
        sent = failed = 0

        # one or all users?
        users = [user] if user else Users().getUsers('1=1')

        time_since = datetime.now() - timedelta(NUM_DAYS_BACK)
        new_posts = self._summary_getNewPosts()
        total_comments = self._getTotalComments(created_after=time_since)
        total_likes = self._getTotalLikes(created_after=time_since)
        for user in users:
            print 'user:'******'created': format_datetime(p['last_updated']),
                    'text': ' '.join(p['text'].split(' ')[0:80]), # 80 words
                    'name': p['author'],
                    'profile_image': getUserImage(p['user_id']),
                    'message_url': 'http://%s/main.py#message_card_%s' \
                           % (self.conf.baseurl, p['message_id'])
                })

            html = open('%s/lib/emails/summary.html' %self.conf.basedir).read()
            html = Template(html)
            html = html.render(likes=total_likes, comments=total_comments,
                               posts=posts, new_posts=new_posts)
            try:
                self.email.send_email(to=user.email,
                                      subject='While you were away',
                                      body="",
                                      html=html)
                sent += 1
            except Exception, e:
                self.logger.error('Summary Email Failed: %s: %s' %
                                  (user.email, e))
                failed += 1
コード例 #17
0
    def __init__(self, data_folder):
        self.parameters_file_path = os.path.join(data_folder, EloBot.parameters_file_name)
        with open(self.parameters_file_path) as parameters_file:
            self.parameters_data = json.load(parameters_file)
        self.logger.info('Loaded parameters file from \'%s\'', self.parameters_file_path)

        super(EloBot, self).__init__(self.parameters_data['discord'])
        self.riot_api = RiotAPI(self.parameters_data['riot_api_key'])
        Users.salt = self.parameters_data['salt']
        self.users = Users(data_folder)
        self.emoji = Emojis()

        self.autoupdate_is_running = False
        self.autoupdate_elo = \
            self.parameters_data['autoupdate_elo'] if 'autoupdate_elo' in self.parameters_data else False
        self.autoupdate_verbose = \
            self.parameters_data['autoupdate_verbose'] if 'autoupdate_verbose' in self.parameters_data else True

        self.last_api_check_time = 0
        self.api_is_working = True
コード例 #18
0
 def test_user_set(self, mock_list_users):
     mock_list_users.return_value.status_code = 200
     mock_list_users.return_value.json.return_value = {
         "data": [{
             "id":
             4,
             "email":
             "*****@*****.**",
             "first_name":
             "Eve1",
             "last_name":
             "Holt",
             "avatar":
             "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
         }]
     }
     u = Users()
     resp = u.list_users()
     assert resp.status_code == 200
     self.assertEqual(resp.json()['data'][0]['first_name'], 'Eve1')
コード例 #19
0
ファイル: cheeseprice.py プロジェクト: Lev4/cheesePrice
def send_updates():

    p = Prices(prices_db)
    p.create_tab()
    current_date = datetime.today().strftime("%d-%m-%Y")
    day_before_current_date = datetime.today() - timedelta(1)
    day_before_current_date = day_before_current_date.strftime("%d-%m-%Y")
    message = p.check_price_change(day_before_current_date, current_date)

    if len(message) > 0:

        u = Users(users_db)
        u.create_tab()
        where_to_send = u.get_users_chatid_to_update()

        if len(where_to_send) > 0:
            where_to_send = [x[0] for x in where_to_send]

            for user_chat_id in where_to_send:
                send_message(user_chat_id, cheeze_token, message)
コード例 #20
0
ファイル: login.py プロジェクト: wu4f/cyberpdx-crypto
 def post(self):
     if 'logout' in flask.request.form:
         flask.session.pop('username', None)
         return flask.redirect(flask.url_for('main'))
     required = ['username', 'passwd']
     for r in required:
         if r not in flask.request.form:
             flask.flash("Error: {0} is required.".format(r))
             return flask.redirect(flask.url_for('main'))
     username = flask.request.form['username']
     passwd = flask.request.form['passwd']
     myusers = Users()
     if myusers.checkUser(username, passwd):
         flask.session['username'] = username
         userdir = "static/obj/" + flask.session['username']
         if not os.path.exists(userdir):
             os.makedirs(userdir)
     else:
         flask.flash("Username doesn't exist or incorrect password")
     return flask.redirect(flask.url_for('main'))
コード例 #21
0
ファイル: webauth.py プロジェクト: samwiseg0/Tautulli
    def on_login(self, username=None, user_id=None, user_group=None, success=False, oauth=False):
        """Called on successful login"""

        # Save login to the database
        ip_address = cherrypy.request.remote.ip
        host = cherrypy.request.base
        user_agent = cherrypy.request.headers.get('User-Agent')

        Users().set_user_login(user_id=user_id,
                               user=username,
                               user_group=user_group,
                               ip_address=ip_address,
                               host=host,
                               user_agent=user_agent,
                               success=success)

        if success:
            use_oauth = 'Plex OAuth' if oauth else 'form'
            logger.debug("Tautulli WebAuth :: %s user '%s' logged into Tautulli using %s login."
                         % (user_group.capitalize(), username, use_oauth))
コード例 #22
0
    def add(self, user_data, user_school_data):
        '''Writes to users, user_schools, follows, and possibly
                     schools database tables

           Expects two dictionaries

              user_data, with keys:
                 first_name, last_name, email, password, status_id

              user_school_data, with keys:
                 school_name, school_relationship_id, original_grade
        '''
        self.db.startTransaction()
        try:
            user_data['password'] = sha256_crypt.encrypt(user_data['password'])
            user = Users().add(user_data)

            # get school_id
            school_name = user_school_data['school_name']
            school_id = self._getSchoolId(school_name)

            # set user_school_rec
            user_school_rec = user_school_data
            user_school_rec['user_id'] = user.id
            user_school_rec['school_id'] = school_id
            user_school_rec['grade'] = user_school_data['original_grade']
            del user_school_rec['school_name']
            UserSchools().add(user_school_rec)

            # set user followings
            Follows().update(user)

            self.db.commit()
        except Exception, e:
            emsg = \
                'Unable to register user: user_data: %s; ' \
                'user_school_data: %s; Error: %s' \
                % (user_data, user_school_data, e)
            self.logger.error(emsg)
            self.db.rollback()
            raise
コード例 #23
0
ファイル: tests_ea_comp.py プロジェクト: ptkhoa1984/CNO
def test_geant():
    network_file = "../Networks/geant.txt"
    n = Network(network_file, "sndlib")

    #filename_tree = "../DataComposite/tree_syn_structure.txt"
    filename_tree = "../DataComposite/linear_structure_loops.txt"
    loops = True
    t = ServicesTree(loops, filename_tree)

    #servers_file = "../DataComposite/geant-loops-costs.txt"
    servers_file = "../DataComposite/geant-lin-alu30-del09-costs.txt"

    s = Servers(t, n, servers_file)

    #users_dem_file = "../DataComposite/geant-treeloops-alu25-del07-users.txt"
    users_dem_file = "../DataComposite/geant-lin-alu30-del09-users.txt"
    #users_top_file = "../DataComposite/geant-treeloops-alu25-del07-user_topo.txt"
    users_top_file = "../DataComposite/geant-user_topo.txt"

    u = Users(n, users_dem_file, users_top_file)

    #    cs = CompositeServices(n, t, s, u, opt_cong = True, cong_opt_method = "sp",
    #                           congestion_cost = True, cong_of = "fortz")

    cs = CompositeServices(n,
                           t,
                           s,
                           u,
                           opt_cong=False,
                           congestion_cost=False,
                           cong_of="fortz")

    ea_par = {"max_evaluations": 20000, "pop_size": 100}
    ea = EACompositeServices(cs)
    #ea = EACompositeServices(cs,optimize_routing_weights = True)

    assig = ea.run_evol_alg(ea_pars=ea_par)

    print("Best solution:")
    print(assig)
コード例 #24
0
ファイル: tests_ea_comp.py プロジェクト: ptkhoa1984/CNO
def test1():
    #etwork_file = "../Networks/isno_30_4"
    network_file = "../Networks/isno_5_2"
    n = Network(network_file)

    filename_tree = "../DataComposite/linear_structure.txt"
    loops = False
    t = ServicesTree(loops, filename_tree)

    #servers_file = "../DataComposite/test-cost.txt"
    #servers_file = "../DataComposite/isno_30_4-t1-costs.txt"
    servers_file = "../DataComposite/isno_5_2-t1-costs.txt"
    s = Servers(t, n, servers_file)

    #users_dem_file = "../DataComposite/test-users.txt"
    #users_top_file = "../DataComposite/test-user_topo.txt"
    #users_dem_file = "../DataComposite/isno_30_4-t1-users.txt"
    #users_top_file = "../DataComposite/isno_30_4-t1-user_topo.txt"
    users_dem_file = "../DataComposite/isno_5_2-t2-users.txt"
    users_top_file = "../DataComposite/isno_5_2-t1-user_topo.txt"

    u = Users(n, users_dem_file, users_top_file)

    cs = CompositeServices(n,
                           t,
                           s,
                           u,
                           opt_cong=False,
                           congestion_cost=True,
                           cong_of="fortz")

    print("Starting EA:")
    ea_par = {"max_evaluations": 500}
    ea = EACompositeServices(cs)

    assig = ea.run_evol_alg(ea_pars=ea_par)
    #assig = ea.run_evol_alg(True, max_cpus = 50)

    print("Best solution:")
    print(assig)
コード例 #25
0
def getUsers():
    conf_ = conf.getInstance()
    users = Users()
    if request.method == 'POST':
        data = dict((k, request.form[k]) for k in request.form.keys())
        return jsonify(users.add(data))
    else:
        users.setColumns([
            'id', 'concat_ws(" ", first_name, last_name) as fullname',
            'created'
        ])
        users.setOrderBy('id')
        results = users.getTable()
        data = {
            'users': [{
                'id': r['id'],
                'fullname': r['fullname'],
                'created': r['created'],
                'uri': 'http://%s/users/%s' % (conf_.serverurl, r['id']),
            } for r in results]
        }
        return jsonify(data)
コード例 #26
0
    def render_admin_panel(self, req, cat, page, path_info):
        req.perm.assert_permission('SLIMTIMER_CONFIG')

        config_file = self._get_user_config_file()
        users = Users(config_file)

        if req.method == 'POST':
            if req.args.get('action', '') == 'modify':
                self._do_mod_user(req, users)
                req.redirect(req.href.admin(cat, page))

            elif req.args.get('action', '') == 'delete':
                self._do_delete_user(req, users)
                req.redirect(req.href.admin(cat, page))

            else:
                self._do_add_user(req, users)
                req.redirect(req.href.admin(cat, page))

        add_stylesheet(req, 'slimtimer/css/slimtimer.css')
        add_script(req, 'slimtimer/js/slimtimer_users.js')
        return 'config_users.html', {'users': users.get_all_users()}
コード例 #27
0
ファイル: search.py プロジェクト: nicholasericksen/graphish
 def __init__(self, graphConnector, includeNestedFolders=True, userPrincipalName=None):
     """The Search class allows you to:
        * Create a new Search
        * Update an existing Search
        * Retrieve messages identified during a search
        * Find search folders on mailboxes
        * Delete a search
     
     Args:
         graphConnector (GraphConnector): A generated GraphConnector object
         includeNestedFolders (bool, optional): When creating a search you can define if you want to search all nested folders or not. Defaults to True.
         userPrincipalName (str, optional): Defaults to the current user, but can be any user defined or provided in this parameter. Defaults to 'me'.
     """
     self.connector = graphConnector
     if not userPrincipalName:
         if self.connector.username and self.connector.password:
             self.user = ['me']
         else:
             self.user = Users(self.connector).get
     else:
         self.user = [userPrincipalName]
     
     self.includeNestedFolders = includeNestedFolders
コード例 #28
0
    def __init__(self) : 
        # Player related variables
        self.players = []
        self.num_active_players = 0

        # Blind Related Values
        self.big_blind_player = 0
        self.small_blind_player = 1
        self.big_blind = 15
        self.small_blind = 5
        self.max_bet = 0

        # Game State Related Variables
        self.game_state = 0
        self.GS_INIT = 0
        self.GS_BETTING = 1

        # Deck related variables
        self.deck = Deck()
        self.community_cards = Hand()

        # Databse related stuff
        self.users_db = Users()
コード例 #29
0
    def loadJSON():
        data = json.load(open('savedUsers.json'))
        users = Users()
        users.userMaxId = data["userMaxId"]

        for userId in data["userList"]:
            createdUser = User(
                data["userList"][userId]["id"],
                data["userList"][userId]["username"],
                data["userList"][userId]["email"],
                data["userList"][userId]["password"],
                data["userList"][userId]["name"],
                data["userList"][userId]["surrname"]
            )
            
            userWallet = Wallet(userId)
            for walletCurrency, count in data["userList"][userId]["wallet"]["currencies"]:
                userWallet.depositMoney(walletCurrency["name"], count)

            createdUser.wallet = userWallet
            users.userList[userId] = createdUser
        
        return users
コード例 #30
0
    def create_node(self):
        '''
        创建friend的节点. 删除该所有的friend数据,再重新建立
        :return:
        '''
        self.delete_node()
        items = []

        for item in self.flow:

            obj = Users(user_id=item['user_id'])
            items.append({
                'uid':
                obj.get_uid()['data'],
                "friend|since":
                time.strftime("%Y-%m-%dT%H:%M:%S",
                              time.gmtime(item['follow_at']))
            })
            del obj

        data = {"uid": self.get_uid()['data'], 'friend': items}

        return self.user.add(data)