Example #1
0
	def post(self):
		token = self.get_argument("token", default=None, strip=False)

		if not get_user(token):
			self.set_status(401)
		else:
			self.write(get_user(token)[1])
Example #2
0
def ban_bots(message):
    """Scans new members for bots,
    if there are user bots among new users -- kicks the bots
    and adds the rest of the users to the database
    """

    # If the members were invited by an admin, skips the bot detection
    admin_invited = message.from_user.id in config.admin_ids

    session = Session()

    # Checks every new member
    for member in message.new_chat_members:
        # If new member is bot, kicks it out and moves on
        if member.is_bot and member.id != bot_id and not admin_invited:
            bot.kick_chat_member(chat_id=config.chat_id, user_id=member.id)
            logger.info("Bot {} has been kicked out".format(get_user(member)))
            continue

        # If new member has joined for the first time
        # adds him/her to the database
        if not session.query(User).get(member.id):
            user_obj = User(member.id)
            session.add(user_obj)
            logger.info("User {} has joined the chat for the first time and "
                        "has been successfully added to the database".format(
                            get_user(member)))

    session.commit()
    session.close()
Example #3
0
    def test_get_user_not_found(self, m):
        from utils import get_user

        m.register_uri('GET', '/api/v1/courses/1/users/1', status_code=404)

        with self.assertRaises(requests.exceptions.HTTPError):
            get_user(1, 1)
Example #4
0
def welcome(message):
    new_members_names = []
    # By default assumes that the new user has joined for the first time
    first_joined = True

    # Gets the information about the current chat members in data
    with shelve.open(config.data_name, 'c', writeback=True) as data:
        data['members'] = {} if not data.get('members') else data['members']
        # Checks every new member
        # NOTE, you can invite multiple users at once
        for member in message.new_chat_members:
            # If new member is bot, skips
            if member.is_bot:
                continue

            # If new member has joined for the first time
            # adds him/her to the database
            if not member.id in data['members']:
                data['members'][member.id] = ' '.join(
                    get_user(member).split(' ')[1:])
                logger.info('User {} has joined the chat for the first time and '\
                            'has been successfully added to the database'.format(get_user(member)))
            # Else, sets first_joined flag to False
            else:
                first_joined = False
                logger.info('User {} has rejoined the chat'.format(
                    get_user(member)))
            new_members_names.append(member.first_name)
    # Welcomes every new member
    if new_members_names:
        welcoming_msg = '{0}, {1}!\nPlease consider the chat rules and enjoy your stay.'.format(random.choice(constants.welcome_list),\
                                    ', '.join(new_members_names)) if first_joined else '{0}, {1}.'.format(random.choice(constants.welcomeback_list),\
                                    ', '.join(new_members_names))
        bot.reply_to(message, welcoming_msg)
Example #5
0
 def test_toggle_user(self):
     assert utils.create_user(self._test_user, password=self._test_user_password, role=self._test_user_role)
     assert utils.toggle_user(self._test_user, False)
     user = utils.get_user(self._test_user)
     assert user != None
     assert user['enabled'] == False
     assert utils.toggle_user(self._test_user, True)
     user = utils.get_user(self._test_user)
     assert user != None
     assert user['enabled'] == True
     assert utils.delete_user(self._test_user)
Example #6
0
def send_to_admin(message, text, admins, is_forward):
    text = text.format(get_user(message.reply_to_message.forward_from)) if is_forward else \
           text.format(get_user(message.reply_to_message.from_user))
    try:
        bot.send_message(message.from_user.id, text)
        logger.info(text.format(get_user(message.reply_to_message.from_user)))
    except ApiException as e:
        if str(e.result) == r'<Response [403]>':
            reply_msg = text + '\nI can\'t contact you. Please start a chat with me.'
            bot.reply_to(message, reply_msg)
            logger.error('Admin {} couldn\'t be reached'.format(
                admins[message.from_user.id]))
Example #7
0
def result(user_id=None):
    if user_id is not None and not g.user.is_admin:
        flash('Нет доступа')
        return redirect(url_for('welcome'))
    if user_id is None:
        user = g.user
    else:
        user = get_user(user_id)
        if not user:
            flash(f'Пользователь с id={user_id} не найден')
            return redirect(back('admin_panel'))
    if request.method == 'POST':
        flash('Тест завершён!', category='success')
        finish_test(user)
        return redirect(url_for('result'))
    if user.end_time is None:
        if user_id is not None:
            flash('Тест ещё не был завершён!')
            return redirect(back('admin_panel'))
        return redirect(url_for('pre_solve'))
    total = 0
    for q in Question.query.all():
        total += q.points
    user_answers = UserAnswer.query.filter_by(user_id=user.id).all()
    failed_questions = [a.question for a in user_answers if not a.answer.is_correct]
    skipped_questions = Question.query.filter(
        ~Question.id.in_([a.question_id for a in user_answers])
    ).order_by(Question.number).all()
    return render_template('result.html', total=total, failed=failed_questions, user=user,
                           show_correct=True, skipped=skipped_questions, shuffle=(lambda x: x),
                           title='Результат тестирования')
Example #8
0
async def run(client, message, args, prefix, db):
    if len(args) == 0:
        user = message.author
    else:
        user = utils.get_user(message.guild, args[0])
        if not user: raise Exception(f"Üye '{args[0]}' bulunamadı")

    embed = discord.Embed(title=f"**{user.name}** hakkında", color=0x6675ff)
    embed.set_footer(text=f"Bu havalı kullanıcının ID'si {user.id}")
    embed.set_thumbnail(url=user.avatar_url)
    j = user.joined_at
    embed.add_field(name="Sunucuya katılma tarihi",
                    value=f"{j.day}/{j.month}/{j.year}  {j.hour}:{j.minute}",
                    inline=True)
    j = user.created_at
    embed.add_field(name="Hesabını açma tarihi",
                    value=f"{j.day}/{j.month}/{j.year}  {j.hour}:{j.minute}",
                    inline=True)
    roles = user.roles
    for r in roles:
        if r.id == 731954285595590678 or r.id == 712996348181610561 or r.id == 712996541119332455:
            roles.remove(r)

    if len(roles) == 1:
        roles = "Bu kişinin hiç rolü yok"
    else:
        roles = [r.mention for r in roles]
        roles.pop(0)
        roles = " ".join(roles)
    embed.add_field(name="Roller", value=roles, inline=False)

    await message.channel.send(embed=embed)
Example #9
0
async def who(ctx: commands.Context, username: str) -> None:

    user = get_user(username, bot)

    if user is not None:
        info = get_user_info(user)
        add_footer(info.embed, ctx.message.author)
        await info.send(ctx)
        return

    # Look for nearest matches, if they exist
    users = bot.get_guild(guild_id).members  # type: List[discord.Member]
    # Just using sequencematcher because its simple and no need to install extra Library
    # If keen on better distrance metrics, look at installing Jellyfish or Fuzzy Wuzzy
    similarities = [(member,
                     max(
                         SequenceMatcher(None, username.lower(),
                                         member.display_name.lower()).ratio(),
                         SequenceMatcher(None, username.lower(),
                                         member.name.lower()).ratio()))
                    for member in users]
    similarities.sort(key=lambda tup: tup[1], reverse=True)

    # unlikely to get 5 with >70% match anyway...
    top_matches = [x for x in similarities[:5]
                   if x[1] > 0.7]  # type: List[Tuple[discord.Member, float]]

    uids = [x[0].id for x in top_matches]
    infos = requests.get("https://dev.openstudyroom.org/league/discord-api/",
                         params={
                             'uids': uids
                         }).json()

    # Split and recombine so that OSR members appear top of list
    osr_members = [
        x for x in top_matches if infos.get(str(x[0].id)) is not None
    ]
    not_osr_members = [x for x in top_matches if x not in osr_members]
    top_matches = osr_members + not_osr_members

    message = ''
    for _i, x in enumerate(top_matches):
        message += '\n{}\N{COMBINING ENCLOSING KEYCAP}**{}**#{} {}'.format(
            _i + 1, x[0].display_name, x[0].discriminator,
            user_rank(x[0], infos))
    if username in roles_dict:
        message += "\n\n However, `" + username + "` is a valid role. Did you mean `!list " + username + "`?"
    nearest_or_sorry = '", nearest matches:' if top_matches else '", sorry'
    embed = discord.Embed(description=message,
                          title='No users by the exact name "' + username +
                          nearest_or_sorry)
    add_footer(embed, ctx.message.author)
    msg = await ctx.send(embed=embed)

    for _i, match in enumerate(
            top_matches):  # type: Tuple[int, Tuple[discord.Member, float]]
        await msg.add_reaction(str(_i + 1) + '\N{COMBINING ENCLOSING KEYCAP}')

    SPECIAL_MESSAGES[msg.id] = WhoMessage(msg, ctx.message.author,
                                          [x[0] for x in top_matches])
Example #10
0
    def get(self, album_id):
        user = get_user()
        album = Album.get_by_id(
            int(album_id),
            DEFAULT_DOMAIN_KEY
        )

        if album:
            upload_url = blobstore.create_upload_url('/album/%s/upload-photo' % album_id)

            photo_query = Photo.query(
                ancestor=album.key
            )

            comments_query = Comment.query(
                Comment.parent == album.key
            ).order(-Comment.date_created)

            template_values = {
                'user': user,
                'album': album,
                'photos': photo_query.fetch(None),
                'comments': comments_query.fetch(None),
                'upload_url': upload_url,
            }

            self.render_template('view_album.html', template_values)
        else:
            self.raise_error(404)
Example #11
0
def wiki():
    pages = db.session.query(Page).order_by(Page.title.desc()).all()
    user = get_user(request.cookies.get('username_cookie'))
    return render_template('wiki.html',
                           title='Directory',
                           pages=pages,
                           user=user)
Example #12
0
    def test_signup(self):
        signup_url = settings.SIGNUP_URL
        self.browser.click_link_by_partial_href(signup_url)

        username = '******'
        password = '******'
        email = '*****@*****.**'
        signup(
            self.browser,
            username,
            password,
            email,
        )

        user_exists = exists_user(username)
        self.assertTrue(user_exists)

        user = get_user(username)
        self.assertEquals(user.username, username)
        #self.assertEquals(user.password, password)
        self.assertEquals(user.email, email)

        document_list_url = \
            self.live_server_url + reverse('documents.views.list_documents')
        self.assertEquals(self.browser.url, document_list_url)

        profile_xpath = '/html/body/div/div[1]/div/ul[2]/li[4]/a'
        profile_link = self.browser.find_by_xpath(profile_xpath)
        self.assertEquals(profile_link.value, '@{}'.format(username))

        #        import time; time.sleep(3)
        self.browser.quit()
Example #13
0
def run():
    # This script should be run as user 'mytardis' via sudo.
    # All users have permission to run it as sudo without a password,
    # thanks to this line in /etc/sudoers:
    # ALL     ALL=(ALL) NOPASSWD: /usr/local/bin/_myapikey,
    #    /usr/local/bin/_datafiledescriptord, /usr/local/bin/_datasetdatafiles

    if getpass.getuser() != "mytardis" or "SUDO_USER" not in os.environ:
        print "Usage: sudo -u mytardis _myapikey " + \
            "mytardis_install_dir auth_provider"
        os._exit(1)

    if len(sys.argv) < 3:
        print "Usage: sudo -u mytardis _myapikey " + \
            "mytardis_install_dir auth_provider"
        sys.exit(1)

    _mytardis_install_dir = sys.argv[1].strip('"')
    _auth_provider = sys.argv[2]

    utils.setup_mytardis_paths(_mytardis_install_dir)

    from tastypie.models import ApiKey

    myTardisUser = utils.get_user(os.environ['SUDO_USER'], _auth_provider)

    key = ApiKey.objects.get(user__username=myTardisUser.username)
    print "ApiKey " + myTardisUser.username + ":" + str(key.key)
 def get(self):
   google_user = users.get_current_user()
   app_user = utils.get_user(google_user)
   if google_user and not app_user:
     app_user = utils.init_new_user(google_user)
   
   self.response.out.write(template.render('player.html', {'user':app_user,'rando': random.random(), 'login_url': users.create_login_url("/"), 'logout_url':users.create_logout_url("/"), 'in_development_enviroment':utils.in_development_enviroment()}))
Example #15
0
def edit(page_title):
    user = get_user(request.cookies.get('username_cookie'))
    page = db.session.query(Page).filter_by(title=page_title).first()
    if not user:
        flash('You must be signed in to make edits.')
        if page:
            return render_template('view.html',
                                   title=page_title,
                                   content=page.content,
                                   user=user)
        else:
            return render_template('view.html', title=page_title, user=user)

    stored_user = db.session.query(User).filter_by(username=user).first()
    if stored_user:
        if stored_user.password_hash.decode('utf-8') != request.cookies.get(
                'username_cookie').split(',')[1]:
            flash(
                'There was a problem authenticating your identity. Please try logging in again.'
            )
            return render_template('view.html',
                                   title=page_title,
                                   content=page.content,
                                   user=user)

    if request.method == 'GET':
        if page:
            return render_template('edit.html',
                                   page_title=page_title,
                                   title='Edit ' + page_title,
                                   saved_content=page.content,
                                   user=user)
        else:
            return render_template('edit.html',
                                   page_title=page_title,
                                   title='Edit ' + page_title,
                                   user=user)
    else:
        content = request.form.get('content')
        if not content:
            flash("You did not enter valid content.")
            if page:
                return render_template('edit.html',
                                       page_title=page_title,
                                       title='Edit ' + page_title,
                                       saved_content=page.content,
                                       user=user)
            else:
                return render_template('edit.html',
                                       page_title=page_title,
                                       title='Edit ' + page_title,
                                       user=user)
        if page:
            page.content = page.content + split + content
            page.users = page.users + split + user
        else:
            page = Page(page_title, content, user)
            db.session.add(page)
        db.session.commit()
        return redirect('/wiki/' + page_title)
    def endpoint_guess_char(self, request):
        """Guess char of the word"""
        # only single char supported
        if len(request.char) != 1:
            raise endpoints.ForbiddenException('ERR_BAD_CHAR_LENGTH')

        # only alphabet supported
        if not request.char.isalpha():
            raise endpoints.ForbiddenException('ERR_NOT_AN_ALPHABET')

        user = get_user(request.user_name)

        game = get_game(request.urlsafe_key, user.user_name)

        # only IN_SESSION game supported
        if game.game_status != GameStatus.IN_SESSION:
            raise endpoints.ForbiddenException('ERR_GAME_NOT_IN_SESSION')

        score = get_game_score(user.user_name, game)

        self._move_game(game, user, score, request.char)

        return GetGameResponse(id=game.game_id,
                               game_name=game.game_name,
                               word=game.word,
                               guessed_chars_of_word=game.guessed_chars_of_word,
                               guesses_left=game.guesses_left,
                               game_over=game.game_over,
                               game_status=game.game_status,
                               urlsafe_key=game.key.urlsafe())
Example #17
0
def index():
    session = get_session(request)
    if session and "username" in session:
        user = get_user(session["username"], session["secret"])
        print(user)
        return render_template("home.html", page="home", user=user)
    return render_template("home.html", page="home")
Example #18
0
def bl_add(message, is_forward):
    user = message.reply_to_message.forward_from if is_forward else message.reply_to_message.from_user
    with shelve.open(config.data_name, 'c', writeback=True) as data:
        data['admins'] = config.admins_default if not data.get(
            'admins') else data['admins']
        data['whitelist'] = {} if not data.get(
            'whitelist') else data['whitelist']
        data['blacklist'] = {} if not data.get(
            'blacklist') else data['blacklist']

        user_id = user.id

        # Checks the user's list status and acts accordingly
        if user_id in data['blacklist']:
            send_to_admin(message, 'User {} is already blacklisted.',
                          data['admins'], is_forward)
            return
        if user_id in data['whitelist']:
            del data['whitelist'][user_id]
        data['blacklist'][user_id] = [
            ' '.join(get_user(user).split(' ')[1:]), message.from_user.id
        ]

        bot.delete_message(chat_id=message.chat.id,
                           message_id=message.reply_to_message.message_id)
        send_to_admin(message,
                      'User {} has been successfully added to the blacklist.',
                      data['admins'], is_forward)
Example #19
0
def comment_list():
    if request.method == 'POST':
        try:
            token = request.headers['token']
            uId = get_user(token).id
        except Exception as e:
            return responseData('token过期或者失效', str(e), False)
        post_data = post_json()
        page_size = post_json()['pageSize']
        page_num = post_json()['pageNum']
        arts = Article.query.filter_by(
            author_id=uId).order_by(-Article.time).limit(
                int(page_size)).offset((int(page_num) - 1) * int(page_size))
        total = Article.query.filter_by(author_id=uId)
        data = []
        for art in arts:
            for comment in art.art:
                data.append({
                    'remarkName': comment.name,
                    'fromArtId': art.id,
                    'fromArtTitle': art.title,
                    'remarkContent': comment.content,
                    'remarkId': comment.id,
                    'remarkTime': comment.time
                })
                pass

        return responseData('success', {'total': '', 'list': data})
Example #20
0
def sysinfo():
    """获取系统信息
    ---
    tags:
    - 系统
    security:
    - api_key: []
    responses:
      200:
        description: 获取成功
        schema:
          type: object
          properties:
            code:
                type: int
            data:
                type: array
                $ref: '#/definitions/Module'
            message:
                type: string
        examples:
          code: 0
          data: [{}, {}]
          message: 'success'
    """
    res = {
        'data': {
            'cpu': get_cpu(),
            'sys': get_sysinfo(),
            'mem': get_memory(),
            'disk': get_disk(),
            'user': get_user()
        }
    }
    return success(res)
Example #21
0
def info():
    session['token_info'], authorized = get_token(session)
    session.modified = True
    if not authorized:
        flash("Please Login with your Spotify Account")
        return redirect('/')

    sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))

    user = get_user(sp)
    songs = get_all_top_tracks(sp)
    artists = get_all_top_artists(sp)
    audio_features = get_audio_features(sp, songs['uri'])
    recommended_artists = get_recommended_artists(
        sp, artists['artists'][0]['url'][32:])
    recommended_songs = get_recommendations(sp, artists, songs['uri'],
                                            artists['genres'][0],
                                            audio_features['values'])
    return render_template('info.html',
                           songs=songs,
                           artists=artists,
                           similar=recommended_artists,
                           tracks=recommended_songs,
                           audio=audio_features,
                           user=user)
Example #22
0
def set_dell_service_tag(host, check):
    """
    :param host: norduniclient node model
    :param check: check dictionary
    :return: None
    """
    tag = None
    try:
        openmanage_linux_tag_regex = re.compile('servicetag=(?P<tag>[\w]+)',
                                                re.IGNORECASE)
        tag = openmanage_linux_tag_regex.search(
            check['plugin_output']).group('tag')
    except AttributeError:
        pass
    try:
        openmanage_win_tag_regex = re.compile('SN: \'(?P<tag>[\w]+)\'',
                                              re.IGNORECASE)
        tag = openmanage_win_tag_regex.search(
            check['plugin_output']).group('tag')
    except AttributeError:
        pass
    try:
        esxi_tag_regex = re.compile('s/n: (?P<tag>[\w]+)', re.IGNORECASE)
        tag = esxi_tag_regex.search(check['plugin_output']).group('tag')
    except AttributeError:
        pass
    if tag:
        property_dict = {'service_tag': tag}
        helpers.dict_update_node(utils.get_user(), host.handle_id,
                                 property_dict, property_dict.keys())
Example #23
0
    def test_signup(self):
        signup_url = settings.SIGNUP_URL
        self.browser.click_link_by_partial_href(signup_url)

        username = "******"
        password = "******"
        email = "*****@*****.**"
        signup(self.browser, username, password, email)

        user_exists = exists_user(username)
        self.assertTrue(user_exists)

        user = get_user(username)
        self.assertEquals(user.username, username)
        # self.assertEquals(user.password, password)
        self.assertEquals(user.email, email)

        document_list_url = self.live_server_url + reverse("documents.views.list_documents")
        self.assertEquals(self.browser.url, document_list_url)

        profile_xpath = "/html/body/div/div[1]/div/ul[2]/li[4]/a"
        profile_link = self.browser.find_by_xpath(profile_xpath)
        self.assertEquals(profile_link.value, "@{}".format(username))

        #        import time; time.sleep(3)
        self.browser.quit()
    def endpoint_new_game(self, request):
        """Create new game."""
        user = get_user(request.user_name)

        game = self._new_game(user, request.game_name)

        return NewGameResponse(urlsafe_key=game.key.urlsafe())
Example #25
0
def set_uptime(host, check):
    """
    Parses uptime collected with check_uptime (https://github.com/willixix/WL-NagiosPlugins).

    :param host: norduniclient node model
    :param check: check dictionary
    :return: None
    """
    try:
        if '-' in check['last_check']:
            last_check = datetime.strptime(check['last_check'],
                                           "%Y-%m-%d %H:%M:%S")
        else:
            last_check = datetime.utcfromtimestamp(check['last_check'])
        uptime = int(check['perf_data'].split('=')
                     [-1]) * 60  # uptime in minutes to uptime in sec
        lastboot = last_check - timedelta(seconds=uptime)
        property_dict = {
            'lastboot': lastboot.strftime("%a %b %d %H:%M:%S %Y"),
            'uptime': uptime
        }
        helpers.dict_update_node(utils.get_user(), host.handle_id,
                                 property_dict, property_dict.keys())
    except ValueError as e:
        logger.info(
            '{name} uptime check did not match the expected format.'.format(
                name=host.data['name']))
        logger.info(check)
        logger.info(e)
Example #26
0
def reset_password_confirmed(request):
    if request.method != 'POST':
        raise PermissionDenied
    uid = request.GET.get('uid')
    uid = sanitize_get_param(uid)
    logged_user = request.zeususer._user
    user = get_user(uid)
    if user:
        if can_do(logged_user, user):
            new_password = random_password()
            user.info['password'] = make_password(new_password)
            user.save()
            message = _("New password for user %(uid)s is "
                        "%(new_pass)s") % {
                            'uid': user.user_id,
                            'new_pass': new_password
                        }
            messages.info(request, message)
        else:
            message = _("You are not authorized to do this")
            messages.error(request, message)
    else:
        message = _("You didn't choose a user")
        messages.error(request, message)
        return redirect(reverse('list_users'))
    url = "%s?uid=%s" % (reverse('user_management'), str(user.id))
    return redirect(url)
Example #27
0
def reset_password(request):
    uid = request.GET.get('uid')
    uid = sanitize_get_param(uid)
    user = get_user(uid)
    context = {"u_data": user}
    return render_template(request, 'account_administration/reset_password',
                           context)
Example #28
0
def receipt(active, mode, trans_acc, amount):
    # print('\n'*5)
    system("cls")
    balance = float(active.balance)
    print("===================================================")
    print("  ████████╗    ██████╗     ██████╗ ")
    print("  ╚══██╔══╝    ██╔══██╗    ██╔══██╗")
    print("     ██║       ██████╔╝    ██████╔╝")
    print("     ██║       ██╔══██╗    ██╔═══╝ ")
    print("     ██║       ██████╔╝    ██║     ")
    print("     ╚═╝       ╚═════╝     ╚═╝   ")
    print("===================================================")
    print("{} ({})".format(config.CMPY_NAME, config.CMPY_SHORT))
    print("===================================================")
    print("TRANSACTION TIME: {}".format(current_time))
    print("CUSTOMER NAME: {}".format(active.get_fullname().upper()))
    print("===================================================")
    print("ACCNT NUM: {}".format(active.accno))

    if mode == "1":
        print("AMT DEPOSIT: PHP {}".format(amount))
    elif mode == "2":
        print("AMT WIDTHRAW: PHP {}".format(amount))
    else:
        print("AMT TRANSFERED: PHP {}".format(amount))
        print("RECEIVER ACCT NO: {}".format(trans_acc))
        print("AMT TRANSFERED TO: {}".format(
            utils.get_user(trans_acc).get_fullname().upper()))

    print("AVAIL BALANCE : PHP {}".format(balance))
    print("Thanks for trusting us, Have good day!")
    print("Please keep the receipt for more info..")
    print("===========================================")
    input("Press any key to continue...")
Example #29
0
def sort_user(request,sort):
	if request.method == 'GET':
		posts = get_posts()
		post_form = PostForm()
		comment_form = CommentForm()

		if sort == 'mybanks':
			username = str(request.user)
			user = get_user(username)
			likes = [int(like) for like in user.get('likes','')]
			posts = [post for post in posts if post.get('post_id','') in likes]
			sorted_posts = sorted(posts,key=get_post_time)
			posts = list(reversed(sorted_posts))
		else:
			username = str(sort)
			posts = [post for post in posts if post.get('author','') == username]

		# if len(posts) > params.post_limit:
		# 	posts = posts[:params.post_limit]

		context = {
			'posts':posts,
			'post_form':post_form,
			'comment_form':comment_form,
			'sort':sort,
			}
	return render(request,'forum/home.html',context)
Example #30
0
def editData():
    token = request.headers['token']

    post_data = post_json()
    try:
        uId = get_user(token).id
    except Exception as e:
        return responseData('token过期或者失效', None, False)

    user = User.query.get(uId)
    '''
      删除之前的头像
      
    '''
    print('用户头像====:', user.avatar)
    if user.avatar is not None:
        prev_path = os.path.join(CENTOS_UPLOAD_PATH, user.avatar)
        if os.path.exists(prev_path):
            print('删除====>:', prev_path)
            os.remove(prev_path)
        else:
            print('====>:没有查找到该文件')

    user.age = post_data['age']
    user.sex = post_data['sex']
    user.address = post_data['address']
    user.nickName = post_data['nickName']
    user.avatar = post_data['avatar']
    user.sign = post_data['sign']
    db.session.commit()
    return responseData(
        '资料更新成功',
        None,
    )
    def endpoint_get_user_games(self, request):
        """Get user's games list"""
        # get user object
        user = get_user(request.user_name)

        # get all games of this user
        all_games = get_user_games(user.user_name)

        if request.game_status is not None:
            # create filter for active games
            if request.game_status == GameStatus.IN_SESSION:
                active_filter = ndb.query.FilterNode('game_status', '=', GameStatus.IN_SESSION.number)
            elif request.game_status == GameStatus.WON:
                active_filter = ndb.query.FilterNode('game_status', '=', GameStatus.WON.number)
            elif request.game_status == GameStatus.LOST:
                active_filter = ndb.query.FilterNode('game_status', '=', GameStatus.LOST.number)
            elif request.game_status == GameStatus.ABORTED:
                active_filter = ndb.query.FilterNode('game_status', '=', GameStatus.ABORTED.number)

            # fetch games of this user
            active_games = all_games.filter(active_filter).fetch()
        else:
            # fetch games of this user
            active_games = all_games.fetch()

        return GetActiveGameResponseList(
            games=[self._create_active_game_list(active_game) for active_game in active_games]
        )
Example #32
0
def insert_interface_unit(iface_node, unit, service_id_regex):
    """
    Creates or updates logical interface units.
    """
    user = utils.get_user()
    unit_name = u'{}'.format(unit['unit'])
    # Unit names are unique per interface
    result = iface_node.get_unit(unit_name)
    if result.get('Part_of', None):
        unit_node = result.get('Part_of')[0].get('node')
    else:
        node_handle = utils.create_node_handle(unit_name, 'Unit', 'Logical')
        unit_node = node_handle.get_node()
        helpers.set_part_of(user, iface_node, unit_node.handle_id)
        logger.info('Unit {interface}.{unit} created.'.format(
            interface=iface_node.data['name'], unit=unit_node.data['name']))
    helpers.set_noclook_auto_manage(unit_node, True)
    unit['ip_addresses'] = [
        address.lower() for address in unit.get('address', '')
    ]
    property_keys = ['description', 'ip_addresses', 'vlanid']
    helpers.dict_update_node(user, unit_node.handle_id, unit, property_keys)
    # Auto depend service on unit
    auto_depend_services(unit_node.handle_id, unit.get('description', ''),
                         service_id_regex, 'Unit')
Example #33
0
 def decorated(*args, **kwargs):
     if 'app_uuid' in kwargs:
         user = utils.get_user(session['user'])
         app = utils.get_application_config(app_uuid=kwargs['app_uuid'])
         if app['owner'] != user['username']:
             flash(messages.ACCESS_DENIED, 'error')
             return redirect(url_for('applications'))
     return f(*args, **kwargs)
    def delete_user(self, request):
        """Delete existing user"""
        user = get_user(request.user_name)

        # delete the entity
        user.key.delete()

        return message_types.VoidMessage()
Example #35
0
def ro_giver(message, r):
    """Gives RO to users who flood with the !report command,
    or bans those who have more than 3 warnings
    """

    bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)

    if int(r.get(
            message.reply_to_message.message_id)) == config.report_threshold:
        return

    session = Session()

    user_obj = session.query(User).get(message.from_user.id)
    if not user_obj:
        user_obj = User(message.from_user.id)
        session.add(user_obj)
        session.commit()

    if message.from_user.id in config.admin_ids:
        logger.info("Admin {} is flooding with !report. Doing nothing".format(
            get_user(message.from_user)))
        session.close()
        return

    user_obj.ro_level += 1
    session.commit()

    if user_obj.ro_level < 4:
        user_ro_minutes = config.ro_levels[user_obj.ro_level]
        bot.restrict_chat_member(
            chat_id=config.chat_id,
            user_id=message.from_user.id,
            until_date=time.time() + 60 * user_ro_minutes,
        )
        logger.info(
            "User {0} got {1} minutes of RO for flooding with !report".format(
                get_user(message.from_user), user_ro_minutes))
    else:
        bot.kick_chat_member(chat_id=config.chat_id,
                             user_id=message.from_user.id)
        session.delete(user_obj)
        logger.info("User {} has been banned for flooding with !report".format(
            get_user(message.from_user)))

    session.close()
Example #36
0
def group_join(group_id):
    user = get_user()
    group = Group.get(group_id)
    if group.get_is_join(user.id):
        group.join_user(user.id, False)
    else:
        group.join_user(user.id, True)
    return redirect(url_for('group_show',group_id = group_id))
Example #37
0
def delete_node(node, dry_run):
    if not dry_run:
        user = utils.get_user()
        helpers.delete_node(user, node.handle_id)
    name = u"{}<name='{}', handle_id={}>".format(type(node).__name__,
                                                 node.data.get('name'),
                                                 node.handle_id)
    logger.info('Deleted node {}.'.format(name))
    delete_log.append(name)
Example #38
0
 def test_create_user(self):
     assert utils.create_user(self._test_user, self._test_user_email, \
         self._test_user_password, self._test_user_role)
     user = utils.get_user(self._test_user)
     assert user != None
     assert user['username'] == self._test_user
     assert user['email'] == self._test_user_email
     assert user['role'] == self._test_user_role
     assert utils.delete_user(self._test_user)
Example #39
0
def reset_password(request):
    uid = request.GET.get('uid')
    uid = sanitize_get_param(uid)
    user = get_user(uid)
    context = {"u_data": user}
    return render_template(
        request,
        'account_administration/reset_password',
        context)
Example #40
0
    def get(self, cursor):
        if 'username' in session:
            response = {'user': get_user(cursor, session['username'])}
            responseCode = 200
        else:
            response = {'status': 'Access denied'}
            responseCode = 403

        return make_response(jsonify(response), responseCode)
Example #41
0
    def render_template(self, template_name, template_values={}):
        template = env.get_template(template_name)

        # Values expected by base
        template_values['user'] = get_user()
        template_values['login_url'] = users.create_login_url(self.request.uri)
        template_values['logout_url'] = users.create_logout_url(self.request.uri)

        self.response.write(template.render(template_values))
Example #42
0
def save_history(user_id, model_response, back_end_search_start, question):
    """
    Save user history
        1. check user id valid
        2. get user history json string
        3. json.loads into a python dict
        4. modify this dict
        5. json.dumps into a json string
        6. save this user into database

    Args:
        user_id: specify a user
        model_response: answers from model
        back_end_search_start: time when user begins search
        question: question that user asks

    Return:
        successful or not

    """
    user = get_user(user_id)
    # 出错了
    if not user:
        return False
    history_str = user.query_json
    # it means history_str is null
    if not history_str:
        history_str = '{"data": []}'

    json_dict = json.loads(history_str)
    # print(json_dict)
    append_dict = dict()
    append_dict['question'] = question
    append_dict['time'] = back_end_search_start
    append_dict['response'] = list()

    for item in model_response:
        append_dict['response'].append({
            'answer': item['model_answer'],
            'grade': item['model_score'],
            'content': item['content'],
            'doc_id': item['doc_id']
        })

    if len(json_dict['data']) < 100:
        json_dict['data'].append(append_dict)
    else:
        json_dict['data'].append(append_dict)
        json_dict['data'] = json_dict['data'][1:101]

    user.query_json = json.dumps(json_dict, ensure_ascii=False)
    try:
        user.full_clean()
        user.save()
    except ValidationError:
        return False
    return True
Example #43
0
 def decorated(*args, **kwargs):
     user = utils.get_user(session['user'])
     if 'uuid' in kwargs:
         evt = g.db.events.find_one({'uuid': kwargs['uuid']})
         if user['role'].lower() != 'admin':
             if evt:
                 if evt['owner'] != session['user_id']:
                     flash(messages.ACCESS_DENIED, 'error')
                     return redirect(url_for('events'))
     return f(*args, **kwargs)
Example #44
0
File: app.py Project: yimun/mygroup
def blog_show(blog_id):
    blog = Blog.get(blog_id)
    user = get_user()
    if not user:
        is_join = False
    else:
        is_join = blog.get_is_join(user.id)
    comment_list = Comment.get_comments(blog_id)
    return header_render('blog_show.html', blog=blog, comment_list = comment_list, 
                         is_join = is_join)
Example #45
0
File: app.py Project: yimun/mygroup
def group_create():
    if request.method == 'POST':
        name = request.form['grp_name']
        intro = request.form['grp_intro']
        id = Group.create(name, intro, get_user().id)
        if not id:
            return header_render('group_create.html')
        return redirect(url_for('group_show',group_id = id))
    else:
        return header_render('group_create.html')
Example #46
0
    def get(self, album_id):
        album = Album.get_by_id(
            int(album_id),
            parent=DEFAULT_DOMAIN_KEY
        )

        if get_user().key == album.author:
            self.render_template('edit_album.html', {'album': album})
        else:
            self.raise_error(500)
Example #47
0
def create_or_login(resp):
    print resp
    session['openid'] = resp.identity_url
    user = get_user(session['openid'])
    if user is None:
        user = create_user(resp.identity_url,
                           resp.fullname or resp.nickname,
                           resp.email)
    session['user'] = user
    session['logged_in'] = True
    return redirect(oid.get_next_url())
Example #48
0
 def test_user_ops(self):
     test_user = get_random_string()
     test_role = get_random_string()
     # create
     assert utils.create_user(username=test_user, password='******', role=test_role)
     assert utils.get_user(test_user) != None
     # toggle
     assert utils.toggle_user(test_user, False)
     user_data = json.loads(utils.get_user(test_user))
     assert user_data['enabled'] == False
     assert utils.toggle_user(test_user, True)
     user_data = json.loads(utils.get_user(test_user))
     assert user_data['enabled'] == True
     assert utils.toggle_user(test_user)
     user_data = json.loads(utils.get_user(test_user))
     assert user_data['enabled'] == False
     # delete
     assert utils.delete_user(test_user)
     assert utils.get_user(test_user) == None
     assert utils.delete_role(test_role)
Example #49
0
def select_server():
    guild_id = request.args.get('guild_id')
    if guild_id:
        log.info("Got guild ID, {}".format(guild_id))
        return redirect(url_for('dashboard', server_id=int(guild_id)))

    user = utils.get_user(session['api_token'])
    guilds = utils.get_user_guilds(session['api_token'])
    user_servers = sorted(utils.get_user_managed_servers(user, guilds),key=lambda s: s['name'].lower())
    log.info("User servers: {}".format(user_servers))
    return render_template('select-server.html', user=user, user_servers=user_servers)
Example #50
0
File: app.py Project: yimun/mygroup
def group_show(group_id):
    group = Group.get(group_id)
    if group:
        creator = doubanusers.User(id=group.creator_id)
        blog_list = Blog.get_all_by_group(group_id)
        is_join = group.get_is_join(get_user().id)
        member_list = group.get_members()
        return header_render('group_show.html',group=group, creator = creator, 
                              blog_list = blog_list, is_join = is_join, member_list = member_list)
    else:
        abort(404)
Example #51
0
File: app.py Project: yimun/mygroup
def blog_create(group_id):
    group = Group.get(group_id)
    if request.method == 'POST':
        title = request.form['blog_title']
        content = request.form['blog_content']
        id = Blog.create(title, content, get_user().id, group_id)
        if not id:
            return header_render('blog_create.html', group = group)
        return redirect(url_for('blog_show',blog_id = id))
    else:
        return header_render('blog_create.html', group = group)
    def update_user(self, request):
        """Update existing user"""
        user = get_user(request.current_user_name)

        for field in request.all_fields():
            # check if any field has been updated
            if getattr(request, field.name) and field.name is not 'current_user_name':
                setattr(user, field.name, getattr(request, field.name))

        user.put()

        return UserResponse(user_name=user.user_name, email=user.email, display_name=user.display_name)
Example #53
0
    def post(self):
        user = get_user()

        if user:
            album = Album(parent=DEFAULT_DOMAIN_KEY)
            album.author = user.key
            album.name = self.request.get('album_name')
            album.description = self.request.get('album_desc')

            album.put()

            self.redirect('/album/%s/view' % album.key.integer_id())
        else:
            self.redirect_to_login()
def index(request):
	if request.user.is_anonymous() or not request.user.is_user:
		return shortcuts.redirect('/horizon/auth/login/')

	instances = utils.get_instances(request)
	user = utils.get_user(request)
	projects = utils.get_projects(request,user)

	for instance in instances:
		instance['console_url'] = utils.get_console_url(request,instance)

	limit = utils.get_project_limit(request)

	return shortcuts.render_to_response('index.html',{"user":user,"instances":instances,"projects":projects,"tenant_name":request.user.tenant_name,'limit':limit})
Example #55
0
	def post(self):
		super_token = self.get_argument("super_token", default=None, strip=False)
		username    = self.get_argument("username"   , default=None, strip=False)
		email       = self.get_argument("email"      , default=None, strip=False)
		password    = self.get_argument("password"   , default=None, strip=False)

		# Only allow root to create users.
		if not (get_user(super_token) and get_user(super_token)[1] == 'root'):
			self.set_status(401)
			return

		cursor = conf.DB_CONN.execute("""
			INSERT INTO Users
				(username, email, hash_scheme, passhash)
			VALUES
				(?, ?, ?, ?)
			""", (username, email, conf.DEFAULT_SCHEME, conf.DEFAULT_HASHER(password))
		)
		conf.DB_CONN.commit()

		# TODO potential race condition if tornado is multithreaded
		token = create_token(cursor.lastrowid)
		self.write(token)
Example #56
0
    def post(self, album_id):
        album = Album.get_by_id(
            int(album_id),
            parent=DEFAULT_DOMAIN_KEY
        )

        if get_user().key == album.author:
            album.name = self.request.get('album_name')
            album.description = self.request.get('album_desc')
            album.put()

            self.redirect('/album/%s/view' % album_id)
        else:
            self.raise_error(500)