コード例 #1
0
async def add_review(id: str,
                     review: ReviewModel = Body(..., embed=True),
                     identity: str = Depends(get_jwt_identity)):
    try:
        if Order.objects(orderer=identity,
                         products__product=id,
                         orderStatus__nin=['not placed',
                                           'failed']).count() == 0:
            raise UnauthorizedError
        product = Product.objects.get(id=id)
        review = Review(reviewer=identity,
                        product=id,
                        score=review.score,
                        review=review.review)
        review.save()
        product.addReview(review.score)
        product.save()
        return review.serialize()
    except UnauthorizedError:
        raise UnauthorizedError(
            detail='User has not purchased this product').http_exception
    except DoesNotExist:
        raise SchemaValidationError().http_exception
    except Exception as e:
        raise e
コード例 #2
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_users(page: Optional[int] = None,
                    size: Optional[int] = None,
                    identity: str = Depends(get_jwt_identity)):
    try:
        user = get_admin_user(identity)
        users = models.User.objects
        if page == None:
            page = 0
            size = users.count()
        elif size == None:
            raise SchemaValidationError
        return {
            'count':
            users.count(),
            'users':
            list(
                map(lambda u: u.serialize(),
                    users[page * size:page * size + size]))
        }
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError(detail='User is not admin')
    except SchemaValidationError:
        raise SchemaValidationError()
    except Exception as e:
        raise e
コード例 #3
0
ファイル: coinbase.py プロジェクト: dman926/SEPHIRA
async def webhook(payload: dict = Body(...), X_CC_Webhook_Signature: str = Header(None), User_Agent: str = Header(None)):
	try:
		if User_Agent != 'weipay-webhooks':
			raise UnauthorizedError
		try:
			event = Webhook.construct_event(dumps(payload).encode(), X_CC_Webhook_Signature, CoinbaseCommerceSettings.SHARED_SECRET)
		except (WebhookInvalidPayload, SignatureVerificationError):
			raise UnauthorizedError
		
		order = Order.objects.get(id=event.data.metadata.order)
		if event.type == 'charge:pending':
			if not order.stockRemoved:
				if price_service.remove_stock(order):
					order.orderStatus = 'placed'
					order.stockRemoved = True
				else:
					order.orderStatus = 'to refund'
		elif event.type == 'charge:confirmed':
			order.orderStatus = 'paid'
		elif event.type == 'charge:failed':
			order.orderStatus = 'failed'
			if order.stockRemoved:
				price_service.add_stock(order)
				order.stockRemoved = False
		elif event.type == 'charge:delayed':
			order.status = 'to refund'
			# TODO: send an email to the user that they payed after expiratin, that the order failed, and they will be refunded (minus transaction fees perhaps)
		order.save()
		return 'ok'
	except UnauthorizedError:
		raise UnauthorizedError().http_exception
	except Exception as e:
		raise e
コード例 #4
0
ファイル: paypal.py プロジェクト: dman926/SEPHIRA
async def webhook(payload: dict = Body(...),
                  PAYPAL_TRANSMISSION_ID: str = Header(None),
                  PAYPAL_TRANSMISSION_TIME: str = Header(None),
                  PAYPAL_TRANSMISSION_SIG: str = Header(None),
                  PAYPAL_AUTH_ALGO: str = Header(None),
                  PAYPAL_CERT_URL: str = Header(None)):
    try:
        # Verify signature
        cert = await getPayPalCert(PAYPAL_CERT_URL)
        if not cert:
            raise ServiceUnavailableError
        signature = f'{PAYPAL_TRANSMISSION_ID}|{PAYPAL_TRANSMISSION_TIME}|{PayPalSettings.WEBHOOK_ID}|{crc32(bytes(payload))}'
        cert = x509.load_pem_x509_certificate(
            cert.encode('ascii'), backend=backends.default_backend())
        public_key = cert.public_key()
        try:
            public_key.verify(PAYPAL_TRANSMISSION_SIG, signature,
                              padding.PKCS1v15(), hashes.SHA256())
        except Exception:
            raise UnauthorizedError
        # Signature verification complete

        if payload['event_type'] == 'CHECKOUT.ORDER.COMPLETED':
            pass

        return 'ok'
    except ServiceUnavailableError:
        raise ServiceUnavailableError().http_exception
    except UnauthorizedError:
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #5
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_post(post: str,
                   id: str,
                   withSchema: Optional[bool] = False,
                   identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        try:
            postType = class_name_to_class(__name__, post)
            if not is_post(postType):
                raise InvalidPostTypeError
        except Exception:
            raise InvalidPostTypeError
        obj = postType.objects.get(id=id)
        out = {'obj': obj.serialize()}
        if withSchema:
            out['schema'] = postType.schema()
        return out
    except DoesNotExist:
        raise NotFoundError()
    except InvalidPostTypeError:
        raise InvalidPostTypeError()
    except Exception as e:
        raise e
コード例 #6
0
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    try:
        if form_data.client_secret:
            user = User.objects.get(
                email=get_jwt_identity(form_data.client_secret))
        else:
            user = User.objects.get(email=form_data.username)
            if not user.check_password(form_data.password):
                raise UnauthorizedError
            if user.twoFactorEnabled:
                otp = form_data.client_id
                if not otp:
                    raise MissingOtpError
                if not user.verify_totp(otp):
                    raise UnauthorizedError
        if not user.verified:
            raise NotVerifiedError
        return {
            'access_token': create_access_token(identity=str(user.id)),
            'refresh_token': create_refresh_token(identity=str(user.id))
        }
    except (UnauthorizedError, DoesNotExist):
        sleep(2)
        raise UnauthorizedError(
            detail='Incorrect email, password, or otp').http_exception
    except MissingOtpError:
        raise MissingOtpError().http_exception
    except NotVerifiedError:
        raise NotVerifiedError().http_exception
    except Exception as e:
        raise e
コード例 #7
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_posts(post: str,
                    page: Optional[int] = None,
                    size: Optional[int] = None,
                    search: Optional[str] = None,
                    identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
        try:
            postType = class_name_to_class(__name__, post)
            if not is_post(postType):
                raise InvalidPostTypeError
        except Exception:
            raise InvalidPostTypeError
        posts = postType.objects
        if search:
            posts.search_text(search).order_by('$text_score')
        if page == None:
            page = 0
            size = posts.count()
        elif size == None:
            raise SchemaValidationError
        return {
            'count':
            posts.count(),
            'posts':
            list(
                map(lambda p: p.serialize(),
                    posts[page * size:page * size + size]))
        }
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except InvalidPostTypeError:
        raise InvalidPostTypeError()
    except Exception as e:
        raise e
コード例 #8
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def add_post(post_body: PostForm,
                   identity: str = Depends(get_jwt_identity)):
    try:
        user = get_admin_user(identity)
        try:
            postType = class_name_to_class(__name__, post_body.post)
            if not is_post(postType):
                raise InvalidPostTypeError
        except Exception:
            raise InvalidPostTypeError
        obj = postType(**post_body.obj)
        obj.author = user

        postTypeName = postType.__name__

        # Do any aditional logic here.
        # Just check with a simple `if postTypeName == POSTTYPENAME:` to see the class name coming in. Do not rely on the post variable

        obj.save()
        return obj.serialize()
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except InvalidPostTypeError:
        raise InvalidPostTypeError()
    except (FieldDoesNotExist, ValidationError, SchemaValidationError):
        raise SchemaValidationError()
    except Exception as e:
        raise e
コード例 #9
0
def login():
    users = db.userinfo
    email = request.get_json()['email']
    password = request.get_json()['password']
    result = ""

    response = users.find_one({'email': email})

    try:
        if response:
            if bcrypt.check_password_hash(response['password'], password):
                access_token = create_access_token(
                    identity={
                        'first_name': response['first_name'],
                        'last_name': response['last_name'],
                        'email': response['email'],
                        'address': response['address'],
                        'city': response['city'],
                        'country': response['country'],
                        'postal_code': response['postal_code'],
                        'about_me': response['about_me']
                    })
                result = jsonify({'token': access_token})
            else:
                raise UnauthorizedError("Invalid username or password")
        else:
            raise UserNotFoundError(
                "User with email {0} does not exist".format(email))
    except UnauthorizedError as e:
        result = jsonify({"exception": str(e)})
    except UserNotFoundError as e:
        result = jsonify({"exception": str(e)})
    except Exception as e:
        result = jsonify({"exception": str(e)})
    return result
コード例 #10
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_is_admin(identity: str = Depends(get_jwt_identity)):
    try:
        user = get_admin_user(identity)
        return user.admin
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError(detail='User is not admin')
    except Exception as e:
        raise e
コード例 #11
0
async def token_refresh2(token: Token = Depends(get_raw_token)):
    try:
        if 'refresh' not in token or not token['refresh']:
            raise UnauthorizedError
        identity = token['sub']
        User.objects.get(id=identity)  # Verify the user exists
        return {
            'access_token': create_access_token(identity=identity),
            'refresh_token': create_refresh_token(identity=identity)
        }
    except UnauthorizedError:
        raise UnauthorizedError(
            detail='Invalid token. Not a refresh token').http_exception
    except DoesNotExist:
        raise UnauthorizedError(detail='Invalid token').http_exception
    except Exception as e:
        raise e
コード例 #12
0
async def get_user(identity: str = Depends(get_jwt_identity)):
    try:
        user = User.objects.get(id=identity)
        return user.serialize()
    except DoesNotExist:
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #13
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_menu_items(identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
        return list(map(lambda m: m.serialize(), models.MenuItem.objects()))
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
コード例 #14
0
async def delete_user(identity: str = Depends(get_jwt_identity)):
    try:
        # TODO: 'archive' the user instead of deleting
        User.objects.get(id=identity).delete()
        return True
    except DoesNotExist:
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #15
0
async def verify_email(identity: str = Depends(get_jwt_identity)):
    try:
        user = User.objects.get(id=identity)
        user.verified = True
        user.save()
        return 'ok'
    except DoesNotExist:
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #16
0
async def get_otp_code(identity: str = Depends(get_jwt_identity)):
    try:
        user = User.objects.get(id=identity)
        user.otpSecret = base64.b32encode(os.urandom(10)).decode('utf8')
        user.save()
        return user.get_totp_uri()
    except DoesNotExist:
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #17
0
async def verify_otp_code(otp_body: OtpForm,
                          identity: str = Depends(get_jwt_identity)):
    try:
        user = User.objects.get(id=identity)
        if user.verify_totp(otp_body.otp):
            return True
        raise UnauthorizedError
    except (UnauthorizedError, DoesNotExist):
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #18
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def save_menu_items(menuItems: MenuItemForm,
                          identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
        models.MenuItem.objects().delete()  # remove all old menu items
        for item in menuItems.menuItems:
            models.MenuItem(**base_model_to_clean_dict(item)).save()
        return 'ok'
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
コード例 #19
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_post_types(identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
        postTypes = map(lambda s: s.__module__[9:] + '.' + s.__name__,
                        all_subclasses(models.Post))
        if not ShopSettings.ENABLE:
            postTypes = filter(lambda p: p != 'models.Product', postTypes)
        return list(postTypes)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
コード例 #20
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def delete_order(id: str, identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        models.Order.objects.get(id=id).delete()
        return 'ok'
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e
コード例 #21
0
async def check_password(password_body: PasswordForm,
                         identity: str = Depends(get_jwt_identity)):
    try:
        user = User.objects.get(id=identity)
        authorized = user.check_password(password_body.password)
        if not authorized:
            raise UnauthorizedError
        return 'ok'
    except (UnauthorizedError, DoesNotExist):
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #22
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_us_shipping_zone(id: str,
                               identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        zone = models.UsShippingZone.objects.get(id=id)
        return zone.serialize()
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e
コード例 #23
0
ファイル: file.py プロジェクト: dman926/SEPHIRA
async def upload_file(background_tasks: BackgroundTasks, response: Response, file: UploadFile = File(...), folder: Optional[str] = Form(''), childOf: Optional[str] = Form(''), identity: str = Depends(get_jwt_identity)):
	try:
		if file.filename == '' or (len(folder) > 0 and folder[0] == '/'):
			raise SchemaValidationError
		User.objects.get(id=identity) # make sure the user exists
		if allowed_file(file.filename):
			# Handle filename collisions
			filename = file.filename
			counter = 2
			while True:
				try:
					Media.objects.get(filename=filename, folder=folder)
					newFilename = filename
					filenameSplit = newFilename.rsplit('.', 1)
					filename = filenameSplit[0] + '_' + str(counter) + '.' + filenameSplit[1]
					counter += 1
				except DoesNotExist:
					break
			mimetype = file.content_type
			if not mimetype:
				mimetype = mimetypes.guess_type(filename)
			
			if FileSettings.ENABLE_FFMPEG and FileSettings.ENABLE_FILE_PROCESSING and (mimetype[:6] == 'video/' or mimetype[:6] == 'audio/' or mimetype == 'application/x-subrip' or mimetype == 'application/ttml+xml'):
				# Process the file
				splitFilename = filename.rsplit('.', 1)
				media = Media(owner=identity, filename=splitFilename[0], folder=folder, container=True, processing=True)
				media.save()
				background_tasks.add_task(processMedia, media, file, splitFilename[1])
				#processMedia(media, file)
				response.status_code = 202
			else:
				media = Media(owner=identity, filename=filename, folder=folder)
				media.file.put(file.file, content_type=mimetype)
				media.save()

				for parent in childOf.split(','):
					try:
						if parent:
							Media.objects.get(id=parent).update(push__associatedMedia=media)
					except DoesNotExist:
						pass
			return media.serialize()
		raise SchemaValidationError
	except SchemaValidationError as e:
		raise SchemaValidationError().http_exception
	except DoesNotExist:
		raise UnauthorizedError().http_exception
	except MediaProcessingError:
		raise MediaProcessingError().http_exception
	except Exception as e:
		raise e
コード例 #24
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_user(id: str, identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
    try:
        user = models.User.objects.get(id=id)
        return user.serialize()
    except DoesNotExist:
        raise NotFoundError(detail='User with id ' + id + ' does not exist')
    except Exception as e:
        raise e
コード例 #25
0
async def update_user(user: UserModel,
                      identity: str = Depends(get_jwt_identity)):
    try:
        foundUser = User.objects.get(id=identity)
        if user.admin:
            raise UnauthorizedError  # Cannot set themselves as admin
        foundUser.update(**base_model_to_clean_dict(user))
        if user.password:
            user.hash_password()
            user.save()
        return True
    except (UnauthorizedError, DoesNotExist):
        raise UnauthorizedError().http_exception
    except Exception as e:
        raise e
コード例 #26
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def update_us_shipping_zone(id: str,
                                  shippingZone: models.UsShippingZoneModel,
                                  identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        toUpdate = models.UsShippingZone.objects.get(id=id)
        toUpdate.update(**base_model_to_clean_dict(shippingZone))
        return 'ok'
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e
コード例 #27
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def update_user(id: str,
                      user: models.UserModel,
                      identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
    try:
        models.User.objects.get(id=id).update(**base_model_to_clean_dict(user))
        return 'ok'
    except DoesNotExist:
        raise NotFoundError(detail='User with id ' + id + ' does not exist')
    except Exception as e:
        raise e
コード例 #28
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def get_post_schema(post: str,
                          identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
        try:
            postType = class_name_to_class(__name__, post)
            if not is_post(postType):
                raise InvalidPostTypeError
        except Exception:
            raise InvalidPostTypeError
        return postType.schema()
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except InvalidPostTypeError:
        raise InvalidPostTypeError()
    except Exception as e:
        raise e
コード例 #29
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def add_us_shipping_zone(shippingZone: models.UsShippingZoneModel,
                               identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
        zone = models.UsShippingZone(**base_model_to_clean_dict(shippingZone))
        try:
            models.UsShippingZone.objects.get(default=True)
        except DoesNotExist:
            zone.default = True
        zone.save()
        return zone.serialize()
    except ValidationError:
        raise SchemaValidationError()
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    except Exception as e:
        raise e
コード例 #30
0
ファイル: admin.py プロジェクト: dman926/SEPHIRA
async def edit_order(id: str,
                     order: models.OrderModel,
                     identity: str = Depends(get_jwt_identity)):
    try:
        get_admin_user(identity)
    except (DoesNotExist, UnauthorizedError):
        raise UnauthorizedError('User is not admin')
    try:
        toUpdate = models.Order.objects.get(id=id)
        toUpdate.update(**base_model_to_clean_dict(order))
        toUpdate.reload()
        toUpdate.modified = datetime.now
        toUpdate.save()
        return 'ok'
    except DoesNotExist:
        raise NotFoundError()
    except Exception as e:
        raise e