Skip to content
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

Add new use cases to authorize user, register SPs, and get id tokens #22

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

ShreyasPrasad
Copy link
Member

Closes #10, #11, #13.

authorizeUserDTO = {
req: httpMocks.createRequest(),
params: {
client_id: 'i291u92jksdn',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are the ids supposed to be hex strings or just any alphanumeric string?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hex strings, but since it doesn't matter for the controller unit test I just made it that. Adding use-case unit tests soon.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the test should reflect real life then and use a hex string. (I'm a massive hypocrite because waterpark is filled with unrealistic test IDs)

Comment on lines 12 to 13
jest.mock('../authorize-user-use-case')
jest.mock('../authorize-user-use-case')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seeing double

Suggested change
jest.mock('../authorize-user-use-case')
jest.mock('../authorize-user-use-case')
jest.mock('../authorize-user-use-case')

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW I've noticed that jest.mock doesn't actually need to be called if we use jest.spyOn on the object rather than on its class prototype.

i.e. here, you can set up a variable authorizeUserUseCase = authorizeUser.authorizeUserUseCase, then call jest.spyOn(authorizeUserUseCase, 'execute') instead of jest.spyOn(AuthorizeUserUseCase.prototype, 'execute').

authorizeUserDTO = {
req: httpMocks.createRequest(),
params: {
client_id: 'i291u92jksdn',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the test should reflect real life then and use a hex string. (I'm a massive hypocrite because waterpark is filled with unrealistic test IDs)

Copy link
Member

@xujustinj xujustinj left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reviewed 1/3, gotta go now but will finish the rest later

}).options({ abortEarly: false })

export const AuthorizeUserDTOSchema = Joi.object<AuthorizeUserDTO>({
req: Joi.object().required(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I understand correctly, the req object is only needed for its .user field. Can we narrow this part of the schema then?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue is that by narrowing the schema at this point, I wouldn't be able to redirect the user to /login if the user doesn't exist, like done in the use-case (we return a 400 for all schema errors currently). The overridable method you showed me earlier would let me change that. Is that something I should include here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since loolabs/waterpark#221 is merged now, feel free to copy over https://github.com/loolabs/waterpark/blob/main/server/src/shared/app/typed-controller.ts and its dependencies to try it out. A word of warning -- it uses Zod. You might be able to modify it to use Joi validation.

}
const authCode = AuthCode.create({
clientId: params.client_id,
userId: user.userId.id.toString(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

userId.id? I think we changed something in waterpark to reduce the level of object nesting here. cc @KTong821

@@ -60,47 +54,41 @@ export class CreateUserUseCase implements UseCaseWithDTO<CreateUserDTO, CreateUs
try {
const userAlreadyExists = await this.userRepo.exists(email)

if (userAlreadyExists && userAlreadyExists.isOk()){
if (userAlreadyExists && userAlreadyExists.isOk()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty sure userAlreadyExists is always truthy. Did you mean

Suggested change
if (userAlreadyExists && userAlreadyExists.isOk()) {
if (userAlreadyExists.isOk() && userAlreadyExists.value) {

return Result.err(new AppError.UnexpectedError(updatedUser.error.message))

if(!dto.params || !dto.params.scope){
if (!dto.params || !dto.params.scope) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there was discussion in the past about spliting the use case into separate use cases, and then moving this if/else splitting into the controller to decide which use case to call

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right - will add that when I add the /logout use-case. Coming soon to a commit near you.

Comment on lines +4 to +5
super()
this.message = `No account with the id ${id} exists`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
super()
this.message = `No account with the id ${id} exists`
super(`No account with the id ${id} exists`)

Comment on lines +4 to 5
super()
this.message = `Incorrect email/password combination provided.`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
super()
this.message = `Incorrect email/password combination provided.`
super(`Incorrect email/password combination provided.`)

public constructor(hashedValue?: string) {
if(hashedValue){
if (hashedValue) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you might run into truthiness problems with empty strings

Suggested change
if (hashedValue) {
if (hashedValue !== undefined) {

Comment on lines 14 to 20
private getRandomCode() {
/*motivation for a 256 bit (= 32 byte) crypographic key can be found here
/*motivation for a 256 bit (= 32 byte) cryptographic key can be found here
https://www.geeksforgeeks.org/node-js-crypto-randombytes-method/
*/
const authCodeBuffer = crypto.randomBytes(32)
return authCodeBuffer.toString('hex')
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this function can just be an unexported global function in this file, rather than a member method

Comment on lines +19 to +20
res.redirect(params.getFormattedUrlWithParams(url))
return res
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious what the change here does; what is the difference between the two implementations?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was overwriting the 302 redirect status of the res. This status code is what instructs the frontend browser to change its page target.

Copy link
Member

@xujustinj xujustinj left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

second batch of comments; slowly chipping away at this PR

Comment on lines +8 to +10
if(len(sys.argv)!=2):
print("Invalid number of cmd line arguments provided.")
client_id = base64.b64decode(sys.argv[1])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to reinvent the wheel, let's use argparse instead

Comment on lines +53 to 57
const createUserErr = createUserResult as Err<
CreateUserSuccess,
UserValueObjectErrors.InvalidEmail
>
expect(createUserErr.error instanceof UserValueObjectErrors.InvalidEmail).toBe(true)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another (also-ugly, but typesafe) way to do it is

Suggested change
const createUserErr = createUserResult as Err<
CreateUserSuccess,
UserValueObjectErrors.InvalidEmail
>
expect(createUserErr.error instanceof UserValueObjectErrors.InvalidEmail).toBe(true)
if (!createUserResult.isErr()) throw new Error('this is impossible')
expect(createUserResult.error instanceof UserValueObjectErrors.InvalidEmail).toBe(true)

Comment on lines +4 to +5
super()
this.message = `The provided client name ${clientName} is already in use.`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
super()
this.message = `The provided client name ${clientName} is already in use.`
super(`The provided client name ${clientName} is already in use.`)


export const getTokenDTOSchema = Joi.object<GetTokenDTO>({
//Example: Authorization: Basic 3904238orfiefiekfhjri3u24r789
authHeader: Joi.string().pattern(new RegExp('^Basic .+$')).required(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the regex could be a bit more specific than that

Comment on lines +4 to +5
super()
this.message = `Incorrect authentication credentials provided.`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
super()
this.message = `Incorrect authentication credentials provided.`
super(`Incorrect authentication credentials provided.`)

Comment on lines -28 to -34
export const loginUserDTOParamsSchema = Joi.object<LoginUserDTOParams>({
client_id: Joi.string().required(),
scope: Joi.string().required(),
response_type: Joi.string().required(),
redirect_uri: Joi.string().required()
}).options({ abortEarly: false })

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is the reason for dropping this?

@@ -30,29 +29,6 @@ describe('User AggregateRoot', () => {
expect(DomainEvents.markAggregateForDispatch).toBeCalled()
})

test('it adds a UserLoggedIn domain event on user login', () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what happened to this test?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Refactor protected-user-use-case to handle global session check
3 participants