Skip to content

refactor: Refactor auth provider #5782

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

Merged
merged 18 commits into from
Jan 20, 2023
Merged

Conversation

BrunoQuaresma
Copy link
Collaborator

@BrunoQuaresma BrunoQuaresma commented Jan 18, 2023

  • Wrap routes directly into the Router component. This makes it possible for us to use createRoutesFromElements to unblock the loader data feature if we want to use it.
  • All the authenticated data that we need to use across the dashboard should be loaded in the DashboardProvider, it also provides an interface for common actions. Right now, the appearance is the only "feature" which is using that but I think it does not have to be there honestly, I will refactor it later. This also helps us to test different "initial loading" strategies for the dashboard. I'm going to also move the permissions loading into it since this is a kind of data that should be loaded when the user is authenticated.
  • The AuthProvider is pretty simple right now, at some point, it will abstract the machine usage and it should provide common auth methods like login, logout, etc, and data. So the consumer doesn't care about what is being used under the hood.
  • I added a paywall in front of the audit page instead of removing it entirely from the route like we do for the template permissions page.

I would extra appreciate it if you could download it locally and just navigate around to see if any bug happens.

There are a lot of changes, but most of them are minor like import updates.

@BrunoQuaresma BrunoQuaresma requested a review from a team as a code owner January 18, 2023 23:52
@BrunoQuaresma BrunoQuaresma self-assigned this Jan 18, 2023
@BrunoQuaresma BrunoQuaresma requested review from Kira-Pilot and presleyp and removed request for a team January 18, 2023 23:53
@BrunoQuaresma BrunoQuaresma requested a review from jsjoeio January 19, 2023 13:01
@@ -0,0 +1,36 @@
import { useActor, useInterpret } from "@xstate/react"
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 we should move all Providers into a provider or state directory instead of them living mixed in with our components.

Copy link
Member

Choose a reason for hiding this comment

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

Actually I would call it contexts. And I might rename these files to AuthContext, DashboardContext, etc.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I see Provider being used more broadly in community but I'm ok with Context too. About where to put them, I think a context directory is good!

Copy link
Member

Choose a reason for hiding this comment

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

As long as we establish a consistent pattern, I'm not too picky!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Totally

authService: ActorRefFrom<typeof authMachine>
}

const AuthProviderContext = createContext<AuthProviderContextValue | undefined>(
Copy link
Member

@Kira-Pilot Kira-Pilot Jan 19, 2023

Choose a reason for hiding this comment

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

NIT: I would probably just name this AuthContext and createContext would take a AuthContextValue type

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

But there is a difference. The AuthContext is the one created from React.createContext, and the Provider is the wrapper around it that define the values like data and additional functions

Copy link
Member

Choose a reason for hiding this comment

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

I get the difference - I would name it AuthContext for brevity, and also because it's named after the thing it's created by: a hook called createContext. You see the React docs using this pattern here. The interface you defined describes the values available on the context (you're right tho - they are enabled through a provider). That being said, if you prefer the longer name, I'm down. We should just establish a pattern since we'll be using React state more frequently.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Ahh I see. But in this case the Context is being used directly. We can think like Material UI that has a wrapper around the their theme context and named it ThemeProvider as example


const AuthProviderContext = createContext<AuthProviderContextValue | undefined>(
undefined,
)
Copy link
Member

Choose a reason for hiding this comment

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

Why would this type be potentially undefined? Because the machine hasn't initialized yet? If so, could we do something like:

const AuthProviderContext = createContext<AuthProviderContextValue>({
  authService: undefined
})

Or whatever the un-initialized value for authService would be? This way we can be a little more explicit about what the machine is returning early-state, and we also set ourselves up for the future where the context is returning other methods.

Copy link
Collaborator Author

@BrunoQuaresma BrunoQuaresma Jan 19, 2023

Choose a reason for hiding this comment

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

It is ok it uses undefined, it should not happen tho but the useAuth hook is doing the type validation already. I see creating empty context values as an anti pattern. There is a good blog post about this somewhere, I will try to find it.

Copy link
Member

Choose a reason for hiding this comment

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

Please do - I wasn't aware and would love to read more. I'm curious how this pattern handles:

  1. data that comes back asynchronously
  2. data that errors differently

For example, if you had an auth context that returned the following values:

type AuthContextValue = {
  error: undefined | ApiError
  anotherSpecificError: undefined | ApiError
  currentUser: null | AuthContextQueryUser
  currentOrg: null | AuthContextQueryOrg
  specificUserPermission: null  | AuthContextQueryPerm
}

It might be nice to not have the entire context return value undefined if currentUser and currentOrg have returned but we are still waiting on specificUserPermission. Similarly, we can specify separate errors with this type of pattern, if we need that distinction within the page.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, at somepoint this provider is going to pass values like these instead of machine actors but I thought it would be too much to do right now.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The undefined is just a type thing tho since the initialization happens when the component is used on AuthContext.Provider and pass the value props. It also help us to throw an erro if the user is using the context or the hook outside of the Provider.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

About errors I don't think we need to be too much specific. We make that in the machines but I don't see too much vale tho and it adds significantly work.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

About the naming, I think I only was able to understand it now 🤦‍♂️ AuthContext is definitely better than AuthProviderContext for sure.

const { entitlements } = entitlementsState.context
const { appearance, preview } = appearanceState.context
const { experiments } = experimentsState.context
const isLoading = !buildInfo || !entitlements || !appearance || !experiments
Copy link
Member

Choose a reason for hiding this comment

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

What happens if one of these is undefined because of an error?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

If they are undefined, we are going to show the loading state. About the error, good catch, I forgot to handle it.

Copy link
Contributor

Choose a reason for hiding this comment

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

Not sure if this can apply here, but I fixed a bug recently where the value had been fetched but was falsy so a check like this left us in the loading state forever. Just something to keep in mind, whether falsiness really indicates loading. I like to put "loading" tags on loading states in the machines.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Interesting case, but in theory, any of these data should be undefined or even false.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Buuuut, this should not be here. This is going to be refactored for something like this: https://codercom.slack.com/archives/CJURPL8DN/p1674072426535449?thread_ts=1674071396.499819&cid=CJURPL8DN

onFilter={onFilter}
presetFilters={presetFilters}
/>
<ChooseOne>
Copy link
Member

Choose a reason for hiding this comment

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

I would break these two outcomes out into separate files: one for the case where audit logs should be hidden, and one for their visibility.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

What benefits do you see on that?

Copy link
Member

Choose a reason for hiding this comment

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

Great question! A couple:

  1. less scrolling through long files
  2. easier to read conditionals, e.g:
<ChooseOne>
    <Cond condition={bool}>
        <OptionAComponent />
    </Cond>
   <Cond condition={bool}>
        <OptionBComponent />
   </Cond>
</ChooseOne>

I know we have a lot of longer files in our repo but this just isn't a pattern I've seen anywhere else. Many companies turn on lint rules to limit file length.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Thx, it definitely makes easier to read conditionals. About long files I personally like them haha it sounds a tooling thing since you can collapse the root functions in the editor tho. What I usually think about it is, if the component or code is only used in that file, it should be on the file so it is easier to find, modify, delete and I know it only affects that scope. When it has your own file, I assume it has been used in more than one place so I have to be more carefully.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

But no strong opinion, I know a lot of people don't like it 😄

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Sure thing!

Copy link
Contributor

Choose a reason for hiding this comment

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

Personally I also like shorter files because I feel less likely to overlook something. I think the concern about stuff that's reused is important but that we can put everything related in one folder, like Kira says. I won't be heartbroken either way though.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Lets go with shorter files!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Another thought, is it ok just to move the Paywall? I would avoid to have one more level of prop drilling

Copy link
Member

Choose a reason for hiding this comment

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

Ya, definitely!

Copy link
Contributor

@jsjoeio jsjoeio left a comment

Choose a reason for hiding this comment

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

Nice work!! I also tested locally and it seems to all work properly.

I did notice some layout shifts on the Deployment Settings pages but probably unrelated to your changes. See video:

Screen.Recording.2023-01-19.at.8.58.00.AM.mov

Co-authored-by: Joe Previte <jjprevite@gmail.com>
@BrunoQuaresma
Copy link
Collaborator Author

@jsjoeio it is because of the scroll bar on the right


if (isLoading) {
return <FullScreenLoader />
}
Copy link
Member

Choose a reason for hiding this comment

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

What do you think about keeping this context 'pure' meaning it doesn't really dictate UI at all? Then we could expose isLoading and isError and the consumer could handle those UI changes. Benefit would be keeping our UI all in one place so folks opening up that page component can see how it's handled at first glance, without having to dig into the context.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Not sure if I got it. I don't see too much value on having it pure since the value, from what I see, is to have a provider that handle that in one single place but maybe I'm missing something. I based this provider on https://kentcdodds.com/blog/authentication-in-react-applications

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 in that example, he's showcasing functionality instead of organization, but I'm happy to talk it through in Discord. It's also not a blocker.

Copy link
Contributor

Choose a reason for hiding this comment

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

Interesting. I'm usually agnostic about where to put these, but I don't know if I've ever seen a provider render a spinner. But I see that Kent really does it intentionally:

  // 🚨 this is the important bit.
  // Normally your provider components render the context provider with a value.
  // But we post-pone rendering any of the children until after we've determined
  // whether or not we have a user token and if we do, then we render a spinner
  // while we go retrieve that user's information.```

Copy link
Member

Choose a reason for hiding this comment

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

Hmm, I could see that. I was looking at his comment below:

The key idea that drastically simplifies authentication in your app is this:

The component which has the user data prevents the rest of the app from being rendered until the user data is retrieved or it's determined that there is no logged-in user

So I figured the component is the consumer of the context, and it should have something like this:

const {isLoading} = useAuth()

if {isLoading} return <Loader/>

return (
 <App />
)

I guess this is an argument for colocation, kind of similar to what we were discussing with long files. But just because it isn't a pattern I've seen before doesn't mean it's wrong! I'm happy to keep the loaders in the context.

Copy link
Collaborator Author

@BrunoQuaresma BrunoQuaresma Jan 19, 2023

Choose a reason for hiding this comment

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

But just because it isn't a pattern I've seen before doesn't mean it's wrong!

I agree 100%. In this case, I just think would be too much to have another component to handle the spinner. If at some point it starts to do more and more stuff, I think would make sense to split it.

Copy link
Contributor

@presleyp presleyp left a comment

Choose a reason for hiding this comment

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

I poked around and the only thing I saw that wasn't also in main was that when I go to create a user, but click cancel instead, on your branch I got a validation error and had to click cancel again, but on main the first click worked. That seems unrelated to your changes but mentioning it in case you can see a connection.

@BrunoQuaresma
Copy link
Collaborator Author

I poked around and the only thing I saw that wasn't also in main was that when I go to create a user, but click cancel instead, on your branch I got a validation error and had to click cancel again, but on main the first click worked. That seems unrelated to your changes but mentioning it in case you can see a connection.

@presleyp I will take a look on that.

@BrunoQuaresma BrunoQuaresma merged commit ff69c0e into main Jan 20, 2023
@BrunoQuaresma BrunoQuaresma deleted the bq/refactor-auth-provider-2 branch January 20, 2023 00:02
@github-actions github-actions bot locked and limited conversation to collaborators Jan 20, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants