def test_update_username_without_login(self): u = Users(id=6, username='******', email='*****@*****.**', password='******') u.save() url = reverse('show-user', args=[6]) data = {'username': '******'} response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.app.app_context().push() with self.app.app_context(): db.create_all() self.user1 = Users( username='******', email='*****@*****.**', password='******') self.user1.save() self.user2 = Users( username='******', email='*****@*****.**', password='******') self.user2.save() self.project1 = Projects( name="User1's Project", description='sample project', contract_value='5000', percentage_return='22', start_date=datetime.date.today(), end_date=datetime.date.today()+datetime.timedelta(days=10), user_email=self.user1.email) self.project1.save() self.project2 = Projects( name="User2's Project", description='sample project', contract_value='3000', percentage_return='10', start_date=datetime.date.today(), end_date=datetime.date.today()+datetime.timedelta(days=10), user_email=self.user2.email) self.project2.save() self.bid = Bids( amount='200', date=datetime.date.today(), user_email=self.user1.email, project_id=self.project2.id,) self.bid.save()
def signup(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) try: body = get_body_as_json(request.body) username = retrieve_username(body) password = retrieve_password(body) email = retrieve_email(body) if username == '' or password == '' or email == '': return HttpResponseBadRequest() except: return HttpResponseBadRequest() try: new_user = Users(username=username, password=password, email=email) user_id = new_user.pk new_user.save() except: return HttpResponseForbidden() joined = get_user(username).joined.__str__() token = get_token_as_string(username, user_id, joined) response = JsonResponse({'token': token}) return response # # q = request.GET.get('q')
def test_login(self): u = Users(username='******', email='*****@*****.**', password='******') u.save() url = reverse('login') data = {'email': '*****@*****.**', 'password': '******'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK)
def register(): email = request.json.get('email') password = request.json.get('password') if email is None or password is None: responseObject = { 'status': 'error', 'message': 'Invalid input.' } return jsonify(responseObject), 400 if Users.query.filter_by(email=email).first() is not None: responseObject = { 'status': 'error', 'message': 'User already exists.' } return jsonify(responseObject), 400 user = Users( email=email, password=password ) db.session.add(user) db.session.commit() auth_token = user.encode_auth_token(user.id) responseObject = { 'status': 'success', 'message': 'Successfully registered', 'auth_token': auth_token.decode() } return jsonify(responseObject), 201
def post(self): args = self.parser.parse_args() try: user = Users(username=args["username"]) # if sign up page if args["email"] is not None: user.email = args["email"] if args["password"] is not None: user.hash_password(args["password"]) if (self.username_in_db(user)): return {"error":"username already exists"}, 404 if (self.email_in_db(user)): return {"error":"email id already exists"}, 404 db.session.add(user) db.session.commit() headers = {'Content-Type': 'text/html'} return make_response(render_template('index.html', user=user),200, headers) # if login page else: user_in_db = Users.query.filter_by(username=user.username).first() if user_in_db is not None: if(user_in_db.verify_password(args["password"])): headers = {'Content-Type': 'text/html'} return make_response(render_template('index.html', user=user_in_db),200, headers) else: return {"error":"Invalid username or password"}, 404 except Exception as e: print(e) return {"error":"Error creating new user", "msg" : str(e) }, 404
def post(self): body = request.get_json() user = Users(**body) user.hash_password() db.session.add(user) db.session.commit() expires = datetime.timedelta(days=7) id = user.id access_token = create_access_token(identity=str(user.id), expires_delta=expires) return {'id': str(id), "token": access_token}, 200
def test_delete_user_with_login(self): u = Users(id=9, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() url = reverse('login') data = {'email': '*****@*****.**', 'password': '******'} response = self.client.post(url, data, format='json') if self.assertEqual(response.status_code, status.HTTP_200_OK): url = reverse('show-user', args=[9]) response = self.client.delete(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK)
def post(self): args = self.parser.parse_args() try: user = Users(username=args["username"]) user_in_db = Users.query.filter_by(username=user.username).first() pwd_in_db = user_in_db.password if(user.verify_password(pwd_in_db)): return {"user" : marshal(user, user_field)}, 200 except Exception as e: print(e) return {"error":"Error creating new user", "msg" : str(e) }, 404
def register(): """Register a user""" data = { 'username': request.json.get('username'), 'email': request.json.get('email'), 'password': request.json.get('password'), } check_valid(RegisterUserSchema().validate(data)) user = Users( username=data['username'], email=data['email'], password=data['password']) user.save() return jsonify({'message': 'Registered Successfully.'}), 201
def logout(): auth_header = request.headers.get('Authorization') auth_token = auth_header.split(' ')[0] if auth_token: decoded = Users.decode_auth_token(auth_token) if isinstance(decoded, str): responseObject = { 'status': 'error', 'message': decoded } return jsonify(responseObject), 401 else: blacklist_token = BlacklistToken(token=auth_token) db.session.add(blacklist_token) db.session.commit() responseObject = { 'status': 'success', 'message': 'Logged out.' } return jsonify(responseObject), 200 else: responseObject = { 'status': 'error', 'message': 'Invalid token.' } return jsonify(responseObject), 403
def get_auth(): auth_header = request.headers.get('Authorization') auth_token = auth_header.split(' ')[0] if auth_token: decoded = Users.decode_auth_token(auth_token) if isinstance(decoded, str): responseObject = { 'status': 'error', 'message': decoded } return jsonify(responseObject), 401 else: user = Users.query.get(decoded) responseObject = { 'status': 'success', 'data': { 'user_id': user.id, 'email': user.email, 'admin': user.admin, 'registered_on': user.registered_on } } return jsonify(responseObject), 200 else: responseObject = { 'status': 'error', 'message': 'Invalid token.' } return jsonify(responseObject), 401
def bid_to_project(): """Bid to fund a project""" data = { 'email': request.json.get('email'), 'password': request.json.get('password'), 'amount': request.json.get('amount'), 'project_id': request.json.get('project_id'), } check_valid(BidSchema().validate(data)) data['amount'] = float(data['amount']) user = Users.get_user(data['email'], data['password']) project = Projects.get_project( request.json['project_id'], data['amount']) bid = Bids( amount=data['amount'], date=datetime.date.today(), user_email=user.email, project_id=project.id,) bid.save() data['user_email'] = user.email data['project_id'] = project.id data['bid_id'] = bid.id data['potential_profit_margin'] = "{0:.2f}".format( float(project.percentage_return) / 100 * data['amount']) return jsonify({ 'message': 'Bid Created Successfully.', 'data': data, }), 201
def update_bid(): """Update a bid""" data = { 'email': request.json.get('email'), 'password': request.json.get('password'), 'amount': request.json.get('amount'), 'bid_id': request.json.get('bid_id'), } check_valid(UpdateBidSchema().validate(data)) user = Users.get_user(data['email'], data['password']) bid = Bids.get_bid(data['email'], data['bid_id']) project = Projects.get_project(bid.project_id, 0) total_bids = 0 current_amnt = float(bid.amount) new_amnt = float(request.json['amount']) for item in project.bids_received: total_bids = total_bids + float(item.amount) total_bids = total_bids - current_amnt + new_amnt if float(project.contract_value) < total_bids: return jsonify({ "msg": "The amount added is too much. Reduce it by {}".format( (total_bids - float(project.contract_value)))}), 400 bid.amount = new_amnt bid.date = datetime.date.today() bid.save() return jsonify({ 'message': 'Updated Bid.', 'data': bid.serialize(), }), 200
def create_project(): """Create a project""" data = { 'email': request.json.get('email'), 'password': request.json.get('password'), 'name': request.json.get('name'), 'description': request.json.get('description'), 'contract_value': request.json.get('value'), 'percentage_return': request.json.get('return'), 'end_date': request.json.get('end_date'), } check_valid(CreateProjectSchema().validate(data)) user = Users.get_user(data['email'], data['password']) project = Projects( name=data['name'], description=data['description'], contract_value=data['contract_value'], percentage_return=data['percentage_return'], start_date=datetime.date.today(), end_date=data['end_date'], user_email=user.email) project.save() data['project_id'] = project.id return jsonify({ 'message': 'Project Created Successfully.', 'data': data, }), 201
def handle_registration(bcrypt): if request.method=='POST': try: user_data =request.get_json()# dict pw_hash = bcrypt.generate_password_hash(user_data['password']).decode('utf-8') # print(pw_hash) # print(user_data) # print(Users) print(user_data['name'],user_data['email'],pw_hash) new_user=Users(name=user_data['name'], email=user_data['email'],password=pw_hash )#add new user- object try: db.session.add(new_user) db.session.commit() except SQLAlchemyError as e: print(str(e)) db.session.rollback() print(new_user.id, new_user.name, new_user.email,new_user.entries,new_user.joindate) # return jsonify('register'),200 return {'id':new_user.id, 'name':new_user.name,'email':new_user.email,'entries':new_user.entries,'joindate':new_user.joindate} except: # return 'didnt save user' return jsonify('didnt save user!!'),400 else: # return 'something went worng , Please try again' return jsonify('something went wrong , Please try again'),400
def test_unfollow_user_without_login(self): u = Users(id=14, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() u = Users(id=15, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() url = reverse('follow', args=[15]) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_follow_user_without_login(self): u = Users(id=10, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() u = Users(id=11, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() url = reverse('follow', args=[11]) response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_update_user_with_login(self): u = Users(id=7, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() url = reverse('login') data = {'email': '*****@*****.**', 'password': '******'} response = self.client.post(url, data, format='json') if self.assertEqual(response.status_code, status.HTTP_200_OK): url = reverse('show-user', args=[7]) data = {'username': '******', 'email':'*****@*****.**', 'password':'******', 'birthday':'1994-04-13', 'company':'Givery', 'location':'Tokyo'} response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Users.objects.get().username, 'user7') self.assertEqual(Users.objects.get().email, '*****@*****.**') self.assertEqual(Users.objects.get().password, 'password7') self.assertEqual(Users.objects.get().birthday, datetime.date(1994, 4, 13)) self.assertEqual(Users.objects.get().company, 'Givery') self.assertEqual(Users.objects.get().location, 'Tokyo')
def post(self): data = request.get_json() or {} if 'username' not in data or 'email' not in data or 'password_hash' not in data: return errors.bad_request('must include username, email and password fields') if Users.query.filter_by(username=data['username']).first(): return errors.bad_request('please use a different username') if Users.query.filter_by(email=data['email']).first(): return errors.bad_request('please use a different email address') user = Users() for field in ['username', 'email', 'user_address']: if field in data: setattr(user, field, data[field]) if 'password_hash' in data: user.set_password(data['password_hash']) db.session.add(user) db.session.commit() response = user_schema.jsonify(user) response.status_code = 201 response.headers['Location'] = url_for('api.usersget', username=user.username) return response
def test_follow_user_with_login(self): u = Users(id=12, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() u = Users(id=13, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() url = reverse('login') data = {'email': '*****@*****.**', 'password': '******'} response = self.client.post(url, data, format='json') if self.assertEqual(response.status_code, status.HTTP_200_OK): url = reverse('follow', args=[13]) response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_unfollow_user_with_login_without_followed_fail(self): u = Users(id=16, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() u = Users(id=17, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() url = reverse('login') data = {'email': '*****@*****.**', 'password': '******'} response = self.client.post(url, data, format='json') if self.assertEqual(response.status_code, status.HTTP_200_OK): url = reverse('follow', args=[17]) response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def signup(): data = request.get_json() username = data.get('username') email = data.get('email') password = data.get('password') user = Users(username, email, password) error = user.validate_input() exists = user.check_user_exist() if error != None: return jsonify({'Error': error}), 400 if not exists: password_hash = generate_password_hash(password, method='sha256') db.register_user(username, email, password_hash) token = create_access_token(username) return jsonify({ 'access_token': token, 'message': f'{username} successfully registered.' }), 201 else: return jsonify({'message': exists}), 401
def signup(): form = RegisterForm() if form.validate_on_submit(): hashed_password = generate_password_hash(form.password.data, method='sha256') new_user = Users(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(new_user) db.session.commit() return '<h1>New user has been created!</h1>' return render_template('signup.html', form=form)
def test_unfollow_user_with_login_with_followed_success(self): u = Users(id=18, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() u = Users(id=19, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() url = reverse('login') data = {'email': '*****@*****.**', 'password': '******'} response = self.client.post(url, data, format='json') if self.assertEqual(response.status_code, status.HTTP_200_OK): url = reverse('follow', args=[19]) response = self.client.post(url) if self.assertEqual(response.status_code, status.HTTP_200_OK): url = reverse('follow', args=[19]) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_person(client): rs = client.get("/users") assert rs.status_code == 200 ret_dict = rs.json # gives you a dictionary assert ret_dict["success"] == True assert ret_dict["result"]["users"] == [] # create Person and test whether it returns a person temp_person = Users(email="*****@*****.**",username="******",password="******") db.session.add(temp_person) db.session.commit() rs = client.get("/users") ret_dict = rs.json assert len(ret_dict["result"]["users"]) == 1 assert ret_dict["result"]["users"][0] == {'_id': 1,'email': '*****@*****.**','is_active': True,'password': '******','username': '******'}
def my_projects(): """Get single user's projects""" data = { 'email': request.json.get('email'), 'password': request.json.get('password'), } check_valid(EmailPasswordSchema().validate(data)) user = Users.get_user(data['email'], data['password']) projects = Projects.query.filter_by(user_email=user.email) res = list() for item in projects: if item.active is False: continue res.append(Projects.serialize(item)) return jsonify({'data': res}), 200
def delete_projects(): """Delete a project""" data = { 'email': request.json.get('email'), 'password': request.json.get('password'), 'project_id': request.json.get('project_id'), } check_valid(DeleteProjectSchema().validate(data)) user = Users.get_user(data['email'], data['password']) project = Projects.query.filter_by( user_email=user.email, id=data['project_id']).first() if project is None: return jsonify({'msg': "Access Denied"}), 401 project.delete() return jsonify({'msg': "Deleted"}), 200
def run(): file = open('scripts/test.json') # Fetching the json file data = json.load(file) for i in data['members']: user = Users() # Creating an user object user.id = i['id'] user.email = i['email'] user.tz = i['tz'] user.real_name = i['real_name'] user.save() for j in i['activity_periods']: activity = Activities() datetime_object = datetime.strptime(j['start_time'], '%b %d %Y %I:%M%p') # converting given datetime format activity.start_time = datetime_object datetime_object2 = datetime.strptime(j['end_time'], '%b %d %Y %I:%M%p') activity.end_time = datetime_object2 activity.user = user activity.save()
def update_projects(): """Update a single project""" changes = { "name": request.json.get('name'), "description": request.json.get('description'), "contract_value": request.json.get('value'), "percentage_return": request.json.get('percentage_return'), "end_date": request.json.get('end_date'), } data = changes.copy() data.update({ 'email': request.json.get('email'), 'password': request.json.get('password'), 'project_id': request.json.get('project_id'), }) check_valid(UpdateProjectSchema().validate(data)) user = Users.get_user(data['email'], data['password']) projects = Projects.query.filter_by( user_email=user.email, id=data['project_id']).first() total_bids = 0 if projects: for item in projects.bids_received: total_bids = total_bids + float(item.amount) if changes['contract_value'] is not None and \ float(changes['contract_value']) < total_bids: return jsonify({ "msg": "Cannot reduce amount below total bids ({})".format( total_bids)}), 400 for key in changes: if changes[key] is None: continue setattr(projects, key, changes[key]) projects.save() return jsonify({ 'msg': "Success", 'data': projects.serialize() }), 200 return jsonify({'msg': "Access Denied."}), 401
def my_bids(): """Get my bid""" data = { 'email': request.json.get('email'), 'password': request.json.get('password'), } err = EmailPasswordSchema().validate(data) if err: return jsonify(err), 400 user = Users.get_user(request.json['email'], request.json['password']) bid = Bids.query.filter_by(user_email=user.email).all() res = [] for item in bid: item = item.serialize() project = Projects.query.filter_by(id=item['project']).first() project = project.serialize() project.pop('bids') item['project'] = project res.append(item) return jsonify({'data': res}), 200
def login(): data = request.get_json() username = data.get('username') password = data.get('password') error = Users.login_validate(username, password) if error != None: return jsonify({'Error': error}), 400 user = db.login(username) if user == None: return jsonify ({'message': 'Wrong login credentials.'}), 400 if check_password_hash(user['password'], password) and user['username'] == username: token = create_access_token(username) return jsonify ({ 'access_token': token, 'message': f'{username} successfully logged in.' }), 200 else: return jsonify ({'message': 'Wrong login credentials.'}), 400
def test_show_user(self): u = Users(id=5, username='******', email='*****@*****.**', password='******') u.save() url = reverse('show-user', args=[5]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_delete_username_without_login(self): u = Users(id=8, username='******', email='*****@*****.**', password='******') u.save() url = reverse('show-user', args=[8]) response = self.client.put(url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_pager_without_param(self): u = Users(id=20, username='******', email='*****@*****.**', password='******', birthday='1997-04-17') u.save() u = Users(id=21, username='******', email='*****@*****.**', password='******', birthday='1991-04-17') u.save() u = Users(id=22, username='******', email='*****@*****.**', password='******', birthday='1992-04-17') u.save() u = Users(id=23, username='******', email='*****@*****.**', password='******', birthday='1993-04-17') u.save() u = Users(id=24, username='******', email='*****@*****.**', password='******', birthday='1994-04-17') u.save() u = Users(id=25, username='******', email='*****@*****.**', password='******', birthday='1995-04-17') u.save() u = Users(id=26, username='******', email='*****@*****.**', password='******', birthday='1996-04-17') u.save() u = Users(id=27, username='******', email='*****@*****.**', password='******', birthday='1991-04-17') u.save() u = Users(id=28, username='******', email='*****@*****.**', password='******', birthday='1990-04-17') u.save() u = Users(id=29, username='******', email='*****@*****.**', password='******', birthday='1990-04-13') u.save() u = Users(id=30, username='******', email='*****@*****.**', password='******', birthday='1991-04-13') u.save() url = reverse('user-list') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '10') self.assertEqual(response['total_count'], '11') self.assertEqual(response.data[0]['username'], 'testing20') url = reverse('user-list', kwargs={'offset':5}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '5') self.assertEqual(response['total_count'], '11') self.assertEqual(response.data[0]['username'], 'testing25') url = reverse('user-list', kwargs={'offset': 0, 'limit':5}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '5') self.assertEqual(response['total_count'], '11') self.assertEqual(response.data[0]['username'], 'testing20') url = reverse('user-list', kwargs={'offset': 2, 'limit':5}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '3') self.assertEqual(response['total_count'], '11') self.assertEqual(response.data[0]['username'], 'testing22') url = reverse('user-list', kwargs={'limit':5}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '5') self.assertEqual(response['total_count'], '11') self.assertEqual(response.data[0]['username'], 'testing20') url = reverse('user-list', kwargs={'orderBy':'birthday'}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '10') self.assertEqual(response['total_count'], '11') self.assertEqual(response.data[0]['birthday'], '1990-04-13') url = reverse('user-list', kwargs={'orderBy':'birthday', 'order': 'desc'}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '10') self.assertEqual(response['total_count'], '11') self.assertEqual(response.data[0]['birthday'], '1997-04-17') """ Add new User 'testing30' to test filtering option """ u = Users(id=31, username='******', email='*****@*****.**', password='******', birthday='1991-04-13') u.save() url = reverse('user-list', kwargs={'filterOn':'username'}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '10') self.assertEqual(response['total_count'], '12') url = reverse('user-list', kwargs={'filterOn':'username', 'filterValue': 'testing30'}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['count'], '2') self.assertEqual(response['total_count'], '12')