def new_user(): """ Create new user POST_Data: { "email": str, "name": str } """ data = request.get_json() or {} # validate is all required fields are present or not v = Validator(user_schema) if not v.validate(data): return error_response(400, v.errors) # create user instance user = User() user.name = data['name'] user.email = data['email'] # save it to db db.session.add(user) db.session.commit() data = user.to_dict() # Add activity_log for user creation add_activity_log('create', user.id, data) response = jsonify(data) response.status_code = 201 return response
def signup(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = SignupForm() if form.validate_on_submit(): user = User(firstname=form.firstname.data, lastname=form.lastname.data, username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are part of the secret santa fun!') return redirect(url_for('auth.login')) return render_template('auth/signup.html', title='Sign Up', form=form)
def test_get_user(self): user = User(first_name='Paco', last_name='Murcia', phone_number='415-694-7777', email='*****@*****.**', address='55 Main St.', password='') user.save() user_id = user.id url = reverse('user-detail', kwargs={'pk': user_id}) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual('Paco', response.data['first_name'])
def test_activate_user_with_missing_data(self): user = User(first_name='Amparo', last_name='Mondragon', phone_number='415-694-5555', email='*****@*****.**', address='55 Main St.', password='') user.save() user_id = user.id data = {'activation_code': user.activation_code} url = reverse('user-activate', kwargs={'pk': user_id}) response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def request_handler(): # Generate cryptographically secure random number y = str(rd.get_random_bytes(256).hex()) # Check if y already exists, should be very unlikely. If true generate new number until unique check = User.query.get(y) while check: y = str(rd.get_random_bytes(256).hex()) check = User.query.get(y) # Add the generated uuid to the db new_user = User(y=y) new_user.save_to_db() return y
def post(self): # get auth token auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): # mark the token as blacklisted blacklist_token = BlacklistToken(token=auth_token) try: # insert the token db.session.add(blacklist_token) db.session.commit() responseObject = { 'status': 'success', 'message': 'Successfully logged out.' } return make_response(jsonify(responseObject), 200) except Exception as e: responseObject = {'status': 'fail', 'message': e} return make_response(jsonify(responseObject), 200) else: responseObject = {'status': 'fail', 'message': resp} return make_response(jsonify(responseObject), 401) else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject), 403)
def test_register(self): request_data = { "username": "******", "first_name": "first_name", "last_name": "last_name", "email": "*****@*****.**", "password": "******", "role": "role" } user_serializer = UserCreateSerializer(data=request_data) if user_serializer.is_valid(): pass else: message = '' for error in user_serializer.errors.values(): message += " " message += error[0] print(message) user = User(username=request_data.get('username'), first_name=request_data.get('first_name'), last_name=request_data.get('last_name'), email=request_data.get('email'), password=request_data.get('password'), role=request_data.get('role')) assert request_data.get('username') == user_serializer.data.get( 'username') assert request_data.get('first_name') == user_serializer.data.get( 'first_name') assert request_data.get('last_name') == user_serializer.data.get( 'last_name') assert request_data.get('email') == user_serializer.data.get('email') assert request_data.get('role') == user_serializer.data.get('role')
def submit(self, request, params={}): duplicat = self.get_service().get_login_id(self.form["login_id"]) if (duplicat.count() > 0): self.form["error"] = True self.form[ "message"] = "User is already exist, Please register with another mail id" res = render(request, self.get_template(), {"form": self.form}) else: user = request.session.get("user", None) emsg = EmailMessage() emsg.to = [self.form["login_id"]] e = {} e["login"] = self.form["login_id"] e["password"] = self.form["password"] emsg.subject = "ORS Registration Successful" mailResponse = EmailService.send(emsg, "signUp", e) if (mailResponse == 1): r = self.form_to_model(User()) self.get_service().save(r) self.form["id"] = r.id self.form["error"] = False self.form["message"] = "You have registered successfully" res = render(request, self.get_template(), {"form": self.form}) else: self.form["error"] = True self.form["message"] = "Please Check Your Internet Connection" res = render(request, self.get_template(), {"form": self.form}) return res
def save(self, request, params={}): json_request = json.loads(request.body) self.request_to_form(json_request) res = {} if (self.input_validation()): res["error"] = True res["message"] = "" else: emsg = EmailMessage() emsg.to = [self.form["login_id"]] e = {} e["login"] = self.form["login_id"] e["password"] = self.form["password"] emsg.subject = "ORS Registration Successful" mailResponse = EmailService.send(emsg, "signUp", e) r = self.form_to_model(User(), json_request) service = UserService() c = service.save(r) res = {} if (mailResponse == 1): res["data"] = r.to_json() res["error"] = False res["message"] = "Data is Successfully saved" else: res["error"] = True res["message"] = "Data is not saved" return JsonResponse({"form": self.form, "data": res})
def submit(self, request, params={}): r = self.form_to_model(User()) self.get_service().save(r) self.form["id"] = r.id self.form["error"] = False self.form["message"] = "Data is saved" res = render(request, self.get_template(), {"form": self.form}) return res
def register_check_arena(request): username = request.POST['username'] user_first_name = request.POST['user_first_name'] user_last_name = request.POST['user_last_name'] user_phone = request.POST['user_phone'] user_dob = request.POST['user_dob'] password = request.POST['password'] repassword = request.POST['repassword'] if username is None or \ user_first_name is None or \ user_last_name is None or \ user_phone is None or \ user_dob is None or \ password is None or \ password != repassword: message = "The password should be same in both the fields" alert_type = "danger" request.session['alert_message'] = message request.session['alert_type'] = alert_type return HttpResponseRedirect(reverse('service:register')) try: get_object_or_404(UserModel, username=username) except Http404: pass else: message = "User ID already present" alert_type = "danger" request.session['alert_message'] = message request.session['alert_type'] = alert_type return HttpResponseRedirect(reverse('service:register')) User.objects.create_user(username, password) user = UserModel(username=username, user_first_name=user_first_name, user_last_name=user_last_name, user_phone=user_phone, user_dob=user_dob) user.save() message = " ".join([user_first_name, user_last_name, "registered successfully"]) alert_type = "success" request.session['alert_message'] = message request.session['alert_type'] = alert_type return HttpResponseRedirect(reverse('service:main_home'))
def test_activate_user_previously_activated_with_valid_data(self): user = User(first_name='Paco', last_name='Murcia', phone_number='415-694-7777', email='*****@*****.**', address='55 Main St.', password='') user.save() user_id = user.id data = { 'activation_code': user.activation_code, 'password': '******' } url = reverse('user-activate', kwargs={'pk': user_id}) response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_register_check_with_duplicate_id(self): """ Checking register check :return: """ client = Client() create_user() user = User(username=context.get('username'), user_first_name=context.get('user_first_name'), user_last_name=context.get('user_last_name'), user_phone=context.get('user_phone'), user_dob=context.get('user_dob')) user.save() response = client.post(reverse('service:register_check'), context, follow=True) self.assertEqual(response.status_code, 200) # Testing redirection redirect_chain = list() redirect_chain.append(("/register/", 302)) self.assertEqual(response.redirect_chain, redirect_chain) # Test if user is created in models try: get_object_or_404(User, username=context.get('username')) except Http404: raise Http404 user.delete() user = authenticate(username=context.get('username'), password=context.get('password')) self.assertEqual(user.is_active, True)
def create_and_save_model(username, first_name="", last_name="", phone="", dob=""): """ Creates and saves new user for the database :param username: :param first_name: :param last_name: :param phone: :param dob: :return: True if new user created or already present else false """ if not username or not username.strip(): raise ValueError("User model cannot be created. Parameter missing.") if UserAdapter.exists(username=username): raise ValueError("User Model already present") else: user = User(username=username, user_first_name=first_name, user_last_name=last_name, user_phone=phone, user_dob=dob) user.save() return user
def reset_password(token): if current_user.is_authenticated: return redirect(url_for('main.index')) user = User.verify_reset_password_token(token) if not user: return redirect(url_for('main.index')) form = ResetPasswordForm() if form.validate_on_submit(): user.set_password(form.password.data) db.session.commit() flash('Your password has been reset.') return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form)
def setUpClass(cls): # create user and set user_id with app.apictx.dbsession_scope() as dbs: user = dbs.query(User).filter_by(username='******').first() if user != None: dbs.delete(user) dbs.commit() rdata = {"username": "******"} dbs = app.apictx.dbsession() user = User(**rdata) dbs.add(user) dbs.commit() cls.user_id = user.id
def test_duplicate_user_email_error(self): user1 = User(first_name='Paula', last_name='Rubio', phone_number='415-694-8888', email='*****@*****.**', address='55 Main St.', password='') user1.save() url = reverse('user-list') data = { 'first_name': 'Paco', 'last_name': 'Murcia', 'phone_number': '415-694-7777', 'email': '*****@*****.**', 'address': '55 Main St.', 'password': '' } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def post(self): # get the post data post_data = request.get_json() # check if user already exists user = User.query.filter_by(username=post_data.get('username')).first() # return make_response(jsonify({'foo': 'bar'}), 200) if not user: try: user = User(username=post_data.get('username'), password=post_data.get('password')) # insert the user db.session.add(user) db.session.commit() # generate the auth token auth_token = user.encode_auth_token(user.id) print(auth_token) responseObject = { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() } return make_response(jsonify(responseObject), 201) except Exception as e: responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return make_response(jsonify(responseObject), 401) else: responseObject = { 'status': 'fail', 'message': 'User already exists. Please Log in.', } return make_response(jsonify(responseObject), 202)
def save(self, request, params={}): json_request = json.loads(request.body) r = self.form_to_model(User(), json_request) service = UserService() c = service.save(r) res = {} if (r != None): res["data"] = r.to_json() res["error"] = False res["message"] = "Data is Successfully saved" else: res["error"] = True res["message"] = "Data is not saved" return JsonResponse({"data": res})
def register(): udata = {} # required paramters # also check limit udata = simpleValidate(request.form, User, \ ('username', 'password', 'first_name', 'last_name', 'email')) emailValidate(udata['email']) # check username availability with app.apictx.dbsession_scope() as dbs: if dbs.query(User).filter_by(username=udata['username']).count() > 0: raise HttpInputError("Username is not available!") salt = bcrypt.gensalt() udata['password'] = bcrypt.hashpw(udata['password'].encode('UTF-8'), salt).decode('UTF-8') user = User(**udata) dbs.add(user) return apiresponse({}) # no need to send id
def test_populated_user_list(self): user1 = User(first_name='Paula', last_name='Rubio', phone_number='415-694-8888', email='*****@*****.**', address='55 Main St.', password='') user1.save() user2 = User(first_name='Paco', last_name='Murcia', phone_number='415-694-7777', email='*****@*****.**', address='55 Main St.', password='') user2.save() url = reverse('user-list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(User.objects.count(), len(response.data))
def get(self): # get the auth token auth_header = request.headers.get('Authorization') if auth_header: try: auth_token = auth_header.split(" ")[1] except IndexError: responseObject = { 'status': 'fail', 'message': 'Bearer token malformed.' } return make_response(jsonify(responseObject), 401) else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): user = User.query.filter_by(id=resp).first() # note this information is not stored in the token, # (the token is used to access the db and fetch this information) responseObject = { 'status': 'success', 'data': { 'user_id': user.id, 'username': user.username, 'admin': user.admin, 'registered_on': user.registered_on } } return make_response(jsonify(responseObject), 200) responseObject = {'status': 'fail', 'message': resp} return make_response(jsonify(responseObject), 401) else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject), 401)
username = sys.argv[1] existing_users = User.query.filter_by(username=username) if existing_users.count() > 0: print "User with name {} already exists".format(username) sys.exit() sid = 'US' + random_uuid() auth_token = random_string() hashed_token = generate_password_hash(auth_token) user = User(username=username, user_sid=sid, hashed_token=hashed_token, date_created=datetime.now(), date_updated=datetime.now()) # creating DB session via Flask app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) db.session.add(user) db.session.commit() db.session.close() print "Created user {}:".format(username) print "curl -u {}:{} -XPOST http://127.0.0.1:5000/users/{}/tweets -d body='Hello, World!'".format(
def get_current_user(): if session.get('user'): return User.get(User.id == session['user']) else: return None
def signup(func_id=2): ''' Registers a user. Returns: 200 -> the user has been registered successfully ''' params = request.get_json() if len(params) > 6: return errors.response(f'{BP_ID}{func_id}1') if not all(x in params for x in ['email', 'username', 'password']): return errors.response(f'{BP_ID}{func_id}2') new_user = User() err_code = None for k in params: if k == 'username': username = params[k] if 5 <= len(username) <= 25 and re.search(r'^\w+$', username): new_user.username = username else: err_code = 3 break elif k == 'email': email = params[k] if re.search(r'^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$', email): new_user.email = email else: err_code = 4 break elif k == 'password': password = params[k] if 8 <= len(password) <= 64: new_user.set_password(password) else: err_code = 5 break elif k == 'firstname': firstname = params[k] if len(firstname) <= 64: new_user.firstname = firstname else: err_code = 6 break elif k == 'lastname': lastname = params[k] if len(lastname) <= 64: new_user.lastname = lastname else: err_code = 6 break elif k == 'dateofbirth': try: new_user.dateofbirth = dt.datetime.strptime( params[k], f'%Y-%m-%d') except ValueError: err_code = 7 break else: err_code = 8 break if err_code is not None: return errors.response(f'{BP_ID}{func_id}{err_code}') db.session.add(new_user) try: db.session.commit() except IntegrityError as e: db.session.rollback() print(e) if 'user.username' in str(e): return errors.response(f'{BP_ID}{func_id}9U') if 'user.email' in str(e): return errors.response(f'{BP_ID}{func_id}9E') return jsonify({}), 200
def replay_logs(): """ Provides the ability to bring an instance database to a known state[POST data] POST_Data: { "logs":[ {...ActivityLog data...}, {...ActivityLog data...} ] } """ data = request.get_json() or {} if 'logs' not in data: return error_response(400, 'Logs key not present') logs = data['logs'] # if logs are empty then wipe all the data if logs == []: User.query.delete() ActivityLog.query.delete() db.session.commit() else: # validate if data sent is in right format v = Validator(log_schema) invalid_logs = [v.errors for log in logs if not v.validate(log)] if invalid_logs: # if any data is invalid then throw 400 return error_response(400, invalid_logs) for log in logs: user_data = log['attributes'] user = User.query.get(user_data['id']) # create user if log['action'] == 'create': if user: return error_response(400, 'User with ID: {} already exist'.format(user_data['id'])) user = User() user.id = user_data['id'] user = get_user_instance(user, user_data) db.session.add(user) # update user elif log['action'] == 'update': if not user: return error_response(404, 'User with ID: {} does not exist'.format(user_data['id'])) user = get_user_instance(user, user_data) elif log['action'] == 'delete': if not user: return error_response(404, 'User with ID: {} does not exist'.format(user_data['id'])) db.session.delete(user) al = ActivityLog.query.get(log['id']) if al: return error_response(400, 'ActivityLog with ID: {} already exist'.format(user_data['id'])) else: # create activity log al = ActivityLog() db.session.add(activity_log_instance(al, log)) db.session.commit() response = jsonify() response.status_code = 204 return response
def post(self): # extract the auth token auth_header = request.headers.get('Authorization') if auth_header: try: auth_token = auth_header.split(" ")[1] except IndexError: responseObject = { 'status': 'fail', 'message': 'Bearer token malformed.' } return make_response(jsonify(responseObject), 401) else: auth_token = '' if auth_token: resp = Organisation.decode_auth_token(auth_token) if not isinstance(resp, str): user_id = resp organisation = Organisation.query.first() # create the counter if we need to if organisation is None: organisation = Organisation( name=DEFAULT_ORGANISATION_NAME, credit=DEFAULT_ORGANISATION_CREDIT) # create the user if we need to user = db.session.query(User).filter_by(id=user_id).first() if user is None: user = User(organisation=organisation, credit=DEFAULT_USER_CREDIT) if organisation.credit < 1 or user.credit < 1: responseObject = { 'status': 'error', 'message': 'insufficient organisation credit remaining', 'organisation': { 'name': organisation.name, 'tally': organisation.tally, 'credit': organisation.credit }, 'user': { 'id': user_id, 'credit': user.credit, 'tally': user.tally, } } return make_response(jsonify(responseObject), 200) else: # decrement credit organisation.credit = organisation.credit - 1 user.credit = user.credit - 1 # increment tally organisation.tally = organisation.tally + 1 user.tally = user.tally + 1 db.session.add(organisation) db.session.add(user) db.session.commit() # TODO re-query to check persistence of updated fields responseObject = { 'status': 'success', 'message': 'updated tally', 'organisation': { 'name': organisation.name, 'tally': organisation.tally, 'credit': organisation.credit }, 'user': { 'id': user_id, 'credit': user.credit, 'tally': user.tally, } } return make_response(jsonify(responseObject), 200) responseObject = {'status': 'fail', 'message': resp} return make_response(jsonify(responseObject), 401) else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject), 401)
def add_users(self, names): for name in names: db.session.add(User(name=name))
def submit(self, request, params={}): if params['id'] > 0: pk = params['id'] dup = self.get_service().get_model().objects.exclude(id=pk).filter( login_id=self.form["login_id"]) if dup.count() > 0: self.form["error"] = True self.form['message'] = "Email Id is already exists" res = render(request, self.get_template(), {"form": self.form}) else: emsg = EmailMessage() emsg.to = [self.form["login_id"]] e = {} e["login"] = self.form["login_id"] e["password"] = self.form["password"] e["firstName"] = self.form["firstName"] e["lastName"] = self.form["lastName"] emsg.subject = "ORS Updated Successful" mailResponse = EmailService.send(emsg, "updateprofile", e) if (mailResponse == 1): r = self.form_to_model(User()) self.get_service().save(r) self.form["id"] = r.id self.form["error"] = False self.form["message"] = "You have Updated successfully" res = render(request, self.get_template(), {"form": self.form}) else: self.form["error"] = True self.form[ "message"] = "Please Check Your Internet Connection" res = render(request, self.get_template(), {"form": self.form}) return res else: duplicate = self.get_service().get_login_id(self.form["login_id"]) if (duplicate.count() > 0): self.form["error"] = True self.form["message"] = "Email Id is already exists" res = render(request, self.get_template(), {"form": self.form}) else: user = request.session.get("user", None) emsg = EmailMessage() emsg.to = [self.form["login_id"]] e = {} e["login"] = self.form["login_id"] e["password"] = self.form["password"] emsg.subject = "ORS Registration Successful" mailResponse = EmailService.send(emsg, "signUp", e) if (mailResponse == 1): r = self.form_to_model(User()) self.get_service().save(r) self.form["id"] = r.id self.form["error"] = False self.form["message"] = "You have registered successfully" res = render(request, self.get_template(), {"form": self.form}) else: self.form["error"] = True self.form[ "message"] = "Please Check Your Internet Connection" res = render(request, self.get_template(), {"form": self.form}) return res
def _check_credentials(username: str, password: str) -> bool: """ Verifies given username and password for DB user """ user = User(username) return user.verify_password(password) and user.is_admin
def _init_database(db): ''' Initializes the database for testing. ''' example1 = User() example1.username = '******' example1.firstname = 'First1' example1.lastname = 'Last1' example1.email = '*****@*****.**' example1.dateofbirth = datetime.datetime(2020, 10, 5) example1.is_admin = False example1.set_password('test1123') db.session.add(example1) example2 = User() example2.username = '******' example2.firstname = 'First2' example2.lastname = 'Last2' example2.email = '*****@*****.**' example2.dateofbirth = datetime.datetime(2020, 10, 5) example2.is_admin = False example2.set_password('test2123') db.session.add(example2) example3 = User() example3.username = '******' example3.firstname = 'First3' example3.lastname = 'Last3' example3.email = '*****@*****.**' example3.dateofbirth = datetime.datetime(2020, 10, 5) example3.is_admin = False example3.set_password('test3123') db.session.add(example3) db.session.commit()