Exemple #1
0
def confirm_email(token):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        if user.confirmed:
            flash('Account already confirmed. Thank you.', 'success')
            return redirect(url_for('member.dashboard_page'))
        else:
            try:
                email = confirm_token(token)
                if user.email == email[0]:
                    r.table('users').get(verify).update(
                        {'confirmed': True}).run(g.rdb_conn)
                    flash('You have confirmed your account. Thanks!', 'success')
                    return redirect(url_for('member.dashboard_page'))
                else:
                    flash('The confirmation link is invalid.', 'danger')
                    return redirect(url_for('user.login_page'))
            except:
                flash('The confirmation link is invalid or has expired.',
                      'danger')
                return redirect(url_for('user.login_page'))
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemple #2
0
def reqister():
    form = RegisterForm()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html',
                                   title='Register Form',
                                   form=form,
                                   message="Пароли не совпадают")
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Register Form',
                                   form=form,
                                   message="Такой пользователь уже есть")
        user = User(surname=form.surname.data,
                    name=form.name.data,
                    email=form.email.data,
                    position=form.position.data,
                    speciality=form.speciality.data,
                    address=form.address.data,
                    age=form.age.data)
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/login')
    return render_template('register.html', title='Register form', form=form)
Exemple #3
0
def next_round():
    global currentRound
    for player in Player.select().where(Player.currentRound == currentRound):
        player.time += timer.get_duration()  # Maximal time
        player.currentRound += 1
        bot.send_message(player.tg_id, config.endingOfRound)
        if player.currentRound <= 9:
            bot.send_message(player.tg_id, config.nextKpName.format(
                config.kp_rus.get(config.kp[player.race - 1][player.currentRound],
                                  default=config.kp[player.race - 1][player.currentRound])))
        player.save()
        try:
            kp = User.get(User.role == Role.KP and User.challenge.round == player.round and User.challenge.name ==
                          config.kp[player.race - 1][player.currentRound])
            # kp = User.get(User.currentTeamName == player.name)
        except DoesNotExist:
            logger.critical("Can't find active kp for {} - @{}".format(player.name, player.username))
            bot.send_message(config.creatorID, "Can't find active kp for {} - @{}".format(player.name, player.username))
            kp = None
        if kp is not None:
            bot.send_message(kp.tg_id, 'Раунд закончился, пожалуйста введите комманду /add <num> чтобы добавить '
                                       'энергию команде. Если энергии не полагается введите /add 0')
    if currentRound < 9:
        for user_kp in User.select().where(User.role == Role.KP and User.currentTeamName == 'waiting'):
            user_kp.currentTeamName = set_next_team(user_kp, currentRound + 1)
            user_kp.save()
    currentRound += 1
    logger.info("Round {} has started".format(currentRound))
    if currentRound < 10:
        timer.start(next_round)
    else:
        everyone(config.startChanging)
        timer.set_duration(60*60)
        timer.start(ending)
Exemple #4
0
class Tank(Singleton):

    def init_os(self):
        self._user = User()
        self._user.setup()


    def init_software(self):
        self._software = Software()
        self._software.setup()
        self._software.print_header()

        self._user = User()
        self._user.setup()


    @property
    def software(self):
        return Software()

    @property
    def user(self):
        return self._user

    @property
    def context(self):
        return self._software.context

    @property
    def data(self):
        return libData.get_data()
Exemple #5
0
class TestUser(unittest.TestCase):
    '''
    Test class that defines test cases for the user class behavior.

    Args:
        unittest.Testcase: helps in creating test cases
    '''

    def setUp(self):
        '''
        set up method to run before each test cases.
        '''
        self.new_user = User("badar","noor","badar124")

    def test_init(self):
        '''
        test case to check if the object is initialized properly.
        '''
        self.assertEqual(self.new_user.first_name,"badar")
        self.assertEqual(self.new_user.last_name,"noor")
        self.assertEqual(self.new_user.password,"badar124")

    def test_save_user(self):
        '''
            test case to check if the user object is saved into the user list
        '''

        self.new_user.save_user()
        self.assertEqual(len(User.user_list),1)
Exemple #6
0
    def login(self):
        username = input("What is your name? ")
        if username.lower() not in SystemInfo.users_info:
            print("You are not part of the system. Contact the admin.")
            sys.exit(0)

        else:
            if SystemInfo.users_info[username]["role"] == "student":
                course = input("What course is this for? ").upper()
                if course not in SystemInfo.users_info[username]["course"]:
                    print("You are not enrolled in this course.")
                    sys.exit(0)
                else:
                    join_this_course = Course(course, SystemInfo.course_info[course])
                    student = User(username, join_this_course)
                    student.startCollab(join_this_course)

            elif SystemInfo.users_info[username]["role"] == "professor":
                course = input("What course are you here for? ").upper()
                if course not in SystemInfo.users_info[username]["course"]:
                    print("You are not teaching this course.")
                    sys.exit(0)
                else:
                    join_this_course = Course(course, SystemInfo.course_info[course])
                    professor = Professor(username, join_this_course)
                    professor.uploadLectureOutline()
                    professor.startCollab(join_this_course)

            elif SystemInfo.users_info[username]["role"] == "admin":
                admin = Administrator(username)
                admin.maintainSystem()
def delreaction_page(rid):
    '''
    Dashboard Delete Domains:
    This will delete a domain based on url parameters
    '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        if user.status != "active":
            pass
        else:

            appliedcount = 0
            results = r.table('monitors').filter({
                'uid': user.uid
            }).run(g.rdb_conn)
            for x in results:
                if rid in x['data']['reactions']:
                    appliedcount = appliedcount + 1

            if appliedcount < 1:
                # Delete the Reaction
                reaction = Reaction(rid)
                result = reaction.deleteReaction(user.uid, rid, g.rdb_conn)
                if result:
                    flash('Reaction was successfully deleted', 'success')
                else:
                    flash('Reaction was not deleted', 'danger')
            else:
                flash(
                    'You must first detach this reaction from all monitors before deleting',
                    'danger')
    return redirect(url_for('member.dashboard_page'))
Exemple #8
0
def delcheck_page(cid):
    '''
    Dashboard Delete Checks:
    This will delete health checks via the url parameters
    '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        if user.status != "active":
            pass
        else:

            # Delete the Monitor
            monitor = Monitor(cid)
            monitor.get(cid, g.rdb_conn)
            result = monitor.deleteMonitor(user.uid, cid, g.rdb_conn)
            if result:
                print("/dashboard/delete-checks - Delete successful")
                flash('Health Check was successfully deleted.', 'success')
            else:
                print("/dashboard/delete-checks - Delete failed")
                flash('Health Check was not deleted', 'danger')
    return redirect(url_for('member.dashboard_page'))
Exemple #9
0
def detailhistory_page(cid, hid):
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/detail-history/' + hid
        tmpl = 'monitors/detail-history.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            monitor = Monitor()
            monitor.get(cid, g.rdb_conn)
            if monitor.uid == user.uid:
                data['monitor'] = {
                    'cid': monitor.cid,
                    'name': monitor.name,
                    'ctype': monitor.ctype,
                    'uid': monitor.uid,
                    'data': monitor.data
                }
                data['monitor-history'] = monitor.history(
                    method="detail-history", hid=hid, rdb=g.rdb_conn)
            else:
                flash('This monitor does not belong to your user.', 'warning')
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
 def setUp(self):
     self.new_user = User('Vikki', 'Ireri', '*****@*****.**',
                          'akisijui', [])
     self.new_account = Account('Instagram', 'https://www.instagram.com/',
                                '*****@*****.**', '12345')
     self.new_account1 = Account('Facebook', 'https://www.facebook.com/',
                                 '*****@*****.**', '67890')
Exemple #11
0
	def add_friend(self, user1_id, user2_id):
		"""
		Checks if either of the users indexed by user id is in the network
		if one of them is not in the nework, creates and adds that user and
		then connects the 2 users

		If both users don't exist in the network, creates both, adds them to the
		network and connects them
		Args:
		    user1_id:
		    user2_id:

		Returns:

		"""
		if (user1_id in self.network or user2_id in self.network):
			if user1_id in self.network and not user2_id in self.network:
				#self.logger.info("User %s does not exist in network.", user2_id)
				# create user 2
				user2 = User(user2_id, self.num_tracked)
				self.add_user(user2)
			elif not user1_id in self.network and user2_id in self.network:
				#self.logger.info("User %s does not exist in network.", user1_id)
				# create user 1
				user1 = User(user1_id, self.num_tracked)
				self.add_user(user1)
		else:
			#self.logger.info("User %s and %s do not exist in network.", user1_id, user2_id)
			user1 = User(user1_id, self.num_tracked)
			user2 = User(user2_id, self.num_tracked)
			self.add_user(user1)
			self.add_user(user2)

		self.network[user1_id].add_friend(user2_id)
		self.network[user2_id].add_friend(user1_id)
Exemple #12
0
def time_checker():
    memo_list = return_overdue_memos(datetime.datetime.now())
    for memo in memo_list:
        if memo.memo_type == 'text':
            text = f"Время повторить 🧠\n<b><i>{memo.memo_name}</i>(Текстовый)</b>\n\n{file_reader.txt_read(memo.link)}"
            bot.send_message(memo.user_id,
                             text,
                             parse_mode='html',
                             reply_markup=keyboards.back_to_main)
            memo.notify_time += test_notify_delta[memo.notify_count + 1]
            memo.notify_count += 1
            if memo.notify_count >= 5:
                bot.send_message(
                    memo.user_id,
                    f"<b>Memo <i>{memo.memo_name}</i></b> закреплен в вашей памяти надолго.",
                    parse_mode='html',
                    reply_markup=keyboards.back_to_main)
            else:
                user = User(memo.user_id)
                user.add_memo(new_memo=memo)

        elif memo.memo_type == 'file':
            pass
        else:
            pass
    print(time.ctime(), "(time_checker)")
    threading.Timer(3, time_checker).start()
Exemple #13
0
 def test_getRID_works(self):
     # Ensure that getRID() works as expected.
     timestamp = str(datetime.datetime.now())
     new_timestamp = timestamp.replace(":", "")
     with self.client:
         self.client.post(
             '/login',
             data=dict(email="*****@*****.**", password="******"),
             follow_redirects=True
         )
         self.client.post(
             '/dashboard/reactions/enotify',
             data=dict(name=new_timestamp, trigger=1,
                       frequency=1, email="*****@*****.**",
                       send_true=True),
             follow_redirects=True
         )
         user = User()
         user_id = user.getUID('*****@*****.**', g.rdb_conn)
         get_reaction_id = Reaction()
         response = get_reaction_id.getRID(
             new_timestamp+':'+user_id, g.rdb_conn)
         results = r.table('reactions').filter(
             {'name': new_timestamp}).run(g.rdb_conn)
         for result in results:
             reaction_id = result['id']
             break
         self.assertEqual(response, reaction_id)
Exemple #14
0
def checkaction_page(cid, action):
  ''' Dashboard Delete Checks: This will delete health checks via the url parameters '''
  verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
  if verify: 
    user = User()
    user.get('uid', verify, g.rdb_conn)
    if user.status != "active":
      pass
    else:
      
      ## Delete the Monitor
      monitor = Monitor(cid)
      monitor.get(cid, g.rdb_conn)
      if user.uid == monitor.uid:
        if action == "failed":
          monitor.healthcheck = "web-failed"
          result = monitor.webCheck(g.rdb_conn)
          print("/dashboard/action-checks - Manual monitor failure")
        elif action == "healthy":
          monitor.healthcheck = "web-healthy"
          print("/dashboard/action-checks - Manual monitor healthy")
          result = monitor.webCheck(g.rdb_conn)
        
        if result:
          print("/dashboard/action-checks - Manual monitor queued")
          flash('Health check status change is queued', 'success')
        else:
          print("/dashboard/action-checks - Manual monitor action failed")
          flash('Something went wrong. Could not modify health check', 'danger')
      else:
        print("/dashboard/action-checks - Manual monitor action failed: do not own")
        flash('It does not appear you own this health check', 'danger')

  return redirect(url_for('dashboard_page'))
Exemple #15
0
def userpref_page():
  ''' Dashbaord User Preferences: This will allow a user to change user preferences, i.e. Password '''
  verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
  if verify:
    user = User()
    user.get('uid', verify, g.rdb_conn)
    data = startData(user)
    data['active'] = 'dashboard'
    if user.status != "active":
      data['url'] = '/dashboard/mod-subscription'
      tmpl = 'mod-subscription.html'
    else:
      
      ## Start processing the change password form
      form = ChangePassForm(request.form)
      if request.method == 'POST':
        if form.validate():
          result = user.setPass(form.password.data, g.rdb_conn)
          if result:
            data['msg'] = "Password successfully changed"
            print("/dashboard/user-preferences - Password changed")
            data['error'] = False
          else:
            data['msg'] = "Password change was unsuccessful"
            print("/dashboard/user-preferences - Password change failed")
            data['error'] = True
      data['url'] = '/dashboard/user-preferences'
      tmpl = 'user-preferences.html'
    page = render_template(tmpl, data=data, form=form)
    return page
  else:
    return redirect(url_for('login_page'))
Exemple #16
0
def language_update_handler(user: User, update: Update,
                            context: CallbackContext):
    if update.message.text == get_language_token(user.language,
                                                 Tokens.LANGUAGE_ENGLISH):
        user.language = "en"
        session.commit()
        del context.user_data["state"]
        update.message.reply_text(
            get_language_token(user.language,
                               Tokens.LANGUAGE_CHANGE_SUCCESSFUL),
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=get_main_keyboard_markup(user.language))
    elif update.message.text == get_language_token(user.language,
                                                   Tokens.LANGUAGE_TURKISH):
        user.language = "tr"
        session.commit()
        del context.user_data["state"]
        update.message.reply_text(
            get_language_token(user.language,
                               Tokens.LANGUAGE_CHANGE_SUCCESSFUL),
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=get_main_keyboard_markup(user.language))
    else:
        update.message.reply_text(
            get_language_token(user.language,
                               Tokens.PLEASE_SELECT_VALID_LANGUAGE),
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=get_language_selection_keyboard_markup(user.language))
Exemple #17
0
 def test_check_password(self):
     # Ensure given password is correct after unhashing
     user = User()
     user.config = app.config
     user = user.get('username', '*****@*****.**', g.rdb_conn)
     self.assertTrue(user.checkPass('password456', g.rdb_conn))
     self.assertFalse(user.checkPass('wrong!', g.rdb_conn))
Exemple #18
0
class TestUsers(unittest.TestCase):
    '''
    Test class that defines test cases for the users class behaviours.
    '''
    def tearDown(self):
        '''
        tearDown method to run after each test case.
        '''

    User.users = []

    def setUp(self):
        '''
        Set up method to run before each test cases.
        '''

        self.new_user = User("Sheila", "SheeKam")

    def test_init(self):
        '''
        test case to test if the object is initialized properly
        '''
        self.assertEqual(self.new_user.user_name, "Sheila")
        self.assertEqual(self.new_user.password, "SheeKam")

    def test_create_account(self):
        '''
        test if the user object is saved into the user list
        '''
        self.new_user.create_account()
        self.assertEqual(len(User.users), 1)
Exemple #19
0
def load():
    from storage import load_users, load_pool
    users = load_users()
    User.users().extend(users)
    _pool = load_pool()
    journal.pool = _pool
    print('load!')
Exemple #20
0
def managereactions_page():
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/'
        data['js_bottom'] = [ 'member/reactions.js' ]
        tmpl = 'member/reactions.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass
        data['reactions'] = user.getReactions(g.rdb_conn)
        if len(data['reactions']) < 1:
            data['reacts'] = False
        else:
            data['reacts'] = True
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemple #21
0
 def test_initial_permissions(self):
     # Ensure initial permissions are set correctly
     user = User()
     user.config = app.config
     user_test = user.get('username', '*****@*****.**', g.rdb_conn)
     self.assertTrue(user_test.acttype == "lite-v2")
     self.assertFalse(user_test.acttype == "pro")
Exemple #22
0
class TestClass(unittest.TestCase):
    """
    A Test class that defines test cases for the User class.
    """
    def setUp(self):
        """
        Method that runs before each individual test methods run.
        """

        self.new_user = User('GeorgeKilewa', 'StAiGhTOrSyoki@#@&')

    def test_init(self):
        """
        test case to chek if the object has been initialized correctly
        """
        self.assertEqual(self.new_user.username, 'GeorgeKilewa')
        self.assertEqual(self.new_user.password, 'StAiGhTOrSyoki@#@&')

    def test_save_user(self):
        """
        test case to test if a new user instance has been saved into the User list

        """
        self.new_user.save_user()
        self.assertEqual(len(User.user_list), 1)
Exemple #23
0
    def init_software(self):
        self._software = Software()
        self._software.setup()
        self._software.print_header()

        self._user = User()
        self._user.setup()
 def setUp(self):
     '''
     This method stands for what is to to be loaded when the test class is run
     '''
     self.new_user = User("admin", "admin")
     self.new_credentials = Credential("admin", "twitter", "admin",
                                       "*****@*****.**", "123456")
Exemple #25
0
    def update(self,
               user: User,
               video: Video,
               watch_time: float,
               gamma: float = 0.05):
        """ Updates the environment
        :param user: user
        :param video: video recommended to the user
        :param watch_time: effective watch time of the video by the user
        :param gamma: evolution parameter (learning rate)
        """

        # Type-checking
        if not isinstance(user, User):
            raise TypeError
        if not isinstance(video, Video):
            raise TypeError
        if not isinstance(watch_time, float):
            raise TypeError
        if not isinstance(gamma, float):
            raise TypeError

        user.add_to_history(video.video_id, watch_time)  # history update
        if self.evolutive:  # if the environment is evolutive,
            user.evolve(video, watch_time, gamma)  # the user tastes can evolve
Exemple #26
0
 def test_getRID_works(self):
     # Ensure that getRID() works as expected.
     timestamp = str(datetime.datetime.now())
     new_timestamp = timestamp.replace(":", "")
     with self.client:
         self.client.post(
             '/login',
             data=dict(email="*****@*****.**", password="******"),
             follow_redirects=True
         )
         self.client.post(
             '/dashboard/reactions/enotify',
             data=dict(name=new_timestamp, trigger=1,
                       frequency=1, email="*****@*****.**",
                       send_true=True),
             follow_redirects=True
         )
         user = User()
         user_id = user.getUID('*****@*****.**', g.rdb_conn)
         get_reaction_id = Reaction()
         response = get_reaction_id.getRID(
             new_timestamp+':'+user_id, g.rdb_conn)
         results = r.table('reactions').filter(
             {'name': new_timestamp}).run(g.rdb_conn)
         for result in results:
             reaction_id = result['id']
             break
         self.assertEqual(response, reaction_id)
Exemple #27
0
def confirm_email(token):
    verify = verifyLogin(app.config["SECRET_KEY"], app.config["COOKIE_TIMEOUT"], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get("uid", verify, g.rdb_conn)
        if user.confirmed:
            flash("Account already confirmed. Thank you.", "success")
            return redirect(url_for("member.dashboard_page"))
        else:
            try:
                email = confirm_token(token)
                if user.email == email[0]:
                    r.table("users").get(verify).update({"confirmed": True}).run(g.rdb_conn)
                    flash("You have confirmed your account. Thanks!", "success")
                    return redirect(url_for("member.dashboard_page"))
                else:
                    flash("The confirmation link is invalid.", "danger")
                    return redirect(url_for("user.login_page"))
            except:
                flash("The confirmation link is invalid or has expired.", "danger")
                return redirect(url_for("user.login_page"))
    else:
        flash("Please Login.", "warning")
        return redirect(url_for("user.login_page"))
Exemple #28
0
def do_login():
	un = request.forms.get('username')
	pw = request.forms.get('password')
	h_pw = computeMD5hash(pw)
	User.create(username=un, password=h_pw)
	macaron.bake()
	redirect("/login")
Exemple #29
0
def delcheck_page(cid):
    '''
    Dashboard Delete Checks:
    This will delete health checks via the url parameters
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        if user.status != "active":
            pass
        else:

            # Delete the Monitor
            monitor = Monitor(cid)
            monitor.get(cid, g.rdb_conn)
            result = monitor.deleteMonitor(user.uid, cid, g.rdb_conn)
            if result:
                print("/dashboard/delete-checks - Delete successful")
                flash('Health Check was successfully deleted.', 'success')
            else:
                print("/dashboard/delete-checks - Delete failed")
                flash('Health Check was not deleted', 'danger')
    return redirect(url_for('member.dashboard_page'))
Exemple #30
0
class Tank(Singleton):
    def init_os(self):
        # self._notificator = Notificator()
        # self._notificator.setup()
        pass

    def init_software(self):
        self._software = Software()
        self._software.setup()
        self._software.print_header()

        self._user = User()
        self._user.setup()

        self._context = Context()
        self._context.setup()

    @property
    def software(self):
        return self._software

    @property
    def user(self):
        return self._user

    @property
    def context(self):
        return self._context
Exemple #31
0
def detailhistory_page(cid, hid):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/detail-history/' + hid
        tmpl = 'monitors/detail-history.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            monitor = Monitor()
            monitor.get(cid, g.rdb_conn)
            if monitor.uid == user.uid:
                data['monitor'] = {
                    'cid': monitor.cid,
                    'name': monitor.name,
                    'ctype': monitor.ctype,
                    'uid': monitor.uid,
                    'data': monitor.data
                }
                data['monitor-history'] = monitor.history(
                    method="detail-history", hid=hid, rdb=g.rdb_conn)
            else:
                flash('This monitor does not belong to your user.', 'warning')
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemple #32
0
def dialog():
    print(1)
    u = User()
    print(2)
    u.chat_id = list(Tags.handlers.keys())[-1]
    print(3)
    print(list(Tags.handlers.keys())[-1])
    print(4)
    print(u.chat_id)
    print(5)
    u.changeScope('/tags')
    print(6)
    print(f'=0 : {check_tags()}')
    print(7)
    if check_tags():
        print(8)
        start = yield from user_has_no_tag(
            '''Набор тегів - це список ключових слів, по яким я можу сказати є вони в законопроекті чи немає.
Дуже корисна річ для моніторингу та аналізу.
Краще поєднувати теги в набори за певною ознакою, наприклад *Корпоративне Управління*.
Давайте створимо ваш перший набір тегів. Як ми будемо його називати?''')
        print(9)
    else:
        start = yield from user_has_tags('У вас вже є набори тегів.')
        print(start)
        print(10)
Exemple #33
0
def attempt_duplicate():
    if not (current_user.get_id() == admin_user.get_id()):
        return jsonify({
            "success": False,
            "message": "not authorized",
            "alert_type": "alert-warning"
        })
    data = request.json
    result_dict = User.create_new({
        "username": data["username"],
        "password": data["password"]
    })
    if result_dict["success"]:
        # Copy over all of the starter resources for the new user
        repository_user = User.get_user_by_username("repository")
        new_user = User.get_user_by_username(data["username"])
        for res_type in res_types:
            starters = repository_user.get_resource_names(res_type,
                                                          tag_filter="starter")
            for rname in starters:
                copy_between_accounts(repository_user, new_user, res_type,
                                      rname, rname)
        old_user = User.get_user_by_username(data["old_username"])
        for res_type in res_types:
            starters = old_user.get_resource_names(res_type)
            for rname in starters:
                copy_between_accounts(old_user, new_user, res_type, rname,
                                      rname)
        result_dict["message"] = "user duplicated apparently"
    else:
        result_dict["message"] = "something went wrong"
    return jsonify(result_dict)
Exemple #34
0
def managereactions_page():
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/'
        data['js_bottom'] = [ 'member/reactions.js' ]
        tmpl = 'member/reactions.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass
        data['reactions'] = user.getReactions(g.rdb_conn)
        if len(data['reactions']) < 1:
            data['reacts'] = False
        else:
            data['reacts'] = True
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemple #35
0
 def test_password_hashing_is_random(self):
     # Ensure that a password salt/hash is random
     user_one = User()
     user_two = User()
     password_one = user_one.createPass("test")
     password_two = user_two.createPass("test")
     self.assertTrue(password_one != password_two)
Exemple #36
0
def delreaction_page(rid):
    '''
    Dashboard Delete Domains:
    This will delete a domain based on url parameters
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        if user.status != "active":
            pass
        else:

            appliedcount = 0
            results = r.table('monitors').filter(
                {'uid': user.uid}).run(g.rdb_conn)
            for x in results:
                if rid in x['data']['reactions']:
                    appliedcount = appliedcount + 1

            if appliedcount < 1:
                # Delete the Reaction
                reaction = Reaction(rid)
                result = reaction.deleteReaction(user.uid, rid, g.rdb_conn)
                if result:
                    flash('Reaction was successfully deleted.', 'success')
                else:
                    flash('Reaction was not deleted.', 'danger')
            else:
                flash('You must first detach this reaction \
                      from all monitors before deleting.', 'danger')
    return redirect(url_for('member.dashboard_page'))
Exemple #37
0
 def test_user_change_password(self):
     u = User.create(name='test', password='******')
     u = User.get(User.name == 'test')
     u.set_password('pass_2')
     u.save()
     u = User.get(User.name == 'test')
     ok_(not u.verify_password('pass_1'))
     ok_(u.verify_password('pass_2'))
 def test_save_multiple_users(self):
         '''
        test_save_multiple_users tests if we can save more than one users on our user list
         '''
         self.new_user.save_user()
         test_user = User("Alice","Umulisa","aliumu") 
         test_user.save_user()
         self.assertEqual(len(User.users_list),2)
Exemple #39
0
    def test_user_exists(self):
        """ confirming tha the user actually exists """
        self.new_user.saveUser()
        test_user = User("ManDavis", "davis@gmail", "dave", "d21")
        test_user.saveUser()

        user = User.user_exists("MbuguaM")
        self.assertTrue(user)
Exemple #40
0
def check_tags():
    u = User()
    u.chat_id = list(Tags.handlers.keys())[-1]
    user_tags = u.getTags()
    if len(user_tags) == 0:
        return True
    else:
        return False
Exemple #41
0
 def test_user_auth(self):
     """
     test_users_auth tests case to authenticate the user
     """
     self.new_user.save_login()
     test_user = User("trinity", "*****@*****.**", "123")
     test_user.save_login()
     self.assertTrue(self.new_user.users_auth("trinity", "123"))
 def test_user_update(self):
     a = User('A', 'Family', date(1990, 12, 1), '*****@*****.**', '1234')
     user_id = self._user_manager.add_user(a)
     b = User('B', 'Family', date(1990, 12, 2), '*****@*****.**', '1234')
     self._user_manager.update_user(user_id, b)
     updated_user = self._user_manager.find_user_by_id(user_id)
     self.assertEqual(updated_user.first_name, b.first_name)
     self.assertEqual(updated_user.email, b.email)
Exemple #43
0
def get_next_best_stations(phone_number):
    user = User(phone_number)

    stations = station_api.get_best_station(user.station_lat, user.station_lon)
    user.add_event("get_next_best_station")
    user.add_event("get_next_best_station_result", stations['second']['bike']['location_name'])

    return stations['second']
Exemple #44
0
 def get(self, user_id="__INVALID__"):
     
     user_data = User()
     if user_id == "__INVALID__":
         #No ID provided, return all users
         return user_data.findAll()
     else:
         #Find user by ID in path
         return user_data.findById(user_id)
Exemple #45
0
 def delete(self, user_id="__INVALID__"):
     
     # --- VALIDATION ----
     if user_id == "__INVALID__": 
         raise MethodNotAllowedError
         
     # --- DATA METHOD ---
     user_data = User()
     return user_data.delete(user_id)
Exemple #46
0
 def add_super_user(self, name='admin', password=None):
     """ Add a new user in the superuser group.
     This is particularly handy to bootstrap a new system in pshell.
     """
     user= User(self.request, firstname=name.capitalize(), lastname='User', groups=['superuser'], active=True, email='')
     if not password:
         password = generate_random_password()
     user.set_password(password)
     self['users'].add_child(name, user)
     print "Created superuser with username %s and password %s" % (name, password)
Exemple #47
0
def get_user(id=None, name=None):
    try:
        if id:
            return User.get(User.id==id)
        elif name:
            return User.get(User.name==name)
        else:
            raise ValueError('nither `id` or `name` was given')
    except User.DoesNotExist:
        raise NotFoundException("no user could be found with these attributes")
Exemple #48
0
 def put(self, user_id="__INVALID__"):
     
     # --- VALIDATION ----
     if user_id == "__INVALID__": 
         raise MethodNotAllowedError
     user = request.json
     
     # --- DATA METHOD ---
     user_data = User()
     return user_data.update(user)
Exemple #49
0
 def post(self, user_id="__INVALID__"):
     
     # --- VALIDATION ----
     if user_id != "__INVALID__": 
         raise MethodNotAllowedError
     
     user = request.get_json()
         
     # --- DATA METHOD ---
     user_data = User()
     return user_data.create(user)
Exemple #50
0
def signup():
  ''' User Sign up page: Very basic email + password sign up form that will also login users. '''
  ## Data is used throughout for the jinja2 templates
  data={
    'active': "signup", # Sets the current page
    'loggedin': False # Don't show the logout link
  }

  ## Define the SignupForm
  form = SignupForm(request.form)
  ## Validate and then create userdata
  if request.method == "POST":
    if form.validate():
      ## Take form data
      email = form.email.data
      password = form.password.data
      company = form.company.data
      contact = form.contact.data
      userdata = {
        'username': email,
        'email': email,
        'password': password,
        'company': company,
        'contact': contact
      }

      ## Create user 
      user = User()
      result = user.createUser(userdata, g.rdb_conn)
      ## Check results for success or failure
      if result == "exists":
        data['error'] = True
        data['msg'] = 'User already exists'
      elif result is not False:
        stathat.ez_count(app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' User Signup', 1)
        print("/signup - New user created") 
        cdata = cookies.genCdata(result, app.config['SECRET_KEY'])
        data['loggedin'] = True
        data['msg'] = 'You are signed up'
        data['error'] = False
        ## Build response
        resp = make_response(redirect(url_for('dashboard_page')))
        timeout = int(time.time()) + int(app.config['COOKIE_TIMEOUT'])
        ## Set the cookie secure as best as possible
        resp.set_cookie('loggedin', cdata, expires=timeout, httponly=True)
        return resp
    else:
      stathat.ez_count(app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Failed User Signup', 1)
      print("/signup - Failed user creation") 
      data['msg'] = 'Form is not valid'
      data['error'] = True

  ## Return Signup Page
  return render_template('signup.html', data=data, form=form)
Exemple #51
0
def signup():
    """
    User Sign up page: Very basic email + password
    sign up form that will also login users.
    """
    # Data is used throughout for the jinja2 templates
    data = {"active": "signup", "loggedin": False}  # Sets the current page  # Don't show the logout link

    # Define the SignupForm
    form = SignupForm(request.form)
    # Validate and then create userdata
    if request.method == "POST":
        if form.validate():
            # Take form data
            email = form.email.data
            password = form.password.data
            company = form.company.data
            contact = form.contact.data
            userdata = {"username": email, "email": email, "password": password, "company": company, "contact": contact}

            # Create user
            user = User()
            user.config = app.config
            result = user.createUser(userdata, g.rdb_conn)
            # Check results for success or failure
            if result == "exists":
                flash("User already exists.", "danger")
            elif result is not False:
                try:
                    stathat.ez_count(app.config["STATHAT_EZ_KEY"], app.config["ENVNAME"] + " User Signup", 1)
                except:
                    pass
                print("/signup - New user created")
                cdata = cookies.genCdata(result, app.config["SECRET_KEY"])
                data["loggedin"] = True
                flash("You are signed up.", "success")

                # Generate confirmation token
                generate_confirmation_token(email, result, time.time())

                # Build response
                resp = make_response(redirect(url_for("member.dashboard_page")))
                timeout = int(time.time()) + int(app.config["COOKIE_TIMEOUT"])
                # Set the cookie secure as best as possible
                resp.set_cookie("loggedin", cdata, expires=timeout, httponly=True)
                return resp
        else:
            stathat.ez_count(app.config["STATHAT_EZ_KEY"], app.config["ENVNAME"] + " False User Signup", 1)
            print("/signup - False user creation")
            flash("Form is not valid.", "danger")

    # Return Signup Page
    return render_template("user/signup.html", data=data, form=form)
    def done(self):
        #make sure the user doesn't already exist
        u = User.by_name(self.username)
        if u:
            msg = 'That user already exists.'
            self.render('signup-form.html', error_username = msg)
        else:
            u = User.register(self.username, self.password, self.email)
            u.put()

            self.login(u)
            self.redirect('/blog')
Exemple #53
0
    def _getKeyboard(self, msg):
        sub = User()
        if sub.isRegistered(msg):
            kb = {'keyboard':[['Check'], ['Unsubscribe']],
                  'resize_keyboard': True}
        else:
            kb = {'keyboard':[['Check'],['Subscribe']],
                  'resize_keyboard': True}

        if sub.isAdmin(msg):
            kb = {'keyboard': [['Check'], ['Update']],
                  'resize_keyboard': True}
        return json.dumps(kb)
Exemple #54
0
	def signUp(username, userid):
		CONST_ERROR_ALR_REG = 0
		CONST_OPTION_REG_SUCCESS = 1

		user_query = (User.query()).fetch()	# Get all users in the datastore
		# If this user already exists
		if (any(q.user_id == userid for q in user_query)):
			return CONST_ERROR_ALR_REG
		# Else if this user has not been registered
		else:
			new_user = User(user_name=str(username), user_id=userid)
			new_user.put()
			return CONST_OPTION_REG_SUCCESS
Exemple #55
0
 def test_correct_login(self):
     # Ensure login behaves correctly with correct credentials
     with self.client:
         self.client.post(
             '/login',
             data=dict(email="*****@*****.**", password="******"),
             follow_redirects=True
         )
         user = User()
         user = user.get('username', '*****@*****.**', g.rdb_conn)
         active = user.is_active('*****@*****.**', g.rdb_conn)
         self.assertTrue(user.email == "*****@*****.**")
         self.assertTrue(active)
Exemple #56
0
def modsub_page():
    '''Dashboard Modify Subscription:
    This will allow a user to modify their subscription and account plan
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/mod-subscription'
        data['uid'] = user.uid
        tmpl = 'member/mod-subscription.html'
        data['js_bottom'].append('forms/subscribe.js')
        form = []
        from generalforms import subscribe

        payment = __import__("payments." + user.payments, globals(),
                             locals(), ['Payments'], -1)

        subscription = payment.Payments(user=user, config=app.config, rdb=g.rdb_conn)
        if request.method == "POST":
            if data['upgraded'] is True:
                result = subscription.adjust(request)
            else:
                result = subscription.create(request)

            if result is True:
                if data['upgraded'] is True:
                    flash('Adjustment to subscription successful', 'success')
                else:
                    data['upgraded'] = True
                    flash('Successfully Subscribed!', 'success')
                newdata = startData(user)
                data['limit'] = newdata['limit']
                data['rlimit'] = newdata['rlimit']
                data['acttype'] = newdata['acttype']
                data['subplans'] = newdata['subplans']
                data['cost'] = newdata['cost']
                data['subscription'] = newdata['subscription']
            else:
                flash('Unable to adjust subscription please notify support', 'danger')
        if data['upgraded'] is True:
            form = subscribe.AddPackForm(request.form)
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Exemple #57
0
def login_page():
    ''' User login page: This is a basic login page'''
    data = {
        'active': 'login',
        'loggedin': False
    }

    # Define and Validate the form
    form = LoginForm(request.form)
    if request.method == "POST":
        if form.validate():
            email = form.email.data
            password = form.password.data

            # Start user definition
            user = User()
            if user.get('username', email, g.rdb_conn):
                result = user.checkPass(password, g.rdb_conn)
                if result is True:
                    data['loggedin'] = True
                    data['msg'] = 'You are logged in'
                    data['error'] = False
                    print("/login - User login successful")
                    # Start building response
                    resp = make_response(
                        redirect(url_for('member.dashboard_page')))
                    cdata = cookies.genCdata(
                        user.uid, app.config['SECRET_KEY'])
                    timeout = int(time.time()) + \
                        int(app.config['COOKIE_TIMEOUT'])
                    # Set cookie as securely as possible
                    resp.set_cookie(
                        'loggedin', cdata, expires=timeout, httponly=True)
                    print("Setting cookie")
                    return resp
                else:
                    data['msg'] = 'Password does not seem valid'
                    data['error'] = True
                    print("/login - User login error: wrong password")
            else:
                data['msg'] = 'Uhh... User not found'
                print("/login - User login error: invalid user")
                data['error'] = True
        else:
            data['msg'] = 'Form is not valid'
            print("/login - User login error: invalid form")
            data['error'] = True

    # Return Login Page
    page = render_template('user/login.html', data=data, form=form)
    return page
Exemple #58
0
 def test_registered_user_time_attribue(self):
     # Ensure that a registered user has creation_time attribute
     with self.client:
         response = self.client.post('/signup', data=dict(
             email='*****@*****.**',
             company="test",
             contact="test",
             password='******',
             confirm='test_user'
         ), follow_redirects=True)
         self.assertEqual(response.status_code, 200)
         user = User()
         user = user.get('username', '*****@*****.**', g.rdb_conn)
         self.assertTrue(user.creation_time)
Exemple #59
0
    def handle_cmd_login(self, user, msg):
        # Usage: login <nick> <password>
        try:
            tmpmsg = msg.split()
            nick = tmpmsg[1]
            password = tmpmsg[2]
        except IndexError:
            self.msg(user, 'Usage: login <nick> <password>')
            return

        # Number of seconds to delay next login attempt on bad password
        penalty = 20
        penalty_delta = datetime.timedelta(seconds=20)
        # Current timestamp
        now = datetime.datetime.now()

        # Check if last attempt is more than penalty seconds ago
        if 'badpass' in self.users[nick]:
            if self.users[nick]['badpass'] >= now:
                self.msg(user, ("You're trying too often to log in! Added %i" +
                                " seconds again.") % penalty)
                log.msg("User '%s' is trying to log in too fast for '%s'." %
                        (user, nick))
                self.users[nick]['badpass'] += penalty_delta
                return

        # Hash the password
        pwd = hashlib.sha256(password).digest()

        # Check if we have a user object, because then you're already logged in
        if 'obj' in self.users[nick]:
            self.msg(user, 'You are already logged in!')
            return

        userobj = User(nick)
        # Compare hashes
        if userobj.pwhash == pwd:
            userobj.add_hostmask(self.users[nick]['hostmask'])
            self.users[nick]['obj'] = userobj
            self.msg(user, "Password recognised. You've been logged in and " +
                     "your hostmask has been added to the known list.")
            log.msg("User '%s' has succesfully logged in as '%s'." % (user,
                                                                      nick))
        else:
            log.msg("Bad password entered for '%s' by '%s'." % (nick, user))
            self.msg(user, 'Password not known. Try again in %i seconds.' %
                     penalty)
            not_allowed_before = now + penalty_delta
            self.users[nick]['badpass'] = not_allowed_before