1.0.3 • Published 2 years ago

@cloudmlm/cloudmlm-auth v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

bioReigns Auth Package

This package facilitates authentication within react clients. It contains helper functions as well as a component that stores authentication state.

Helper Functions

logUserIn

logUserIn makes a request to the token endpoint and returns the resulting authentication data. See below for an example. Thise code runs inside a React function component. It can easily be refactored to run inside a class component. offline_access must be within the scope string in order for refreshToken to be defined.

const authenticationContext = useContext(AuthenticationContext);

const userNameRef = useRef<HTMLInputElement | null>(null);
const passwordRef = useRef<HTMLInputElement | null>(null);

const login = async () => {
    try {
      const result = await logUserIn({
        username: userNameRef.current!.value,
        password: passwordRef.current!.value,
        grantType: 'password',
        clientId: 'public-client-id-her4e',
        responseType: 'token',
        tokenUrl: 'token-url-here',
        scope: 'openid offline_access',
      });
      authenticationContext.logUserIn(result);
    } catch (e) {
      console.error(e);
    }
};

AuthenticationContext

The authentication context allows you to access auth data from anywhere downstream in the React Application. You can access it through a hook like this:

const authenticationContext = useContext(AuthenticationContext);

The following is the typescript definition of the context data:

export interface IAuthenticationState<T = Partial<IUserInfo>> {
  isLoggedIn: boolean;
  accessToken: string | null;
  refreshToken: string | null;
  accessTokenExpirationDate: Date | null;
  userInfo: T | null;
  logUserIn: (loginData: ILoginResponse) => void;
  logUserOut: () => void;
  setUserInfo: (userInfo: T) => void;
  isLoading: boolean;
}

userInfo is a partial of the following interface:

export interface IUserInfo {
  givenName: string;
  familyName: string;
  name: string;
  emails: string[];
  userId: string;
}

Context Functions

logUserIn

Stores the data in the authentication context. Parses the access token and loads it into the user data.

logUserOut

Clears the authentication context of all login data.

setUserInfo

Saves user info into the context.

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago