Exemple #1
0
def register_security_answer():
    # auth user
    request_data = request.get_json(force=True)

    try:
        user = auth()
    except AuthenticationFailed:
        return rAuthError

    try:
        params = get_from_request_data(["service_info"])
        service_info = params["service_info"]
    except MissingRequestParams:
        return rMissingServiceInfo

    service_name = service_info.get("service_name")
    question = service_info.get("question")
    answer = service_info.get("answer")
    if None in [service_name, question, answer]:
        return rMissingParams(["service_name", "question", "answer"])

    try:
        Users.register_security_answer(username, service_name, question, answer)
    except RuntimeError as e:
        return rInternalServerError

    return "OK"
Exemple #2
0
class UUS:

    def __init__(self):
        self.__LOG_TAG__ = "UUS"
        self.rss_list = URL_list()
        self.html_list = URL_list()
        self.users = Users()

    def to_str(self):
        return "rss_list:\n"+self.rss_list.to_str()+'\n\nhtml_list:\n'+self.html_list.to_str()

    def print_users(self, p_users):
        for user in self.users.get_users():
            print str(user.get_id()) + "   " + str(user.get_nick()) + "   " + str(user.get_url_list())
            print 

    def get_url_split(self, p_url):
        "RSS|http://www.hardware.com.br/feeds/global.xml"
        ret = "", ""
        try:
            ret = p_url.split('|')
        except:
            log.error(self.__LOG_TAG__, "Error getting URL type")
        return ret[0], ret[1]

    def update(self, p_user):
        user_id = p_user.get_id()
        user_urls = p_user.get_url_list()
        for url in user_urls:
            url_type, url_link = self.get_url_split(url)
            if url_type == "RSS":
                self.rss_list.add_link(url_link)
                self.rss_list.add_user(url_link, user_id)
            elif url_type == "HTML":
                self.html_list.add_link(url_link)
                self.html_list.add_user(url_link, user_id)
            else:
                log.error(self.__LOG_TAG__, "URL type[%s] invalid" % (url_type))

    def maintenance_url_lists(self):
        #atualizar tabela user
        self.users.update_users()
        
        #atualizar tabela url de acordo com nova tabela user
        for user in self.users.get_users():
            user_status = user.get_status() 
            if user_status == 0:
                #status 0 = funcionando. nao fazer nada.
                pass
            elif (user_status == 1) or (user_status == 2):
                #novo ou alterado. atualizar.
                self.update(user)
            elif (user_status == 3):
                #block(user)
                pass
            elif (user_status == 9):
                #delete(user)
                pass
            else:
                log.error(self.__LOG_TAG__, "Error: invalid status[%s]" % (user_status))
Exemple #3
0
def enroll_in_service():
    # Lets assume for now the only service we support is vanguard
    # For that reason, all service info validation logic shall be in this sole handler

    # required: service_name, username, password
    request_data = request.get_json(force=True)

    try:
        user = auth()
    except AuthenticationFailed:
        return rAuthError

    service_info = request_data.get("service_info")
    if service_info is None:
        return "Please provide service information for enrollment", 400

    service_name = service_info.get("service_name")
    username = service_info.get("username")
    password = service_info.get("password")
    if None in [service_name, username, password]:
        return "Please provide service information for enrollment", 400

    try:
        Users.enroll_in_service(username, service_info)
    except RuntimeError as e:
        print "ERROR:", e
        return rInternalServerError

    return "OK"
Exemple #4
0
def add_user():
  """
  Register a user, looking up username and password in request.form.
  Validates the username and password.

  Returns:
    A JSON string about the registration status.
  """
  username = request.form['username']
  password = request.form['password']
  confirmation = request.form['confirmPassword']
  if not confirmed_password_valid(password, confirmation):
    return fail_registration(
        "Your password and confirmation didn't match up.")
  if password.strip() == '':
    return fail_registration("Passwords can not be blank.")
  if ' ' in password:
    return fail_registration("Passwords can not have spaces")
  users = Users(g.database_service)
  if not users.is_valid_username(username):
    error = """
        Username %s is not valid.
        Either it's taken, it has a space, or it's blank.
        """ % (username)
    return fail_registration(error)
  new_user = users.register_user(username, password)
  session['user_id'] = new_user.get_id()
  return success_registration()
Exemple #5
0
def register():
  """
  Sending a GET request returns the register.html page.
  Sending a POST request validates, then registers the user.
  If successful, the user is immediately brought to the sticky note page.
  """
  if request.method == 'GET':
    return render_template('register.html')
  else:
    username = request.form['username']
    password = request.form['password']
    confirmation = request.form['confirmPassword']
    if not confirmed_password_valid(password, confirmation):
      return fail_registration(
          "Your password and confirmation didn't match up.")
    if len(password) == 0:
      return fail_registration("Passwords can not be blank.")
    if ' ' in password:
      return fail_registration("Passwords can not have spaces")
    with closing(shelve.open(users_file)) as user_shelf:
      users = Users(user_shelf)
      if not users.is_valid_user(username):
        flash("Username %s is not valid." % (username))
        flash("Either it's taken, it has a space, or it's blank")
        return render_template('register.html')
      users.register_user(username, password)
      session['username'] = username
    return redirect(url_for('notes'))
Exemple #6
0
def register():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        user = Users(form.firstname.data, form.lastname.data, form.email.data, form.password.data)
        user.add_user(user)
        flash('Thanks for registering')
        return redirect('/')
    return render_template('register.j2', form=form)
def add_members(obj, srcId, dstId):
	# delete all the existing members first (objects' creator should be here)
	for mbr in map(lambda m: m['id'], obj.get_members(dstSys, dstId)):
		obj.del_member(dstSys, dstId, mbr)
	# return an user_id in the destination system according to a given member dict from the source system
	usr = Users()
	uidByMember = lambda mbr: get_user(dstSys, usr.by_id(srcSys, mbr['id']))
	for mbr in obj.get_members(srcSys, srcId):
		obj.add_member(dstSys, dstId, uidByMember(mbr), mbr['access_level'])
Exemple #8
0
def login():
    dsn = app.config['dsn']
    page = Users(dsn)
    if request.method == 'GET':
        return render_template('user/login.html')
    else:
        username = request.form['username']
        password = request.form['password']
        return page.login(username, password)
Exemple #9
0
def updateUser():
    conn = MySQLdb.connect(host='127.0.0.1',user='******',passwd='******',db='github')
    cur = conn.cursor()
    with open("/Users/dreamteam/Documents/study/sonar/results/oss developer evaluation/update_star_num.csv") as seed:
        reader = csv.reader(seed)
        next(reader,None)
        mUsers = Users(conn,cur,1,'1','1',"2016-03-01 00:00:00")
        for line in reader:
            mUsers.getFollowerAndStar(str(line[1]))
    def get_category_info(category):
        result = Objects.get_object_info(category)
        owners = list()
        for owner in category.owners.all():
            user_extension = Users.get_user_extension(owner.username)
            if user_extension:
                owners.append(Users.get_user_info(user_extension))

        result["owners"] = owners
        return result
Exemple #11
0
class UsersTest(unittest.TestCase):
  def setUp(self):
    """ Using dicts instead of Shelve objects to speed up testing. """
    self.fake_database = FakeDatabaseService()
    self.users = Users(self.fake_database)
    self.username = '******'
    self.password = '******'

  def test_confirm_passwords(self):
    self.assertTrue(confirmed_password_valid('foo', 'foo'))
    self.assertFalse(confirmed_password_valid('foo', 'bar'))

  def test_simple_add_users(self):
    self.assertFalse(self.users.has_user(self.username))
    self.users.register_user(self.username, self.password)
    self.assertTrue(self.users.has_user(self.username))
    self.assertTrue( \
        self.users.try_login_user(self.username, self.password) is not None)

  def test_login_before_register(self):
    self.assertTrue( \
        self.users.try_login_user(self.username, self.password) is None)

  def test_login_with_wrong_password(self):
    self.users.register_user(self.username, self.password)
    self.assertTrue( \
        self.users.try_login_user(self.username, 'bad_password') is None)
 def get_post_win_count_by_user(user_id):
     try:
         user = Users.get_user_by_id(user_id)
         user_extension = Users.get_user_extension(user.username)
         count = 0
         for fp in ForumPost.objects.all():
             if user_extension in fp.win_users.all():
                 count += 1
         return count
     except Exception as ex:
         Logs.print_current_function_name_and_line_number(ex)
         return 0
Exemple #13
0
def person_page():
     now = datetime.datetime.now()
     uses = Users(app.config['dsn'])
     if request.method == 'GET':
        now = datetime.datetime.now()
        return render_template('persons.html', current_time=now.ctime())
     elif 'persons_to_control' in request.form:
        searchList = uses.control_user(request.form['username'],request.form['password']);
        if searchList == 1:
            return redirect(url_for('person_page'))
        else:
            return redirect(url_for('home_page2'))
Exemple #14
0
def sign_up():
    dsn = app.config['dsn']
    page = Users(dsn)
    if request.method == 'GET':
        return render_template('user/signup.html')
    else:
        username = request.form['username']
        password = request.form['password']
        if username and password:
            return page.sign_up(username, password)
        else:
            flash("You must enter a username and a password!")
            return render_template('user/signup.html')
Exemple #15
0
def login():
    from users import Users
    if request.method == "POST":
        if not Users.authentification(str(request.form["username"]), str(request.form["password"])):
            return render_template("login.html", citation=getCitation(), message="Invalid credential.")
        else:
            print Users.get_by_pseudonyme(request.form["username"])
            # login_user(Users.get_by_pseudonyme(request.form["username"]))
            return redirect(request.args.get("next") or "/")
    else:


        return render_template("login.html", citation=getCitation())
Exemple #16
0
def auth():
    """
    Call this in the beginning of a handler in order to authenticate the request
    """
    params = get_from_request_data(["username", "password"])

    user = Users.find_user(params["username"])
    if user is None:
        raise UserNotFound

    authenticated = Users.auth_user(params["username"], params["password"])
    if authenticated is not True:
        raise AuthenticationFailed

    return user
Exemple #17
0
def run(conn,cur,repo_id,repo_name,repo_fullname,deadline):
    try:
        # mIssues = Issues(conn,cur,repo_id,repo_fullname)
        # mIssues.get_issues(1)
        # mIssues.get_issue_comments(1)
        # mCommits = Commits(conn,cur,repo_id,repo_fullname)
        # mCommits.get_commits(1)
        # mCommits.get_commit_comments(1)
        mUsers = Users(conn,cur,repo_id,repo_name,repo_fullname,deadline)
        # # starts from 0
        # mUsers.updateUsers(0)
        # mUsers.connectUser()
        mUsers.getFollowerAndStar(0)
    except MySQLdb.Error, e:
        print "Mysql Error!", e;
Exemple #18
0
    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
                )
Exemple #19
0
    def generateLeaderboard(self):
        leaderboard = []

        leaderboard_a = []

        cntr = 0

        for user in Users.query().fetch():
            u = user.get(user.key.id())
            p = user.get_points_sum(user.key.id())

            leaderboard.append(Leaderboard_entry_m(
                user=u,
                points=p
            ))

            if p > 0:
                cntr += 1

        logging.info("total playing count: " + str(cntr))

        leaderboard.sort(key=lambda x: x.points, reverse=True)
        lb_m = Leaderboard_m(leaderboard=leaderboard[:20])

        if Leaderboard().query().get():
            lb = Leaderboard().query().get()
            lb.leaderboard = lb_m
            lb.put()
        else:
            lb = Leaderboard(leaderboard=lb_m)
            lb.put()

        # lb_short = Leaderboard_m(leaderboard=lb_m.leaderboard[:20])
        memcache.add(key="leaderboard", value=lb_m, time=500)
Exemple #20
0
    def stats(self):
        data = memcache.get('stats')
        if data is not None:
            return data
        else:
            self.users = Users()
            users = [0, 0, 0]
            points = [0, 0, 0]

            for user in Users.query().fetch():
                if user.faction:
                    users[user.faction-1] += 1
                    points[user.faction-1] += user.get_points_sum(user.key.id())

            faUsers = []
            for usr in users:
                faUsers.append(FactionUsers_m(users=usr))

            stats = []
            for usr in points:
                stats.append(Stats_m(points=usr))

            logging.info("%s", users)

            fa_stats = FactionStats_m(users=faUsers, stats=stats)
            memcache.add(key="stats", value=fa_stats, time=160)
            return fa_stats
Exemple #21
0
def login():
  """
  Handle a login attempt

  Returns:
    A JSON string that JavaScript will process communicating the results
    of the login attempt.
  """
  username = request.form['username']
  password = request.form['password']
  users = Users(g.database_service)
  user = users.try_login_user(username, password)
  if user is None:
    return fail_login('Login failed. Maybe you made a typo?')
  else:
    session['user_id'] = user.get_id()
    return success_login()
Exemple #22
0
def login():
  """
  Sending a GET request gets the login form page.
  Sending a POST request tries to logs in the user.
  """
  if request.method == 'GET':
    return render_template('login.html')
  else:
    username = request.form['username']
    password = request.form['password']
    with closing(shelve.open(users_file)) as user_shelf:
      users = Users(user_shelf)
      if users.login_is_valid(username, password):
        session['username'] = username
        return redirect(url_for('notes'))
    flash('Login failed. Maybe you made a typo?')
    return render_template('login.html')
Exemple #23
0
def main():
    webmon = Users()
    state_changes = []

    for row in webmon.get_distinct_urls():
        # For each distinct URLs do HTTP GET request
        # and collect the status code
        try:
            resp = requests.get(row[0])
            status_code = resp.status_code
        except requests.exceptions.ConnectionError:
            status_code = -1

        # State Changed: If current state is not
        # equal to previous state, collect as state_changes
        if status_code != row[1]:
            state_changes.append((row[0], row[1], status_code))

    for url, old_state, new_state in state_changes:
        # For each state changes, send notification to all the
        # users who subscribed to that URL and enabled.
        if new_state == 200:
            # Good status, Website is Healty
            title = "Status: Healthy"
            subtitle = "%s is Up" % (url)
            warning = False
        else:
            # Bad status, may be temporary add error message along
            # with the actual message
            title = "Status: Faulty"
            subtitle = "%s is Down, Error code: %s" % (url, new_state)
            warning = True

        for user in webmon.get_users_from_url(url):
            # If multiple users subscribed to same URL
            # Send notification to all enabled users.
            resp = timeline.send_notification(user.token, title,
                                              subtitle, warning)
            print "[%s] URL: %s, Status: %s => %s, %s" % (datetime.utcnow(),
                                                          url,
                                                          old_state,
                                                          new_state,
                                                          resp)

        # Update the current status in db
        webmon.update_state(url, new_state)
Exemple #24
0
def run(db_session, strain):
  users = Users(db_session)
  events = Events(db_session)
  
  while (1):
    # Very slow poppin' from the DB so 
    # we build a nice queue of events
    event = events.pop(strain)

    if event == None:
      continue

    print "ENGINE: Event Strain: '{strain}'".format(strain=event.strain)
    if event.strain == "request_user":
      user = event.payload_dec
      users.create(user['name'], user['email'])
      events.push("created_user", user)
      print "ENGINE: User '{email}' created.".format(email=user['email'])
    elif event.strain == "destroy_user":
      user = event.payload_dec
      users.destroy(user['id'])
      events.push("destroyed_user", user)
      print "ENGINE: User '{id}' destroyed.".format(id=user['id'])
    elif event.strain == "update_user":
      user = event.payload_dec
      users.update(user)
      events.push("updated_user", user)
      print "ENGINE: User '{email}' updated.".format(email=user['email'])
    
    sleep(5)
Exemple #25
0
def main():

    display = Screen('marvinconfig.txt', parser)
    menu = Pages('marvinconfig.txt', parser)
    artifacts = Items('marvinconfig.txt', parser)
    players = Users('marvinconfig.txt', parser)
    universe = Devices('marvinconfig.txt', parser)
    while True:
        '''TODO:
Exemple #26
0
    async def eventListener(self) -> None:
        while self.running:
            self.Ans = self.getAnswer().split(str('\n'))

            for line in self.Ans:
                # just ignore quit messages
                if '[email protected] QUIT' in line:
                    continue

                # On action
                elif 'ACTION' in line:
                    try:
                        self.content = re.findall(ReContent, line)[0]
                        self.user = re.findall(ReUsername, line)[0]
                        self.channel = re.findall(ReRoomName, line)[0]

                        await self.action(self.user, self.content)
                    except Exception as e:
                        print('Error in ACTION', str(e))
                        continue

                # On private message
                elif 'PRIVMSG' in line:
                    self.content = re.findall(ReContent, line)[0]
                    self.user = re.findall(ReUsername, line)[0]
                    self.channel = re.findall(ReRoomName, line)[0]

                    try:
                        if self.user != 'BanchoBot':
                            # set language to a new user
                            lang = lang_init.Initialization()
                            lang.new(self.user)

                            # Update user's stats if there are 24h since last update
                            us.dailyUpdate(self.user)
                    except Exception as e:
                        print('Error in PRIVMSG', str(e))
                        continue

                    await self.private(self.user, self.content, self.channel)
                elif 'PING' in line:
                    await self.send_content("PONG :cho.ppy.sh\r\n")

                await asyncio.sleep(0)
Exemple #27
0
def checkSession(url):

    if "SessionCookie" in request.cookies:

        if 'username' in session and 'password' in session:

            if Users.checkUser(session['username'], session['password']):
                return render_template(url, user=session['username'])

    return redirect("/server.wsgi/")
Exemple #28
0
def _context():
    print("getting a new context")
    with open('fixtures/test_state.yaml', 'r') as stream:
        maintenance.import_content(stream)
    identities.store = Users()

    class Context:
        pass

    return Context()
Exemple #29
0
def register():
    # Register a user profile (user, password)
    try:
        params = get_from_request_data(["username", "password", "email"])
    except MissingRequestParams:
        return rMissingParams(["username, password", "email"])

    try:
        Users.register_user(username, email, password)
    except RuntimeError as e:
        return rInternalServerError

    try:
        user = auth()
    except AuthenticationFailed:
        return rAuthError

    user = Users.clean_user(user)
    return jsonify(user)
Exemple #30
0
 def __init__(self):
     logging.basicConfig(
         format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
         level=logging.INFO)
     self.config = Config()
     self.updater = Updater(token=self.config.get_config(TOKEN))
     self.dispatcher = self.updater.dispatcher
     self.filter_users = Filters.user(username=Users().get_list_users())
     self.rso = ReportSO()
     self.command_list = CommandList()
Exemple #31
0
    def getUserByCookie(self, user_id):
        user = check_secure_val(user_id)

        if (user):
            UserData = Users.by_id(user)

            if (UserData is not None):
                self.redirect("/allposts")

        self.render('home.html')
Exemple #32
0
class Authentication:
    def __init__(self):
        self.users = Users()

    def is_user_exist(self, user):
        if self.users.is_exist(user):
            return True
        return False

    def get_token_data(self, user):
        user_data = self.users.get_user_data(user)
        token_datetime = user_data.get('token_datetime', None)
        verify_token = user_data.get('token', None)
        return verify_token, token_datetime

    def is_authorized(self, user, verify_token):
        if self.is_user_exist(user):
            user_token, user_datetime = self.get_token_data(user)
            if user_token == verify_token:
                dt = datetime.now()
                if dt - user_datetime > timedelta(hours=CLIENT_AUTH_TIMEOUT):
                    return 'timeout'
                self.update_token(user, verify_token, dt)
                return True
            return 'invalid token'
        return 'user not exist'

    def create_user(self, user):
        if self.is_user_exist(user):
            user_token, user_datetime = self.get_token_data(user)
            dt = datetime.now()
            if dt - user_datetime > timedelta(hours=CLIENT_AUTH_TIMEOUT):
                new_token = self.users.create_token()
                self.update_token(user, new_token, dt)
                return new_token
            return None
        new_token = self.users.insert_user(user)
        return new_token

    def update_token(self, user, token, token_datetime):
        result = self.users.update_user(user, token, token_datetime)
        return result
Exemple #33
0
def register():
    # Register a user profile (user, password)
    try:
        params = get_from_request_data(["username", "password", "email"])
    except MissingRequestParams:
        return rMissingParams(["username", "password", "email"])

    try:
        Users.register_user(params["username"], params["email"],
                            params["password"])
    except RuntimeError as e:
        return rInternalServerError

    try:
        user = auth()
    except AuthenticationFailed:
        return rAuthError

    user = Users.clean_user(user)
    return jsonify(user)
Exemple #34
0
    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'].iteritems()]
     
        super(Application, self).__init__(*args, **kwargs)
Exemple #35
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')
Exemple #36
0
def notes_storage():
  """
  Sending a GET request to this URL retrieves the notes associated with
  the user logged in (checked via the session).
  
  Sending a POST request updates the shelf with the provided new values.

  JavaScript calls this function to save/load notes.
  """
  if 'username' not in session:
    abort(401)

  with closing(shelve.open(users_file)) as user_shelf:
    users = Users(user_shelf)
    if request.method == 'GET':
      return users.stickies_for_user(session['username'])
    else:
      data = request.form['noteSet']
      users.save_stickies_for_user(session['username'], data)
      return 'Post successful'
Exemple #37
0
def update_user(user_manage: Users, username):
    if len(request.json) != 1:
        raise InvalidRequestException
    if "password" in request.json:
        password_hash = generate_password_hash(request.json["password"])
        user_manage.update_password(username, password_hash)
    elif "phone" in request.json:
        if not phonenumbers.is_valid_number(
                phonenumbers.parse(request.json["phone"], None)):
            raise InvalidRequestException
        user_dict = user_manage.update_phone(username, request.json["phone"])
        return jsonify({"user": user_dict})
    elif "role" in request.json:
        if request.json["role"] not in ["admin", "regular"]:
            raise InvalidRequestException
        user_dict = user_manage.update_role(username, request.json["role"])
        return jsonify({"user": user_dict})
    else:
        raise InvalidRequestException
    return jsonify({"message": "Password successfully changed."})
Exemple #38
0
def test2():
    n = Network("../Networks/isno_5_2")
    filename_tree = "../DataComposite/linear_structure.txt"
    loops = False
    t = ServicesTree(loops, filename_tree)
    s = Servers(t, n, "../DataComposite/test-cost.txt")
    u = Users(n, "../DataComposite/test-users.txt",
              "../DataComposite/test-user_topo.txt")

    cs = CompositeServices(n, t, s, u, opt_cong=True, congestion_cost=True)
    print(cs)
Exemple #39
0
def setup(base, conf_fn):
    print '\n**** service initialization ****\n'
    global room, courseobj, categoryobj, userobj, announcementobj, discussionobj, quizobj, messageobj
    room = Room(base, conf_fn)
    courseobj = Course()
    categoryobj = Category()
    userobj = Users()
    announcementobj = Announcement()
    discussionobj = Discussion()
    quizobj = Quiz()
    messageobj = Message()
Exemple #40
0
 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'))
Exemple #41
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
Exemple #42
0
def test_tree_syn_structure():
    filename_tree = "../DataComposite/tree_syn_structure.txt"
    loops = False
    t = ServicesTree(loops, filename_tree)
    n = Network("../Networks/geant.txt", "sndlib")
    u = Users(n)
    u.generate_users(len(t), target_alu=0.25, target_delay=0.8)
    u.write_demands("../DataComposite/geant-treesyn-alu25-del08-users.txt")
    u.write_user_topo(
        "../DataComposite/geant-treesyn-alu25-del08-user_topo.txt")
    s = Servers(t, n)
    s.generate_servers()
    s.write_servers("../DataComposite/geant-treesyn-alu25-del08-costs.txt")
Exemple #43
0
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)
Exemple #44
0
    def leaderboard(self, limit):
        leaderboard = []

        for user in Users.query().fetch():
            leaderboard.append(
                Leaderboard_entry_m(user=user.get(user.key.id()),
                                    points=user.get_points_sum(user.key.id())))

        leaderboard.sort(key=lambda x: x.points, reverse=True)

        return Leaderboard_m(leaderboard=leaderboard[:limit])
    def get_publish_info4discovery(publish, *params):
        result = {}
        longitude = params[0]
        latitude = params[1]
        user_id = params[2]
        try:
            if user_id == 0:
                result["attribute"] = -1
            else:
                result["attribute"] = UserPublishRelationMethods.get_attribute_by_user_and_publish(user_id, publish.id)

            result["publish_id"] = publish.id
            result["created_at"] = Datetimes.utc2east8(publish.created_at)
            result["win"] = UserPublishRelationMethods.get_win_attribute_count_by_publish(publish)
            result["lost"] = UserPublishRelationMethods.get_lost_attribute_count_by_publish(publish)

            if publish.user and publish.user.userextension:
                result["user_nickname"] = publish.user.userextension.nickname
            else:
                result["user_nickname"] = ""

            temp_image = Users.get_user_image(publish.user)
            result["user_small_image"] = temp_image["small_user_image"]

            temp_publish_images = Publishes.get_publish_images(publish)
            result["publish_image_url"] = temp_publish_images["publish_image_url"]
            result["publish_image_big_url"] = temp_publish_images["publish_image_big_url"]
            result["publish_image_medium_url"] = temp_publish_images["publish_image_medium_url"]
            result["publish_image_small_url"] = temp_publish_images["publish_image_small_url"]
            result["PM2_5"] = publish.PM2_5

            result["comment"] = Comments.get_by_publish(publish.id)
            result["content"] = publish.content

            result["bonus"] = RedEnvelopes.get_red_envelope_by_publish(publish.id)

            s = publish.shop
            big_category = ShopCategories.get_shop_big_category(publish.shop.category)

            if not big_category:
                big_category = ShopCategories.get_category_default()
            big_category_key = big_category.id
            result["big_category_name"] = big_category.name
            result["big_category_key"] = big_category.id

            if not big_category_key:
                result["category_operation"] = {}
            else:
                result["category_operation"] = PublishCategories.get_category_info_by_shop_category(big_category)
        except Exception as ex:
            Logs.print_current_function_name_and_line_number(ex)

        return result
Exemple #46
0
def test_add_users():
    usr1 = User("a", "*****@*****.**", "aa")
    usr2 = User("b", "*****@*****.**", "bb")
    usr3 = User("c", "*****@*****.**", "cc")
    users = Users()
    users.addUser(usr1)
    users.addUser(usr2)
    users.addUser(usr3)
    usr4 = users.getUser("*****@*****.**")
    assert usr1 == usr4
Exemple #47
0
    def leaderboard(self, limit):
        leaderboard = []

        for user in Users.query().fetch():
            leaderboard.append(Leaderboard_entry_m(
                user=user.get(user.key.id()),
                points=user.get_points_sum(user.key.id())
            ))

        leaderboard.sort(key=lambda x: x.points, reverse=True)

        return Leaderboard_m(leaderboard=leaderboard[:limit])
def login():
    if request.method == 'POST':
        if request.form['password'] == password and request.form[
                'username'] == username:
            session['admin_logged_in'] = True
            return index()
        elif Users.checkLoginAndPassword(request.form['username'],
                                         request.form['password']):
            session['logged_in'] = True
            session['user_name'] = Users.getUser(
                username=request.form['username'],
                email=request.form['username']).getName()
            session['user_id'] = Users.getUser(
                username=request.form['username'],
                email=request.form['username']).getId()
            return index()
        else:
            flash('You typed wrong username/email or password!', 'danger')
            return render_template('login.html')
    else:
        return render_template('login.html')
Exemple #49
0
def add():
    if not "user" in session:
        return redirect('/')
    if request.method == 'GET':
        return render_template('addmovie.html',
                               user=Users.loadUserId(session["user"]))
    if request.method == 'POST':
        values = (None, request.form['title'], request.form['description'],
                  session["user"], request.form['agelimit'],
                  request.form['moviedate'])
        movie = Movies(*values).create()
        return redirect('/')
Exemple #50
0
    def get(self):
        id=self.request.get('did')
        user_id = self.request.cookies.get('user_id', '0')
        user=check_secure_val(user_id)

        if(user):
            Auser=Users.by_id(user)
            if Auser :
                b=Blog.get_by_id_str(id)
                if b:
                    Like.like_on_blog(b,Auser,'down')
        self.redirect('/')
Exemple #51
0
def checkSessionPelis(url, peliculas, search):
    ret = {}
    dict_aux = {}
    if "SessionCookie" in request.cookies:
        if "basket" in session:

            obj = json.loads(session['basket'])

            buscar = obj["films"]

            dict_aux = peliculaEnCarrito(buscar)
            for resultado in peliculas:
                for peli, value in dict_aux.items():
                    if peli.titulo == resultado.titulo:
                        ret[peli] = value

        if 'username' in session and 'password' in session:

            if Users.checkUser(session['username'], session['password']):
                if len(ret) != 0:
                    if search == False:
                        return render_template(url,
                                               dict_peliculas=ret,
                                               user=session['username'])

                    else:
                        return render_template(url,
                                               dict_peliculas=ret,
                                               user=session['username'],
                                               search=True)
                else:
                    if search == False:
                        return render_template(url,
                                               peliculas=peliculas,
                                               user=session['username'])
                    else:
                        return render_template(url,
                                               peliculas=peliculas,
                                               user=session['username'],
                                               search=True)
    if len(ret) != 0:
        if search == False:
            return render_template(url, dict_peliculas=ret)

        else:
            return render_template(url, dict_peliculas=ret, search=True)
    else:
        if search == False:
            return render_template(url, peliculas=peliculas)

        else:
            return render_template(url, peliculas=peliculas, search=True)
Exemple #52
0
    def predict(self, user: str, stars: float) -> None:
        self.name = user
        self.stars = stars

        # Getting info about player and his scores
        self.user_data = us.getStat(user)
        self.user_stats = {
            'acc': self.user_data[1],
            'star_avg': self.user_data[3]
        }

        # Process prediction
        self.process()
Exemple #53
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() }
Exemple #54
0
 def checkauth(handle):
     if handle and handle not in self.open_handlers:
         username, sign = params.get('user', ''), params.get('sign', '')
         user = Users.get(username)
         if not user:
             raise AuthFailed('帐号或密码错误')
         content = message[:-(len(username) + len(sign) + 21)] + '}'
         if not all([user.secret_key, sign,
                     sign == hmac.new(ensure_utf8(user.secret_key), ensure_utf8(content), hashlib.sha256).hexdigest()]):
             raise AuthFailed('帐号或密码错误')
         if not user.able_to(protocol):
             raise AuthFailed('没有权限')
     return handle
Exemple #55
0
    def __init__(self,
                 username=None,
                 password=None,
                 access_token=None,
                 request=None):

        self.request = request or PlayNicelyRequest(username, password)

        self.projects = Projects(self.request)
        self.milestones = Milestones(self.request)
        self.items = Items(self.request)
        self.users = Users(self.request)
        self.echo = Echo(self.request)
class UserManagementTestcase(unittest.TestCase):

    def setUp(self):
        self.user = Users()
        self.current_user = USERS
        self.email = "*****@*****.**"
        self.username = "******"
        self.password = "******"


        def test_if_user_added(self):
            test_user = self.user.add_user(self.user_email, self.username, self.password)
            self.assertEqual(test_user, "User added successfully.")
Exemple #57
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()}
def is_auth():
    if request.authorization:
        user = Users.find(request.authorization['username'])
        if user and user.auth(request.authorization['password']):
            origin_url = request.headers.get("X-Original-URI")
            if [l for l in user.getPathList() if origin_url.startswith(l)]:
                return '', 200
            else:
                return '', 403
        else:
            return '', 401
    else:    
        return '', 401
Exemple #59
0
     def get(self):
        id=self.request.get('deleteid')
        user_id = self.request.cookies.get('user_id', '0')
        user=check_secure_val(user_id)

        if(user):
            Auser=Users.by_id(user)

            b=Blog.get_by_id_str(id)
            
            if (b and int(user)==int(Blog.get_by_id_str(id).created_by.key().id())):
                Blog.get_by_id_str(id).delete()
        self.redirect('/')
Exemple #60
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'))