Example #1
0
def handle_send_message_event(data):
    sender = User(username=data['username'], user_id=data['user_id'])
    user_type = data['user_type']
    current_room = get_room(data['room_id'])
    last_sender = None
    prev_msg = None
    if len(current_room.messages) > 0:
        index = len(current_room.messages) - 1
        prev_msg = current_room.messages[index]
        last_sender = prev_msg.sender

    if user_type == "BOT":
        sender.personality = data['personality']
        sender.user_type = user_type
        bot = assign_bot(personality=sender.personality)
        prev_content = prev_msg.content.message if prev_msg else None
        message = bot(prev_content)
    else:
        message = Message(sender=sender, content=Content(message=data['msg']))
        data['ok'] = "DIN TUR"

    if last_sender is None or last_sender.user_id != sender.user_id:
        data['message'] = asdict(message)
        current_room.messages.append(message)
        socket.emit('receive_message', data, to=current_room.room_id)
Example #2
0
def register():
    # verify if user is already logged in.
    # if he is, redirect home. otherwise continue showing login page.
    try:
        displayname = session['displayname']
        if displayname is not None:
            return redirect(url_for('home'))

    except KeyError as error:
        # User is not logged in. continue on this page.
        pass

    userform = UserForm()
    if userform.validate_on_submit():
        # if the request.method == POST and the form is valid,
        # register the user and redirect to home
        displayname = userform.displayname.data
        password = userform.password.data

        # check if user is already registered
        try:
            user = User(displayname=displayname, password=None)
            i = users.index(user)
            userform.displayname.errors.append('Display name already taken')

        except ValueError as e:
            # Display name available to use.
            # Create the user.
            newuser = User(displayname=displayname, password=password)
            users.append(newuser)
            session['displayname'] = displayname
            return redirect(url_for('home'))

    return render_template('register.html', form=userform)
Example #3
0
def auth_registration():
    data = request.get_json()
    username = data.get('username')
    first_name = data.get('first_name')
    last_name = data.get('last_name')
    email = data.get('email')
    pass1 = data.get('password1')
    pass2 = data.get('password2')

    no_exist = User.query.filter_by(email=email).first() is None
    pass_equiv = pass1 == pass2

    xhr = MakeResponse()

    if not pass_equiv:
        xhr.set_error(422, "Paswords do not match.")
    elif not no_exist:
        xhr.set_error(409, "Email address is not available for use.")
    else:
        user = User({
            "username": username,
            "first_name": first_name,
            "last_name": last_name,
            "email": email,
            "password": pass1
        })
        user.save()
        xhr.set_status(200)

    return xhr.response
Example #4
0
def registration():
    form = RegisterForm()
    if form.validate_on_submit():
        # Проверка правильности повторного ввода пароля
        if form.password.data != form.password_again.data:
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают")

        # Проверка наличия в системе такого пользователя
        session = db_session.create_session()
        if session.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")

        # Создание пользователя
        user = User(surname=form.surname.data,
                    name=form.name.data,
                    age=form.age.data,
                    email=form.email.data)

        # Добавление пользователя в БД
        user.set_password(form.password.data)
        session.add(user)
        session.commit()

        return redirect('/login')
    return render_template('register.html', title='Регистрация', form=form)
Example #5
0
def auth_registration():
    data = request.get_json()
    username = data.get('username')
    first_name = data.get('first_name')
    last_name = data.get('last_name')
    email = data.get('email')
    pass1 = data.get('password1')
    pass2 = data.get('password2')

    no_exist = User.query.filter_by(email=email).first() is None
    pass_equiv = pass1 == pass2

    xhr = MakeResponse()

    if not pass_equiv:
        xhr.set_error(422, "Paswords do not match.")
    elif not no_exist:
        xhr.set_error(409, "Email address is not available for use.")
    else:
        user = User({
            "username": username,
            "first_name": first_name,
            "last_name": last_name,
            "email": email,
            "password": pass1
        })
        user.save()
        xhr.set_status(200)

    return xhr.response
Example #6
0
def load_user():
    user = None

    # Ignore all non-admin users for now.
    if not is_admin():
        g.user = None
        return

    # Ignore all non-admin users during maintenance mode.
    if current_app.config["MAINTENANCE_MODE"]:
        return

    if is_authenticated():
        data = session["user_info"]
        email = data["email"]

        user = User.query.filter_by(email=email).one_or_none()
        if not user:
            user = User(email=email,
                        full_name=data["name"],
                        profile_picture=data["picture"])
        else:
            user.full_name = data["name"]
            user.profile_picture = data["picture"]
        db.session.add(user)
        db.session.commit()

    g.user = user
Example #7
0
def get_user_language(user_id=None, update=None, short=False):
    # If passed update, not user_id
    if update:
        user_id = update.message.from_user.id

    # Create database session
    session = db_session.create_session()

    # Get user information
    user = session.query(User).filter(User.telegram_id == user_id).first()

    # If user doesn't exist
    if not user:
        # Create new object for user with standard parameters
        new_user = User()
        new_user.telegram_id = user_id
        new_user.language_id = 0
        session.add(new_user)
        session.commit()
        user = new_user

    # Get user language
    language_id = user.language_id
    language = LANGUAGES[language_id]

    # Close database session
    session.close()

    # If passed "short"=True parameter, return short language
    if short:
        return language["short"]

    # Return language
    return language
Example #8
0
def login():
    userf = UserForm()
    admin = AdminForm()

    if userf.validate_on_submit():

        comand = userf.comand_name.data
        username = userf.username.data
        password = userf.password.data
        db_sess = db_session.create_session()
        team = db_sess.query(Teams).filter(Teams.name == comand).filter(
            Teams.name != 'Admins').first()

        if team and check_password_hash(team.password_hash, password):
            users = db_sess.query(
                User.username).filter(User.team == team.name).all()
            users_names = [x[0] for x in users]

            if username in users_names:
                login_user(
                    db_sess.query(User).filter(User.team == team.name).filter(
                        User.username == username).first())
                return redirect("/user")

            else:
                if len(users) < 6:
                    us = User()
                    us.username = username
                    us.team = comand
                    db_sess.add(us)
                    db_sess.commit()
                    login_user(us)
                    return redirect("/user")

                else:
                    return render_template('login.html',
                                           form=userf,
                                           adm_form=admin)
        return render_template('login.html', form=userf, adm_form=admin)

    if admin.validate_on_submit():

        name = admin.ad_username.data
        password = admin.ad_password.data
        db_sess = db_session.create_session()
        admins = db_sess.query(User).filter(User.username == name).filter(
            User.role == 1).first()
        team = db_sess.query(Teams).filter(Teams.name == 'Admins').first()

        if admins and check_password_hash(team.password_hash, password):
            login_user(admins)
            return redirect('/admin')

        else:
            return render_template('login.html', form=userf, adm_form=admin)
    return render_template('login.html',
                           title='Авторизация',
                           form=userf,
                           adm_form=admin)
Example #9
0
 def test_get_user_tags_not_owner(self):
     user = User(username='******', password='******', email='*****@*****.**')
     user.save()
     get = self.client.get(
         '/users/%s/tags' % user.id,
         headers=self.headers
     )
     self.assertStatus(get, 401)
Example #10
0
 def tearDown(self):
     # delete the items
     Item.delete_item(self.item1)
     Item.delete_item(self.item2)
     # delete the categories
     Category.delete_category(self.category1)
     Category.delete_category(self.category2)
     # delete the users
     User.delete_user(self.buyer)
     User.delete_user(self.seller)
Example #11
0
    def tearDown(self):
        Reservation.delete_reservation(self.reservation1)
        self.user.remove_reservation(self.reservation2)

        Item.delete_item(self.item1)
        Item.delete_item(self.item2)
        Item.delete_item(self.item3)

        User.delete_user(self.user)
        Category.delete_category(self.category)
Example #12
0
 def test_create(self):
     User.create({
         "username": "******",
         "email": "*****@*****.**",
         "password": "******"
     })
     db.session.flush()
     db.session.expire_all()
     get = User.query.filter_by(username="******").first()
     self.assertIsNotNone(get)
     self.assertEqual(get.email, "*****@*****.**")
Example #13
0
 def test_create(self):
     User.create({
         "username": "******",
         "email": "*****@*****.**",
         "password": "******"
     })
     db.session.flush()
     db.session.expire_all()
     get = User.query.filter_by(username="******").first()
     self.assertIsNotNone(get)
     self.assertEqual(get.email, "*****@*****.**")
Example #14
0
    def tearDown(self):
        # delete the items
        Item.delete_item(self.textbook_3091_1)
        Item.delete_item(self.textbook_3091_2)
        Item.delete_item(self.video_5111)
        Item.delete_item(self.cheat_sheets)

        # delete the categories
        Category.delete_category(self.textbooks)
        Category.delete_category(self.videos)
        Category.delete_category(self.girs)

        # delete the user
        User.delete_user(self.user)
Example #15
0
    def setUp(self):
        super(BaseTestCase, self).setUp()
        self.app = create_app(config.Testing)
        self.app_context = self.app.app_context()
        self.client = self.app.test_client()
        self.app_context.push()
        self.db = db
        self.db.drop_all()
        self.db.create_all()
        self.user = dict(username="******",
                         password="******",
                         first_name="Test",
                         last_name="User",
                         _admin=True)
        self.document = dict(title="This is a Test Title",
                             body="Body Body Body, likeasomebody")
        self.tag = {"title": "TAGGY"}

        self.default_user = User.create(self.user)
        self.default_document = Document.create(self.document)
        self.default_document.user = self.default_user
        self.tag = Tag.create(self.tag)
        self.tag.user = self.default_user
        self.default_document.tags.append(self.tag)
        self.db.session.commit()
        self.redis_store = RedisStore(store=FakeStrictRedis, name='test')
        token = jwt.create_token_for_user(self.default_user)
        self.headers = [('Content-Type', 'application/json'),
                        ('Authorization', 'Bearer %s' % token)]
Example #16
0
def register_user():
    """
    This method registers a user with the data provided and returns corresponding response
    """
    fmt = __format(request)
    if request.content_type == "application/json":
        username = request.json['username']
        name = request.json['name']
        password = request.json['password']
    else:
        username = request.forms.get("username")
        name = request.forms.get("name")
        password = request.forms.get("password")
    user = User(name=name, username=username, password=password)
    result = db.insert_registration(user)
    if result:
        response._status_line = "201 Created"
        response_to_user = {
            "status": response._status_line,
            "success": True,
            "message": "Created",
            "user_id": result
        }
        return format_checker(response_to_user, fmt)
    else:
        response._status_line = "500 Internal Server Error"
        response_to_user = {
            "status": response._status_line,
            "success": False,
            "message": "Could Not Process Request!!!"
        }
        return format_checker(response_to_user, fmt)
Example #17
0
    def setUp(self):
        super(BaseTestCase, self).setUp()
        self.app = create_app(config.Testing)
        self.app_context = self.app.app_context()
        self.client = self.app.test_client()
        self.app_context.push()
        self.db = db
        self.db.drop_all()
        self.db.create_all()
        self.user = dict(
            username="******",
            password="******",
            first_name="Test",
            last_name="User",
            _admin=True
        )
        self.document = dict(
            title="This is a Test Title",
            body="Body Body Body, likeasomebody"
        )
        self.tag = {"title": "TAGGY"}

        self.default_user = User.create(self.user)
        self.default_document = Document.create(self.document)
        self.default_document.user = self.default_user
        self.tag = Tag.create(self.tag)
        self.tag.user = self.default_user
        self.default_document.tags.append(self.tag)
        self.db.session.commit()
        self.redis_store = RedisStore(store=FakeStrictRedis, name='test')
        token = jwt.create_token_for_user(self.default_user)
        self.headers = [
            ('Content-Type', 'application/json'),
            ('Authorization', 'Bearer %s' % token)
        ]
Example #18
0
 def username_email_exists(self, username, email):
     """Validates if a user exists by username or email"""
     self.__open_connection()
     cursor = self.__db.cursor()
     result = {}
     try:
         sql_query = """select user_id, username, email, entry_date from user where username = %s or email = %s"""
         cursor.execute(sql_query, (
             username,
             email,
         ))
         dataset = cursor.fetchall()
         for user_id, user_name, email, entry_date in dataset:
             result = User(user_id, user_name, email, '', '', entry_date)
         if not result:
             return {}
         values = {}
         if result.username == username:
             values['username'] = True
         if result.email == email:
             values['email'] = True
         return values
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
     finally:
         self.__close_connection(cursor)
     return result
Example #19
0
 def fetch_user(self, user_name, passwd):
     """Fetch an specific user by username"""
     self.__open_connection()
     cursor = self.__db.cursor()
     result = {}
     try:
         error_message = "Usuario y contras&eacute;a no coinciden."
         sql_query = """select user_id, username, email, password, salt, entry_date from user where username = %s"""
         cursor.execute(sql_query, (user_name, ))
         dataset = cursor.fetchall()
         if not dataset:
             self.__log(error_message)
             return result
         for user_id, user_name, email, password, salt, entry_date in dataset:
             user = User(user_id, user_name, email, password, salt,
                         entry_date)
         if not check_password(user, passwd):
             self.__log(error_message)
             user = result
         return user
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
     finally:
         self.__close_connection(cursor)
     return result
Example #20
0
def registration():
    form = RegistrationForm()
    response = requests.get(f'{HOST_PORT}/api/token/departament').json()
    form.departament.choices = \
        [(val['id'], val['organization']['title'] + ', ' + val['title']) for val in response['departament']]
    auth_error = ''

    if request.method == 'POST' and form.validate_on_submit():
        session = db_session.create_session()
        result = session.query(User).filter(
            User.email == request.form.get('email')).first()
        if request.form.get('password') == request.form.get('repeat_password'):
            if result == 0:
                user = User(name=request.form.get('name'),
                            email=request.form.get('email'),
                            hashed_password=request.form.get('password'),
                            departament_id=request.form.get('departament'))
                session.add(user)
                session.commit()
                session.close()
                return render_template('status.html',
                                       status=True,
                                       message='Вы успешно зарегистрированы!')
            else:
                auth_error = 'Такой пользователь уже существует'
        else:
            auth_error = 'Пароли не совпадают'
    return render_template('registration.html',
                           title='Регистрация',
                           form=form,
                           auth_error=auth_error)
Example #21
0
 def get_cookie_id(self, cookie_id, cursor):
     """Validate product properties bofore save, for example, that the code_id does not exists yet"""
     response = None
     data = None
     try:
         response = '403'
         #cursor1 = cursor(buffered=True)
         sql_query_user = """SELECT user_session_history_id, user_id FROM user_session__history WHERE cookie_id = %s limit 1"""
         test = cursor.execute(sql_query_user, (cookie_id, ))
         rows = cursor.fetchall()
         results = len(rows)
         result = results
         if results > 0:
             row = rows[0]
             sql_query_user = """SELECT user_id, name, email FROM user WHERE user_id = %s limit 1"""
             cursor.execute(sql_query_user, (row[1], ))
             rows = cursor.fetchall()
             results = len(rows)
             if results > 0:
                 row = rows[0]
                 user = User(row[0], '', row[2], '', '', row[1])
                 return user
         return response
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
         return response
     finally:
         self.__close_connection(cursor)
     return True
Example #22
0
def register():
    """
    用户注册
    """
    if request.method == 'POST':
        username = request.form.get("username")
        password = request.form.get("password")
        password2 = request.form.get("password2")
        if not all([username, password, password2]):
            return render_template('login.html', error="用户名或密码不允许为空")
        user = db.query(User).filter(User.username == username).one_or_none()
        if user:
            return render_template('register.html', error="该用户名已注册")
        if password2 != password:
            return render_template('register.html', error="两次输入的密码不匹配")
        token = create_token()
        user = User(username=username,
                    password=generate_password_hash(password),
                    active=True,
                    token=token)
        db.session.add(user)
        db.session.commit()
        response = make_response(redirect('/'))
        response.set_cookie("token", token)
        return response
    return render_template('register.html')
Example #23
0
def registration():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(form.login.data, form.password.data)
        session = db_session.create_session()
        try:
            session.add(user)
            session.commit()
        except IntegrityError:
            return render_template(
                'registration.html',
                title='Регистрация',
                form=form,
                message='Такой пользователь уже существует.')
        except Exception as e:
            print(e)
            return render_template(
                'registration.html',
                title='Регистрация',
                form=form,
                message='Произошла ошибка. Пожалуйста, повторите попытку позже.'
            )
        finally:
            session.close()
        return redirect('/login')
    return render_template('registration.html', title='Регистрация', form=form)
Example #24
0
def saveModel(name, email1, pincode, password, number, city, address, state):
    if name != None:
        try:
            a = User.objects.get(email=email1)
            dict.update({print: "User exits already try different email"})
        except User.DoesNotExist:
            pro1 = User(name=name,
                        email=email1,
                        pincode=pincode,
                        password=password,
                        number=number,
                        city=city,
                        address=address,
                        state=state)
            pro1.save()
            return True
Example #25
0
    def obj_create(self, bundle, **kwargs):
        # get the API key associated with the request
        apikey = api.auth.DatabaseAuthentication().get_identifier(
            bundle.request)

        # try and get an existing user
        try:
            bundle.obj = User.objects.get(email=bundle.data['email'])
        # no existing user, create them
        except User.DoesNotExist as e:
            if 'password' not in bundle.data:
                kwargs['password'] = User.generate_password(
                    api.auth.get_nonce(32))

            bundle = super(UserResource, self).obj_create(bundle, **kwargs)

        # create a new account entry
        account = Account()
        account.api_account = apikey.account  # set the api key's account as the creator
        account.save()

        # add the user as an admin to the new account
        accountuser = AccountUser(account=account,
                                  user=bundle.obj,
                                  is_admin=True)
        accountuser.save()

        return bundle
Example #26
0
def create_default_chat():
    try:
        default_chat = Chat.get(name="default")
    except Chat.DoesNotExist:
        default_chat = Chat()
        default_chat.name = "default"
        default_chat.admin = User.get(login="******")
        default_chat.save()
        users = User.select()
        default_chat.users.add(users)
        default_chat.save()
    else:
        users = User.select()
        for user in users:
            if user not in default_chat.users:
                default_chat.users.add(user)
        default_chat.save()
Example #27
0
 def setUp(self):
     super(SharesTestCase, self).setUp()
     self.user2 = User.create(dict(
         username="******",
         password="******",
         email="*****@*****.**"
     ))
     Share.create_or_update(self.user2, self.default_document)
Example #28
0
def create_fake_user():
    user = User(
        username="******",
        password=generate_password_hash("testword"),
        email="*****@*****.**",
    )
    db.session.add(user)
    db.session.commit()
Example #29
0
 def setUp(self):
     # create the users
     self.buyer = User.create_user(self.BUYER_USERNAME, \
             self.BUYER_FIRST_NAME, self.BUYER_LAST_NAME, \
             self.BUYER_EMAIL, self.BUYER_CELL_PHONE,
             self.BUYER_LOCATION)
     self.seller = User.create_user(self.SELLER_USERNAME, \
             self.SELLER_FIRST_NAME, self.SELLER_LAST_NAME, \
             self.SELLER_EMAIL, self.SELLER_CELL_PHONE,
             self.SELLER_LOCATION)
     # create the categories
     self.category1 = Category.create_category(self.CATEGORY_1)
     self.category2 = Category.create_category(self.CATEGORY_2)
     # create the items
     self.item1 = Item.create_item(self.seller, self.ITEM_1_NAME, \
             self.ITEM_1_DESCRIPTION, self.category1, self.ITEM_1_PRICE)
     self.item2 = Item.create_item(self.seller, self.ITEM_2_NAME, \
             self.ITEM_2_DESCRIPTION, self.category2, self.ITEM_2_PRICE)
Example #30
0
 def setUp(self):
     super(DocumentModelTestCase, self).setUp()
     self.user2 = User.create({
         "username": "******",
         "email": "*****@*****.**",
         "password": "******",
     })
     Share.create_or_update(self.user2, self.default_document, read=True)
     self.random_doc = Document.create({"title": "random document"})
Example #31
0
    def from_file(cls, filename='data/db.json'):
        with open(filename) as f:
            data = json.load(f)

        db = {}
        for user_data in data:
            db[user_data['user_id']] = User.from_json(user_data)

        return cls(db)
Example #32
0
 def test_filter_by_access(self):
     user = User.create(
         dict(username='******', password='******', email='*****@*****.**'))
     Document.create(dict(title="title", body="d", user=user))
     available = filter_by_access(
         user,
         Document.query.all(),
     )
     self.assertEqual(len(available), 1)
Example #33
0
def get_all():
    users = []

    cursor = users_collection.find({})

    for document in cursor:
        users.append(User(document['chat_id'], document['year']))

    return users
Example #34
0
 def setUp(self):
     super(DocumentModelTestCase, self).setUp()
     self.user2 = User.create({
         "username": "******",
         "email": "*****@*****.**",
         "password": "******",
     })
     Share.create_or_update(self.user2, self.default_document, read=True)
     self.random_doc = Document.create({"title": "random document"})
Example #35
0
def api_displayname_available(displayname):
    try:
        user = User(displayname=displayname, password="")
        i = users.index(user)
        # Display Name already exists
        return 'Not Available', 404

    except ValueError as e:
        # Display name available to use
        return 'Available', 200
Example #36
0
def get_messages_from_channel(channel_id: str, date: datetime.date):
    channel = TextChannel.get_by_id(channel_id)
    users = User.select()
    message_contents = MessageContent.select().order_by(
        MessageContent.timestamp.desc())
    messages = Message \
        .select() \
        .where((Message.channel == channel) & (Message.timestamp.day == date.day)) \
        .order_by(Message.timestamp)
    return prefetch(messages, users, message_contents)
Example #37
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.find_by_email(db.session, form.email.data)
        if user and user.verify_password(form.password.data):
            login_user(user)
            flash("Logged in successfully")
            return redirect(request.args.get('next') or url_for('main.index'))
        else:
            flash("Invalid email/password combination")
    return render_template("auth/login.tmpl", form=form)
Example #38
0
 def create_user(self,
                 user_id,
                 user_name,
                 first_name,
                 last_name,
                 is_bot=False):
     user = User(user_id, user_name, first_name, last_name, is_bot)
     self._context.get_context().add(user)
     self._context.get_context().flush()
     self._context.get_context().refresh(user)
     return user
Example #39
0
 def test_filter_by_access(self):
     user = User.create(dict(
         username='******',
         password='******',
         email='*****@*****.**'
     ))
     Document.create(dict(title="title", body="d", user=user))
     available = filter_by_access(
         user,
         Document.query.all(),
     )
     self.assertEqual(len(available), 1)
Example #40
0
def register_user(login, password, mail, name) -> User:
    session = db_session.create_session()
    user = User()
    auth = Auth()

    user.is_approved = False
    user.name = name
    user.role = 'user'
    user.key = geherate_key()
    auth.login = login
    auth.password = password
    auth.email = mail
    user.auth.append(auth)

    session.add(user)
    session.flush()

    application = Applications()
    application.user_id = user.id
    application.login = login
    session.add(application)

    session.commit()
    session.close()
    return user
Example #41
0
def displayfunc(request):
    pro1 = Product(
        title="Float Recliner",
        price_reg="Rs 750/month",
        description=
        "Rent our Float, a neutral fabric recliner, which merges seamlessly with any decor in your home.",
        qauntity=8,
        image="ridada",
        weight=40,
        depth=90,
        width=80,
        height=110,
        price_sale="Rs 550/month",
        bestseller="yes",
        status="available",
        productlink="/sofa/bcde/",
        category="sofa")

    pro = User(name="Rishab",
               email="*****@*****.**",
               password="******",
               number=9971775086,
               pincode=110032,
               city="Delhi",
               address="1/757 West rohtash nagar shahdara",
               state="Delhi")

    # Product.objects.all().delete()
    # for xyz in range(1,20):
    #    Product.objects.filter(id=xyz).delete()
    design = ""

    # design ='Printing all Dreamreal entries in the DB : <br>'
    # a = Product.objects.get(title="Dhyanachand Bed (Brown)")
    # design +=a.price_sale + "<br>"
    # list1=["1000","899","899","800","750","750",]
    # i=0
    b = User.objects.get(email="*****@*****.**")
    c = b.id

    objects = UserPurchase.objects.filter(email=c)
    for a in objects:
        # xyz.price_reg=list1[i]
        design += a.productid + "<br>"

    # objects = TestModels.objects.all()
    # for xyz in objects:
    #     p=xyz.price
    #     p= str(p)
    #     p = p + "<br>"
    #     design += p
    return HttpResponse(design)
Example #42
0
def user_add():
    """
        添加用户
    """
    data = request.get_json()
    username = data.get('username')
    password = data.get("password")
    if db.session.query(User).filter(User.username == username).one_or_none():
        return make_response(jsonify({"msg": "用户名已存在"}), 400)
    safe_password = generate_password_hash(password)
    db.session.add(User(username=username, password=safe_password))
    db.session.commit()
    return jsonify({})
Example #43
0
 def setUp(self):
     self.category = Category.create_category(self.GIRS_CATEGORY)
     self.user = User.create_user(self.USERNAME, self.FIRST_NAME, self.LAST_NAME, \
             self.EMAIL, self.PHONE, self.LOCATION)
     self.item1 = Item.create_item(self.user, self.PHYSICS_NAME, \
             self.PHYSICS_DESCRIPTION, self.category, self.PHYSICS_PRICE_1)
     self.item2 = Item.create_item(self.user, self.PHYSICS_NAME, \
             self.PHYSICS_DESCRIPTION, self.category, self.PHYSICS_PRICE_2)
     self.item3 = Item.create_item(self.user, self.VIDEO_NAME, \
             self.VIDEO_DESCRIPTION, self.category, self.VIDEO_PRICE)
     self.reservation1 = Reservation.create_reservation(self.user, \
             self.SEARCH_QUERY1, self.MAX_PRICE)
     self.reservation2 = self.user.add_reservation(self.SEARCH_QUERY2, self.MAX_PRICE)
Example #44
0
    def test_user(self):
        '''
        Tests to make sure that users can be queried
        and that their attributes are correct.
        '''
        # create a user

        # find the user and check it
        u = User.get_user(self.USERNAME)
        self.assertEqual(u, self.user)
        self.assertEqual(u.username, self.USERNAME)
        self.assertEqual(u.first_name, self.FIRST_NAME)
        self.assertEqual(u.last_name, self.LAST_NAME)
        self.assertEqual(u.email, self.EMAIL)
        self.assertEqual(u.cell_phone, self.PHONE)
Example #45
0
    def setUp(self):
        # create the user
        self.user = User.create_user(self.USERNAME, self.FIRST_NAME, \
                self.LAST_NAME, self.EMAIL, self.PHONE, self.LOCATION)

        # create the categories
        self.textbooks = Category.create_category(self.TEXTBOOK_CATEGORY)
        self.videos = Category.create_category(self.VIDEOS_CATEGORY)
        self.girs = Category.create_category(self.GIRS_CATEGORY)

        # create the items
        self.textbook_3091_1 = Item.create_item(self.user, self.TEXTBOOK_NAME, \
                self.TEXTBOOK_DESCRIPTION, self.textbooks, self.TEXTBOOK_PRICE)
        self.textbook_3091_2 = self.user.add_item(self.TEXTBOOK_NAME, \
                self.TEXTBOOK_DESCRIPTION, self.textbooks, self.TEXTBOOK_PRICE)
        self.video_5111 = self.user.add_item(self.VIDEOS_NAME, \
                self.VIDEOS_DESCRIPTION, self.videos, self.VIDEOS_PRICE)
        self.cheat_sheets = self.user.add_item(self.CHEAT_SHEET_NAME, \
                self.CHEAT_SHEET_DESCRIPTION, self.girs, self.CHEAT_SHEET_PRICE)
Example #46
0
 def test_password_verification(self):
     u = User(password='******')
     self.assertTrue(u.verify_password('cat'))
     self.assertFalse(u.verify_password('dog'))
Example #47
0
 def setUp(self):
     # create a user
     self.user = User.create_user(self.USERNAME, self.FIRST_NAME, \
             self.LAST_NAME, self.EMAIL, self.PHONE, self.LOCATION)
Example #48
0
 def tearDown(self):
     # delete the user
     User.delete_user(self.user)
Example #49
0
def username_is_available(username):
    if not username:
        return True
    return not User.find_by_username(db.session, username)
Example #50
0
macgregor = Location.create_location('MacGregeor House', '42.35543', '-71.09981')
maseeh = Location.create_location('Maseeh Hall', '42.35764801061463', '-71.09338732275393')
mccormick = Location.create_location('McCormick Hall', '42.35731', '-71.09454')
new_house = Location.create_location('New House', '42.35543', '-71.10023')
next_house = Location.create_location('Next House', '42.354714540813504', '-71.10203476461794')
random_hall = Location.create_location('Random Hall', '42.36191', '-71.09821')
senior = Location.create_location('Senior House', '42.36007', '-71.08689')
simmons = Location.create_location('Simmons Hall', '42.35733', '-71.10105')

# Add in categories
girs = Category.create_category('GIRs')
furniture = Category.create_category('Furniture')
clothing = Category.create_category('Clothing')
santorum = Category.create_category('Rainbow-colored Santorum Posters')

kerry = User.create_user('kxing', 'Kerry', 'Xing', '*****@*****.**', '(123)456-7890', next_house)
paul = User.create_user('pwh', 'Paul', 'Hemberger', '*****@*****.**', '(234)567-8901', maseeh)
sean = User.create_user('scockey', 'Sean', 'Cockey', '*****@*****.**', '(345)678-9012', maseeh)
sarine = User.create_user('sarine', 'Sarine', 'Shahmirian', '*****@*****.**', '(456)789-0123', bexely)

kerry.add_item('5.111 Textbook', 'In great condition.', girs, '30.99')
time.sleep(1.0)
kerry.add_item('Wooden Chair', 'Slightly worn.', furniture, '24.97')
time.sleep(1.0)
kerry.add_item('Santorum Poster', 'Really want to get rid of this...', santorum, '0.01')
time.sleep(1.0)
kerry.add_item('Blue Jeans', 'size 30-30. New.', clothing, '30.00')
time.sleep(1.0)
kerry.add_item('3.091 Textbook', 'Simply awesome.', girs, '1000.00')
time.sleep(1.0)
kerry.add_item('Couch', 'Very comfortable.', furniture, '99.99')
Example #51
0
def get_current_user(request):
    return User.get_user('kxing')
Example #52
0
def get_current_user(request):
    return User.get_user('pwh')
Example #53
0
def email_is_available(email_address):
    if not email_address:
        return True
    return not User.find_by_email(db.session, email_address)