Example #1
0
def logout():
    if current_user:
        current_user.save()
    resp = make_response(redirect(url_for("users.login")))
    unset_access_cookies(resp)
    unset_refresh_cookies(resp)
    return resp
Example #2
0
 def post(self, uuid):
     args = parser.parse_args(strict=True)
     project = Project.query.filter_by(uuid=uuid).first_or_404()
     project.comments.append(ProjectComment(**args,
                                            user_id=current_user.id))
     current_user.save(**args)
     return schema.dump(project.comments, many=True), 201
Example #3
0
def edit_employee():
    try:
        kwargs = request.body_params.dict()

        current_user.first_name = kwargs.get(
            "first_name") or current_user.first_name
        current_user.last_name = kwargs.get(
            "last_name") or current_user.last_name
        current_user.telephone = kwargs.get(
            "telephone") or current_user.telephone
        current_user.city = kwargs.get("city") or current_user.city
        current_user.country = kwargs.get("country") or current_user.country

        current_user.save()

        services = current_user.services.all()

        user_dto = EmployeeRepUser.from_orm(current_user).dict()
        services_dto = [
            EmployeeRepServices.from_orm(service).dict()
            for service in services
        ]

        return jsonify(employee={
            "user": user_dto,
            "services": services_dto
        }), 200

    except Exception as e:
        print(e)
        return jsonify(error="Employee edit error"), 500
 def post(self):
     if current_user.role == 'CLIENT':
         parser.remove_argument('status')
         args = parser.parse_args(strict=True)
         if current_user.projects.filter_by(name=args.name).first():
             return {'message': 'Please project name already exist'}, 400
         current_user.projects.append(Project(**args))
         args.update({'due_date': str(args.due_date)})
         return current_user.save(**args), 201
     parser.add_argument('start_date',
                         required=True,
                         location='json',
                         type=inputs.date_from_iso8601)
     parser.add_argument('teams', required=True, type=list, location='json')
     args = parser.parse_args(strict=True)
     # args.update({'start_date': str(args.start_date)})
     # args.update({'due_date': str(args.due_date)})
     collection = []
     for team in args.teams:
         collection.append(Team.query.get(team))
     args.pop('teams')
     proj = Project(**args)
     proj.project_team = collection
     current_user.projects.append(proj)
     current_user.save(**args)
     return schema.dump(proj), 201
 def post(self):
     """Update current user's info"""
     data = request.json
     try:
         current_user.name = data['name']
         current_user.tempo = data['tempo']
         current_user.save()
     except KeyError as e:
         return marshal({"msg": f'{e.args[0]} is a required parameter'},
                        models.error), 400
     return marshal(current_user, models.user), 200
Example #6
0
 def post(self):
     args = user_avatar_parser.parse_args()
     print(args)
     avatar = args["avatar"]
     avatar.filename = "{}.{}.{}".format(
         '.'.join(avatar.filename.split('.')[:-1]),
         binascii.b2a_hex(os.urandom(4)).decode(),
         avatar.filename.split('.')[-1])
     current_user.avatar.save(avatar)
     current_user.save()
     return {
         "message": "User profile avatar was successfully uploaded"
     }, 201
Example #7
0
 def put(self):
     data = parser.parse_args()
     resp = jsonify({'message': 'User was edited successfully'})
     if data['email'] != '':
         current_user.email = data['email']
     if data['password'] != '':
         current_user.password = User.encrypt_password(data['password'])
         access_token = create_access_token(identity=data['username'])
         refresh_token = create_refresh_token(identity=data['username'])
         set_access_cookies(resp, access_token)
         set_refresh_cookies(resp, refresh_token)
     current_user.save()
     return resp
Example #8
0
def update_profile():
    try:
        kwargs = request.body_params.dict()

        current_user.first_name = kwargs.get("first_name") or current_user.first_name
        current_user.last_name = kwargs.get("last_name") or current_user.last_name
        current_user.telephone = kwargs.get("telephone") or current_user.telephone
        current_user.country = kwargs.get("country") or current_user.country
        current_user.city = kwargs.get("city") or current_user.city
        current_user.street = kwargs.get("street") or current_user.street
        current_user.is_active = True

        current_user.save()

        customer_dto = CustomerSchema.from_orm(current_user).dict()

        return jsonify(customer=customer_dto), 200
    except Exception as e:
        return jsonify(error="Customer profile update error"), 500
 def post(self):
     """Add new push subscription to current user"""
     data = request.json
     if current_user.push_subscriptions.count(data) == 0:
         current_user.push_subscriptions.append(data)
         push_message = PushNotification(
             title='Upozornenia fungujú!',
             body='Ďakujeme za povolenie upozornení.').to_dict()
         try:
             pywebpush.webpush(subscription_info=data,
                               data=json.dumps(push_message),
                               vapid_private_key=VAPID_PRIVATE_KEY,
                               vapid_claims={'sub': VAPID_CLAIMS_SUB},
                               headers=PUSH_HEADERS)
         except pywebpush.WebPushException as e:
             return marshal({'msg': e.message}, models.error), 400
     else:
         return 'Push subscription already registered', 204
     current_user.save()
     return 'OK', 200
Example #10
0
def settings(message : OptionSet):
	print(current_user)
	if not current_user:
		raise APIRedirectingException(redirect="users.login", displayMessage={"message" : "You must first login to view this page"}, actionLabel="Login")
	account = Account.get({"user" : ObjectId(current_user._id)})
	if request.method == "GET":
		return render_template("account/pages/settings.html", user=current_user, info=account)
	if request.method == "POST":
		message.validate()
		if not message.valid:
			raise message.errorMessage
		k, v = message.setting
		if k == "gender" or k == "interest" or k == "lname" or k == "fname" or k == "biography":
			setattr(account, k, v)
			account.save()
		elif k == "uname":
			current_user.uname = v
			current_user.save()
		elif k == "password":
			current_user.password = generate_password_hash(v)
			current_user.save()
		elif k == "email":
			current_user.verified = False
			current_user.email = v
			create_token(current_user, Callback("verify_email", module="app.users", cls="User"))
			current_user.save()
		elif k == "tags":
			if not isinstance(v, list):
				raise APIException(message="Tags can only be submitted as an array")
			things = [x.lower() for x in v]
			setattr(account, k, list(set(things)))
			account.save()
		elif k == "image":
			if len(account.images) < 5:
				account.images.append(v)
				account.save()
			return APISuccessMessage(displayMessage={"message" : "Image uploaded"}, update={"action" : "insert","subject" : ".options", "before" : ".usr_img.add", "fn" : "userImage", "data" : {
				"src" : url_for("accounts.user_image", uid=current_user._id, id=len(account.images) - 1),
				"image_id" : len(account.images) - 1
				}}).messageSend()
		return "OK"
    def put(self, option):
        profile_parser = RequestParser(trim=True, bundle_errors=True)
        if option == 'general':
            profile_parser.add_argument('username',
                                        required=True,
                                        type=string,
                                        location='json')
            profile_parser.add_argument('full_name',
                                        required=True,
                                        type=string,
                                        location='json')
            profile_parser.add_argument('gender',
                                        required=True,
                                        type=str,
                                        choices=['Male', 'Female', 'Others'],
                                        help='Gender is required',
                                        location='json')
            args = profile_parser.parse_args(strict=True)
            if User.query.filter(User.username == args.username,
                                 User.id != current_user.id).first():
                return {
                    'message':
                    'Username already exist, please use different one'
                }, 400
            current_user.full_name = args.full_name
            current_user.gender = args.gender
            return current_user.save(**args)

        if option == 'pwd':
            profile_parser.add_argument('old_pwd',
                                        required=True,
                                        type=str,
                                        location='json')
            profile_parser.add_argument(
                'new_pwd',
                type=inputs.regex('[A-Za-z0-9@#$%^&+=]{8,}'),
                required=True,
                location='json',
                help='Password must have a minimum of eight characters.')
            profile_parser.add_argument(
                'confirm_pwd',
                type=inputs.regex('[A-Za-z0-9@#$%^&+=]{8,}'),
                required=True,
                location='json',
                help='Password must have a minimum of eight characters.')
            args = profile_parser.parse_args(strict=True)
            if not bcrypt.check_password_hash(current_user.password,
                                              args.old_pwd):
                return {
                    'message': 'Old password doesnt match current password'
                }, 400
            if not safe_str_cmp(args.confirm_pwd, args.new_pwd):
                return {"message": 'passwords dont match'}
            current_user.password = bcrypt.generate_password_hash(
                args.new_pwd).decode()
            current_user.save()
            send_mail_rq.queue('Your password was changed!',
                               [current_user.email], 'Password Changed')
            return {'message': 'Your password has been updated successfully'}
        if option == 'email':
            profile_parser.add_argument('pwd',
                                        required=True,
                                        type=str,
                                        location='json')
            profile_parser.add_argument('old_email',
                                        required=True,
                                        type=inputs.email(),
                                        help='Email address is required',
                                        location='json')
            profile_parser.add_argument('new_email',
                                        required=True,
                                        type=inputs.email(),
                                        help='Email address is required',
                                        location='json')
            args = profile_parser.parse_args(strict=True)
            if not bcrypt.check_password_hash(current_user.password, args.pwd):
                return abort(401)
            token = current_user.create_token(
                payload={'email': args.new_email})
            url = url_for('api.auth_change_email', token=token, _external=True)
            send_mail_rq.queue(
                CHANGE_EMAIL.format(name=current_user.full_name, url=url),
                [args.new_email], 'Change Email')
            return {'message': 'Email has been sent'}
        if option == 'img':
            profile_parser.add_argument(
                'files',
                required=True,
                location='files',
                type=werkzeug.datastructures.FileStorage)
            args = profile_parser.parse_args(strict=True)
            file = img_upload(args.file)
            if file.get('message'):
                return file, 400
            current_user.img = file.get('filename')
            file.get('upload').save(file.get('full_path'))
            return current_user.save(filename=current_user.img), 201
        return abort(404)
Example #12
0
def create_checkout():
    try:


        # TODO: create booking in different thread
        kwargs = request.body_params.dict()

        booking_dto = kwargs.get("booking")
        booking_contact_dto = kwargs.get("booking_contact")
        schedules = kwargs.get("schedules")
        coupon_code = booking_dto.get("coupon_code")
        booking_dto.pop("coupon_code")

        service = ServiceModel.get_service_and_status(booking_dto.get("service_id"))
        if service is None:
            return jsonify(error=" Service not found or no longer active"), 400

        checkout_session = stripe.checkout.Session.create(
            payment_method_types=['card'],
            line_items=[
                {
                    'price_data': {
                        'currency': 'usd',
                        'unit_amount': booking_dto.get("price") * 100,  # Converts to cents so multiply by 100
                        'product_data': {
                            'name': service.name,
                            'description': service.description,

                        },
                    },
                    'quantity': 1
                },
            ],
            mode='payment',
            customer_email=current_user.email,
            customer=current_user.payment_gateway_id,
            client_reference_id=current_user.id,
            discounts=[{
                'coupon': coupon_code,
            }],
            allow_promotion_codes=True,
            success_url=current_app.config.get("FRONTEND_URL") + '/success',
            cancel_url=current_app.config.get("FRONTEND_URL") + '/canceled',
        )

        booking = BookingModel(**booking_dto, customer_id=current_user.id)
        booking.save()

        payment = PaymentModel(stripe_id=checkout_session.id, currency=checkout_session.currency,
                               customer_id=current_user.id,
                               coupon_code=coupon_code,
                               amount_subtotal=checkout_session.amount_subtotal,
                               amount_total=checkout_session.amount_total,
                               booking_id=booking.id,
                               payment_method=checkout_session.payment_method_types[0])

        booking_contact = BookingContactModel(**booking_contact_dto, booking_id=booking.id)

        current_user.payment_gateway_id = checkout_session.customer

        db.session.add(payment)
        db.session.add(booking_contact)
        current_user.save()

        TimeSheetModel.populate_schedules(schedules, booking.id, booking_dto.get("employee_id"), booking_dto.get(
            "service_id"))

        return jsonify(id=checkout_session.id), 200
    except Exception as e:
        print(e)
        print(str(e))
        return jsonify(error="Booking error"), 500
Example #13
0
 def delete(self):
     """Disable email notifications for user"""
     current_user.email_notifications = False
     current_user.save()
     return 'OK', 200
Example #14
0
 def post(self):
     """Enable email notifications for user"""
     current_user.email_notifications = True
     current_user.save()
     return 'OK', 200