-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[#175395536] Add Organization logo's upload #83
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9a204b0
[#175395536] Add upload organization logo
AleDore 25e0975
[#175395536] Removed useless tests
AleDore b27cb06
[#175395536] Refactor over review
AleDore fc08559
[#175395536] Rebase
AleDore 40b2530
[#175395536] Rebase
AleDore 090232f
[#175395536] Refactor over review
AleDore File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
/* tslint:disable:no-any */ | ||
/* tslint:disable:no-duplicate-string */ | ||
/* tslint:disable:no-big-function */ | ||
/* tslint:disable: no-identical-functions */ | ||
|
||
import { | ||
IAzureApiAuthorization, | ||
UserGroup | ||
} from "io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; | ||
import { IAzureUserAttributes } from "io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; | ||
|
||
import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; | ||
import { | ||
EmailString, | ||
NonEmptyString, | ||
OrganizationFiscalCode | ||
} from "italia-ts-commons/lib/strings"; | ||
|
||
import { toAuthorizedCIDRs } from "io-functions-commons/dist/src/models/service"; | ||
|
||
import { MaxAllowedPaymentAmount } from "io-functions-commons/dist/generated/definitions/MaxAllowedPaymentAmount"; | ||
|
||
import { left, right } from "fp-ts/lib/Either"; | ||
import * as reporters from "italia-ts-commons/lib/reporters"; | ||
import { Logo } from "../../generated/api-admin/Logo"; | ||
import { UploadOrganizationLogoHandler } from "../handler"; | ||
|
||
const mockContext = { | ||
// tslint:disable: no-console | ||
log: { | ||
error: console.error | ||
} | ||
} as any; | ||
|
||
afterEach(() => { | ||
jest.resetAllMocks(); | ||
jest.restoreAllMocks(); | ||
}); | ||
|
||
const anOrganizationFiscalCode = "01234567890" as OrganizationFiscalCode; | ||
const anEmail = "test@example.com" as EmailString; | ||
|
||
const aServiceId = "s123" as NonEmptyString; | ||
const someSubscriptionKeys = { | ||
primary_key: "primary_key", | ||
secondary_key: "secondary_key" | ||
}; | ||
|
||
const aService = { | ||
authorizedCIDRs: toAuthorizedCIDRs([]), | ||
authorizedRecipients: new Set([]), | ||
departmentName: "IT" as NonEmptyString, | ||
isVisible: true, | ||
maxAllowedPaymentAmount: 0 as MaxAllowedPaymentAmount, | ||
organizationFiscalCode: anOrganizationFiscalCode, | ||
organizationName: "AgID" as NonEmptyString, | ||
requireSecureChannels: false, | ||
scope: "NATIONAL", | ||
serviceId: aServiceId, | ||
serviceName: "Test" as NonEmptyString, | ||
version: 1 as NonNegativeInteger, | ||
...someSubscriptionKeys | ||
}; | ||
|
||
const someUserAttributes: IAzureUserAttributes = { | ||
email: anEmail, | ||
kind: "IAzureUserAttributes", | ||
service: aService | ||
}; | ||
|
||
const aUserAuthenticationDeveloper: IAzureApiAuthorization = { | ||
groups: new Set([UserGroup.ApiServiceRead, UserGroup.ApiServiceWrite]), | ||
kind: "IAzureApiAuthorization", | ||
subscriptionId: aServiceId, | ||
userId: "u123" as NonEmptyString | ||
}; | ||
|
||
const aLogoPayload: Logo = { | ||
logo: "base64-logo-img" as NonEmptyString | ||
}; | ||
|
||
describe("UploadOrganizationLogo", () => { | ||
it("should respond with 202 if logo upload was successfull", async () => { | ||
const apiClientMock = { | ||
uploadOrganizationLogo: jest.fn(() => | ||
Promise.resolve(right({ status: 201 })) | ||
) | ||
}; | ||
|
||
const uploadOrganizationLogoHandler = UploadOrganizationLogoHandler( | ||
apiClientMock as any | ||
); | ||
const result = await uploadOrganizationLogoHandler( | ||
mockContext, | ||
aUserAuthenticationDeveloper, | ||
undefined as any, // not used | ||
someUserAttributes, | ||
anOrganizationFiscalCode, | ||
aLogoPayload | ||
); | ||
|
||
expect(result.kind).toBe("IResponseSuccessAccepted"); | ||
if (result.kind === "IResponseSuccessAccepted") { | ||
expect(result.detail).toBeUndefined(); | ||
} | ||
}); | ||
|
||
it("should respond with an internal error if upload service logo does not respond", async () => { | ||
const apiClientMock = { | ||
uploadOrganizationLogo: jest.fn(() => | ||
Promise.reject(new Error("Timeout")) | ||
) | ||
}; | ||
|
||
const uploadOrganizationLogoHandler = UploadOrganizationLogoHandler( | ||
apiClientMock as any | ||
); | ||
const result = await uploadOrganizationLogoHandler( | ||
mockContext, | ||
aUserAuthenticationDeveloper, | ||
undefined as any, // not used | ||
someUserAttributes, | ||
anOrganizationFiscalCode, | ||
aLogoPayload | ||
); | ||
|
||
expect(result.kind).toBe("IResponseErrorInternal"); | ||
}); | ||
|
||
it("should respond with an internal error if uploadOrganizationLogo returns Errors", async () => { | ||
const apiClientMock = { | ||
uploadOrganizationLogo: jest.fn(() => | ||
Promise.resolve(left({ err: "ValidationError" })) | ||
) | ||
}; | ||
|
||
jest | ||
.spyOn(reporters, "errorsToReadableMessages") | ||
.mockImplementation(() => ["ValidationErrors"]); | ||
|
||
const uploadOrganizationLogoHandler = UploadOrganizationLogoHandler( | ||
apiClientMock as any | ||
); | ||
const result = await uploadOrganizationLogoHandler( | ||
mockContext, | ||
aUserAuthenticationDeveloper, | ||
undefined as any, // not used | ||
someUserAttributes, | ||
anOrganizationFiscalCode, | ||
aLogoPayload | ||
); | ||
|
||
expect(result.kind).toBe("IResponseErrorInternal"); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
{ | ||
"bindings": [ | ||
{ | ||
"authLevel": "function", | ||
"type": "httpTrigger", | ||
"direction": "in", | ||
"name": "req", | ||
"route": "v1/organizations/{organization_fiscal_code}/logo", | ||
"methods": [ | ||
"put" | ||
] | ||
}, | ||
{ | ||
"type": "http", | ||
"direction": "out", | ||
"name": "res" | ||
} | ||
], | ||
"scriptFile": "../dist/UploadOrganizationLogo/index.js" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,140 @@ | ||||||
import * as express from "express"; | ||||||
|
||||||
import { | ||||||
ClientIp, | ||||||
ClientIpMiddleware | ||||||
} from "io-functions-commons/dist/src/utils/middlewares/client_ip_middleware"; | ||||||
|
||||||
import { RequiredParamMiddleware } from "io-functions-commons/dist/src/utils/middlewares/required_param"; | ||||||
|
||||||
import { | ||||||
AzureApiAuthMiddleware, | ||||||
IAzureApiAuthorization, | ||||||
UserGroup | ||||||
} from "io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; | ||||||
import { | ||||||
AzureUserAttributesMiddleware, | ||||||
IAzureUserAttributes | ||||||
} from "io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; | ||||||
import { | ||||||
withRequestMiddlewares, | ||||||
wrapRequestHandler | ||||||
} from "io-functions-commons/dist/src/utils/request_middleware"; | ||||||
import { | ||||||
IResponseErrorForbiddenNotAuthorized, | ||||||
IResponseErrorInternal, | ||||||
IResponseErrorTooManyRequests, | ||||||
IResponseSuccessAccepted, | ||||||
ResponseSuccessAccepted | ||||||
} from "italia-ts-commons/lib/responses"; | ||||||
import { OrganizationFiscalCode } from "italia-ts-commons/lib/strings"; | ||||||
|
||||||
import { | ||||||
checkSourceIpForHandler, | ||||||
clientIPAndCidrTuple as ipTuple | ||||||
} from "io-functions-commons/dist/src/utils/source_ip_check"; | ||||||
|
||||||
import { Context } from "@azure/functions"; | ||||||
import { identity } from "fp-ts/lib/function"; | ||||||
import { TaskEither } from "fp-ts/lib/TaskEither"; | ||||||
import { ServiceModel } from "io-functions-commons/dist/src/models/service"; | ||||||
import { ContextMiddleware } from "io-functions-commons/dist/src/utils/middlewares/context_middleware"; | ||||||
import { RequiredBodyPayloadMiddleware } from "io-functions-commons/dist/src/utils/middlewares/required_body_payload"; | ||||||
import { APIClient } from "../clients/admin"; | ||||||
import { Logo } from "../generated/api-admin/Logo"; | ||||||
import { withApiRequestWrapper } from "../utils/api"; | ||||||
import { getLogger, ILogger } from "../utils/logging"; | ||||||
import { | ||||||
ErrorResponses, | ||||||
IResponseErrorUnauthorized, | ||||||
toDefaultResponseErrorInternal | ||||||
} from "../utils/responses"; | ||||||
|
||||||
type ResponseTypes = | ||||||
| IResponseSuccessAccepted | ||||||
| IResponseErrorUnauthorized | ||||||
| IResponseErrorForbiddenNotAuthorized | ||||||
| IResponseErrorTooManyRequests | ||||||
| IResponseErrorInternal; | ||||||
|
||||||
const logPrefix = "UploadOrganizationLogoHandler"; | ||||||
|
||||||
/** | ||||||
* Type of a UploadOrganizationLogoHandler handler. | ||||||
* | ||||||
* UploadOrganizationLogo expects an organization fiscal code and a logo as input | ||||||
* and returns informations about upload outcome | ||||||
*/ | ||||||
type IUploadOrganizationLogoHandler = ( | ||||||
context: Context, | ||||||
auth: IAzureApiAuthorization, | ||||||
clientIp: ClientIp, | ||||||
attrs: IAzureUserAttributes, | ||||||
organizationFiscalCode: OrganizationFiscalCode, | ||||||
logoPayload: Logo | ||||||
) => Promise<ResponseTypes>; | ||||||
|
||||||
const uploadOrganizationLogoTask = ( | ||||||
logger: ILogger, | ||||||
apiClient: APIClient, | ||||||
organizationFiscalCode: OrganizationFiscalCode, | ||||||
logo: Logo | ||||||
): TaskEither<ErrorResponses, IResponseSuccessAccepted> => | ||||||
withApiRequestWrapper( | ||||||
logger, | ||||||
() => | ||||||
apiClient.uploadOrganizationLogo({ | ||||||
body: logo, | ||||||
organization_fiscal_code: organizationFiscalCode | ||||||
}), | ||||||
201 | ||||||
).map(_ => ResponseSuccessAccepted()); | ||||||
|
||||||
/** | ||||||
* Handles requests for upload a service logo by a service ID and a base64 logo' s string. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
*/ | ||||||
export function UploadOrganizationLogoHandler( | ||||||
apiClient: APIClient | ||||||
): IUploadOrganizationLogoHandler { | ||||||
return (_, __, ___, ____, organizationFiscalCode, logoPayload) => { | ||||||
return uploadOrganizationLogoTask( | ||||||
getLogger(_, logPrefix, "UploadOrganizationLogo"), | ||||||
apiClient, | ||||||
organizationFiscalCode, | ||||||
logoPayload | ||||||
) | ||||||
.mapLeft(errs => | ||||||
// Not found is never returned by uploadOrganizationLogo but, due to request wrapping return type, we have to wrap it | ||||||
errs.kind !== "IResponseErrorNotFound" | ||||||
? errs | ||||||
: toDefaultResponseErrorInternal(errs) | ||||||
) | ||||||
.fold<ResponseTypes>(identity, identity) | ||||||
.run(); | ||||||
}; | ||||||
} | ||||||
|
||||||
/** | ||||||
* Wraps a UploadOrganizationLogo handler inside an Express request handler. | ||||||
*/ | ||||||
export function UploadOrganizationLogo( | ||||||
serviceModel: ServiceModel, | ||||||
client: APIClient | ||||||
): express.RequestHandler { | ||||||
const handler = UploadOrganizationLogoHandler(client); | ||||||
const middlewaresWrap = withRequestMiddlewares( | ||||||
ContextMiddleware(), | ||||||
AzureApiAuthMiddleware(new Set([UserGroup.ApiServiceWrite])), | ||||||
ClientIpMiddleware, | ||||||
AzureUserAttributesMiddleware(serviceModel), | ||||||
RequiredParamMiddleware("organization_fiscal_code", OrganizationFiscalCode), | ||||||
RequiredBodyPayloadMiddleware(Logo) | ||||||
); | ||||||
return wrapRequestHandler( | ||||||
middlewaresWrap( | ||||||
checkSourceIpForHandler(handler, (_, __, c, u, ___, ____) => | ||||||
ipTuple(c, u) | ||||||
) | ||||||
) | ||||||
); | ||||||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { Context } from "@azure/functions"; | ||
import * as express from "express"; | ||
import { cosmosdbInstance } from "../utils/cosmosdb"; | ||
|
||
import { | ||
SERVICE_COLLECTION_NAME, | ||
ServiceModel | ||
} from "io-functions-commons/dist/src/models/service"; | ||
import { secureExpressApp } from "io-functions-commons/dist/src/utils/express"; | ||
import { setAppContext } from "io-functions-commons/dist/src/utils/middlewares/context_middleware"; | ||
|
||
import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; | ||
|
||
import { apiClient } from "../clients/admin"; | ||
import { UploadOrganizationLogo } from "./handler"; | ||
|
||
// Setup Express | ||
const app = express(); | ||
secureExpressApp(app); | ||
|
||
const serviceModel = new ServiceModel( | ||
cosmosdbInstance.container(SERVICE_COLLECTION_NAME) | ||
); | ||
|
||
app.put( | ||
"/api/v1/organizations/:organization_fiscal_code/logo", | ||
UploadOrganizationLogo(serviceModel, apiClient) | ||
); | ||
|
||
const azureFunctionHandler = createAzureFunctionHandler(app); | ||
|
||
// Binds the express app to an Azure Function handler | ||
function httpStart(context: Context): void { | ||
setAppContext(app, context); | ||
azureFunctionHandler(context); | ||
} | ||
|
||
export default httpStart; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We must map it in the specs as well