1.2.0 • Published 5 months ago

@hilma/auth v1.2.0

Weekly downloads
61
License
MIT
Repository
-
Last release
5 months ago

Auth

Auth is an autentication package for react.js client applications. This package works with Hilma servers, like auth-nest or hilma-auth-server (for Loopback applications.)

Installation

npm install --save @hilma/auth axios react-router-dom

Main exports:

AuthProvider - component

AuthProvider is the main component needed from this package. It includes all the logic and methods needed for your application. AuhtProvider is as wrapping component that uses context to pass all its logic to the rest of your application. Before implemetation, let's examine some of the logic in AuthProvider . There's an object stored in the component called storage . This object includes 5 fields, all of which are either a string or null. They all come from the browser's cookies:

keydescription
klan encoded version of the role keys of the authenticated user
kloan encoded version of roleAccessConfig. Find more info in Hilma docs
klooa random string
klka random string
access_token (or what ever you choose)the current users access token

Most of the methods and properties stored in AuthProvider use this object in some way, whether it being for making fetch request, or showing certain components to the client

Let's look at an example of how to implement it:

App.js:

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { AuthProvider } from '@hilma/auth';

import Admin from './components/Admin';
import Client from './components/Client';
import Login from './components/Login';

const App = () => (
    <Router>
        <AuthProvider>
            <Switch>
                <Route path="/admin" component={Admin} />
                <Route path="/client" component={Client} />
                <Route path="/login" component={Login} />
            </Switch>
        </AuthProvider>
    </Router>
);

export default App;

If you want to make this shorter you can use provide from the @hilma/tools package:

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { AuthProvider } from '@hilma/auth';
import { provide } from '@hilma/tools';

import Admin from './components/Admin';
import Client from './components/Client';
import Login from './components/Login';

const App = () => (
    <Switch> 
        <Route path="/admin" component={Admin} />
        <Route path="/client" component={Client} />
        <Route path="/login" component={Login} />
    </Switch>
);

export default provide(Router, AuthProvider)(App);

AuthProvider Props

proptyperequireddescriptiondefault
logoutOnUnauthorizedbooleanfalseIf true, when a fetch request is made via superAuthFetch or authFetch and the user is unauthorized, the logout function will invokedfalse
refReact.Ref<HilmaAuth>falseIf you want a reference to the auth object pass a ref. This will be explored later on
accessTokenCookiestringfalse (if your'e using loopback don't use this prop)the key of your access token. make sure its the same in your server (in nestjs its in configuration.ts) every application should have a different key. make sure its not obvious that its the access token. make its similar to your other cookies like kloook'access_token'
basenamestringfalsethis will be put be added to every request that you make, including the proxy of your app''
inactivityTimebooleanfalseif true, if your app has not been interacted with after ten minutes, the logout function will be invoked. this is needed in some projectfalse

Auth Properties

Now let's look at whats included in the auth object:

propertytypedescription
kls{ kl: string \| null; klo: string \| null; };includes the kl and klo stored in AuthProvider (from the browser's cookies). You will most likely not need to access this property
setAuthItemsetAuthItem(key: keyof Storage, value: string): void;Sets the key value pair in AuthProvider and cookies
getAuthItemgetAuthItem(key: keyof Storage): string \| null;Returns the auth storage item
removeAuthItemremoveAuthItem(key: keyof Storage): void;Removes the item from AuthProvider and cookies
getAccessTokengetAccessToken(): string \| null;Returns the acces token
isAuthenticatedbooleanIf true, the user is authenticated
logoutlogout(): void;Removes all storage in AuthProvider
superAuthFetchsuperAuthFetch(input: RequestInfo, init?: RequestInit \| undefined): Promise<[any, any]>;Will fetch from data from the server. @param input the url. @param init. @returns A Promise with the resloved value being a tuple of the response and the error (if one accured)
authFetchauthFetch(input: RequestInfo, init?: RequestInit \| undefined): Promise<any>;Will fetch from data from the server. @param input the url. @param init. @returns A Promise with the resloved value being the response. the response will already be in json format
loginlogin(input: string, body: Record<'password' \| 'username' \| 'email', string>): Promise<{ success: boolean; user?: any; msg?: any; }>;Log in function @param body The body you want to send to the server. example: { email: hilma@gmail.com , password: somepassword } @param input The login endpoint. @returns A Promise with the resolved value being an object: { success: boolean; user?: any; msg?: any; }
interceptorsRecord<'proxyAndHeadersId' | 'capacitorHeadersId' | 'logoutId', number | null>an object that holds the ids of Axios interceptors

Accessing the auth object:

Now let's see how we actually access all these properties. There are a few ways to access all these propeties:

via Context:

AuthProvider is mainly built on React's Context API which allows you to access a certain value in any part of an application. There are two ways to access via The Context API:

  1. Recommended: Each property has its own context object (kls: KlsContext , superAuthFetch: SuperAuthFetchContext , and so on...). Each one of these context objects also include a custom hook that returns the property (kls: useKls , superAuthFetch: useSuperAuthFetch , and so on...).
import { useSuperAuthFetch } from '@hilma/auth';

// in some functional component
const superAuthFetch = useSuperAuthFetch();

if you are using class-based components you can use the withContext HOC from @hilma/tools:

import React, { Component } from 'react';
import { SuperAuthFetchContext, LoginContext } from '@hilma/auth';
import { withContext } from '@hilma/tools';

class MyComp extends Component {

    async doSomething() {
        const [res, err] = await this.props.superAuthFetch('...');
        const loginRes = await this.props.login(res, '/api/....');
    }
    
    render() {
        return <div></div>;
    }
}

// this object represents how the values will be passed via props, the key being the prop name and the value being the context object.

const mapContextToProps = {
    superAuthFetch: SuperAuthFetchContext,
    login: LoginContext
}

export default withContext(mapContextToProps)(MyComp);
  1. Not Recommended: You can access the whole auth object via the AuthContext context object. You can also use the useAuth hook or the withAuth HOC. The reason this method is not recommended is because each time you access this context object, you are recieving the whole object. It is very unlikeky you'll need to access the whole abject. The performance of your application will drop significantly. So please use the first method.

useAuth:

import { useAuth } from '@hilma/auth';

// in some functional component
const { superAuthFetch } = useAuth();

withAuth:

import React, { Component } from 'react';
import { withAuth } from '@hilma/auth';

class MyComp extends Component {

    async doSomething() {
        const [res, err] = await this.props.auth.superAuthFetch('...');
        const loginRes = await this.props.auth.login(res, '/api/....');
    }
    
    render() {
        return <div></div>;
    }
}

export default withAuth(MyComp);

via Refs:

Another way you can access the auth object is via React's refs. This method is useful if you want to access auth outside of components, like in redux middleware or mobx stores.

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { AuthProvider, createAuthRef } from '@hilma/auth';

import Admin from './components/Admin';
import Client from './components/Client';
import Login from './components/Login';

export const authRef = createAuthRef();

const App = () => (
    <Router>
        <AuthProvider ref={authRef}>
            <Switch>
                <Route path="/admin" component={Admin} />
                <Route path="/client" component={Client} />
                <Route path="/login" component={Login} />
            </Switch>
        </AuthProvider>
    </Router>
);

export default App;

In the file where you use AuthProvider import createAuthRef , invoke the function. this returns a ref object. A ref object is an object that includes one property which is current . current holds the value stored in the ref object. In AuthProvider we use forwardRef's to pass the auth object to the provided ref. Now when you want to access the auth object you can export the ref and access the properties via authRef.current:

import { authRef } from './App';

class ErrorStore {
	async addError() {
		const [res, err] = await authRef.current.superAuthFetch('....');
	}
}

Making http requests

An important part of an application is making requests to a server. The process of making a request with the fetch api provided by the browser is very limited and doesn't provide much customization. In this package there are two main ways you can make requests: Axios and superAuthFetch. Let's take a look at these methods:

before we get in to that, make sure in package.json your proxy is set to your server. example: "proxy": "http://127.0.0.1:8080"

Axios - new approach (recommended)

Axios is a Promise based HTTP client for the browser and node.js. It's recommended that you read the docs first: https://github.com/axios/axios. Axios is a very simple package but it also comes with a lot of very useful features. The main feature we use in auth is interceptors. Interceptors can intercept requests or responses before they are handled by then or catch. That allows us to add some very useful functionality. There a three interceptors that we create in auth. their ids are stored in AuthProvider in the interceptors key so you can cancel them at any time (although there should be no reason to do so):

  1. proxyAndHeadersId: this interceptor adds before every request the proxy of the server so you don't have to write 'http://localhost:8080/...' every time, and it adds some basic headers to requests: 'Content-Type': 'application/json', 'Accept': 'application/json'.
  2. capacitorHeadersId: this interceptor adds two headers to a request if the application is running in Capacitor: 'Authorization', 'Cookie'. In a Capacitor environment, there's no browser cookies so you need to store information in localStorage and send them in every request in the Cookie header.
  3. logoutId: this interceptor checks if the status code of a response is 401 (Unauthorized) and if so, dispatches the logout function. It also changes the default error given by Axios: the default error object thrown by Axios has a lot of fields that are not very useful and rarely needed. The error this interceptor throws has only the important stuff in it.

A very big benefit of using Axios over the next approach is that there is nothing special you need to import or do. Just use it as if noting has changed. It can be easily used in mobx or redux.

example:

import Axios from 'axios';

const MyComp = () => {
    const [user, setUser] = useState(null);

    useEffetct(() => {
        (async () => {
            try {
                const res = await Axios.get('/api/users/1');
                setUser(res.data);
            } catch (error) {
                console.error(error);
            }
        })();
    }, [);
    
    return <div></div>;
}

superAuthFetch - old approach (not recommended)

This approach is based on the fetch API given by the browser. superAuthFetch is very similar to fetch: It calls fetch with the same parameters but instead of returning the default response object, it returns an array: The first item being the json response of the request, and the second item being the error of the request (if there was one). This function also adds default headers, logs out on 401 statuses, and adds cookie headers if your using it in a Capacitor environment, just like in Axios Accessing superAuthFetch: superAuthFetch is stored in AuthProvider and therefore can only be accessed thrhough its equivalent Context object or a ref object passed to AuthProvider. If you need a reminder, go back to the 'Accessing the auth object' section. In short, for using Context you have the SuperAuthFetchContext Context object, the useSuperAuthFetch hook that returns that object, and withContext from @hilma/tools for class components.

useSuperAuthFetch example:

import { useSuperAuthFetch } from '@hilma/auth';

const MyComp = () => {
    const [user, setUser] = useState(null);
    
    const superAuthFetch = useSuperAuthFetch();
    
    useEffetct(() => {
        (async () => {
            const [res, err] = await superAuthFetch('/api/users/1');
            if (err) return console.error(err);
            setUser(res);
        })();
    }, [);
    
    return <div></div>;
}

Private Routes

A very important part of the auth package is private routes. What are private routes? the are different routes in an application that we only want certain uesrs to be able to access. say we have a route that shows a list of a teacher's students, we only want to expose that route if ah user is authenticated. There are four different private route components and they all extend the functionality of the Route component from react-router-dom therefore all the props of that components apply to these components (except the render and children prop):

PrivateRoute:

You would use this component if you want your component to only accessible when a user is logged in and authenticated.

PrivateRoute Props:

proptyperequireddescriptiondefault
componentNamestringtrueif the user is authenticated and its roleAccessConfig includes this string you can access this component
redirectComponentRequired<RouteProps>['component']falseif the client is not allowed to access the route then this component will be rendered instead
redirectPathstringfalseif the redirectComponent is not provided, this prop will be navigated to"/"
pathstringtrueregular route path
componentReact.Component or functiontruecomponent to display for authorized users

MultipleRoute:

If you want components rendered under the same route name but render different components per role. For example: if we have 2 components: TeacherSchedule and StudentSchedule , now you want them to be rendered under the same route: /schedule , You want that when a user with a Teacher role is logged in, they will see the TeacherSchedule component and for a Student role, StudentSchedule . MultipleRoute was made just for this. Note that this component doesn't recieve a component prop.

MultipleRoute Props:

proptyperequireddescriptiondefault
componentsRecord<string, Required<RouteProps>['component']>truean object where the key being the component name that appears in roleAccessConfig and the value the component that you want to render
redirectComponentRequired<RouteProps>['component']falseif the client is not allowed to access the route then this component will be rendered instead
redirectpathstringfalseif the redirectComponent is not provided, this prop will be navigated to"/"
pathstringtrueregular route path

HomeRoute:

Similar to Multiple route but instead of going to see if the component names are in the components in roleAccessConfig, it goes to defaultHomePage . This compnent is good if you want a main route per role.

HomeRoute Props:

proptyperequireddescriptiondefault
componentsRecord<string, Required<RouteProps>['component']>truean object where the key being the component name that appears in roleAccessConfig and the value the component that you want to render
redirectComponentRequired<RouteProps>['component']falseif the client is not allowed to access the route then this component will be rendered instead
redirectPathstringfalseif the redirectComponent is not provided, this prop will be navigated to"/"
pathstringtrueregular route path

PublicOnlyRoute:

When a user is authenticated, a PrivateRoute will be rendered and if not a regular Route will be rendered. That means that if a user is not authenticated the component will be rendered and when not will be redirected

PublicOnlyRoute Props:

The props are the exact same as PrivateRoute .

Example

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { AuthProvider, PrivateRoute, HomeRoute, MultipleRoute } from '@hilma/auth';

import Admin from './components/Admin';
import AdminComp from './components/AdminComp';
import Client from './components/Client';
import ClientComp from './components/ClientComp';
import Login from './components/Login';
import NotFound from './components/NotFound';

const App = () => (
    <Router>
        <AuthProvider>
                <Switch>
                    <PrivateRoute path="/admin" component={Admin} componentName="adminComp" redirectComponent={NotFound} />
                    <HomeRoute path="/" components={{ adhome:Admin, clientHome:Client}} redirectPath="/login">
                    <MultipleRoute path="/pathToSomewher" components={{ comp:ClientComp, AdminComp:Client}} redirectPath="/login">
                    <Route path="/login" component={Login} />
                </Switch>
        </AuthProvider>
    </Router>
);

export default App;

UserProvider - components

A very useful component if you would like to get a current authenticated user. What this component will do is the following: Each time your access token changes, a new request will be made. It is up to you to decide what that request is. The request will be made with Axios. When the request is completed, the response will be stored in the UserContext context object:

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { AuthProvider, UserProvider } from '@hilma/auth';

import Admin from './components/Admin';
import Client from './components/Client';
import Login from './components/Login';

const App = () => (
    <Router>
        <AuthProvider>
            <UserProvider url="/api/users/getUser">
                <Switch>
                    <Route path="/admin" component={Admin} />
                    <Route path="/client" component={Client} />
                    <Route path="/login" component={Login} />
                </Switch>
            </UserProvider>
        </AuthProvider>
    </Router>
);

export default App;

UserProvider Props:

proptyperequireddescriptiondefault
urlstringtureThe url that you want to make a request to
configAxiosRequestConfigfalsethe request payload for Axios
onFinishonFinish?<U extends any>(user: U): void;falsewill be invoked with the response
onNoAccessTokenonNoAccessToken?(): void;falsewill be invoked when there is no access token
onErroronError?(error: any): void;falsewill be invoked when an error occurred
refReact.Ref<any>falsewill inject the user into the ref

Accessing the user value:

The way the user is stored is almost identical to the auth object:

via Context:

UserProvider is mainly built on React's Context API which allows you to access a certain value in any part of an application. You can use the UserContext context object however you want.

There is a custom hook that accesses the UserContext value: useUser:

import { useUser } from '@hilma/auth';

// in some functional component
const user = useUser();

There is also a HOC that can pass the user via props called withUser:

import React, { Component } from 'react';
import { withUser } from '@hilma/auth';

class MyComp extends Component {
    render() {
        <div>{this.props.user}</div>
    }
}

export default withUser(MyComp);
via Refs:

Another way you can access the user object is via React's refs. This method is useful if you want to access auth outside of components, like in redux middleware or mobx stores.

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { AuthProvider, UserProvider, createUserRef } from '@hilma/auth';

import Admin from './components/Admin';
import Client from './components/Client';
import Login from './components/Login';

export const userRef = createUserRef();

const App = () => (
    <Router>
        <AuthProvider>
            <UserProvider url="/api/users/getUser" ref={userRef}>
                <Switch>
                    <Route path="/admin" component={Admin} />
                    <Route path="/client" component={Client} />
                    <Route path="/login" component={Login} />
                </Switch>
            </UserProvider>
        </AuthProvider>
    </Router>
);

export default App;

In the file where you use UserProvider import createUserRef , invoke the function. this returns a ref object. A ref object is an object that includes one property which is current . current holds the value stored in the ref object. In UserProvider we use forwardRef's to pass the user value to the provided ref. Now when you want to access the auth object you can export the ref and access the properties via userRef.current:

import { userRef } from './App';

class ErrorStore {
	async addError() {
        const id = userRef.current.id;
        ///....
	}
}

privatize - HOC (function)

A HOC that renders a component only if the user is authenticated and the component is in roleAccessConfig. If the component is not in roleaccessconfig then nothing is rendered.

privatize params:

paramtyperequireddescriptiondefault
ComponentReact.ComponentType<P>tureThe Component you want to privatize
componentNamestringtrueThe component's name to look up in roleaccessconfig
DefaultComponentReact.ComponentType<any>falseThe component that's rendered if you cant access the component() => null

example:

import React from 'react';
import { privatize } from '@hilma/auth';

const MyComp = () => {
    return <div>Im private</div>;
}

export default privatize(MyComp);
import React from 'react';
import MyComp from './MyComp';

const App = () => {
    // will only be rendered if the name is in roleaccessconfig
    return <div><MyComp /></div>;
}

export default App;

useKlskDhp - hook

import { useKlskDhp } from '@hilma/auth';

// in some functional component
const klskDhp = useKlskDhp();

use this hook if you want to know the current roleaccessconfig thats decoded. this is more part of the private api but you can still use it.

the hook returns an object. here are the key value pairs:

keytypedescription
klskstring[]this represents the components from roleaccessconfig
dhpstringthis represents the defaultHomePage from roleaccessconfig

useRoleKeys - hook

import { useRoleKeys } from '@hilma/auth';

// in some functional component
const roleKeys = useRoleKeys();

use this hook if you want to get the decoded version of the kl cookie.

the hook returns an array of strings.

CookieTools - object

import { CookieTools } from '@hilma/auth';

This object includes functions that deal with cookies:

1. getCookieByKey returns the cookie value given by the key.

2. deleteAllCookies deletes all the browser's cookies

1. deleteCookieByKey deletes a cookie by its key

0.0.0-d1cd45fa6bb7

5 months ago

0.0.0-ec9cc4d452c5

5 months ago

0.0.0-6e2eba0fc0ad

5 months ago

0.0.0-2e9fa4d4e664

5 months ago

0.0.0-15d1c214d344

5 months ago

0.0.0-4ab9e9b184b1

5 months ago

0.0.0-89a4d3e9e1a8

5 months ago

0.0.0-977a6f61d0bd

5 months ago

0.0.0-7deebce98232

5 months ago

0.0.0-0ba347dd8821

5 months ago

0.0.0-fb1e0f8007fa

5 months ago

0.0.0-38e261c91c49

5 months ago

0.0.0-fdbc0c1b6729

5 months ago

0.0.0-0092e74e48bf

5 months ago

0.0.0-09412c21b556

5 months ago

0.0.0-c045c9ea1f9d

5 months ago

0.0.0-c94d85b0bd76

5 months ago

1.2.0

8 months ago

1.1.0

1 year ago

1.1.0-beta0

1 year ago

0.3.2

2 years ago

0.3.3

2 years ago

1.0.1-beta.9

2 years ago

1.0.1-beta.10

2 years ago

1.0.1-beta.11

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.3.1-beta.2

2 years ago

0.3.1-beta.3

2 years ago

0.3.1-beta.0

2 years ago

1.0.1-beta.2

2 years ago

1.0.0-beta.2

2 years ago

1.0.1-beta.1

2 years ago

1.0.0-beta.3

2 years ago

1.0.1-beta.0

2 years ago

1.0.1-beta.6

2 years ago

1.0.1-beta.5

2 years ago

1.0.1-beta.4

2 years ago

1.0.1-beta.3

2 years ago

1.0.0-beta.1

2 years ago

1.0.1-beta.8

2 years ago

1.0.1-beta.7

2 years ago

0.3.1

3 years ago

0.3.1-beta.1

3 years ago

0.3.0

3 years ago

0.3.0-beta.0

3 years ago

0.3.0-beta.1

3 years ago

0.2.47-beta.1

3 years ago

0.2.47-beta.0

3 years ago

0.2.48

3 years ago

0.2.47

3 years ago

0.2.4-6.beta.1

3 years ago

0.2.4-6.beta.0

3 years ago

0.2.45

3 years ago

0.2.44

3 years ago

0.2.43

3 years ago

0.2.4-2.beta.0

3 years ago

0.2.41

3 years ago

0.2.42

3 years ago

0.2.40

3 years ago

0.2.39

3 years ago

0.2.38

4 years ago

0.2.37

4 years ago

0.2.36

4 years ago

0.2.35

4 years ago

0.2.34

4 years ago

0.2.33

4 years ago

0.2.32

4 years ago

0.2.31

4 years ago

0.2.30

4 years ago

0.2.29

4 years ago

0.2.28

4 years ago

0.2.27

4 years ago

0.2.26

4 years ago

0.2.25

4 years ago

0.2.24

4 years ago

0.2.23

4 years ago

0.2.22

4 years ago

0.2.21

4 years ago

0.2.20

4 years ago

0.2.19

4 years ago

0.2.18

4 years ago

0.2.17

4 years ago

0.2.16

4 years ago

0.2.15

4 years ago

0.2.14

4 years ago

0.2.13

4 years ago

0.2.12

4 years ago

0.2.11

4 years ago

0.2.10

4 years ago

0.2.9

4 years ago

0.2.8

4 years ago

0.2.7

4 years ago

0.2.6

4 years ago

0.2.5

4 years ago

0.2.4

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago

0.2.3

4 years ago

0.2.2

4 years ago

0.1.10

4 years ago

0.1.8

4 years ago

0.1.9

4 years ago

0.1.7

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.2

4 years ago

0.1.4

4 years ago

0.1.3

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago