def new_user(): """ Creates a new user. """ user = User() try: # validates user key/value inputs using a try-catch block sanitized = user.import_data(request.json) if sanitized == "Invalid": return jsonify({"Message": "Username and Password are required"}), 400 except ValidationError as e: return jsonify({"Message": str(e)}), 400 # check for duplicates before creating the new user duplicate = User.query.filter_by(username=user.username).first() if not duplicate: user.set_password(user.password_hash) db.session.add(user) db.session.commit() return jsonify( {"Message": user.username.title() + " has been created"}), 201 return jsonify( {"Message": "A user with that name already exists. Please try again"}), 400
def post(self): data = request.get_json() user = User.query.filter_by(email=data['email']).first() if not user: new_user = User(email=data['email'], admin=False, password=data['password']) new_user.save() response = jsonify({ "status": "Success", "message": "User registered successfully." }) response.status_code = 201 else: response = jsonify( {"message": "User already registered. Kindly Login"}) response.status_code = 202 return make_response(response)
def post(self): # get the post data data_posted = request.get_json() # check if the user already exists user = User.query.filter_by(email=data_posted.get('email')).first() if not user: try: new_user = User(username=data_posted.get('username'), email=data_posted.get('email'), password=data_posted.get('password')) # insert the user db.session.add(new_user) db.session.commit() response = { 'status': 'success', 'message': 'You have been successfully registered' } return make_response(jsonify(response)), 201 except Exception as e: response = { 'status': 'fail' + str(e), 'message': 'Some error occurred. Please try again' } return make_response(jsonify(response)), 401 else: response = {'status': 'fail', 'message': 'User already exists!'} return make_response(jsonify(response)), 409
def put(self, bucketlist_id): '''.. :quickref: Bucketlist; Update this bucket list .. sourcecode:: http PUT /bucketlists/1/ HTTP/1.1 Host: localhost:5000 Accept: application/json Authentication: <token> :<json string name: Edited bucketlist name :resheader Content-Type: application/json :status 200: bucketlist updated :status 422: invalid parameters ''' token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: return {'message': 'Unauthorized Access!'} if current_user: arguments = request.get_json(force=True) name = arguments.get('name') bucketlist = Bucketlist.query.filter_by(created_by=current_user.id, id=bucketlist_id).first() if bucketlist: bucketlist.name = name bucketlist.save() return {'message': 'Successfully updated the bucketlist'} else: return {'message': 'Could not find bucketlist'} else: return {'message': 'Expired or invalid token'}
def get(self, id=None): if id: user = User.query.filter_by(id=id).first() if user: response = jsonify({"email": user.email, "admin": user.admin}) response.status_code = 200 else: response = jsonify({ "status": "Fail", "message": "User does not exist" }) response.status_code = 404 return make_response(response) else: users = User.get_all() user_results = [] for user in users: user_obj = {"email": user.email, "admin": user.admin} user_results.append(user_obj) response = jsonify({"users": user_results}) return make_response(response), 200
def delete(self, bucketlist_id, item_id): '''.. :quickref: Bucketlist; Delete this single bucket list .. sourcecode:: http DELETE /bucketlists/1/items/1/ HTTP/1.1 Host: localhost:5000 Accept: application/json Authentication: <token> :resheader Content-Type: application/json :status 204: bucketlist deleted ''' token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: return {'message': 'Unauthorized Access!'} if current_user: bucketlist = Bucketlist.query.filter_by(created_by=current_user.id, id=bucketlist_id).first() if bucketlist: item = Item.query.filter_by( id=item_id, bucketlist_id=bucketlist_id).first() if item: item.delete() response = {'message': 'Successfully deleted Item'} return response, 200 else: abort(message='Item not found') else: abort(message='Expired or invalid token')
def delete(self, bucketlist_id): '''.. :quickref: Bucketlist; Delete this single bucket list .. sourcecode:: http DELETE /bucketlists/1/ HTTP/1.1 Host: localhost:5000 Accept: application/json Authentication: <token> :resheader Content-Type: application/json :status 204: bucketlist deleted ''' token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: return {'message': 'Unauthorized Access!'} if current_user: bucketlist = Bucketlist.query.filter_by(created_by=current_user.id, id=bucketlist_id).first() if bucketlist: bucketlist.delete() return {'message': 'Bucketlist successfully deleted'} else: return {'message': 'Could not find bucketlist'} else: return {'message': 'Expired or invalid token'}
def get(self, bucketlist_id): '''.. :quickref: Bucketlist; Get single bucket list **Example request**: .. sourcecode:: http GET /bucketlists/1/ HTTP/1.1 Host: localhost:5000 Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: application/json Authentication: Token [ { "id": 1, "name": "Before 50", "items": [ { "id": 1, "name": "Watch F1", "date_created": "2017-07-30T22:29:10.044464", "date_modified": "2017-07-31T10:13:44.926045", "done": true } ], "date_created": "2017-07-30T21:36:32.754289", "date_modified": "2017-07-30T21:36:32.754289", "created_by": 1 }, ] :resheader Content-Type: application/json :status 200: bucketlist found ''' token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: abort(400, message='Unauthorized Access!') if current_user: bucketlistitem = db.session.query(Bucketlist).filter_by( created_by=current_user.id, id=bucketlist_id).first() if not bucketlistitem: abort(404, message='Bucketlist not found') else: return bucketlistitem else: abort(400, message='Expired or invalid token')
def login(): """ Login a pre-existing user and return a token. """ user = User() user.import_data(request.json) username = user.username password = user.password_hash """Uses a custom verify_password function and flask auth extensions to check the password and generate a token""" if verify_password(username, password): return jsonify({ "Hello": user.username.title(), "Token": generate_auth_token(g.user.id), "View your bucketlists here": user.export_data() }), 200 return jsonify( {"Message": "Invalid username or password. Please try again"}), 401
def post(self): """.. :quickref: Bucketlists Collection; Create a new bucket list. .. sourcecode:: http POST /bucketlists/1/ HTTP/1.1 Host: localhost:5000 Accept: application/json Authentication: <token> :reqheader Accept: application/json :reqheader Authentication: <token> :<json string name: bucketlist name :resheader Content-Type: application/json :status 201: bucketlist created :status 422: invalid parameters """ token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: abort(400, message='Unauthorized Access!') if current_user: arguments = request.get_json(force=True) try: name = arguments['name'] except: return {'message': 'Invalid parameter entered'} bucketlists = Bucketlist.query.filter_by( created_by=current_user.id) current_bucketlists = [] if not name: # we return bad request since we require name return {'message': 'Missing required parameters.'}, 400 for bucketlist in bucketlists: current_bucketlists.append(bucketlist.name) if name not in current_bucketlists: new_bucketlist = Bucketlist(name=name, created_by=current_user.id) new_bucketlist.save() return {'message': 'successfully added a new bucketlist'} return {'message': 'bucketlist already exists'} else: abort(400, message='Expired or invalid token')
def setUp(self): """Set up the test database and test user.""" self.app = create_app(config_name="testing") self.client = self.app.test_client() self.app_context = self.app.app_context() self.app_context.push() db.create_all() user = User(username="******", email="*****@*****.**", password="******") bucketlist = Bucketlist(bucketlist_title="Visit Paris", creator_id=1) item = Item(item_name="The Eiffel Tower", description="Wrought iron lattice tower in France", bucketlist_id=1) db.session.add(user) db.session.add(bucketlist) db.session.add(item) db.session.commit() # set header self.auth_header = {'Authorization': user.generate_auth_token(user.id)} self.token = user.generate_auth_token(user.id)
def verify_token(*args, **kwargs): # check if token in request headers if 'token' in request.headers: token = request.headers['token'] # authenticate token user = User.verify_auth_token(token) if not user: abort(403, message='authentication failed') else: # set user in g g.user = user return f(*args, **kwargs) else: abort(401, message='token missing from header')
def test_register_user_twice(self): """Test if registering the same user twice returns an error""" user = User(name='joe', email='*****@*****.**', password='******') user.save() response = base.base_registration(self) data = json.loads(response.data.decode()) self.assertTrue(data['message'] == 'Failed!! User already exists') self.assertEqual(response.status_code, 200) user.delete()
def post(self, bucketlist_id): """.. :quickref: Bucketlists Collection; Add a new bucketlist item. .. sourcecode:: http POST /bucketlists/1/items/ HTTP/1.1 Host: localhost:5000 Accept: application/json Authentication: <token> :reqheader Accept: application/json :<json string id: bucketlist id :<json string name: bucketlist name :resheader Content-Type: application/json :status 201: bucketlist created :status 422: invalid parameters """ token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: abort(message='Unauthorized Access!') if current_user: arguments = request.get_json(force=True) name = arguments.get('name') bucketlist = db.session.query(Bucketlist).filter_by( created_by=current_user.id, id=bucketlist_id) if bucketlist: try: item = Item(name=name, bucketlist_id=bucketlist_id) item.save() response = { 'message': 'Item successfully added to bucketlist' } return response except: abort(message='Failed to create item') else: abort(message='Bucketlist not found') else: abort(message='Expired or invalid token')
def before_request(): """Set global attributes.""" if request.endpoint in [ "createitem", "updateitem", "deleteitem", "createbucketlist", "getallbucketlists", "getsinglebucketlist", "updatebucketlist", "deletebucketlist", "getallitems", "changeusername" ]: token = request.headers.get("token") if token is not None: user = User.verify_auth_token(token) if user == "Expired": return jsonify({"message": "Error: Expired Token"}), 401 if user == "Invalid": return jsonify({"message": "Error: Invalid Token"}), 401 g.user = user else: return jsonify({"message": "Error: Please enter a token"}), 401
def setUp(self): """Fixture to create test database and set up test client.""" self.app = app.test_client() db.create_all() user = User(username="******", email="*****@*****.**", password="******") bucketlist = Bucketlist(title="Travel", description="Places I have to visit", created_by=1) item = Item(name="Enjoy the beautiful beaches of Hawaii", bucketlist_id=1) db.session.add(user) db.session.add(bucketlist) db.session.add(item) db.session.commit()
def put(self, bucketlist_id, item_id): '''.. :quickref: Bucketlist; Update this bucket list item .. sourcecode:: http PUT /bucketlists/1/items/1/ HTTP/1.1 Host: localhost:5000 Accept: application/json Authentication: <token> :<json string name: New item name :resheader Content-Type: application/json :status 200: Item updated :status 422: invalid parameters ''' token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: abort(message='Unauthorized Access!!') if current_user: arguments = request.get_json(force=True) name, done = arguments.get('name'), arguments.get('done') bucketlist = Bucketlist.query.filter_by(created_by=current_user.id, id=bucketlist_id).first() if bucketlist: item = Item.query.filter_by( id=item_id, bucketlist_id=bucketlist_id).first() if item: item.name = name if name is not None else item.name item.done = done if done is not None else item.done item.save() return {'message': 'Successfully updated the item'} else: abort(message='Item not found') else: abort(message='Bucketlist not found') else: abort(message='Expired or invalid token')
def create_user(self, first_name, last_name, email, password): """creates a new User object and stores it in self.users""" if not self.__is_valid_input(first_name, str): raise ValueError() if not self.__is_valid_input(first_name, str): raise ValueError() if not self.__is_valid_input(last_name, str): raise ValueError() if not self.__is_valid_input(email, str): raise ValueError() if not self.__is_valid_input(password, str): raise ValueError() user_id = self.__generate_user_id() user = User(user_id=user_id, first_name=first_name, last_name=last_name, email=email, password=password) self.__index[email] = user_id self.users[user_id] = user return user
def post(self): """.. :quickref: User Authentication; Register a new user .. sourcecode:: http POST /auth/register/ HTTP/1.1 Host: localhost:5000 Accept: application/json :reqheader Accept: application/json :<json string name: username :<json string email: user email :<json string password: user password :resheader Content-Type: application/json :status 200: user created :status 422: invalid parameters """ arguments = request.get_json(force=True) if not arguments['name'] or not arguments['password'] or not arguments['email']: # we return bad request since we require name, email and password return {'message': 'Missing required parameters.'}, 400 name = arguments['name'] email = arguments['email'] password = arguments['password'] users = db.session.query(User).all() registered_emails = [] for user in users: registered_emails.append(user.email) if email not in registered_emails: new_user = User( name=name, password=password, email=email) new_user.hash_password(password) new_user.save() # return a success message return {'message': 'Successfully added a user'}, 201 return {'message': 'Failed!! User already exists'}
def get(self): ''' .. :quickref: Bucketlists Collection; List all the created bucket lists **Example request**: .. sourcecode:: http GET /bucketlists/ HTTP/1.1 Host: localhost:5000 Accept: application/json Authentication: <token> **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: application/json [ { "id": 1, "name": "Before 30", "items": [ { "id": 1, "name": "Sky Dive", "date_created": "2017-07-30T22:29:10.044464", "date_modified": "2017-07-31T10:13:44.926045", "done": false } ], "date_created": "2017-07-30T21:36:32.754289", "date_modified": "2017-07-30T21:36:32.754289", "created_by": 1 }, { "id": 2, "name": "Before 50", "items": [ { "id": 2, "name": "Climb Mt.Everest", "date_created": "2017-08-07T06:39:22.466605", "date_modified": "2017-08-07T06:39:22.466537", "done": false } ], "date_created": "2017-07-30T22:28:54.824647", "date_modified": "2017-07-30T22:28:54.824647", "created_by": 1 }, ] :query q: full text search query :query limit: number of bucket lists per page :query page: select page :resheader Content-Type: application/json :status 200: bucketlists found ''' token = request.headers.get('Authorization') if token: current_user = User.verify_auth_token(token) else: abort(401, message='Unauthorized Access!') if not isinstance(current_user, User): abort(401, current_user) # get arguments parser = reqparse.RequestParser() parser.add_argument('q', type=str, required=False, location='args') parser.add_argument('limit', type=int, required=False, default=20, help='Results per page', location='args') parser.add_argument('page', type=int, default=1, help='Page number', required=False, location='args') arguments = parser.parse_args(request) q = arguments.get("q") limit = arguments.get("limit") page = arguments.get("page") if q: bucketlists = Bucketlist.query.filter( Bucketlist.name.ilike('%' + q + '%'), Bucketlist.created_by == current_user.id).paginate( page, limit, False) else: bucketlists = Bucketlist.query.filter_by( created_by=current_user.id).paginate(page, limit, False) if bucketlists.items: # return marshal(bucketlists) return bucketlists.items abort(400, message='Bucketlists not found')
def post(self): # noqa """ This is the register end point for creating a user account --- parameters: - in: formData name: email type: string description: The email of the to be registered required: true - in: formData name: username description: The name of the user to be created type: string required: true - in: formData name: password type: string description: The password of the user required: true responses: 201: description: Create a user account schema: id: Register properties: username: type: string description: The name of the user to be created default: user email: type: string description: The email of the to be registered default: [email protected] password: type: string description: The password of the user default: passw0rD """ parser = reqparse.RequestParser() parser.add_argument( "username", required=True, help="Please enter a username.") parser.add_argument( "email", required=True, help="Please enter an email address.") parser.add_argument( "password", required=True, help="Please enter a password.") args = parser.parse_args() username, email, password = (args["username"], args["email"], args["password"]) if len(password) < 6: return {"message": "ERROR!, Password must be at" " least 6 characters"}, 400 # if validate_email(email): if username.isalnum(): user = User(username=username, email=email, password=password) return add_user(user) else: return {"message": "ERROR!, Username cannot contain" " special characters or spaces." " Please check and try again"}, 400