Exemplo n.º 1
0
def feeddetails(**kwargs):
    # app.logger.info(kwargs['email'])
    # app.logger.info(request.args.get('feedurl'))
    user = User()
    nobj = user.getfeeddata(db.connection, kwargs['email'],
                            request.args.get('feedurl'))
    return buildresponse(nobj, {'http_status': 200})
Exemplo n.º 2
0
def register():
	# app.logger.info("inside register")
	# app.logger.info(request.json)
	if not request.json or not 'email' in request.json:
		nobj = Notification()
		nobj.setdata(True,"Wrong Email or password !!",None)
		return buildresponse(nobj,{'http_status':400})
	else:
		user = User()
		# app.logger.info("after user--form")
		# app.logger.debug(request.form)
		# app.logger.info("in register, calling save {},{},{}".format(request.form['email'],request.form['name'],request.form['pwd']) )
	#	app.logger(request.form["email"])
		nobj = user.login(db.connection,request.json['email'],request.json['pwd'])
		if nobj.result is None:
			nobj = user.save(db.connection,request.json['email'],request.json['name'],request.json['pwd'])
		
		if not nobj.haserrors and nobj.result is not None:
			nobj.result={}
			resobj = user.getfeedtree(db.connection,request.json['email'])
			if not resobj.haserrors: 
				nobj.result["feedlist"] = resobj.result
				resobj = user.getcategorylist(db.connection,request.json['email'])
				if not resobj.haserrors:
					nobj.result["categories"] = resobj.result
					
		# app.logger.info("returning response")
		return buildresponse(nobj,{'http_status':201})
Exemplo n.º 3
0
    def post(self):
        keys = ('username', 'password', 'email')

        rjson = request.json
        if rjson is None: return Response.missing_parameters()
        if all(elem in rjson for elem in keys):
            if '' in rjson.values():
                return Response.invalid_arguments()

            if User.objects(username=rjson['username']):
                return Response.user_exists()
            if User.objects(email=rjson['email']):
                return Response.email_taken()

            User(password=bcrypt.generate_password_hash(rjson['password']),
                 username=rjson['username'],
                 email=rjson['email']).save()

            return make_response(
                jsonify({
                    "status": "success",
                    "message": "user successful created"
                }), 201)

        else:
            return Response.missing_parameters()
        return Response.unexpected_error()
Exemplo n.º 4
0
    def put(self, username):
        user = get_jwt_identity()

        password = request.json['password']
        allowed_fields = ('username', 'email', 'admin', 'password')

        if UserModel.objects(username=user).first().admin:
            user = UserModel.objects(username=username).first_or_404()

            for field in allowed_fields:
                fieldValue = request.json.get(field)
                if fieldValue is not None:
                    if field == 'password':
                        if password is not None:
                            setattr(
                                user, field,
                                str(
                                    bcrypt.generate_password_hash(
                                        password).decode('utf-8')))
                            user.save()
                    else:
                        setattr(user, field, fieldValue)
                    user.save()

            return make_response(
                jsonify({
                    "status": "success",
                    "message": "resource updated successfully"
                }), 200)

        return Response.insufficient_permissions()
Exemplo n.º 5
0
def changecategory(**kwargs):
    user = User()
    nobj = user.changecategory(db.connection, kwargs['email'],
                               request.json['url'], request.json['category'])
    if not nobj.haserrors:
        nobj = user.getfeedtree(db.connection, kwargs['email'])
    return buildresponse(nobj, {'http_status': 200})
Exemplo n.º 6
0
    def setUp(self):
        """ Création d'une base de données avant le test"""
        warnings.filterwarnings('ignore', category=DeprecationWarning)

        db.create_all()
        user = User(username="******")
        user.hash_password("admin")
        db.session.add(user)
        db.session.commit()
Exemplo n.º 7
0
def updateitem(**kwargs):
	if not request.json or not 'id' in request.json:
		nobj = Notification()
		nobj.setdata(True,"ID Not found!!",None)
		return buildresponse(nobj,{'http_status':400})
	else:
		user = User()
		nobj = user.updatefeeditem(db.connection,kwargs['email'],request.json['feedurl'],request.json['id'],request.json['isread'],request.json['isstarred'])
		return buildresponse(nobj,{'http_status':200})
Exemplo n.º 8
0
def check_auth(email, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    # app.logger.info("in check auth {} , {}".format(email,password))
    user = User()
    ret = user.login(db.connection, email, password)
    #app.logger.info(ret.haserrors)
    #app.logger.info(ret.result)
    return ret.result
Exemplo n.º 9
0
def check_auth(email, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    # app.logger.info("in check auth {} , {}".format(email,password))
    user = User()
    ret = user.login(db.connection,email,password)
    #app.logger.info(ret.haserrors)
    #app.logger.info(ret.result)
    return ret.result
Exemplo n.º 10
0
 def setUp(self):
     self.app = app
     self.ctx = self.app.app_context()
     self.ctx.push()
     db.drop_all()
     db.create_all()
     u = User(username=self.default_username)
     u.set_password(self.default_password)
     db.session.add(u)
     db.session.commit()
     self.client = TestClient(self.app, u.generate_auth_token(), '')
Exemplo n.º 11
0
 def setUp(self):
     self.app = app
     self.ctx = self.app.app_context()
     self.ctx.push()
     db.drop_all()
     db.create_all()
     u = User(username=self.default_username)
     u.set_password(self.default_password)
     db.session.add(u)
     db.session.commit()
     self.client = TestClient(self.app, u.generate_auth_token(), '')
Exemplo n.º 12
0
def updateitem(**kwargs):
    if not request.json or not 'id' in request.json:
        nobj = Notification()
        nobj.setdata(True, "ID Not found!!", None)
        return buildresponse(nobj, {'http_status': 400})
    else:
        user = User()
        nobj = user.updatefeeditem(db.connection, kwargs['email'],
                                   request.json['id'], request.json['isread'],
                                   request.json['isstarred'])
        return buildresponse(nobj, {'http_status': 200})
Exemplo n.º 13
0
def refreshfeed(**kwargs):
	# app.logger.info(kwargs['email'])
	feed = Feed()
	nobj = feed.updatefeed(db.connection,request.args.get('feedurl'),
	{'http_proxy':app.config.get('HTTP_PROXY',None)})
	
	if not nobj.haserrors:
		user = User()
		nobj = user.getfeeddata(db.connection,kwargs['email'],request.args.get('feedurl'))
		# app.logger.info(nobj)	
		
	return buildresponse(nobj,{'http_status':200})	
Exemplo n.º 14
0
 def validate(self):
     if not Form.validate(self):
         return False
     user_name = self.user_name.data.lower()
     user_pass = self.user_pass.data.lower()
     if User.exists(user_name, user_pass):
         if AddUser.gen_temp_url_key(user_name, user_pass):
             print 'DEBUG: forms.validate.LoginForm :: gen_temp_url_key : True'
             return User.get_info(user_name, user_pass)
     else:
         self.submit.errors.append("Invalid user name or password !!!")
         return False
Exemplo n.º 15
0
def refreshfeed(**kwargs):
    # app.logger.info(kwargs['email'])
    feed = Feed()
    nobj = feed.updatefeed(db.connection, request.args.get('feedurl'),
                           {'http_proxy': app.config['HTTP_PROXY']})

    if not nobj.haserrors:
        user = User()
        nobj = user.getfeeddata(db.connection, kwargs['email'],
                                request.args.get('feedurl'))
        # app.logger.info(nobj)

    return buildresponse(nobj, {'http_status': 200})
Exemplo n.º 16
0
def feeddetails(**kwargs):
	# app.logger.info(kwargs['email'])
	# app.logger.info(request.args.get('feedurl'))	
	user = User()
	print "*** printing request params"
	print request.args.get('pageno')
	print request.args.get('pagesize')	
	if request.args.get('pageno') is not None and request.args.get('pagesize') is not None:
		nobj = user.getfeeddata(db.connection,kwargs['email'],request.args.get('feedurl'),
		request.args.get('pageno'),request.args.get('pagesize'))		
	else:
		nobj = user.getfeeddata(db.connection,kwargs['email'],request.args.get('feedurl'))
		
	return buildresponse(nobj,{'http_status':200})
Exemplo n.º 17
0
def seed_data():
    prxyval = Helper.getconfigvalue('dev.cfg', 'http_proxy', None)

    if prxyval is not None:
        prxydict = {'http_proxy': prxyval}
    else:
        prxydict = None

    dburl = Helper.getconfigvalue('dev.cfg', 'DATABASE_URI', None)
    dbname = Helper.getconfigvalue('dev.cfg', 'DBNAME', None)

    db = pymongo.MongoClient(dburl)[dbname]

    emailid = "*****@*****.**"
    user = User()
    notobj = user.save(db, emailid, emailid, 'pwd')
    notobj = user.addcategory(db, emailid, 'fun')
    notobj = user.addcategory(db, emailid, 'money')
    notobj = user.addfeed(db, emailid, 'http://raptitude.com/rss', 'fun',
                          prxydict)
    notobj = user.addfeed(db, emailid,
                          'http://feeds.feedburner.com/typepad/sethsmainblog',
                          'fun', prxydict)
    notobj = user.addfeed(db, emailid,
                          'http://feeds.feedburner.com/TheInvestorBlog',
                          'money', prxydict)
Exemplo n.º 18
0
def google_login_callback():
    # Get authorization code Google sent back to you.
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user.
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send a request to get tokens.
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code)
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens.
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Find and hit the URL from Google that gives you the user's profile
    # information, including their Google profile image and email.
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    if not userinfo_response.json().get("email_verified"):
        print("User email not available or not verified by Google.")
        return None

    user_id = userinfo_response.json()["sub"]
    user_name = userinfo_response.json()["given_name"]
    user_email = userinfo_response.json()["email"]
    user_picture = userinfo_response.json()["picture"]

    # If the user is not already in our database, add them.
    if not User.get(user_id):
        User.create(user_id, user_name, user_email, user_picture)

    # Begin user session
    user = User(user_id, user_name, user_email, user_picture)
    login_user(user)

    return redirect('http://localhost:3000/')
Exemplo n.º 19
0
def markasread(**kwargs):
	# app.logger.info(kwargs['email'])
	user = User()
	nobj = user.markallread(db.connection,kwargs['email'],request.json['feedurl'],request.json['ts'])
	
	if not nobj.haserrors:
		nobj.result={}
		resobj = user.getfeedtree(db.connection,kwargs['email'])
		if not resobj.haserrors:
			nobj.result['feedlist'] = resobj.result
			resobj = user.getfeeddata(db.connection,kwargs['email'],request.json['feedurl'])
			if not resobj.haserrors:
				nobj.result['feeddata'] = resobj.result
		
	return buildresponse(nobj,{'http_status':200})
Exemplo n.º 20
0
    def test_update_order_price_string(self):
        """  Price cannot be string """
        business_name = "FAST FOOD"
        location = "nakulabye"
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        role_id = 1
        hashed_password = generate_password_hash(password, method='sha256')
        new_admin = User(first_name= first_name, last_name=last_name,\
                      email=email, password= hashed_password, role_id=role_id,\
                      business_name=business_name, location=location)
        db.session.add(new_admin)
        db.session.commit()

        details = {"email": "*****@*****.**", "password": "******"}
        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.get_data())
        token = data['token']

        details = {"meal_name": "katogo", "price": "8000"}
        response = self.app.put("/bookmealapi/v1.0/orders/2",\
                data=json.dumps(details), content_type='application/json',\
                headers={'x-access-token' : token})
        self.assertEqual(response.status_code, 400)
Exemplo n.º 21
0
Arquivo: user.py Projeto: TizTime/test
def user_login():
    """
    测试账号 username:gogo
    测试账号 password:gogogo
{
    "username": "******",
    "password": "******"
}
    :rtype: object
    """
    get_data = request.get_json()
    username = get_data.get("username")
    password = get_data.get("password")

    if not all([username, password]):
        return jsonify(msg="参数输入不完整,请重新输入。", code=4000)

    # TODO 通过id配对数据库,输入密码加盐hash加密与数据库里的password_md5对比。
    input_user = User.select().where(User.username == username).first()
    # 如果用户密码存在并且密码正确
    if input_user is not None:
        # 取出salt并给输入密码+salt
        salt = input_user.salt
        md5 = create_md5(password, salt)
        if input_user.password_md5 == md5:
            # 如果验证通过 将登录状态保存到session中
            session["user_username"] = username
            session["user_id"] = input_user.id
            return jsonify(msg="登录成功。", code=200, username=username)
        else:
            return jsonify(msg="密码错误,请重新输入", code=4000)
    else:
        return jsonify(msg="账号不存在,请注册账户或重新输入。", code=4000)
Exemplo n.º 22
0
    def test_delete_menu_non_existant_data(self):
        """ Deleting menu that doesnt exist """
        business_name = "FAST FOOD"
        location = "nakulabye"
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        role_id = 1
        hashed_password = generate_password_hash(password, method='sha256')
        new_admin = User(first_name= first_name, last_name=last_name,\
                      email=email, password= hashed_password, role_id=role_id,\
                      business_name=business_name, location=location)
        db.session.add(new_admin)
        db.session.commit()

        details = {"email": "*****@*****.**", "password": "******"}
        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        data = json.loads(response.get_data())
        token = data['token']

        response = self.app.delete('/bookmealapi/v1.0/menu/10',\
            headers={'x-access-token' : token})
        self.assertEqual(response.status_code, 404)
Exemplo n.º 23
0
    def test_delete_order_data_exists(self):
        """ Deleting an order """
        business_name = "FAST FOOD"
        location = "nakulabye"
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        role_id = 1
        hashed_password = generate_password_hash(password, method='sha256')
        new_admin = User(first_name= first_name, last_name=last_name,\
                      email=email, password= hashed_password, role_id=role_id,\
                      business_name=business_name, location=location)
        db.session.add(new_admin)
        db.session.commit()

        meal_name = "katogo"
        price = 3000
        process_status = "Pending"
        user_id = 1
        order = Orders(meal_name=meal_name, price=price, user_id=user_id,\
         process_status=process_status)
        db.session.add(order)
        db.session.commit()

        details = {"email": "*****@*****.**", "password": "******"}
        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        data = json.loads(response.get_data())
        token = data['token']

        response = self.app.delete('/bookmealapi/v1.0/orders/1',\
            headers={'x-access-token' : token})
        self.assertEqual(response.status_code, 200)
Exemplo n.º 24
0
    def test_set_menu(self):
        """ setting the menu """
        business_name = "FAST FOOD"
        location = "nakulabye"
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        role_id = 1
        hashed_password = generate_password_hash(password, method='sha256')
        new_admin = User(first_name= first_name, last_name=last_name,\
                      email=email, password= hashed_password, role_id=role_id,\
                      business_name=business_name, location=location)
        db.session.add(new_admin)
        db.session.commit()
        """ correct details admin """
        details = {"email": "*****@*****.**", "password": "******"}
        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        data = json.loads(response.get_data())
        token = data['token']
        """
        details = {
            "meal_name": "rolex", 
            "price": 2000, 
            "meal_type": "breakfast"
        }
        """

        details = {"meal_ids": [1, 2, 3, 4], "user_id": 1}
        response = self.app.post("/bookmealapi/v1.0/menu",
                data=json.dumps(details), content_type='application/json',\
                headers={'x-access-token' : token})
        self.assertEqual(response.status_code, 201)
Exemplo n.º 25
0
Arquivo: user.py Projeto: TizTime/test
def change_admin_password():
    """
{
    "old_password": "******",
    "new_password": "******"
}
    :rtype: object
    """
    user_id = g.user_id
    my_json = request.get_json()
    old_password = my_json.get("old_password")
    new_password = my_json.get("new_password")

    if not all([new_password, old_password, user_id]):
        return jsonify(code=4000, msg="参数不完整,请重新输入。")

    # 从g中获得uid并在admin中查找,查找到修改密码并提交
    user = User.select().where(User.id == user_id).first()
    if user.password != old_password:
        return jsonify(code=4000, msg="输入密码错误,请重试!")
    user.password = new_password

    try:
        user.save()
    except Exception as e:
        print(e)
        user.rollback()
        return jsonify(code=4000, msg="修改密码失败,请重试!")

    return jsonify(code=200, msg="修改密码成功!")
Exemplo n.º 26
0
def generate_bill(from_day, to_day):
    f = calendar.timegm(from_day.timetuple()) * 1000000000
    t = calendar.timegm(to_day.timetuple()) * 1000000000
    collection = db['users']
    users = collection.find({})

    for user in users:
        u = User(user)
        bill = Bill(u, from_day, to_day)

        for device in u.devices:
            measurements = get_measurements(device, f, t, None, "job")
            bill.fill_measurements(device, measurements)

            total = 0
            for m in measurements:
                total += m["value"]

            bill.waterflow = total
            bill.price = total * 0.015

            insert_json = {
                "username": bill.username,
                "date": bill.to_date.strftime("%Y-%m-%d"),
                "waterflow": bill.waterflow,
                "price": bill.price
            }

            db.bills.insert(insert_json)
Exemplo n.º 27
0
    def delete(self, username):
        user = get_jwt_identity()

        if UserModel.objects(username=user).first().admin:
            if UserModel.objects(username=username).first().username == user:
                return Response.operation_not_allowed()

            user = UserModel.objects(username=username).first_or_404().delete()

            return make_response(
                jsonify({
                    "status": "success",
                    "message": "resource deleted successfully"
                }), 200)

        return Response.insufficient_permissions()
Exemplo n.º 28
0
    def post(self) :
        try : 
            args = self.reqparse.parse_args()
            user = User.authenticate(args['email'], args['password'])

            if not user :
                print "can't find user"
                abort(404)

            # first try and get an existing and valid token
            tokens = Token.query.filter((Token.user_id==user.id and Token.valid)).first()
            if tokens :
                return jsonify({"code" : 200, "user" : marshal(user, user_fields), "token" : tokens.value})
                
            # otherwise make them a new one
            new_token = Token(user_id=user.id)
            if not new_token :
                print "can't make new token"
                abort(403)
            user.tokens.append(new_token)

            db.session.add(user)
            db.session.commit()
            return jsonify({"code" : 200, "user" : marshal(user, user_fields), "token" : new_token.value})
        except Exception, e :
            print str(e)
            return abort(403)
Exemplo n.º 29
0
def signup_admin():
    # let's inicizlize db
    db.init_app(app)
    # let's create db
    with app.app_context():
        db.create_all()

        name = 'admin'
        password = '******'
        user = User.query.filter_by(name=name).first(
        )  # if this returns a user, then the email already exists in database

        if user:  # if a user is found, we want to redirect back to signup page so user can try again
            # return redirect(url_for('auth.signup'))
            return 'it is ALREADY exists ADMIN'
        # create new user with the form data. Hash the password so plaintext version isn't saved.
        new_user = User(public_id=str(uuid.uuid4()),
                        name=name,
                        password=generate_password_hash(password,
                                                        method='sha256'),
                        admin=True)

        # add the new user to the database
        db.session.add(new_user)
        db.session.commit()
Exemplo n.º 30
0
def createUser():
    data = request.get_json(force=True)

    hashed_password = generate_password_hash(data["password"], method="sha256")

    try:
        new_user = User(public_id=str(uuid.uuid4()),
                        username=data["username"],
                        email=data["email"],
                        password=hashed_password,
                        admin=False)
        db.session.add(new_user)
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return make_response("User already exists", 409)

    token = jwt.encode(
        {
            "public_id": new_user.public_id,
            "username": new_user.username
        }, app.config["SECRET_KEY"])
    print("Sending response")
    return jsonify({
        "token": token,
        "username": new_user.username,
        "pub_id": new_user.public_id
    })
Exemplo n.º 31
0
    def test_select_meal_valid(self):
        """  valid json """
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        role_id = 2
        hashed_password = generate_password_hash(password, method='sha256')
        new_user = User(first_name= first_name, last_name=last_name,\
                      email=email, password= hashed_password, role_id=role_id)
        db.session.add(new_user)
        db.session.commit()

        meal_name = "katogo"
        price = 2000
        meal_type = "breakfast"
        meal = Meals(meal_name=meal_name, price=price, meal_type=meal_type)
        db.session.add(meal)
        db.session.commit()
        """ correct details """
        details = {"email": "*****@*****.**", "password": "******"}
        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        data = json.loads(response.get_data())
        token = data['token']

        details = {"meal_name": "katogo", "price": 2000, "userId": 1}
        response = self.app.post("/bookmealapi/v1.0/orders",\
            data=json.dumps(details), content_type='application/json',\
                headers={'x-access-token' : token})
        self.assertEqual(response.status_code, 201)
Exemplo n.º 32
0
    def test_get_all_meals(self):
        """ Get all meals """
        business_name = "FAST FOOD"
        location = "nakulabye"
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        role_id = 1
        hashed_password = generate_password_hash(password, method='sha256')
        new_admin = User(first_name= first_name, last_name=last_name,\
                      email=email, password= hashed_password, role_id=role_id,\
                      business_name=business_name, location=location)
        db.session.add(new_admin)
        db.session.commit()

        meal_name = "katogo"
        price = 2000
        meal_type = "breakfast"
        meal = Meals(meal_name=meal_name, price=price, meal_type=meal_type)
        db.session.add(meal)
        db.session.commit()

        details = {"email": "*****@*****.**", "password": "******"}
        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        data = json.loads(response.get_data())
        token = data['token']

        response = self.app.get('/bookmealapi/v1.0/meals',\
                headers={'x-access-token' : token})
        data = json.loads(response.get_data())
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(data['meals']), 1)
Exemplo n.º 33
0
    def test_login_valid_details_user(self):
        """
        user = {
            "fname": "toast", 
            "lname": "bull",
            "email": "*****@*****.**",
            "password": "******"
        }
        response = self.app.post("/bookmealapi/v1.0/auth/signup",\
            data=json.dumps(user), content_type='application/json')
        """
        first_name = "toast"
        last_name = "bull"
        email = "*****@*****.**"
        password = "******"
        hashed_password = generate_password_hash(password, method='sha256')
        new_user = User(first_name=first_name, last_name=last_name,\
          email=email, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()
        """ correct details """
        details = {"email": "*****@*****.**", "password": "******"}

        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        data = json.loads(response.get_data())
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.get_data())
        self.assertEqual(data['message'], "Successfully login")
Exemplo n.º 34
0
    def test_get_menu_day(self):
        """ Get menu  for the day """
        business_name = "FAST FOOD"
        location = "nakulabye"
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        role_id = 1
        hashed_password = generate_password_hash(password, method='sha256')
        new_admin = User(first_name= first_name, last_name=last_name,\
                      email=email, password= hashed_password, role_id=role_id,\
                      business_name=business_name, location=location)
        db.session.add(new_admin)
        db.session.commit()
        """ To pass the test """
        first_name = "atlas"
        last_name = "waters"
        email = "*****@*****.**"
        password = "******"
        hashed_password = generate_password_hash(password, method='sha256')
        new_user = User(first_name=first_name, last_name=last_name,\
          email=email, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()

        meal_ids = [6, 2, 7, 4]
        meal_ids_string = ""
        for ids in meal_ids:
            meal_ids_string += ';%s' % ids
        user_id = 1
        menu = Menu(user_id=user_id, meal_ids=meal_ids_string)
        db.session.add(menu)
        db.session.commit()

        details = {"email": "*****@*****.**", "password": "******"}
        response = self.app.post("/bookmealapi/v1.0/auth/login",\
            data=json.dumps(details), content_type='application/json')
        data = json.loads(response.get_data())
        token = data['token']

        response = self.app.get('/bookmealapi/v1.0/menu',\
                headers={'x-access-token' : token})
        data = json.loads(response.get_data())
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(data['menu_day']), 1)
Exemplo n.º 35
0
def markasread(**kwargs):
    # app.logger.info(kwargs['email'])
    user = User()
    nobj = user.markallread(db.connection, kwargs['email'],
                            request.json['feedurl'], request.json['ts'])

    if not nobj.haserrors:
        nobj.result = {}
        resobj = user.getfeedtree(db.connection, kwargs['email'])
        if not resobj.haserrors:
            nobj.result['feedlist'] = resobj.result
            resobj = user.getfeeddata(db.connection, kwargs['email'],
                                      request.json['feedurl'])
            if not resobj.haserrors:
                nobj.result['feeddata'] = resobj.result

    return buildresponse(nobj, {'http_status': 200})
Exemplo n.º 36
0
def addfeed(**kwargs):
	# app.logger.info(kwargs['email'])
	# app.logger.info(request.json['feedurl'])	
	# app.logger.info(request.json['category'])		
	# app.logger.info(app.config['HTTP_PROXY'])
	user = User()
	nobj = user.addfeed(db.connection,kwargs['email'],request.json['feedurl'],request.json['category'],
	{'http_proxy':app.config.get('HTTP_PROXY',None)})
	if not nobj.haserrors and nobj.result is not None:
		nobj.result={}
		resobj = user.getfeedtree(db.connection,kwargs['email'])
		if not resobj.haserrors: 
			nobj.result["feedlist"] = resobj.result
			resobj = user.getcategorylist(db.connection,kwargs['email'])
			if not resobj.haserrors:
				nobj.result["categories"] = resobj.result
	
	return buildresponse(nobj,{'http_status':201})
Exemplo n.º 37
0
def feeddetails(**kwargs):
    # app.logger.info(kwargs['email'])
    # app.logger.info(request.args.get('feedurl'))
    user = User()
    print "*** printing request params"
    print request.args.get('pageno')
    print request.args.get('pagesize')
    if request.args.get('pageno') is not None and request.args.get(
            'pagesize') is not None:
        nobj = user.getfeeddata(db.connection, kwargs['email'],
                                request.args.get('feedurl'),
                                request.args.get('pageno'),
                                request.args.get('pagesize'))
    else:
        nobj = user.getfeeddata(db.connection, kwargs['email'],
                                request.args.get('feedurl'))

    return buildresponse(nobj, {'http_status': 200})
Exemplo n.º 38
0
 def post(self):
     registerData = {
         'username': request.json['username'],
         'password': request.json['password'],
         'email': request.json['email']
     }
     if not registerData['username'] or not registerData[
             'password'] or not registerData['email']:
         return jsonify(message='Missing parameters')
     if User.objects(username=registerData['username']).first():
         return jsonify(message='This user already exist!')
     if User.objects(email=registerData['email']).first():
         return jsonify(
             message='This email address is already used, please use other')
     User(password=bcrypt.generate_password_hash(registerData['password']),
          username=registerData['username'],
          email=registerData['email']).save()
     return jsonify(message='User successful created!')
Exemplo n.º 39
0
 def get(self, username):
     user = UserModel.objects(username=username).first()
     return make_response((jsonify({
         "status": "success",
         "content": {
             'username': user.username,
             'email': user.email,
             'register_date': user.register_date
         }
     }) if user else ""), 200 if user else 404)
Exemplo n.º 40
0
def addfeed(**kwargs):
    # app.logger.info(kwargs['email'])
    # app.logger.info(request.json['feedurl'])
    # app.logger.info(request.json['category'])
    # app.logger.info(app.config['HTTP_PROXY'])
    user = User()
    nobj = user.addfeed(db.connection, kwargs['email'],
                        request.json['feedurl'], request.json['category'],
                        {'http_proxy': app.config['HTTP_PROXY']})
    if not nobj.haserrors and nobj.result is not None:
        nobj.result = {}
        resobj = user.getfeedtree(db.connection, kwargs['email'])
        if not resobj.haserrors:
            nobj.result["feedlist"] = resobj.result
            resobj = user.getcategorylist(db.connection, kwargs['email'])
            if not resobj.haserrors:
                nobj.result["categories"] = resobj.result

    return buildresponse(nobj, {'http_status': 201})
Exemplo n.º 41
0
def seed_data():
	db = pymongo.MongoClient("localhost",27017,safe=True).feedtest
	emailid = "*****@*****.**"
	user  = User()
	prxydict = {'http_proxy':'http://www-proxy.au.oracle.com:80'}	
	notobj = user.save(db,emailid,emailid,'pwd')
	notobj = user.addcategory(db,emailid,'fun')
	notobj = user.addcategory(db,emailid,'money')	
	notobj = user.addfeed(db,emailid,'http://raptitude.com/rss','fun',prxydict)
	notobj = user.addfeed(db,emailid,'http://feeds.feedburner.com/typepad/sethsmainblog','fun',prxydict)
	notobj = user.addfeed(db,emailid,'http://feeds.feedburner.com/TheInvestorBlog','money',prxydict)
Exemplo n.º 42
0
def login():
    form = LoginForm()
    if request.method == 'POST':
        if not form.validate():
            return render_template('login.html',
                                   title='Login',
                                   form=form)
        else:
            if User.exists(form.user_name.data.lower(), form.user_pass.data.lower()):
                ses = User.get_info(form.user_name.data.lower(), form.user_pass.data.lower())
                print 'DEBUG: views.login :: ' + ses['StorageURL'], ses['Token']
                session['user_name'] = form.user_name.data.lower()
                session['url'] = ses['StorageURL']
                session['token'] = ses['Token']
                session['temp_url_key'] = ses['Temp_Url_Key']
                session['account'] = ses['Account']
                return redirect(url_for('account'))
    elif request.method == 'GET':
        if 'url' in session and 'token' in session:
            return redirect(url_for('account'))
        else:
            return render_template('login.html',
                                   title='Login',
                                   form=form)
Exemplo n.º 43
0
 def validate(self):
     if not Form.validate(self):
         return False
     name = self.user_name.data.lower()
     passwd = self.user_pass.data.lower()
     if self.user_pass.data != self.confirm_user_pass.data:
         self.confirm_user_pass.errors.append("Passwords do not match !")
         return False
     if User.exists(name, passwd):
         self.user_name.errors.append("This Username is already taken !")
         return False
     email = self.user_email.data.lower()
     if AddUser.add_user(name, passwd, email):
         if AddUser.gen_temp_url_key(name, passwd):
             print 'DEBUG: forms.validate.add_user :: gen_temp_url_key : True'
             return True
     else:
         self.user_email.errors.append("This email is already taken !")
         return False
Exemplo n.º 44
0
def seed_data():
	prxyval = Helper.getconfigvalue('dev.cfg','http_proxy',None)
	
	if prxyval is not None:
		prxydict = {'http_proxy':prxyval}
	else:
		prxydict = None
		
	dburl = Helper.getconfigvalue('dev.cfg','DATABASE_URI',None)
	dbname = Helper.getconfigvalue('dev.cfg','DBNAME',None)		

	db = pymongo.MongoClient(dburl)[dbname]

	emailid = "*****@*****.**"
	user  = User()
	notobj = user.save(db,emailid,emailid,'pwd')
	notobj = user.addcategory(db,emailid,'fun')
	notobj = user.addcategory(db,emailid,'money')	
	notobj = user.addfeed(db,emailid,'http://raptitude.com/rss','fun',prxydict)
	notobj = user.addfeed(db,emailid,'http://feeds.feedburner.com/typepad/sethsmainblog','fun',prxydict)
	notobj = user.addfeed(db,emailid,'http://feeds.feedburner.com/TheInvestorBlog','money',prxydict)
Exemplo n.º 45
0
def feeddetails(**kwargs):
	# app.logger.info(kwargs['email'])
	# app.logger.info(request.args.get('feedurl'))	
	user = User()
	nobj = user.getfeeddata(db.connection,kwargs['email'],request.args.get('feedurl'))
	return buildresponse(nobj,{'http_status':200})
Exemplo n.º 46
0
def addcategory(**kwargs):
	user = User()
	nobj = user.addcategory(db.connection,kwargs['email'],request.json['category'])
	return buildresponse(nobj,{'http_status':201})
Exemplo n.º 47
0
def getcatlist(**kwargs):
	user = User()
	nobj = user.getcategorylist(db.connection,kwargs['email'])
	return buildresponse(nobj,{'http_status':200})
Exemplo n.º 48
0
def changecategory(**kwargs):
	user = User()
	nobj = user.changecategory(db.connection,kwargs['email'],request.json['url'],request.json['category'])
	if not nobj.haserrors:
		nobj = user.getfeedtree(db.connection,kwargs['email'])
	return buildresponse(nobj,{'http_status':200})
Exemplo n.º 49
0
def changefeedcategory(**kwargs):
	user = User()
	nobj = user.changefeedcategory(db.connection,kwargs['email'],request.form['feedurl'],request.form['category'])
	return buildresponse(nobj,{'http_status':200})
Exemplo n.º 50
0
def removefeed(**kwargs):
	user = User()
	nobj = user.removefeed(db.connection,kwargs['email'],request.args.get('feedurl'))
	return buildresponse(nobj,{'http_status':204})
Exemplo n.º 51
0
def feedlist(**kwargs):
	# app.logger.info(kwargs['email'])
	user = User()
	nobj = user.getfeedtree(db.connection,kwargs['email'])
	# app.logger.info(nobj)	
	return buildresponse(nobj,{'http_status':200})
Exemplo n.º 52
0
def allfeeds(**kwargs):
	# app.logger.info(kwargs['email'])
	user = User()
	nobj = user.getfeeddata(db.connection,kwargs['email'],None)
	# app.logger.info(nobj)	
	return buildresponse(nobj,{'http_status':200})