Пример #1
0
    def test_delete_membership_before_user(self):
        """
         if user's membership is deleted then user should still exist
        """
        u, m = self._create_user_with_membership()
        self.assertIsNotNone(m)
        self.assertEqual(User.get_by_id(u.id).members, [m])

        m.delete()
        self.assertIsNone(Member.get_by_id(m.id))
        self.assertIsNotNone(User.get_by_id(u.id))
        self.assertEqual(User.get_by_id(u.id).members, [])
Пример #2
0
 def get(self):
     user = users.get_current_user()
     if user:
         logging.info(user)
         query = db.Query(User)
         query.filter('user =', user)
         uo = query.get()
         if uo is None:
             uo = User()
             uo.user = user
             uo.put()            
         self.response.out.write(simplejson.dumps({"login":"******", "user":str(user),"title":uo.title}))
     else:
         self.response.out.write(simplejson.dumps({"login":"******"}))
Пример #3
0
 def _create_user_with_membership(self):
     """
     Create a user and a member
     """
     u = User.create(account_id=self.account_id, secret_key=self.secret_key)
     m = Member.create(account_id=u.account_id, email=self.email)
     return [u, m]
Пример #4
0
def create():
    print "Creating tables..."
    db.create_all()

    print "Fixture: Creating Frontier's system account"
    if User.create(account_id="aabacd", secret_key="123", email="*****@*****.**"):
        print "Fixture: Create Success!"
Пример #5
0
 def test_delete_purchase(self):
     """
     Purchase deleted -> Member NOT deleted -> User NOT deleted
     """
     p, m, u = self._create_purchase_with_member_with_user()
     p.delete()
     self.assertEqual(Purchase.query.count(), 0)
     assert not Purchase.get_by_id(p.id) and Member.get_by_id(m.id) and User.get_by_id(u.id)
     self.assertEqual(len(m.purchases), 0)
Пример #6
0
 def test_delete_membership(self):
     """
     Member deleted -> Purchases by that member deleted -> User NOT deleted
     """
     p, m, u = self._create_purchase_with_member_with_user()
     m.delete()
     self.assertIsNone(Purchase.get_by_id(p.id))
     self.assertIsNone(Member.get_by_id(m.id))
     self.assertIsNotNone(User.get_by_id(u.id))
     self.assertEqual(u.members, [])
Пример #7
0
    def test_delete_user_before_membership(self):
        """
        if user is deleted then user's membership should be deleted
        """
        u, m = self._create_user_with_membership()
        self.assertEqual(u.members, [m])
        self.assertIsNotNone(m)

        u.delete()
        self.assertIsNone(User.get_by_id(u.id))
        self.assertIsNone(Member.get_by_id(m.id))
def register():
    # If user is already logged in then redirect to home page but not in our case
    # if current_user.is_authenticated:
    #     return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=hashed_password)
        db.session.add(user)
        db.session.commit()
        flash(
            'A new user account has been created! You can now log in with this user also',
            'success')
        return redirect(url_for('home'))
    return render_template('registeration.html.j2', form=form)
Пример #9
0
def register():
    """
    Handle requests to create a new acount
    """
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    username=form.username.data,
                    password=form.password.data)

        db.session.add(user)
        db.session.commit()
        flash('You have successfully registered! You many now login.')

        return redirect(url_for('auth.login'))

    return render_template('auth/register.html', form=form, title='Register')
Пример #10
0
    def test_comment_unauthorized_update(self):
        new_data = {
            'contents': 'New contents'
        }
        user = User(**self.user)
        user.save()
        user2 = User('Another', 'another', '*****@*****.**', 'secret')
        user2.save()
        post = Post(**self.post, owner_id=user.id)
        post.save()
        comment = Comment(**self.comment, post_id=post.id, author_id=user.id)
        comment.save()

        res = self.authorized_put(
            f"/posts/{post.id}/comments/{comment.id}",
            user2,
            json=new_data
        )

        self.assertEqual(res.status_code, 403)
        self.assertEqual(res.json['message'], 'Permission denied')
Пример #11
0
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('main.hello'))  
    user = User.verify_reset_token(token)
    if user is None:
        flash('Срок действия ссылки истек')
        return redirect(url_for('users.reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash(f'Пароль успешно изменен! Можете войти в систему', 'success')
        return redirect(url_for('users.login'))
    context = {
        'title': 'Новый пароль',
        'form': form
    }
    return render_template('reset_token.html', context=context, form=form)
Пример #12
0
async def expelliarmus(in_vote: VoteM, game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        current_player = Player.user_player(user, game_id)
        username = User.get(id=current_player["user"]).username
        detail = f"The player {username} has played expelliarmus!"

        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        if current_player["current_position"] != "minister" and current_player[
                "current_position"] != "headmaster":
            raise HTTPException(
                status_code=400,
                detail="this player is not the minister nor the headmaster")
        if game.board.de_proc < 5 or game.status["phase"] != "headmaster play":
            raise HTTPException(status_code=400,
                                detail="It is not time for expelliarmus!!!")

        if "headmaster_expelliarmus" not in game.status.keys():
            if current_player["current_position"] == 'headmaster':
                game.status["headmaster_expelliarmus"] = in_vote.vote
            else:
                raise HTTPException(
                    status_code=400,
                    detail="The headmaster must play the expelliarmus first!")
        else:
            if current_player["current_position"] == 'minister':
                game.status["minister_expelliarmus"] = in_vote.vote
            else:
                raise HTTPException(
                    status_code=400,
                    detail="The minister must confirm the expelliarmus!")
            detail = "The expelliarmus has failed!"
            if game.status["minister_expelliarmus"] and game.status[
                    "headmaster_expelliarmus"]:
                cards = game.board.deck.split(',')[2:]
                game.board.deck = ','.join(cards)
                detail = "the expelliarmus was played succesfully!, cards discarded"
                Player.reassign_minister(game)

        return {detail}
Пример #13
0
def sign_up():
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))

    form = SignUpForm()
    if form.validate_on_submit():
        hashed_pw = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        new_user = User(username=form.username.data,
                        email=form.email.data,
                        password=hashed_pw)
        db.session.add(new_user)
        db.session.commit()
        flash(
            'Your account was successfully created. You are now able to log in.',
            'success')
        return redirect(url_for('users.login'))

    return render_template('users/signup.html', title='Sign Up', form=form)
Пример #14
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=hashed_password)
        db.session.add(user)
        db.session.commit()
        flash(
            f'Account created for {form.username.data}! you are now able to login.',
            'success')
        return redirect(url_for('login'))
    return render_template("register.html",
                           title="Flask | REGISTER",
                           form=form)
Пример #15
0
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('users.reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('Your password has been updated! You are now able to log in',
              'success')
        return redirect(url_for('users.login'))
    return render_template('reset_token.html',
                           title='Reset Password',
                           form=form)
Пример #16
0
def signup_post():
    email_address = request.form.get('email_address')
    username = request.form.get('username')
    password = request.form.get('password')

    user = User.query.filter_by(username=username).first()

    if user:
        flash('Email Address already exists')
        return redirect(url_for('auth.signup'))

    new_user = User(username=username,
                    password=generate_password_hash(password, method='sha256'),
                    email_address=email_address)

    scrap_database.session.add(new_user)
    scrap_database.session.commit()

    return redirect(url_for('auth.login'))
Пример #17
0
def add_user():
    """
    create new user in db
    :return:
    """
    username = args.username
    password = args.password
    name = args.name
    email = args.email

    if username and password and name and email:

        user = User(username=username,
                    password=password,
                    name=name,
                    email=email)
        session.add(user)
        session.commit()
        print("User added successfully")
Пример #18
0
def register():
    '''Register a new user'''
    headers = {'Content-Type': 'application/json'}
    request_data = request.get_json()
    # print(request_data)
    body = {
        'provider': 'email',
        'data': {
            'email': request_data['email'],
            'password': request_data['password']
        }
    }
    # print(body)
    auth_url = 'https://auth.{}.hasura-app.io/v1/signup'.format(CLUSTER_NAME)
    auth_response = requests.post(auth_url,
                                  data=json.dumps(body),
                                  headers=headers).json()
    print(auth_response)
    if 'hasura_id' not in auth_response:
        return jsonify(status='failed',
                       description=auth_response['message']), 400
    new_user = User(hasura_id=auth_response.get('hasura_id'),
                    username=request_data['username'],
                    avatar_file_link=request_data['avatar'])
    try:
        db.session.add(new_user)
        db.session.commit()
        data = {
            "status": "success",
            "description": "User successfully registered."
        }
    except Exception as e:
        print(e)
        admin.delete_user(auth_response['hasura_id'])
        data = {
            "status":
            "failed",
            "description":
            "Username already exists. Please enter a different username."
        }
        return jsonify(data=data), 400
    return jsonify(data=data), 201
Пример #19
0
 def post(self):
     json_data = request.get_json(force=True)
     if not json_data:
         return {'message': 'No input data provided'}, 400
     # Validate and deserialize input
     data, errors = user_schema.load(json_data)
     if errors:
         return errors, 422
     users = User.query.filter_by(email=data['email']).first()
     if users:
         return {'message': 'users already exists'}, 400
     users = User(
         username=json_data['username'],
         email=json_data['email'],
         passworhash=json_data['passworhash'],
     )
     db.session.add(users)
     db.session.commit()
     result = user_schema.dump(users).data
     return {"status": 'success', 'data': result}, 201
Пример #20
0
def registerInput(session):
    valid_username = False
    while not valid_username:
        username = input("Username: "******"Password: "******"Username is Already in Use" + bcolors.ENDC)
        else:
            print(bcolors.OKBLUE + "Successfully Registered!" + bcolors.ENDC)
            valid_username = True
            new_user = User(username=username,
                            password=password,
                            creation_date=current_date())
            session.add(new_user)
            session.commit()
Пример #21
0
def create_savvy_submission():
    post_data = request.get_json()
    email_address = post_data.get('email_address')
    title = post_data.get('title')
    body = post_data.get('body')
    with db_session() as session:
        user = session.query(User).filter_by(
            email_address=email_address).first()
        if not user:
            user = User(email_address=email_address)
            session.add(user)
            session.commit()
        savvy_submission = SavvySubmission(user_id=user.id,
                                           title=title,
                                           body=body)
        session.add(savvy_submission)
        session.commit()
        return make_response(jsonify({
            'message': 'success',
        })), 200
Пример #22
0
def test_resolve_user_url(db_mock, app):
    """Tests that it resolves a user url"""
    with app.test_request_context():
        with db_mock.scoped_session() as session:
            User.__table__.create(db_mock._engine)
            session.add(
                User(
                    blockhash=
                    "0x2969e88561fac17ca19c1749cb3e614211ba15c8e471be55de47d0b8ca6acf5f",
                    is_current=True,
                    updated_at=datetime.now(),
                    created_at=datetime.now(),
                    blocknumber=16914541,
                    handle="Urbanbankai",
                    handle_lc="urbanbankai",
                    user_id=42727))
            url = 'https://audius.co/urbanbankai'
            resolved_url = resolve_url(session, url)

            assert resolved_url == '/v1/users/DE677'
Пример #23
0
async def process_price(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['price'] = message.text
        user = User.get(User.external_id == message.from_user.values.get('id'))
        Expense.create(**data, user=user)
        # summary of saved expense
        await bot.send_message(
            message.chat.id,
            md.text(
                md.text('Gasto de ', md.bold(data['description']),
                        ' guardado! '),
                md.text('Categorias: ', md.code(data['categories'])),
                md.text('Price: $', data['price']),
                sep='\n',
            ),
            parse_mode=ParseMode.MARKDOWN,
        )

    # Finish conversation
    await state.finish()
Пример #24
0
def signup():
    if request.method == 'GET':
        return render_template('signup.html')
    else:
        if len(
                request.form['password']
        ) is 0 or request.form['password'] != request.form['confirmpassword']:
            error = 'Password confirmation must match the password.'
            return render_template('signup.html', error=error)
        user = User.query.filter_by(username=request.form['username']).first()
        if user is None:
            new_user = User(username=request.form['username'],
                            password_hash=generate_password_hash(
                                request.form['password']))
            db.session.add(new_user)
            db.session.commit()
            session['username'] = request.form['username']
            return redirect(url_for('brackets'))
        else:
            error = 'User already exists.'
            return render_template('signup.html', error=error)
Пример #25
0
    def user_add_teacher(self, *args):
        """
        增加学员
        :param args:
        :return:
        """
        name = self.format.input_str_format("请输入用户名")
        password = self.format.input_str_format("请输入密码")
        qq = self.format.input_str_format("请输入QQ号")
        role_obj = self.session.query(Role).filter_by(name="student").first()

        user_obj = User(name=name,
                        password=password,
                        qq=qq,
                        role_id=role_obj.id)
        try:
            self.session_add(user_obj)
            self.logger.debug("学员[%s]添加成功" % name)
        except:
            self.session.rollback()
            self.logger.error("学员名或者QQ已存在")
Пример #26
0
 def user_add(self, *args):
     """
     增加用户
     :param args:
     :return:
     """
     name = self.format.input_str_format("请输入用户名")
     password = self.format.input_str_format("请输入密码")
     qq = self.format.input_str_format("请输入QQ号")
     if self.role_list():
         role_id = self.format.input_str_format("请输入角色ID号")
         user_obj = User(name=name,
                         password=password,
                         qq=qq,
                         role_id=role_id)
         try:
             self.session_add(user_obj)
             self.logger.debug("用户[%s]添加成功" % name)
         except:
             self.session.rollback()
             self.logger.error("用户名或者QQ已存在")
Пример #27
0
 def post(self):
     args = parser.parse_args(strict=True)
     new_user = User(firstname=args['firstname'],
                     lastname=args['lastname'],
                     email=args['email'],
                     password=args['password'],
                     ispremium=args['ispremium'],
                     serialnumber=args['serialnumber'],
                     isadmin=args['isadmin'])
     id_ = User.query.filter_by(email=args['email']).first()
     if id_ is not None:
         return Response(response=json.dumps(
             dict(error='user exist already')),
                         status=400,
                         mimetype='application/json')
     db.session.add(new_user)
     db.session.commit()
     id_ = User.query.filter_by(email=args['email']).first()
     return Response(response=id_.to_json(),
                     status=200,
                     mimetype='application/json')
Пример #28
0
def signup():
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))
    form = SignupForm()
    if form.validate_on_submit():
        try:
            hashed_password = bcrypt.generate_password_hash(
                form.password.data).decode('utf-8')
            time = datetime.utcnow()
            user = User(username=form.username.data,
                        showname=form.showname.data,
                        email=form.email.data,
                        password=hashed_password,
                        created_utc=time)
            db.session.add(user)
            db.session.commit()
            flash('Your account has been created. Login Now', 'success')
            return redirect(url_for('main.home'))
        except Exception as e:
            flash(e, 'error')
    return render_template('users/signup.html', title='Sign Up', form=form)
Пример #29
0
def portal():
    form = SignUpLoginForm()
    if form.validate_on_submit():
        secret_key, account_id = request.form.get('secret_key'), request.form.get('account_id')

        # whether enrolling or login in: we need to check if account with current info already exists
        user = User.query.filter(User.secret_key == secret_key, User.account_id == account_id).first()

        if request.form.get('submit') == 'Login':
            if not user:
                return render_template('portal.html', form=form, errors=["User does not exist. Please sign up first."])
        elif request.form.get('submit') == 'Sign Up':
            if user:
                return render_template('portal.html', form=form, errors=["Account exists, you may just Login"])
            user = User.create(secret_key=secret_key, account_id=account_id)

        # whether login or enroll, login the user eventually
        login_user(user)
        return redirect(url_for('profile'))

    return render_template('portal.html', form=form, errors=form.get_error_msgs())
Пример #30
0
async def on_reaction_remove(reaction, user):
    author = reaction.message.author
    for e in reaction.message.embeds:
        try:
            author_name = e['author']['name']
            author_avatar = e['author']['icon_url']
        except:
            pass
        real_author = find_member(author_name, author_avatar,
                                  reaction.message.channel.server)
        if (real_author != None):
            author = real_author

    if (str(reaction.emoji) == EDIT_EMOJI
            or (reaction.custom_emoji and reaction.emoji.name == EDIT_EMOJI)):
        for react in reaction.message.reactions:
            if (str(reaction.emoji) == EDIT_EMOJI or
                (reaction.custom_emoji and reaction.emoji.name == EDIT_EMOJI)):
                return
        await delete_popup(reaction.message)

    if ((author != user or user.id == JOHNYS_ID) and author != client.user):
        if (author.id not in karma_dict):
            karma_dict[author.id] = [2, 2, 2, 2]
            new_user = User(author.id, karma_dict[author.id])
            session.add(new_user)
        if (str(reaction.emoji) == AUT_EMOJI or
            (reaction.custom_emoji and reaction.emoji.name == AUT_EMOJI)):
            karma_dict[author.id][0] -= 1
        elif (str(reaction.emoji) == NORM_EMOJI or
              (reaction.custom_emoji and reaction.emoji.name == NORM_EMOJI)):
            karma_dict[author.id][1] -= 1
        elif (str(reaction.emoji) == NICE_EMOJI or
              (reaction.custom_emoji and reaction.emoji.name == NICE_EMOJI)):
            karma_dict[author.id][2] -= 1
        elif (str(reaction.emoji) == TOXIC_EMOJI or
              (reaction.custom_emoji and reaction.emoji.name == TOXIC_EMOJI)):
            karma_dict[author.id][3] -= 1

        update_user(author.id)
Пример #31
0
async def kill_player(player_id: PlayerM, game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        current_player = Player.user_player(user, game_id)
        victim_player = Player.select(
            lambda p: p.id == player_id.id and p.game.id == game_id).first()
        deck = game.board.spell_fields.split(",")
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if game.status["phase"] != "spell play":
            raise HTTPException(status_code=400,
                                detail="Its not time for playing spells!")
        if not game.board.de_proc or deck[game.board.de_proc -
                                          1] != 'avadakedavra':
            raise HTTPException(
                status_code=400,
                detail="The avadakedavra spell is not available")
        if not victim_player:
            raise HTTPException(
                status_code=400,
                detail="The victim player does not belong to this game")
        if current_player["current_position"] != "minister":
            raise HTTPException(status_code=404,
                                detail="This player is not the minister")
        victim_player.alive = False
        if victim_player.is_voldemort:
            game.status = {
                "info": "game ended",
                "winner": "Phoenix Order",
                "detail": "voldemort killed"
            }
        else:
            Player.reassign_minister(game)
        victim_user = User.select(
            lambda u: u.id == victim_player.user.id).first()
        return {
            "avadakedavra": "succeed!",
            "dead_player_id": player_id.id,
            "dead_player_alias": victim_user.useralias
        }
Пример #32
0
async def on_reaction_add(reaction, user):
    author = reaction.message.author
    server = reaction.message.channel.server
    settings = server_settings(session, server)
    print (settings.aut_emoji)
    for e in reaction.message.embeds:
        author_name, author_avatar = '',''
        try:
            author_name = e['author']['name']
            author_avatar = e['author']['icon_url']
        except: pass # not the type of embed we were expecting
        # this won't work if the user has default avatar
        real_author = discord.utils.get(server.members, name=author_name, avatar_url=author_avatar)
        if (real_author != None):
            author = real_author

    if settings.edit_emoji in str(reaction.emoji):
        await add_popup(reaction.message)

    if STAR_EMOJI in str(reaction.emoji):
        if reaction.count == 5:
            await starboard_post(reaction.message, server)

    if ((author != user or user.id == JOHNYS_ID or user.id == MATTS_ID) and author != client.user and user != client.user):
        if (author.id not in karma_dict):
            karma_dict[author.id] = [2,2,2,2,0]
            new_user = User(author.id, karma_dict[author.id])
            session.add(new_user)

        if settings.aut_emoji in str(reaction.emoji):
            karma_dict[author.id][0] += 1
        elif settings.norm_emoji in str(reaction.emoji):
            karma_dict[author.id][1] += 1
        elif settings.nice_emoji in str(reaction.emoji):
            karma_dict[author.id][2] += 1
        elif settings.toxic_emoji in str(reaction.emoji):
            karma_dict[author.id][3] += 1
        elif settings.bot_emoji in str(reaction.emoji):
            karma_dict[author.id][4] += 1
        update_user(author.id)
Пример #33
0
 def post(self):
     # get auth token
     auth_header = request.headers.get("Authorization")
     if auth_header:
         try:
             auth_token = auth_header.split(" ")[1]
         except IndexError:
             responseObject = {
                 "status": "fail",
                 "message": "Bearer token malformed.",
             }
             return make_response(jsonify(responseObject)), 401
     else:
         auth_token = None
     if auth_token:
         resp = User.decode_auth_token(auth_token)
         if not isinstance(resp, str):
             # mark the token as blacklisted
             blacklist_token = BlacklistToken(token=auth_token)
             try:
                 # insert the token
                 db.session.add(blacklist_token)
                 db.session.commit()
                 responseObject = {
                     "status": "success",
                     "message": "Successfully logged out.",
                 }
                 return make_response(jsonify(responseObject)), 200
             except Exception as e:
                 responseObject = {"status": "fail", "message": e}
                 return make_response(jsonify(responseObject)), 500
         else:
             responseObject = {"status": "fail", "message": resp}
             return make_response(jsonify(responseObject)), 401
     else:
         responseObject = {
             "status": "fail",
             "message": "Provide a valid auth token.",
         }
         return make_response(jsonify(responseObject)), 403
Пример #34
0
def signup():
    '''
    User sign-up page.

    [GET] sign-up page.
    [POST] validate form & user creation.
    '''

    form = SignupForm()
    if form.validate_on_submit():
        email = form.email.data
        if User.exist(email=email):  # User exists.
            flash('User exists.')
        else:
            create_u = CreateUser(email=email)
            user = create_u.create(name=form.name.data,
                                   password=form.password.data,
                                   login_type="site")
            create_u.commit_db()

            from src.mailer.mail import Mailer, ConfirmMail
            msg = ConfirmMail(user.email)
            mailer = Mailer(msg)

            # Send email with reset uri.
            mailer.send()
            flash('We just sent you an email to confirm your account.')

        # Login page.
        return render_template('login.jinja2',
                               form=form,
                               title='Log in.',
                               template='login-page')

    # Signup page.
    return render_template('signup.jinja2',
                           title='Join  our community!',
                           form=form,
                           template='signup-page')
Пример #35
0
def create():
    if current_user.is_authenticated:
        return 'Selection screen'
    if request.method == 'GET':
        return 'Sign up screen'
    else:
        email = request.form.get('email')
        password = request.form.get('password')

        user = User.query.filter_by(email=email).first()

        if user:
            flash('Email address already exists.')
            return redirect(url_for('authentication.create'))

        user = User(email,
                    password=generate_password_hash(password, method='sha256'))

        db.session.add(user)
        db.session.commit()

        return 'Selection screen'
Пример #36
0
def test_create_user():
    for i, u in enumerate(pytest.users.values()):
        with db_session:
            response = client.post("/users/",
                                   headers={},
                                   json={
                                       "username": u['username'],
                                       "useralias": u["useralias"],
                                       "email": u['email'],
                                       "password": "******",
                                       "frontURL": "ded"
                                   })
    with db_session:
        for i, u in enumerate(pytest.users.values()):
            user = User.get(email=u["email"])
            user.verified = True
            u["user_id"] = int(user.id)
    response = client.post("/users/",
                           headers={},
                           json={
                               "username": "******",
                               "useralias": "andres",
                               "email": "*****@*****.**",
                               "password": "******",
                               "frontURL": "ded"
                           })
    assert response.status_code == 400
    assert response.json() == {"detail": "Username already registered"}
    response = client.post("/users/",
                           headers={},
                           json={
                               "username": "******",
                               "useralias": "andres234",
                               "email": "*****@*****.**",
                               "password": "******",
                               "frontURL": "ded"
                           })
    assert response.status_code == 400
    assert response.json() == {"detail": "Email already registered"}
Пример #37
0
async def check(context):
    await client.send_typing(context.message.channel)
    for member in context.message.mentions:
        if (member == client.user):
            await client.send_message(
                context.message.channel,
                "Leave me out of this, " + context.message.author.mention)
            return
        if (member.id not in karma_dict):
            karma_dict[member.id] = [2, 2, 2, 2]
            new_user = User(member.id, karma_dict[member.id])
            session.add(new_user)
        response = member.display_name + " is "
        response += (
            "{:3.1f}% autistic".format(get_autism_percent(member.id)) if
            (get_autism_percent(member.id) >= get_normie_percent(member.id))
            else "{:3.1f}% normie".format(get_normie_percent(member.id)))
        response += " and " + (
            "{:3.1f}% toxic.".format(get_toxc_percent(member.id)) if
            (get_toxc_percent(member.id) >= get_nice_percent(member.id)) else
            "{:3.1f}% nice.".format(get_nice_percent(member.id)))
        await client.send_message(context.message.channel, response)
Пример #38
0
 def post(self):
     # args = login_parsers['POST'].parse_args()
     args = self.get_args('post')
     user = User.authenticate(args['username'], args['password'])
     if user:
         resp_json = jsonify({
             'status': '200',
             'msg': 'ok',
             'token': user.generate_auth_token()
         })
         resp = make_response(resp_json, 200)
         if args['remembered']:
             resp.headers['Authorization'] = user.generate_auth_token(
                 7 * 24 * 60 * 60)
         else:
             resp.headers['Authorization'] = user.generate_auth_token(
                 2 * 60 * 60)
         resp.headers['Access-Control-Expose-Headers'] = 'Authorization'
         return resp
     else:
         current_app.logger.info('test')
         return {'status': 403, 'message': '用户名或密码错误'}
Пример #39
0
def load_user(user_id):
    """
    User by the login manager
    Load the user object from user id stored in session
    """
    return User.get_by_id(user_id)
Пример #40
0
 def test_update_user(self):
     u = self._create_user()
     new_account_id = 'abc456'
     u.update(account_id=new_account_id)
     self.assertEqual(User.get_by_id(u.id).account_id, new_account_id)
Пример #41
0
 def test_delete_user(self):
     u = self._create_user()
     u.delete()
     self.assertEqual(User.query.count(), 0)
     self.assertIsNone(User.get_by_id(u.id))
Пример #42
0
 def _create_user(self):
     return User.create(account_id=self.account_id, secret_key=self.secret_key)
Пример #43
0
 def _create_purchase_with_member_with_user(self):
     u = User.create(account_id=self.account_id, secret_key=self.secret_key)
     m = Member.create(email=self.email, account_id=u.account_id)
     p = Purchase.create(title='TEST', price=100, member_id=m.id)
     return [p, m, u]