Exemple #1
0
    def check(self):
        from web import form
        validList=(
            form.Textbox("username", form.regexp(r".{3,20}$", 'User name: 3-20 chars')),
            form.Password("password", form.regexp(r".{3,20}$", 'Password: 3-20 chars')),
        )

        if not self.validates(validList):
            return self.error(self.errorMessage)

        inputData = self.getInput()
        if config.ADMIN_USERNAME == inputData['username'] and config.ADMIN_PASSWORD == inputData['password']:
            self.setLogin(inputData['username'])
            return self.success(msg='管理员登陆成功', url=self.makeUrl('/admin'))
        else:
            if not self.isInstalled():
                return self.error(msg='用户登录失败, 系统未初始化!', url=self.makeUrl('/admin'))

            userName = inputData['username']
            password = hashlib.md5(inputData['password']).hexdigest()
            try:
                userObj = Users().select().where(Users.name == userName)
                if userObj.where(Users.name == userName, Users.password == password).exists() == False:
                    return self.error(msg='用户登录失败,请检查用户名和密码是否匹配', url=self.makeUrl('/admin'))
                self.setLogin(inputData['username'])
                return self.success(msg='用户登陆成功', url=self.makeUrl('/admin'))
            except  Users.DoesNotExist:
                return self.error(msg='用户登录失败,请检查用户名和密码是否匹配!', url=self.makeUrl('/admin'))
Exemple #2
0
def update_user():
    response.content_type = 'application/json'
    user = request.json
    new_user = Users(**user)
    session.add(new_user)
    session.commit()
    return json.dumps(new_user.to_dict())
Exemple #3
0
 def post(self) -> Response:
     body = request.get_json()
     try:
         key = uuid.uuid4().int
         data = {
             'staffID': str(key)[0:6],
             'username': body['username'],
             'password': body['password'],
             'name': body['name'],
             'role': body['role'],
             'department': body['department'],
             'create_at': str(datetime.utcnow()),
             'update_at': str(datetime.utcnow()),
         }
         user = Users(**data)
         user.save()
         response = jsonify({
             "data": data,
             "message": "success",
             "status": 200
         })
         response.status_code = 201
         return response
     except Exception as e:
         response = jsonify({
             "data": None,
             "message": "error",
             "status": 204
         })
         response.status_code = 204
         return response
def test_edit_user(test_client, admin_user, dummy_user):
    """ Test that the changes a user makes to their fullname persists to the database """
    response_login = test_client.post('/login',
                                      data=dict(email=admin_user.email,
                                                password="******"),
                                      follow_redirects=True)
    response_login_json = response_login.get_json()
    header = {
        'Authorization':
        'Bearer {}'.format(response_login_json["access_token"])
    }

    response_change = test_client.post('/admin/edit_user',
                                       data=dict(email=dummy_user.email,
                                                 fullname="Not a dummy",
                                                 password="******",
                                                 admin=False,
                                                 activated=False),
                                       headers=header,
                                       follow_redirects=True)
    assert response_change.status_code == 200
    changed_user = Users.find_by_email(dummy_user.email)
    assert changed_user.fullname == "Not a dummy"
    assert Users.verify_hash("new password".encode("utf8"),
                             dummy_user.password.encode("utf8")) == True
    assert changed_user.admin == False
    assert changed_user.admin == False
def test_create_user(test_client, admin_user):
    """ Test for successful creation of a new user by an admin and for presense of user in the database  """
    response_login = test_client.post('/login',
                                      data=dict(email=admin_user.email,
                                                password="******"),
                                      follow_redirects=True)
    response_login_json = response_login.get_json()
    header = {
        'Authorization':
        'Bearer {}'.format(response_login_json["access_token"])
    }

    response_create = test_client.post('/admin/create_new_user',
                                       data=dict(email="*****@*****.**",
                                                 fullname="New User",
                                                 admin="True",
                                                 password="******"),
                                       headers=header,
                                       follow_redirects=True)
    response_create_json = response_create.get_json()
    assert b"created successfull" in response_create.data
    assert response_create.status_code == 201
    assert Users.find_by_email("*****@*****.**") != None

    db.session.delete(Users.find_by_email("*****@*****.**"))
    db.session.commit()
Exemple #6
0
 def create(cls, session: Session, user: UserBaseCreate) -> Users:
     db_user = Users(**user.dict())
     db_user.password = Security.get_pwd_hash(user.password)
     session.add(db_user)
     session.commit()
     session.refresh(db_user)
     return db_user
Exemple #7
0
    def post(self):

        try:
            user_id = get_jwt_identity()
            try:
                user = Users.query.get(user_id)
                if request.json.get('name'):
                    user.name = request.json.get('name')
                if request.json.get('email') and Users.isMail(
                        request.json.get('email')):
                    user.email = request.json.get('email')
                if request.json.get('password'):
                    user.password = Users.setPassword(
                        request.json.get('password'))
                db.session.add(user)
                db.session.commit()
                db.session.remove()
                userschema = UserSchema(
                    only=['id', 'name', 'email', 'password'])
                db.session.remove()
                request.close()
                return {'response': 'Sus datos han sido actualizados'}, 200

            except:
                request.close()
                return {'response': ' El registro no existe'}, 401
        except:
            request.close()
            return {'response': ' El registro no existe'}, 401
Exemple #8
0
def registrationroute():
    fullname = request.form['fullname']
    email = request.form['email']
    password_1 = request.form['password_1']
    password_2 = request.form['password_2']
    Users.insert_from_form(fullname, email, password_1, password_2)
    return redirect('/login')
Exemple #9
0
    def patch(self) -> (str, int):
        """
		API that allows a user change their password in the users table
		Parameters can be passed using a PATCH request that contains a JSON
		with the following fields:
		:param email: users email address
		:param password_old: users current password
		:param password_new: users new password that they want to replace
							 password_old
		:type email: string
		:type password_old: string
		:type password_new: string
		:return: A message that indicates whether a user's password has been
				updated. If they have not, the message indicates why not.
		:rtype: JSON
		"""
        args = self.parser.parse_args()
        current_user = Users.find_by_email(args['email'])  #t

        if current_user and Users.verify_hash(
                args['password_old'].encode("utf8"),
                current_user.password.encode("utf8")):
            current_user.password = Users.generate_hash(
                args["password_new"].encode("utf8")
            ).decode(
                "utf8"
            )  # decode necessary so that string (and not binary) is stored in the DB
            current_user.commit()
            return {"message": "Password has been updated"}, 200
        else:
            return {"message": "Incorrect credentials. Please Try again"}, 403
Exemple #10
0
def register():
    if request.method == 'POST' and 'register' in request.form:
        full_name = request.form['full_name']
        email = request.form['email']
        password = Utils.encrypt_pass(request.form['password'])
        tickets_amount = request.form['tickets_amount']
        mat, instrument, food, camp = 0, 0, 0, 0
        if request.form.get('mat'):
            mat = 1
        if request.form.get('instrument'):
            instrument = 1
        if request.form.get('food'):
            food = 1
        if request.form.get('camp'):
            camp = 1

        items = Users.toJson(full_name, email, password, tickets_amount, mat, instrument, food, camp)
        if not Users.register(email, items):
            return render_template('user/unsuccessful_register.html', message='דואר אלקטרוני זה כבר רשום במערכת',
                                   url='register')
        else:
            return render_template('user/confirm_registration.html', name=full_name, email=email)

    else:
        return render_template("user/registration.html")
Exemple #11
0
def export(direction=None, user=None, date=None):
    '''Export loan entries'''

    current_user_id = session.get('logged_in_user')

    our_loans = Loans(current_user_id)
    our_users = Users(current_user_id)

    # fetch loans
    loans = our_loans.get_loans()

    # fetch users from connections from us
    users = our_users.get_connections()

    # provided user?
    if user:
        # valid slug?
        user_id = our_users.is_connection(slug=user)
        if user_id: loans = our_loans.get_loans(user_id=user_id)

    # provided a date range?
    date_range = translate_date_range(date)
    if date_range:
        loans = our_loans.get_loans(date_from=date_range['low'], date_to=date_range['high'])
    # date ranges for the template
    date_ranges = get_date_ranges()

    # provided a direction?
    if direction: loans = our_loans.get_loans(direction=direction)

    response = make_response(render_template('admin_export_loans.html', **locals()))
    response.headers['Content-type'] = 'text/csv'
    response.headers['Content-disposition'] = 'attachment;filename=' + 'loans-' + str(today_date()) + '.csv'
    return response
Exemple #12
0
def user_login():
    try:
        user_data = request.get_json()
        username = user_data['username']
        password = user_data['password']
    except Exception as error:
        return jsonify({
            "Error": "Invalid User Input",
            "message": "missing either username or password",
            "status": 400
        }), 400
    user = Users(['', username, password, ''])
    found_user = user.query_login()
    if found_user is not None:
        print(password)
        print(found_user.password)
        if found_user.password == password:
            token = found_user.generate_auth_token()
            return jsonify({
                'user': username,
                'token': token['sub'],
                'message': 'login was successful'
            }), 200
        else:
            return jsonify({'Error': 'Incorrect Password'}), 403
    return jsonify({'Error': 'Username not found'}), 403
    def post() -> Response:
        """
        POST response method for creating user.

        :return: JSON object
        """
        data = request.get_json()

        usercart = Cart().save()
        output = {'id': str(usercart.id)}

        y = {"cartId": str(usercart.id)}
        print('usercart')
        print(usercart.id)
        print(usercart.products)
        print('data')
        print(data)
        data.update(y)
        print('data')
        print(data)
        post_user = Users(**data)
        try:
            post_user.save()
        except NotUniqueError as exc:

            return {'message': "Email Id already exits!!"}, 400
        output = {'id': str(post_user.id)}
        return jsonify({'result': output})
Exemple #14
0
def user_register():
    try:
        user_data = request.get_json()
        name = user_data['name']
        username = user_data['username']
        password = hash_password(user_data['password'])
        email = user_data['email']
    except Exception as error:
        return make_response(
            jsonify({
                "error": "invalid user data input",
                "message": "missing either name, username, email or password",
                "status": 400
            }), 400)
    new_user = Users([name, username, password, email])
    if not new_user.is_existing_user():
        new_user.create_new_user()
        return make_response(
            jsonify({
                "status": 201,
                "message": "user created successfully"
            }), 201)
    return make_response(
        jsonify({
            "status": 403,
            "message": "username already exists"
        }), 403)
Exemple #15
0
    def modify(self):
        userInput= self.getInput()

        userObj = Users.get(Users.id == int(userInput['id']))
        current_user = Users.get(Users.name == self.isLogin())   

        if userObj.id != current_user.id and not self.isAdmin():
            return self.error(msg = '权限不足!', url=self.makeUrl('/admin/users/list'))

        thumbnail_id = int(userInput['thumbnail']) if userInput.has_key('thumbnail') else 0
        if thumbnail_id:
            thumbnail_data = Images.get(Images.id == thumbnail_id).thumbnail
        else:
            import base64
            from imaging import imaging
            thumbnail_data = base64.b64encode(buffer(imaging.default_thumbnail()))

        try:
            userObj = Users.get(Users.id == int(userInput['id']))
            userObj.email = userInput['email']
            userObj.name = userInput['name']
            userObj.cellphone = userInput['cellphone']
            userObj.description = userInput['desc']
            userObj.gender = int(userInput['gender'])
            userObj.avatur = thumbnail_data
            if self.isAdmin():
                userObj.role = userInput['role']
            userObj.save()
        except Exception, e:
            return self.error(msg = '会员修改失败: %s' % e, url=self.makeUrl('/admin/users/list'))
Exemple #16
0
    def save(self):
        userInput = self.getInput()  
        # 只有admin才能新增用户
        if not self.isAdmin():
            return self.error(msg = '权限不足!', url=self.makeUrl('/admin/users/list'))

        thumbnail_id = int(userInput['thumbnail']) if userInput.has_key('thumbnail') else 0
        if thumbnail_id:
            thumbnail_data = Images.get(Images.id == thumbnail_id).thumbnail
        else:
            import base64
            from imaging import imaging
            thumbnail_data = base64.b64encode(buffer(imaging.default_thumbnail()))

        try:
            Users.create(
                cellphone = userInput['cellphone'],
                email = userInput['email'],
                name = userInput['name'],
                password = hashlib.md5(userInput['passwd']).hexdigest(),
                avatur = thumbnail_data,
                gender = int(userInput['gender']),
                description = userInput['desc'],
                role = int(userInput['role'])
            )
        except Exception, e:
            return self.error(msg = '会员保存失败: %s' % e, url=self.makeUrl('/admin/users/list'))
    def post():

        data = request.get_json()
        post_user = Users(**data)
        post_user.save()
        output = {'id': str(post_user.id)}
        return jsonify({'result': output})
Exemple #18
0
 def testAdd(self):
     users = Users()
     before_count = len(users.all())
     self.assertTrue(users.add(users.new(), persist=False))
     after_count = len(users.all())
     self.assertGreater(after_count, before_count)
     self.assertEqual(before_count + 1, after_count)
Exemple #19
0
def del_repo(git_name, git_repository_blog):
    args = request.args.get('access_token')
    if not args:
        return jsonify({'access_token': args})
    git_access = GitAccess(git_name, git_repository_blog, args)
    data = git_access.get_all_posts()
    users_list = Users(git_name, git_repository_blog)
    session_git = users_list.open_base()
    users = session_git.query(Users)
    query_fav = session_git.query(Favorites).filter(
        Favorites.user_name == git_name.lower())
    for one_fav in query_fav:
        session_git.delete(one_fav)
    if data.status_code == 200:
        for dir_ in data.json():
            git_access.del_one_post(dir_['sha'], dir_['path'])
        for user in users:
            if user.user_name == git_name.lower(
            ) and user.user_repo_name == git_repository_blog.lower():
                session_git.delete(user)
        session_git.commit()
        session_git.close()
        git_access.del_branch()
        remove_files(git_name, git_repository_blog)
        return '', 200
    else:
        for user in users:
            if user.user_name == git_name.lower(
            ) and user.user_repo_name == git_repository_blog.lower():
                session_git.delete(user)
        session_git.commit()
        session_git.close()
        git_access.del_branch()
        remove_files(git_name, git_repository_blog)
        return '', 200
Exemple #20
0
def connect_with_user():
    '''Make a connection with a 'normal' user'''

    error = None
    current_user_id = session.get('logged_in_user')

    if request.method == 'POST':
        # fetch values and check they are actually provided
        if 'key' in request.form:
            key_value = request.form['key']

            useri = Users(current_user_id)

            key_user_id = useri.validate_key(key_value)

            # valid key
            if key_user_id:
                # cannot connect to ourselves and make a connection that has already been made ;)
                if not key_user_id == current_user_id and not useri.is_connection(user_id=key_user_id):

                    # create connections from us to them and back
                    useri.add_connection(key_user_id)

                    flash('Connection made')

                else: error = 'I can haz myself impossible'
            else: error = 'Invalid key'
        else: error = 'You need to provide a key'

    return render_template('admin_connect_with_user.html', **locals())
def logout():
    data = request.get_json()
    token = data.get("token")
    user_info = Users.authenticate(token)
    user = Users(user_info[0][1], user_info[0][2], user_info[0][4])
    user.logout()
    return jsonify({"logout": "successful"})
def schedule():
    data = request.get_json()
    token = data.get("token")
    user_info = Users.authenticate(token)
    user = Users(user_info[0][1],
                 user_info[0][2],
                 user_info[0][4],
                 twitch_id=user_info[0][3])
    # get schedule info from react the "data" coming in will need to have a lot of info
    # i.e. date, a time slots array, a performers array, user_id will come from the auth here in the route,
    # and the unique sked_id generated here:
    sk_id = sked_id_gen()
    # print(sk_id)
    time_slots = data.get("timeSlots")
    # print(time_slots)
    performers = data.get("performers")
    # print(performers)
    print(user_info[0][3], data.get("date"), time_slots[0], performers[0])
    for i in range(len(time_slots)):
        sked = Schedule(user_info[0][3],
                        data.get("date"),
                        time_slots[i],
                        performers[i],
                        sked_id=sk_id)
        sked._insert()
    return jsonify({"create": "successful", "sk_id": sk_id})
    def put(self, id):
        try:
            user = Users.query.get(id)
            if request.json.get('name'):
                user.name = request.json.get('name')
            if request.json.get('email') and Users.isMail(
                    request.json.get('email')):
                user.email = request.json.get('email')
            if request.json.get('password'):
                user.password = Users.setPassword(request.json.get('password'))
            db.session.add(user)
            db.session.commit()
            db.session.remove()

            userschema = UserSchema(only=['id', 'name', 'email', 'password'])

            get_users = Users.query.filter(Users.status == 1).order_by(
                Users.id.desc()).all()
            users_schema = UserSchema(many=True)
            users = users_schema.dump(get_users)

            db.session.remove()
            request.close()

            return {'response': 'Registro Actualizado', 'users': users}, 200

        except:

            request.close()
            return {'response': ' El registro no existe'}, 400
 def create_user(self):
     username = input("Please enter a username: "******"Enter your password: ")
     password_hash = hashlib.sha256(str_password.encode()).hexdigest()
     user = Users(username)
     user.save_user_to_mongo(password_hash)
     self.user = username
Exemple #25
0
 def get_file(self, ref=False):
     list_git_files = self.get_posts_json(ref)
     if not list_git_files:
         list_git_files = False
         if ref:
             get_file('static/%s_%s_branch.txt' % (self.git_name.lower(), self.git_repository_blog.lower()),
                      list_git_files)
         elif not ref:
             get_file('static/%s_%s.txt' % (self.git_name.lower(), self.git_repository_blog.lower()),
                      list_git_files)
         return False
     if ref:
         get_file('static/%s_%s_branch.txt' % (self.git_name.lower(), self.git_repository_blog.lower()),
                  list_git_files)
     elif not ref:
         get_file('static/%s_%s.txt' % (self.git_name.lower(), self.git_repository_blog.lower()),
                  list_git_files)
     user_s = Users(self.git_name, self.git_repository_blog)
     session_git = user_s.open_base()
     users = session_git.query(Users)
     new_user = True
     for user in users:
         if user.user_name == self.git_name.lower() and user.user_repo_name == self.git_repository_blog.lower():
             session_git.close()
             new_user = False
     if new_user:
         new_user = Users(user_name=self.git_name.lower(), user_repo_name=self.git_repository_blog.lower())
         session_git.add(new_user)
         session_git.commit()
         session_git.close()
     posts = sorted(list_git_files, key=lambda d: d['date'], reverse=True)
     if not posts[0]['date']:
         return [{'date': False}]
     return posts
Exemple #26
0
def give():
    '''Give a loan or pay someone back'''

    current_user_id = session.get('logged_in_user')

    our_accounts = Accounts(current_user_id)

    if request.method == 'POST':

        dict = __validate_give_loan_form()
        for key in dict.keys(): exec(key + " = dict['" + key + "']")

        # 'heavier' checks
        if not error:
            # valid amount?
            if is_float(amount):
                # valid date?
                if is_date(date):
                    # valid account?
                    if our_accounts.is_account(account_id=deduct_from_account):

                        # add our loans entry
                        our_loans = Loans(current_user_id)
                        our_loan_id = our_loans.add_loan(other_user_id=to_user, date=date, account_id=deduct_from_account,
                                     description=description, amount=-float(amount))

                        # add their loans entry
                        their_loans = Loans(to_user)
                        their_loan_id = their_loans.add_loan(other_user_id=current_user_id, date=date,
                                                           account_id=deduct_from_account, description=description,
                                                           amount=amount)

                        # generate slugs for the new loans
                        our_slugs = Slugs(current_user_id)
                        slug = our_slugs.add_slug(type='loan', object_id=our_loan_id, description=description)
                        their_slugs = Slugs(to_user)
                        their_slugs.add_slug(type='loan', object_id=their_loan_id, slug=slug)

                        their_accounts = Accounts(to_user)

                        # transfer money from/to respective accounts
                        our_accounts.modify_user_balance(account_id=deduct_from_account, amount=-float(amount))
                        their_accounts.modify_user_balance(amount=amount)

                        # fudge loan 'account' monies
                        our_accounts.modify_loan_balance(amount=amount, with_user_id=to_user)
                        their_accounts.modify_loan_balance(amount=-float(amount), with_user_id=current_user_id)

                        flash('Loan given')

                    else: error = 'Not a valid source account'
                else: error = 'Not a valid date'
            else: error = 'Not a valid amount'

    # fetch users from connections from us
    our_users = Users(current_user_id)
    users = our_users.get_connections()
    accounts = our_accounts.get_accounts()

    return render_template('admin_give_loan.html', **locals())
Exemple #27
0
def index(direction=None, user=None, date=None, page=1, items_per_page=10):
    '''List loans user has with other users'''

    current_user_id = session.get('logged_in_user')

    our_loans = Loans(current_user_id)
    our_users = Users(current_user_id)

    # fetch loans
    loans = our_loans.get_loans()

    # fetch users from connections from us
    users = our_users.get_connections()

    # provided user?
    if user:
        # valid slug?
        user_id = our_users.is_connection(slug=user)
        if user_id: loans = our_loans.get_loans(user_id=user_id)

    # provided a date range?
    date_range = translate_date_range(date)
    if date_range:
        loans = our_loans.get_loans(date_from=date_range['low'], date_to=date_range['high'])
    # date ranges for the template
    date_ranges = get_date_ranges()

    # provided a direction?
    if direction: loans = our_loans.get_loans(direction=direction)

    # build a paginator
    paginator = Pagination(loans, page, items_per_page, loans.count(),
                           loans.offset((page - 1) * items_per_page).limit(items_per_page))

    return render_template('admin_show_loans.html', **locals())
Exemple #28
0
 async def join(self, ctx):
     species = Species.select().order_by(fn.Random()).first()
     message = ctx.message
     if not Users.select().where((Users.discord_id == message.author.id)
                                 & (Users.server_id == message.guild.id)):
         user_id = Users.insert(discord_id=str(message.author.id),
                                server_id=str(message.guild.id)).execute()
         colony_id = Colony.insert(user=user_id,
                                   species=species.id,
                                   colony_name=message.author.name +
                                   "'s Colony",
                                   current_food_supply=100,
                                   max_food_supply=100).execute()
         Ants.insert(colony=colony_id,
                     name=names.get_full_name(gender="female"),
                     role=AntRole.QUEEN,
                     life_stage=3).execute()
         await message.channel.send("You have joined the game!")
         embed = discord.Embed(
             title=f"You have selected {species.species_name}",
             description=
             f"HP: {species.hp_multiplier} Forage: {species.forage_multiplier}",
             color=0x00ff00)
         embed.set_image(url=species.image_url)
         await message.channel.send(embed=embed)
     else:
         await message.channel.send("You have already joined this game.")
Exemple #29
0
def edit_register(email_):
    if request.method == 'POST' and 'edit' in request.form:
        user = Database.find_one_by('participants', {"email": email_})
        full_name = user['full_name']
        email = email_
        password = user['password']
        tickets_amount = request.form['tickets_amount']
        mat, instrument, food, camp = False, False, False, False
        if request.form.get('mat'):
            mat = request.form.get('mat')
        if request.form.get('instrument'):
            instrument = request.form.get('instrument')
        if request.form.get('food'):
            food = request.form.get('food')
        if request.form.get('camp'):
            camp = request.form.get('camp')
        items = Users.toJson(full_name, email, password, tickets_amount, mat, instrument, food, camp)
        Database.update('participants', {"email": email}, items)
        return render_template('user/confirm_editing.html', name=full_name, email=email)
    elif request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        if Database.find_one_by('participants', {"email": email}) is None:
            return render_template('user/unsuccessful_register.html', message='דואר אלקטרוני זה אינו קיים במערכת',
                                   url='edit_register', email_='$')
        if not Users.login_valid(email, password):
            return render_template('user/unsuccessful_register.html', message='סיסמא שגויה', url='edit_register',
                                   email_='$')
        user = Database.find_one_by('participants', {"email": email})
        return render_template('user/edit_registration.html', email_=email, user=user)
    else:
        return render_template('user/edit_registration.html', email_='$')
Exemple #30
0
def get_key():
    '''Get a user key for a logged in user'''

    u = Users(session.get('logged_in_user'))
    # fetch/generate key
    key = u.get_key()

    return make_response(key.key, 200)
Exemple #31
0
def get_key():
    '''Get a user key for a logged in user'''

    u = Users(session.get('logged_in_user'))
    # fetch/generate key
    key = u.get_key()

    return make_response(key.key, 200)
Exemple #32
0
    def testInit(self):
        users = Users()
        self.assertIsInstance(users, ModelCollection)
        self.assertGreater(users._items, 0)
        self.assertIsInstance(users.all(), list)

        for i in users.all():
            self.assertIsInstance(i, User)
 def update_user(email_id, fav_food):
     user_obj = Users.get_by_id(email_id)
     if user_obj:
         Users.create_or_update(user_obj.name, email_id, fav_food,
                                user_obj.platform)
         return {"status": "success", "msg": " updated"}
     else:
         return {"status": "error", "msg": "invalid credentials"}
Exemple #34
0
def signup():
    data = request.get_json()
    hashed_password = generate_password_hash(data["password"])

    new_user = Users(name=data["name"], password=hashed_password)
    new_user.save()

    return jsonify({"message": "registered successfully"})
 def register_a_user(name, email_id, fav_food, platform):
     log.info(name)
     user_obj = Users.get_by_id(email_id)
     if not user_obj:
         Users.create_or_update(name, email_id, fav_food, platform)
         return {"status": "success", "msg": " you are registered"}
     else:
         return {"status": "error", "msg": "you have already registered"}
Exemple #36
0
    def __init__(self, *args, **kwargs):
        super(LoginWidget, self).__init__(*args, **kwargs)
        uic.loadUi(self._path, self)
        self.show()

        self.users = Users()
        self.sign_in.clicked.connect(self.handle_sign_in)
        self.sign_up.clicked.connect(self.handle_sign_up)
Exemple #37
0
def register():
	register_error = None
	form = RegisterFormExt(csrf_enabled=False)
	if request.method == 'POST' and form.validate():
		password = security.generate_password_hash(form.password.data, length=32)
		user = Users(username=form.username.data, password=password)
		user.put()
		return redirect(url_for('login'), code=302)
	return render_template('register.html', form=form, register_error=register_error)
Exemple #38
0
 async def leave(self, ctx):
     message = ctx.message
     if Users.select().where((Users.discord_id == message.author.id)
                             & (Users.server_id == message.guild.id)):
         Users.delete().where((Users.discord_id == message.author.id) & (
             Users.server_id == message.guild.id)).execute()
         await message.channel.send("You have killed your queen ant.")
     else:
         await ctx.send("You are not a part of this game.")
class SignUpWidget(QtGui.QWidget):

    _path = SIGN_UP_WIDGET

    def __init__(self, *args, **kwargs):
        super(SignUpWidget, self).__init__(*args, **kwargs)
        uic.loadUi(self._path, self)
        self.show()

        self.role_selector.currentIndexChanged\
            .connect(self.changed_role_selector)
        self._driver_form = DriverForm()
        self._company_form = CompanyForm()
        self.additional_data.addWidget(self._driver_form)
        self.additional_data.addWidget(self._company_form)
        self.role_selector.setCurrentIndex(0)
        self.changed_role_selector(0)
        self.sign_up.clicked.connect(self.sign_up_user)
        self.cancel.clicked.connect(self.cancel_sign_up)
        self.users = Users()

    def changed_role_selector(self, index):
        role = self.role_selector.itemText(index)
        if role == 'Driver':
            self.additional_data.setCurrentWidget(self._driver_form)
        else:
            self.additional_data.setCurrentWidget(self._company_form)

    def sign_up_user(self):
        login = self.login_input.text()
        password = self.password_input.text()
        repeated_password = self.repeated_password.text()
        data = self.additional_data.currentWidget().get_data()
        if data['success'] and password == repeated_password and len(login) > 0:
            role = self.role_selector.currentText()
            if role == 'Driver':
                self.users.register_driver(
                    login,
                    hashlib.sha224(password).hexdigest(),
                    data['capacity'],
                    data['location'],
                )
            else:
                self.users.register_organization(
                    login,
                    hashlib.sha224(password).hexdigest(),
                    data['name'],
                    data['location'],
                )
            self.parent().close_sign_up()
        else:
            self.error.setText('Something wrong with your form data.')

    def cancel_sign_up(self):
        self.parent().close_sign_up()
Exemple #40
0
def generate_key():
    '''Generate/get a user key for the current user'''

    current_user_id = session.get('logged_in_user')

    useri = Users(current_user_id)

    # fetch/generate key
    key = useri.get_key()

    return render_template('admin_generate_user_key.html', **locals())
Exemple #41
0
    def test_InsertQuery(self):
        users = Users()
        entity = users.new()

        expected = OrderedDict([
            ('id', None), ('user_group', 'user'), ('username', None),
            ('name', None), ('email', None), ('password', None),
            ('virt_auth_data', None)
        ])
        data = users._generate_query_data(entity)
        self.assertEqual(expected, data)

        expected = 'INSERT INTO users(id,user_group,username,name,email,password,virt_auth_data) VALUES (?,?,?,?,?,?,?)'
        self.assertEqual(users._generate_insert_query(data), expected)
class LoginWidget(QtGui.QWidget):

    _path = LOGIN_WIDGET
    
    def __init__(self, *args, **kwargs):
        super(LoginWidget, self).__init__(*args, **kwargs)
        uic.loadUi(self._path, self)
        self.show()

        self.users = Users()
        self.sign_in.clicked.connect(self.handle_sign_in)
        self.sign_up.clicked.connect(self.handle_sign_up)

    def handle_sign_in(self):
        login = self.login_field.text()
        password = self.password_field.text()
        password = hashlib.sha224(password).hexdigest()
        try:
            result = self.users.login(login, password)
        except ValueError as v:
            # TODO: change it on 'Login or password is incorrect.'
            self.error_label.setText(v.message)
            result = False
        if result:
            self.parent().successful_sign_in(result)

    def handle_sign_up(self):
        self.parent().sign_up_user()
Exemple #43
0
    def edit(self):
        inputParams = self.getInput()
        album_id = int(inputParams['id'])
        album = Albums.get(Albums.id == album_id)

        current_user = Users.get(Users.name == self.isLogin())
        if current_user.id != album.owner.id and not self.isAdmin():
            return self.error(msg = '权限不足!', url=self.makeUrl('/admin/albums/list'))

        self.privData['ALBUM_ID'] =   album.id
        self.privData['ALBUM_NAME'] = album.name
        self.privData['ALBUM_DESC'] = album.description
        self.privData['ENABLE_SELECT_THUMBNAIL'] = False

        imagesList = Images().select()
        if not self.isAdmin():
            imagesList = imagesList.where(Images.owner == current_user)

        imagesList = imagesList.where(Images.album == album)
        if imagesList.count():
            self.privData['ENABLE_SELECT_THUMBNAIL'] = True
            self.privData['ALBUMS_LIST'] = [album]
            self.privData['IMG_ALBUMS_LIST'] = {album.id: imagesList}
            self.privData['CURRENT_IMG'] = imagesList[0]
            self.privData['CURRENT_ALBUM'] = album
            self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('albumEdit')
Exemple #44
0
 def confirm_select_order(self):
     inputs = self.getInput()
     try:
         product = Products.get(Products.id == int(inputs['product']))
         user =Users.get(Users.name == self.isLogin())
         price = inputs['price']
         if inputs.has_key('add'):
             order = Orders.create(
                 owner = user,
                 price = price,
                 description = product.category.name,
             )
         else:
             if not inputs.has_key('selected'):
                 return self.orders_list()
             order = Orders.get(Orders.id == int(inputs['selected']))
         
         details = OrderDetails.create(
             name = product.category.name + "   "+product.diameter,
             product = product,
             count = user,
             price = price,
             ratio = 0.0,
             order = order,
         )
         return web.seeother(self.makeUrl('/wap/edit_price_sheet', {'id': order.id}))
     except Exception, e:
         print 'exc',e
         return self.error(msg='保存订单失败!')
Exemple #45
0
 def save_my_information(self):
     inputs = web.input()
     try:
         try:
             if len(inputs['imgfile'])>10:
                 htmlimg = httpUploadedFile(inputs['imgfile'])
                 userimg=Images().create(
                     uuid =  htmlimg.uuid(),
                     description = self.htmlunquote("上传图片"),
                     thumbnail = self.wap_imgsave(htmlimg)
                     )
         except Exception, e:
             print e
             userimg=Images().get(Images.id == 1)
         
         user = Users.get(Users.id == int(inputs['userid']))
         user.name = inputs['name']
         user.cellphone = inputs['cellphone']
         user.gender = inputs['gender']
         user.email = inputs['email']
         user.job = inputs['job']
         user.avatur=userimg
         user.address = inputs['address']
         user.save()
         return self.my_information()
Exemple #46
0
    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0

        current_user = Users.get(Users.name == self.isLogin())   
        usersList = Users().select()
        if not self.isAdmin():
            usersList = usersList.where(Users.id == current_user)

        usersList = usersList.order_by(Users.id.desc())
        pageString = self.getPageStr('/admin/users/list', page, count, usersList.count())
        self.privData['USERS_LIST'] = usersList
        self.privData['PAGE_STRING'] = pageString
        return self.display('usersList')
Exemple #47
0
    def add(self):
        chatroomsList = Chatrooms().select()

        userName = self.isLogin()
        if userName != 'admin':
            return self.error(msg = '权限不足!', url=self.makeUrl('/admin/chatrooms/list'))
        user = Users.get(Users.name == userName)
        albumsList = Albums().select().where(Albums.owner == user.id)
        imagesList = Images().select().where(Images.owner == user.id)

        if not albumsList.count():
            return self.error(msg = '请创建至少一个专辑!', url=self.makeUrl('/admin/chatrooms/list'))
        if not imagesList.count():
            return self.error(msg = '请创建至少一个图片!', url=self.makeUrl('/admin/chatrooms/list'))

        album_images_map = {}
        excluded_albums = []
        for album in albumsList:
            album_images = imagesList.where(Images.album == album.id)
            if album_images.count():
                album_images_map[album.id] = album_images
            else:
                excluded_albums.append(album.id)

        self.privData['ALBUMS_LIST'] = \
            [album for album in albumsList if album.id not in excluded_albums]
        self.privData['IMG_ALBUMS_LIST'] = album_images_map

        # 默认专辑为当前用户的第一个专辑
        self.privData['CURRENT_ALBUM'] = self.privData['ALBUMS_LIST'][0]
        # 默认图片为默认专辑的第一张图片
        self.privData['CURRENT_IMG'] = album_images_map[self.privData['CURRENT_ALBUM'].id][0]
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('chatroomAdd')
Exemple #48
0
    def modify(self):
        inputParams= self.getInput()
        album_id = int(inputParams['id'])
        thumbnail_id = int(inputParams['thumbnail']) if inputParams.has_key('thumbnail') else 0
 
        if album_id == 1:
            return self.error(msg='不能编辑系统专辑', url=self.makeUrl('/admin/albums/list'))

        album = Albums.get(Albums.id == album_id)
        current_user = Users.get(Users.name == self.isLogin())
        if current_user.id != album.owner.id and not self.isAdmin():
            return self.error(msg = '权限不足!', url=self.makeUrl('/admin/albums/list'))

        if thumbnail_id:
            thumbnail_data = Images.get(Images.id == thumbnail_id).thumbnail
        else:
            import base64
            from imaging import imaging
            thumbnail_data = base64.b64encode(buffer(imaging.default_thumbnail()))

        try:
            album.name  = inputParams['name']
            album.description = inputParams['desc']
            album.thumbnail = thumbnail_data
            album.save()
        except Exception, e:
            return self.error(msg = '专辑修改失败: %s' % e, url=self.makeUrl('/admin/albums/list'))
Exemple #49
0
    def update(self):
        inputParams= self.getInput() 
        group = Groups.get(Groups.id == int(inputParams['id']))
 
        current_user = Users.get(Users.name == self.isLogin())
        if current_user.id != group.owner.id and not self.isAdmin() or not current_user.role.type < 100:
            return self.error(msg = '权限不足!', url=self.makeUrl('/admin/groups/list'))

        try:
            group.regions = inputParams['regions']
            group.name = inputParams['name']
            group.owner = current_user
            group.phoneno = inputParams['phoneno']
            group.cellphone = inputParams['cellphone']
            group.faxno = inputParams['faxno']
            group.postcode = inputParams['postcode']
            group.contact = inputParams['contact']
            group.description = self.htmlunquote(inputParams['description'])
            group.thumbnail = int(inputParams['thumbnail'])
            group.team_description = self.htmlunquote(inputParams['team_description'])
            group.regions = inputParams['regions']
            group.service_modes = inputParams['service_modes']
            group.specials = inputParams['specials']
            group.swipeshow_album = int(inputParams['swipeshow_album'])
            group.groups_album = int(inputParams['groups_album'])
            group.price1 = float(inputParams['price1'])
            group.price2 = float(inputParams['price2'])
            group.address = inputParams['address']
            group.longitude = float(inputParams['longitude'])
            group.latitude = float(inputParams['latitude'])
            group.category = int(inputParams['category'])
            group.save()
        except Exception, e:
            return self.error(msg = '公司修改失败: %s' % e, url=self.makeUrl('/admin/groups/list'))
Exemple #50
0
    def save(self):
        inputParams= self.getInput()

        try:
            current_user = Users.get(Users.name == self.isLogin())
            inputParams['longitude'] = inputParams['longitude'] if inputParams['longitude'] else 116.397428
            inputParams['latitude'] = inputParams['latitude'] if inputParams['latitude'] else 39.90923

            Groups.create(
                name = inputParams['name'],
                owner = current_user,
                address = inputParams['address'],
                phoneno = inputParams['phoneno'],
                cellphone = inputParams['cellphone'],
                faxno = inputParams['faxno'],
                postcode = inputParams['postcode'],
                contact = inputParams['contact'],
                description = self.htmlunquote(inputParams['description']),
                thumbnail = int(inputParams['thumbnail']), 
                team_description = self.htmlunquote(inputParams['team_description']),
                regions = inputParams['regions'],
                service_modes = inputParams['service_modes'],
                specials = inputParams['specials'],
                swipeshow_album = int(inputParams['swipeshow_album']),
                groups_album = int(inputParams['groups_album']),
                price1 = float(inputParams['price1']),
                price2 = float(inputParams['price2']),
                longitude = float(inputParams['longitude']),
                latitude = float(inputParams['latitude']),
                category = int(inputParams['category']),
            )  
        except Exception, e:
            return self.error(msg = '新增公司失败: %s' % e, url=self.makeUrl('/admin/groups/list'))
Exemple #51
0
    def save_price_sheet(self):
        inputs = self.getInput()
        print inputs
        try:
            if inputs.has_key('add'):
                return web.seeother(self.makeUrl('/wap/categories', {'parent': 1, 'order': int(inputs['id'])}))

            order = Orders.get(Orders.id == int(inputs['id']))

            attrs = {}
            for k, v in inputs.items():
                try:
                    attr, oid = k.split('_')
                except Exception, e:
                    continue

                if not attrs.has_key(oid):
                    attrs[oid] = {}
                attrs[oid][attr] = v

            if not inputs['customer'] or not inputs['description']:
                raise Exception("询价方或备注不能为空!")

            order.customer = inputs['customer']
            order.description = inputs['description']
            order.owner = Users.get(Users.name == self.isLogin())
            order.save()

            for k, v in attrs.items():
                #import pdb;pdb.set_trace()
                import traceback
                if not v['count'] or not v['ratio']:
                    raise Exception("数量或利润率不能为空!")
                nameform = v['name']
                diameterform = v['diameter']
                oldinput= v['can']
                name, diameter = oldinput.split('   ')
                details = OrderDetails.get(OrderDetails.id == int(k))
                details.name = oldinput
                flag = v['bool']
                if flag.find("True")>=0:
                   details.flag=True
                elif details.name!=(details.product.category.name+'   '+details.product.diameter):
                   details.flag=True
                else:                   
                   details.flag=False
                   
                try:
                    product = Products().get(Products.name==name,Products.diameter == diameter)
                except Exception,e:
                    details.price = float(v['input'])
                    details.count = v['count']
                    details.ratio = float(v['ratio'])/100.0
                    details.save()
                  
                details.price = float(v['input'])
                details.count = v['count']
                details.ratio = float(v['ratio'])/100.0
                details.save()
Exemple #52
0
    def beginflight_cmd(self, version, data3, data4):
        ''' Begin Flight logging on ACARS '''
        data = data3.split("|")
        
        if len(data) < 16:
            self.response.out.write('0|Invalid login data ('+ str(len(data)) +')')
            return
        
        user_id = Users.test_user_login(data[0], data[17]);
        if user_id is None:
            self.response.out.write('0|Login failed')
            return
        
        acars_flight = AcarsFlight();
        acars_flight.flight_id = str(time.time()).replace('.', '')
        acars_flight.user_id = user_id;
        acars_flight.acars_id  = version;

        # *** Origin and Destination Airports
        if len(data[5]) != 0:
            plan = data[5].split('~')
            acars_flight.departure = plan[0].upper()
            if len(plan) > 1:
                acars_flight.destination = plan[-1].upper()
        
        acars_flight.aircraft_type = data[3]  #AircraftRegistration
        acars_flight.flight_type = data[15] #flightType
        acars_flight.flight_plan = plan  #flightPlan
        acars_flight.flight_number = data[2]  #FlightNumber

        acars_flight.add_flight()

        acars_position = AcarsPosition();
        acars_position.flight_id = acars_flight.flight_id
        acars_position.message_type = 'PR'
        
        if data[6] != '':
            #N52 23.1890 E13 31.0944
            parts = data[6].split(' ');

            posLat = lat_degdecmin_2_decdeg(parts[0].strip(), parts[1].strip())
            posLon = lon_degdecmin_2_decdeg(parts[2].strip(), parts[3].strip())
            
            acars_position.lat_lon = model.GeoPt(posLat, posLon)
        
        acars_position.flight_status = FLIGHTSTATUS_BOARDING;
        acars_position.waypoint = acars_flight.departure;
        acars_position.hdg = int(data[12])
        acars_position.alt = int(data[7])
        acars_position.wnd = data[13]
        acars_position.oat = int(data[14])
        acars_position.tat = int(data[14])
        acars_position.fob = int(data[11])
        acars_position.distance_total = int(data[16])
        acars_position.message = data3
        
        acars_position.add_position()
        
        self.response.out.write('1|'+acars_flight.flight_id)
Exemple #53
0
 def edit_my_information(self):
     inputs = self.getInput()
     try:
         user = Users.get(Users.id == inputs['id'])
         self.privData['USER'] = user
         return self.display('edit-my-information')
     except Exception,e:
         return self.error(msg='获取当前用户信息失败!')
Exemple #54
0
 def my_information(self):
     try:
         user =Users.get(Users.name == self.isLogin())
         self.privData['USER'] = user
         return self.display('my-information')
     except Exception, e:
         print e
         return self.error(msg='获取用户信息失败!')
    def get(self, user_id, confirmation_code):
        user = Users.get_by_id(int(user_id))

        if user:
            if user.confirmation_code == confirmation_code:
                user.confirmed_email = True
                user.put()

        self.redirect('/login')
 def check_user_logged_in(self):
     if self.request.cookies.get('User'):
         user_id = self.read_cookie('User')
         if user_id:
             from models.users import Users
             return Users.get_by_id(int(user_id))
         else:
             return None
     return None