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 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 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()
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)
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 _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