def create_user_account(self, email, first_name="", last_name="", sns=False): # opinion: front-end should validate email format user = Users(email=email, first_name=first_name, last_name=last_name) if sns: user.confirmed = True else: # set up account confirmation steps self.create_account_token(user) user.save() return user
async def store(request: Request) -> JSONResponse: try: body = await request.json() name = body['name'] if name == "": raise Exception("name couldn't be empty!") user = Users(name=name) user.save() transformer = UserTransformer.singleTransform(user) return response.ok(transformer, "Berhasil Membuat User!") except Exception as e: return response.badRequest('', f'{e}')
def accept_invite(token): try: invited_user = InvitedUser.from_token(token) except InviteTokenError as exception: flash(_(str(exception))) return redirect(url_for("main.sign_in")) if not current_user.is_anonymous and current_user.email_address.lower() != invited_user.email_address.lower(): message = Markup( _( "You’re signed in as %(email)s. This invite is for another email address. " + "<a href=%(href)s>Sign out</a> and click the link again to accept this invite.", email=current_user.email_address, href=url_for("main.sign_out", _external=True), ) ) flash(message=message) abort(403) if invited_user.status == "cancelled": service = Service.from_id(invited_user.service) return render_template( "views/cancelled-invitation.html", from_user=invited_user.from_user.name, service_name=service.name, ) if invited_user.status == "accepted": session.pop("invited_user", None) return redirect(url_for("main.service_dashboard", service_id=invited_user.service)) session["invited_user"] = invited_user.serialize() existing_user = User.from_email_address_or_none(invited_user.email_address) if existing_user: invited_user.accept_invite() if existing_user in Users(invited_user.service): return redirect(url_for("main.service_dashboard", service_id=invited_user.service)) else: service = Service.from_id(invited_user.service) # if the service you're being added to can modify auth type, then check if this is relevant if service.has_permission("email_auth") and ( # they have a phone number, we want them to start using it. if they dont have a mobile we just # ignore that option of the invite (existing_user.mobile_number and invited_user.auth_type == "sms_auth") or # we want them to start sending emails. it's always valid, so lets always update invited_user.auth_type == "email_auth" ): existing_user.update(auth_type=invited_user.auth_type) existing_user.add_to_service( service_id=invited_user.service, permissions=invited_user.permissions, folder_permissions=invited_user.folder_permissions, ) return redirect(url_for("main.service_dashboard", service_id=service.id)) else: return redirect(url_for("main.register_from_invite"))
def process_resource(self, req, resp, resource, params): """ Middleware Request """ try: message_data = req.context['request'] reply = SkypeAPI() try: print('message data', message_data) user = Users.get(user_id=message_data['from']['id'][3:]) print('User', user) if user.is_active is True: message_data['user'] = user else: self.registerUser(message_data, reply) message_data['user'] = None except BaseException: print('Inside user except') self.registerUser(message_data, reply) message_data['user'] = None req.context['request'] = message_data except BaseException: print('Inside user base exception') req.context['request'] = {}
async def index(request: Request) -> JSONResponse: try: users = Users.objects() transformer = UserTransformer.transform(users) return response.ok(transformer, "") except Exception as e: return response.badRequest('', f'{e}')
def test_insert_user(self): name = "Hudya" response = client.post("/users", json={"name": name}) assert response.status_code == 200 user = Users.objects(name=name).first() assert user.name == name
def create_user(req_json): new_user = Users(username=req_json['username'], email=req_json['email'], password_hash=bcrypt.generate_password_hash( req_json['password']).decode('utf-8')) db.session.add(new_user) db.session.commit() return new_user
def accept_invite(token): invited_user = InvitedUser.from_token(token) if not current_user.is_anonymous and current_user.email_address.lower( ) != invited_user.email_address.lower(): message = Markup(""" You’re signed in as {}. This invite is for another email address. <a href={} class="govuk-link govuk-link--no-visited-state">Sign out</a> and click the link again to accept this invite. """.format(current_user.email_address, url_for("main.sign_out", _external=True))) flash(message=message) abort(403) if invited_user.status == 'cancelled': service = Service.from_id(invited_user.service) return render_template('views/cancelled-invitation.html', from_user=invited_user.from_user.name, service_name=service.name) if invited_user.status == 'accepted': session.pop('invited_user', None) return redirect( url_for('main.service_dashboard', service_id=invited_user.service)) session['invited_user'] = invited_user.serialize() existing_user = User.from_email_address_or_none(invited_user.email_address) if existing_user: invited_user.accept_invite() if existing_user in Users(invited_user.service): return redirect( url_for('main.service_dashboard', service_id=invited_user.service)) else: service = Service.from_id(invited_user.service) # if the service you're being added to can modify auth type, then check if this is relevant if service.has_permission('email_auth') and ( # they have a phone number, we want them to start using it. if they dont have a mobile we just # ignore that option of the invite (existing_user.mobile_number and invited_user.auth_type == 'sms_auth') or # we want them to start sending emails. it's always valid, so lets always update invited_user.auth_type == 'email_auth'): existing_user.update(auth_type=invited_user.auth_type) existing_user.add_to_service( service_id=invited_user.service, permissions=invited_user.permissions, folder_permissions=invited_user.folder_permissions, ) return redirect( url_for('main.service_dashboard', service_id=service.id)) else: return redirect(url_for('main.register_from_invite'))
def test_insert_user_with_long_name(self): name = "SngQ8CL1kqtowD4rl1kYrWG2WmLhvB6HQ7exaY3a5fFkG6LPBn4s" \ "Gtc5HZw7QHiQtsLKrAX7G7wBPp5of6utYDeTLllNPMJfE1m" response = client.post("/users", json={"name": name}) assert response.status_code == 200 user = Users.objects(name=name).first() assert user.name == name
def test_delete_user_wrong_id(self): name = "Hudya" response = client.post("/users", json={"name": name}) res = response.text res = json.loads(res) id = res['values']['id'] fake_id = str(ObjectId()) response = client.delete(f"/users/{fake_id}") assert response.status_code == 400 user = Users.objects(id=id).first() assert user.name == name user = Users.objects(id=fake_id).first() assert user is None
def post(self): parser = reqparse.RequestParser() parser.add_argument('email', help='Please provide us with your email address', required=True) parser.add_argument('password', help='Please provide us with a password', required=True) data = parser.parse_args() # Fetch the user details try: current_user = Users.join('roles', 'roles.id', '=', 'users.role_id') \ .where('email', data['email']).select('users.*', 'roles.role_code').first() if current_user is None: response = jsonify({ 'status': 'Fail', 'message': 'The user does not exist in the system' }) response.status_code = status.HTTP_200_OK return response if flask_bcrypt.check_password_hash(current_user.password, data['password']): expires = datetime.timedelta(days=60) access_token = create_access_token(identity=data['email'], expires_delta=expires) refresh_token = create_refresh_token(identity=data['email']) response = jsonify({ 'status': 'Success', 'message': 'Logged in successfully', 'access_token': access_token, 'refresh_token': refresh_token, 'data': current_user.serialize() }) response.status_code = status.HTTP_202_ACCEPTED return response else: response = jsonify({ 'status': 'Fail', 'message': 'You have entered wrong credentials combination' }) response.status_code = status.HTTP_401_UNAUTHORIZED return response except Exception as err: response = jsonify({ 'status': 'Fail', 'message': 'There was an issue with the request please contact support' ' if the issue persists.' }) response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR return response
async def show(id) -> JSONResponse: try: user = Users.objects(id=id).first() if user is None: raise Exception('user tidak ditemukan!') transformer = UserTransformer.singleTransform(user) return response.ok(transformer, "") except Exception as e: return response.badRequest('', f'{e}')
def init_database(): # Create the database and the database table db.create_all() # Insert user data user1 = Users(username='******', email='*****@*****.**', password_hash=bcrypt.generate_password_hash('blahblah').decode('utf-8')) user2 = Users(username='******', email='*****@*****.**', password_hash=bcrypt.generate_password_hash('cawcaw').decode('utf-8')) db.session.add(user1) db.session.add(user2) workout1 = Workouts( date = "1578204182.000337", user_id = 2 ) climb1 = Climbs( type = 0, grade = 6, user_id = 2, workout_id = 1 ) climb2 = Climbs( type = 0, grade = 5, user_id = 2, workout_id = 1 ) db.session.add(workout1) db.session.add(climb1) db.session.add(climb2) # Commit the changes for the users db.session.commit() yield db # this is where the testing happens! db.drop_all()
async def delete(id: str) -> JSONResponse: try: user = Users.objects(id=id).first() if user is None: raise Exception('user tidak ditemukan!') user.delete() return response.ok('', "Berhasil Menghapus User!") except Exception as e: return response.badRequest('', f'{e}')
def test_update_user_with_wrong_id(self): name = "Hudya" client.post("/users", json={"name": name}) id = str(ObjectId()) new_name = "Kiddy" response = client.put(f"/users/{id}", json={"name": new_name}) assert response.status_code == 400 user = Users.objects(id=id).first() assert user is None
def test_update_user_with_empty_name(self): name = "Hudya" response = client.post("/users", json={"name": name}) res = response.text res = json.loads(res) id = res['values']['id'] response = client.put(f"/users/{id}", json={"name": ""}) assert response.status_code == 400 user = Users.objects(id=id).first() assert user.name == name
def test_delete_user(self): name = "Hudya" response = client.post("/users", json={"name": name}) res = response.text res = json.loads(res) id = res['values']['id'] response = client.delete(f"/users/{id}") assert response.status_code == 200 user = Users.objects(id=id).first() assert user is None
def test_update_user_with_long_name(self): name = "Hudya" response = client.post("/users", json={"name": name}) res = response.text res = json.loads(res) id = res['values']['id'] new_name = "SngQ8CL1kqtowD4rl1kYrWG2WmLhvB6HQ7exaY3a5fFkG6LPBn4s" \ "Gtc5HZw7QHiQtsLKrAX7G7wBPp5of6utYDeTLllNPMJfE1m" response = client.put(f"/users/{id}", json={"name": new_name}) assert response.status_code == 200 user = Users.objects(id=id).first() assert user.name == new_name
def create_user(name, email, password): from app.models.user import Users user = Users() user.id = str(uuid4()) user.name = name user.email = email user.password = generate_password_hash(password) from app import db db.session.add(user) print(user)
def verifyOTP(self, skypedata): """ Verify OTP with of specific user """ try: pattern = '[#!@$%]{{{}}}[\d]{{{}}}[!@#$%]{{{}}}'.format(os.environ.get('OTP_SPECIAL_CHARACTERS_LIMIT'), os.environ.get('OTP_DIGITS_LIMIT'), os.environ.get('OTP_SPECIAL_CHARACTERS_LIMIT')) # finds opt from the text entered by the user using regex otp = re.findall(pattern, skypedata['text']) #otp = re.findall(r'FUJIAMAZE+[\d]+', skypedata['text']) if len(otp)==1 and (otp[0] in skypedata['text'].split()): # using split coz regex gives valid(matching regex) string from an invalid(valid regex but an incorrect otp) one too. it gives @#12345@# from string !@#12345@#$ otp_obj = OTP.get(otp=otp[0]) user = Users.get(id=otp_obj.user_id) if (user and user.user_id == skypedata['from']['id'][3:]): user.is_active = True user.save() # Make the user as active return True return False except BaseException as e: return False
def checkOTPExistance(self, skypedata, replyObj): """ Check if OTP already exists for the specific email address """ try: user = Users.get(user_id=skypedata['from']['id'][3:]) try: OTP.get(user_id=user.id) replyObj.send_reply(skypedata, "Incorrect OTP, please send the correct one.") #return True except OTP.DoesNotExist: self.otp_generated = False self.user_registered = False replyObj.send_reply(skypedata, """I think you were off for a long time and the OTP would hav been expired. Can you please provide your servicenow registered email address?""") #return False except Users.DoesNotExist: self.user_registered = False self.otp_generated = False replyObj.send_reply(skypedata, """I think you were off for a long time or would have entered a wrong email address. Can you please provide your servicenow registered email address?""")
def createUserOTP(self, user_data, skypedata, otp): """ Creates or fetches User and OTP atomically """ try: user = Users.get_or_create( name=user_data['name'], user_id=skypedata['from']['id'][3:], servicenow_id=user_data['sys_id'], is_active=False) try: otp_obj = OTP.get(user_id=user[0].id) otp_obj.otp = otp otp_obj.save() except OTP.DoesNotExist: OTP.create(user_id=user[0].id, otp=otp) return True except Exception as e: return False
async def update(id: str, request: Request) -> JSONResponse: try: body = await request.json() name = body['name'] if name == "": raise Exception("name couldn't be empty!") user = Users.objects(id=id).first() if user is None: raise Exception('user tidak ditemukan!') user.name = name user.save() transformer = UserTransformer.singleTransform(user) return response.ok(transformer, "Berhasil Mengubah User!") except Exception as e: return response.badRequest('', f'{e}')
def checkOTPExistance(self, skypedata, replyObj): """ Check if OTP already exists for the specific email address """ try: print('Inside checkORPexistance first try') user = Users.get(user_id=skypedata['from']['id'][3:]) try: print('Inside checkORPexistance seconf try') OTP.get(user_id=user.id) replyObj.send_reply(skypedata, "Incorrect OTP, please send the correct one.") except OTP.DoesNotExist: print('Inside checkORPexistance first except') self.otp_generated = False self.user_registered = False replyObj.send_reply(skypedata, """I think you were off for a long time and the OTP would hav been expired. Can you please provide your email address?""") except Users.DoesNotExist: print('Inside checkORPexistance second except') self.user_registered = False self.otp_generated = False replyObj.send_reply(skypedata, """I think you were off for a long time or would have entered a wrong email address. Can you please provide your email address?""")
def _check_messages(service_id, template_id, upload_id, preview_row, letters_as_pdf=False): try: # The happy path is that the job doesn’t already exist, so the # API will return a 404 and the client will raise HTTPError. job_api_client.get_job(service_id, upload_id) # the job exists already - so go back to the templates page # If we just return a `redirect` (302) object here, we'll get # errors when we try and unpack in the check_messages route. # Rasing a werkzeug.routing redirect means that doesn't happen. raise PermanentRedirect( url_for('.send_messages', service_id=service_id, template_id=template_id)) except HTTPError as e: if e.status_code != 404: raise statistics = service_api_client.get_service_statistics(service_id, today_only=True) remaining_messages = (current_service.message_limit - sum(stat['requested'] for stat in statistics.values())) contents = s3download(service_id, upload_id) db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template['template_type'] == 'email': email_reply_to = get_email_reply_to_address_from_session() elif db_template['template_type'] == 'sms': sms_sender = get_sms_sender_from_session() template = get_template( db_template, current_service, show_recipient=True, letter_preview_url=url_for( '.check_messages_preview', service_id=service_id, template_id=template_id, upload_id=upload_id, filetype='png', row_index=preview_row, ) if not letters_as_pdf else None, email_reply_to=email_reply_to, sms_sender=sms_sender, page_count=get_page_count_for_letter(db_template), ) recipients = RecipientCSV( contents, template_type=template.template_type, placeholders=template.placeholders, max_initial_rows_shown=50, max_errors_shown=50, whitelist=itertools.chain.from_iterable( [user.name, user.mobile_number, user.email_address] for user in Users(service_id)) if current_service.trial_mode else None, remaining_messages=remaining_messages, international_sms=current_service.has_permission('international_sms'), ) if request.args.get('from_test'): # only happens if generating a letter preview test back_link = url_for('.send_test', service_id=service_id, template_id=template.id) choose_time_form = None else: back_link = url_for('.send_messages', service_id=service_id, template_id=template.id) choose_time_form = ChooseTimeForm() if preview_row < 2: abort(404) if preview_row < len(recipients) + 2: template.values = recipients[preview_row - 2].recipient_and_personalisation elif preview_row > 2: abort(404) return dict( recipients=recipients, template=template, errors=recipients.has_errors, row_errors=get_errors_for_csv(recipients, template.template_type), count_of_recipients=len(recipients), count_of_displayed_recipients=len(list(recipients.displayed_rows)), original_file_name=request.args.get('original_file_name', ''), upload_id=upload_id, form=CsvUploadForm(), remaining_messages=remaining_messages, choose_time_form=choose_time_form, back_link=back_link, help=get_help_argument(), trying_to_send_letters_in_trial_mode=all(( current_service.trial_mode, template.template_type == 'letter', )), required_recipient_columns=OrderedSet( recipients.recipient_column_headers) - optional_address_columns, preview_row=preview_row, sent_previously=job_api_client.has_sent_previously( service_id, template.id, db_template['version'], request.args.get('original_file_name', '')))
def active_users(self): return Users(self.id)
def post(self): parser = reqparse.RequestParser() parser.add_argument('username', help='Please provide us with a username', required=True) parser.add_argument('password', help='Please provide us with a password', required=True) parser.add_argument('phone_number', help='Please provide us with your phone number', required=True) parser.add_argument('role_id', help='Please provide us with the user role', required=True) parser.add_argument('email') data = parser.parse_args() # with db.transaction(): try: users = Users() users.username = data['username'] users.email = data['email'] users.role_id = data['role_id'] users.password = flask_bcrypt.generate_password_hash( data['password']).decode('utf-8') users.phone_number = data['phone_number'] users.save() expires = datetime.timedelta(days=60) access_token = create_access_token(identity=data['phone_number'], expires_delta=expires) refresh_token = create_refresh_token(identity=data['phone_number']) response = jsonify({ 'status': 'Success', 'message': 'A new user has been created successfully', 'access_token': access_token, 'refresh_token': refresh_token }) response.status_code = status.HTTP_201_CREATED return response except Exception as e: if 'Duplicate' in str(e): response = jsonify({ 'status': 'Fail', 'message': 'The user with the provided details already exists' }) response.status_code = status.HTTP_409_CONFLICT return response else: response = jsonify({ 'status': 'Fail', 'message': 'There was an issue in trying to save the user. Please contact support at ' '*****@*****.**', }) response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR return response