-
Notifications
You must be signed in to change notification settings - Fork 1
Exports
- ACCESS_TOKEN_AVAILABLE
- ACCESS_TOKEN_UNAVAILABLE
- AUTH_SESSION_END
- AUTH_SESSION_PAUSE
- AUTH_SESSION_RESUME
- AUTH_SESSION_START
- LOGIN_FAILURE
- LOGIN_SUCCESS
- RETRIEVE_TOKENS_REQUEST
- RETRIEVE_TOKENS_RESOLVE
Ƭ PetrusCredentials: any
Ƭ PetrusLogger: Object
Name | Type |
---|---|
error |
Console ["error" ] |
Ƭ PetrusOAuth: Object
Name | Type |
---|---|
searchParams |
Record <string , any > |
Ƭ PetrusTokens: Object
Name | Type |
---|---|
accessToken |
{ expiration? : string | null ; token : string } & Record <string , any > |
refreshToken? |
{ token : string } & Record <string , any > |
Ƭ PetrusUser: any
Ƭ StorageDriver: Object
Name | Type |
---|---|
get |
<Key, Value>(k : Key ) => HandlerReturnValue <void | Value > |
remove |
<Key>(k : Key ) => HandlerReturnValue <void > |
set |
<Key, Value>(k : Key , v : Value ) => HandlerReturnValue <void > |
• Const
storageDrivers: Object
Name | Type |
---|---|
indexedDB |
{ get : <Key>(key : Key ) => Promise <any > ; remove : <Key>(key : Key ) => Promise <void > ; set : <Key, Value>(key : Key , val : Value ) => Promise <void | IDBValidKey > } |
indexedDB.get |
[object Object] |
indexedDB.remove |
[object Object] |
indexedDB.set |
[object Object] |
resetStorage |
{ get : () => null ; set : () => void ; remove : <Key>(key : Key ) => Promise <void > } |
resetStorage.get |
() => null
|
resetStorage.set |
() => void
|
resetStorage.remove |
[object Object] |
sessionStorage |
{ get : <Key>(key : Key ) => any ; remove : <Key>(key : Key ) => void ; set : <Key, Value>(key : Key , values : Value ) => void } |
sessionStorage.get |
[object Object] |
sessionStorage.remove |
[object Object] |
sessionStorage.set |
[object Object] |
• Const
checkAccessTokenExpiration: ActionCreatorWithoutPayload
<"@@petrus/CHECK_ACCESS_TOKEN_EXPIRATION"
>
This action will trigger a saga that checks if the access token is expired. If it's, then the access token is refreshed.
src/modules/tokens/modules/refreshment/actions/general.ts:12
• Const
loginRequest: ActionCreatorWithPayload
<any
, "@@petrus/LOGIN_REQUEST"
> = login.request
The credentials object is passed to the authenticate
handler you've provided in the configure
method.
example
import { loginRequest } from '@ackee/petrus';
function* login() {
yield put(loginRequest({
email: '[email protected]',
password: 'password123'
}))
}
// ...
// in `authenticate` handler:
configure({
// ...
handlers: {
// ...
authenticate: function* authenticateHandler({ email, password }) {
// Use the credentials to sign-in user
}
}
})
src/modules/auth-session/actions/login.ts:50
• Const
logoutRequest: ActionCreatorWithoutPayload
<"@@petrus/LOGOUT_REQUEST"
> = logout.request
Triggers a user logout flow: tokens are cleared from a persistent storage and any auth. data are cleared from the reducer.
example
import { put } from 'redux-saga/effects';
import { logoutRequest } from '@ackee/petrus';
function* logoutSaga() {
yield put(logoutRequest());
}
src/modules/auth-session/actions/logout.ts:35
• Const
setUserWithTokens: ActionCreatorWithPreparedPayload
<[user: any, tokens: PetrusTokens], { tokens
: PetrusTokens
; user
: any
}, "@@petrus/SET_USER_WITH_TOKENS"
, never
, never
>
If there is available an auth. user and tokens (e.g. from a user sign up),
this action will store these data as they would come from the authenticate
handler.
Thus, the user is signed in without an additional API request required.
Note: If you dispatch this action when a user is already logged in, the logoutRequest action will be first dispatched and then the flow will continue as usual.
example
import { put } from 'redux-saga/effects';
import { setUserWithTokens } from '@ackee/petrus';
function* signUp({ email, password }) {
const { data } = yield api.post('/auth/sign-up', {
email,
password,
});
const { user, accessToken, refreshToken, expiration } = data;
yield put(
setUserWithTokens(user, {
accessToken: {
token: accessToken,
expiration,
},
refreshToken: {
token: refreshToken,
},
}),
);
}
src/modules/auth-session/actions/setUserWithTokens.ts:41
• Const
terminate: ActionCreatorWithoutPayload
<"@@petrus/TERMINATE"
>
Calls cancel redux saga effect on root Petrus saga and therefore end all infinite loops within.
This cancel the saga returned from the configure
method.
src/services/actions/control.ts:14
• Const
setTokensPersistence: ActionCreatorWithPayload
<TokensPersistence
, "@@petrus/SET_TOKENS_PERSISTENCE"
>
example
import { configure, TokensPersistence } from '@ackee/petrus';
const { saga, reducer } = configure({
// ...
initialState: {
tokensPersistence: TokensPersistence.NONE,
},
});
example
import { put } from 'redux-saga/effects';
import { setTokensPersistence, TokensPersistence } from '@ackee/petrus';
function* disableTokensPersistence() {
yield put(setTokensPersistence(TokensPersistence.NONE));
}
function* enableTokensPersistence() {
yield put(setTokensPersistence(TokensPersistence.LOCAL));
}
src/modules/tokens/modules/storage/actions/index.ts:40
• Const
ACCESS_TOKEN_AVAILABLE: "@@petrus/ACCESS_TOKEN_AVAILABLE"
When the access token becomes available, this action is dispatched (on LOGIN_SUCCESS and REFRESH_TOKENS_SUCCESS).
src/services/actions/accessTokenAvailability.ts:28
• Const
ACCESS_TOKEN_UNAVAILABLE: "@@petrus/ACCESS_TOKEN_UNAVAILABLE"
Access token becomes unavailable on logout or when tokens refreshment start.
It's guaranteed that the ACCESS_TOKEN_UNAVAILABLE
action will be dispatched only once after ACCESS_TOKEN_AVAILABLE
.
src/services/actions/accessTokenAvailability.ts:35
• Const
AUTH_SESSION_END: "@@petrus/AUTH_SESSION_END"
The AUTH_SESSION_END
action is triggered on AUTH_LOGOUT_SUCCESS
or REFRESH_TOKENS_FAILURE
.
src/services/actions/authSession.ts:69
• Const
AUTH_SESSION_PAUSE: "@@petrus/AUTH_SESSION_PAUSE"
This action is triggered on the access token refreshment start.
src/services/actions/authSession.ts:55
• Const
AUTH_SESSION_RESUME: "@@petrus/AUTH_SESSION_RESUME"
If access token refreshment was successful, AUTH_SESSION_RESUME
is triggered. It's guaranteed it will be dispatched only after AUTH_SESSION_PAUSE
action.
src/services/actions/authSession.ts:62
• Const
AUTH_SESSION_START: "@@petrus/AUTH_SESSION_START"
Once a user has been successfully logged in, this action is dispatched. It's guaranteed that AUTH_SESSION_END
must be triggered first before another AUTH_SESSION_START
trigger.
example
import { put } from 'redux-saga/effects';
import { AUTH_SESSION_START } from '@ackee/petrus';
function* watchAuthSession() {
yield takeEvery(AUTH_SESSION_START, function* (action) {
// ...
});
}
src/services/actions/authSession.ts:48
• Const
LOGIN_FAILURE: "@@petrus/LOGIN_FAILURE"
Triggered on failed login.
src/modules/auth-session/actions/login.ts:80
• Const
LOGIN_SUCCESS: "@@petrus/LOGIN_SUCCESS"
Triggered on successful login.
example
function* handleLogin() {
// dispatch login request to '@ackee/petrus'
yield put(loginRequest({
email: '[email protected]',
password: 'supersecret',
}));
// wait for the request to resolve
const result = yield take([LOGIN_SUCCESS, LOGIN_FAILURE]);
// and then do something (e.g. display login error, redirect user to auth. content)
}
src/modules/auth-session/actions/login.ts:73
• Const
RETRIEVE_TOKENS_REQUEST: "@@petrus/RETRIEVE_TOKENS_REQUEST"
This action is triggered right before tokens retrieval from a local storage begins.
src/modules/tokens/modules/retrieval/actions/index.ts:27
• Const
RETRIEVE_TOKENS_RESOLVE: "@@petrus/RETRIEVE_TOKENS_RESOLVE"
This action contains payload.tokensRetrieved
flag with the tokens retrieval result.
src/modules/tokens/modules/retrieval/actions/index.ts:33
• Const
accessTokenSelector: (state
: never
, ...params
: []) => null
| { expiration?
: null
| string
; token
: string
} & Record
<string
, any
> & OutputSelectorFields
<(...args
: [null
| PetrusTokens
]) => { expiration?
: null
| string
; token
: string
} & Record
<string
, any
> & { clearCache
: () => void
}> & { clearCache
: () => void
}
src/services/selectors/tokens.ts:17
• Const
tokensPersistenceSelector: (state
: {}, ...params
: []) => TokensPersistence
& OutputSelectorFields
<(...args
: [PetrusEntitiesState
<unknown
>]) => NONE
& { clearCache
: () => void
} & LOCAL
& { clearCache
: () => void
} & SESSION
& { clearCache
: () => void
}> & { clearCache
: () => void
}
src/services/selectors/tokens.ts:12
• Const
tokensSelector: (state
: {}, ...params
: []) => null
| PetrusTokens
& OutputSelectorFields
<(...args
: [PetrusEntitiesState
<unknown
>]) => PetrusTokens
& { clearCache
: () => void
}> & { clearCache
: () => void
}
src/services/selectors/tokens.ts:7
▸ authorizable(AuthorizableComponent
, Firewall
, Loader?
): (props
: any
) => Element
High order component that based on current state of the auth
reducer renders one of these components:
-
AuthorizableComponent
it is rendered only if an authorized user had been fetched (->state.auth.user
) -
Firewall
is rendered if application isn't authorized -
Loader
(optional) is renderer whenever the app can't determinate if it's authorized or not (e.g. when app is loading and it doesn't know yet if tokens are available or not)
deprecated
Use Authenticated
component instead.
example
import React from 'react';
import { authorizable } from '@ackee/petrus';
const AuthContent = <div>User is logged in</div>;
const Firewall = <div>Please login</div>;
const Loader = <div>Loading...</div>;
const AuthorizedComponent = authorizable(AuthContent, Firewall, Loader);
export default AuthorizedComponent;
Name | Type | Default value |
---|---|---|
AuthorizableComponent |
any |
undefined |
Firewall |
any |
undefined |
Loader |
() => Element
|
MockAppLoader |
fn
▸ (props
): Element
Name | Type |
---|---|
props |
any |
Element
Name | Type |
---|---|
displayName |
string |
▸ configure<User
, Credentials
, AppState
>(customConfig
): Object
Name | Type |
---|---|
User |
extends unknown = any
|
Credentials |
extends unknown = any
|
AppState |
extends Record <string , any > = Record <string , any > |
Name | Type |
---|---|
customConfig |
PetrusCustomConfig <User , Credentials , PetrusConfig <User , Credentials , PetrusLogger >> |
Object
Name | Type |
---|---|
reducer |
Reducer <CombinedState <Object >, AnyAction > |
saga |
() => Generator <TakeEffect | CancelEffect | ForkEffect <Generator <AllEffect <Generator <AllEffect <false | Generator <any , void , unknown >>, void , unknown >>, void , unknown >>, void , Task > |
▸ Authenticated(__namedParameters
): null
| Element
-
children
rendered ifflowType === FlowType.AUTHENTICATED
: valid access token and auth user are available. -
FallbackComponent
rendered ifflowType === FlowType.ANONYMOUS
: app is unauthorized -
Loader
renderer whenever the app can't determinate if theflowType
isFlowType.AUTHENTICATED
irFlowType.ANONYMOUS
: authorized or not.
example
import React from 'react';
import { Authenticated } from '@ackee/petrus';
import MyLoginForm from './MyLoginForm';
const MyLoader = () => <div>Loading...</div>;
const MyComponent = () => (
<Authenticated FallbackComponent={MyLoginForm} LoaderComponent={MyLoader}>
<div>Private content</div>
</Authenticated>
);
Name | Type |
---|---|
__namedParameters |
AuthenticatedProps |
null
| Element
src/components/Authenticated/Authenticated.tsx:35
▸ useAuthenticated(): FlowType
src/hooks/useAuthenticated.ts:8
▸ getAccessToken(): Generator
<any
, null
| { expiration?
: null
| string
; token
: string
} & Record
<string
, any
>, unknown
>
Generator function returning PetrusTokens['accessToken'] or null
.
example
import { getAccessToken } from '@ackee/petrus';
function* mySaga() {
const accessToken = yield* getAccessToken();
console.log(accessToken);
}
Generator
<any
, null
| { expiration?
: null
| string
; token
: string
} & Record
<string
, any
>, unknown
>
src/services/sagas/getAccessToken.ts:88
▸ retrieveTokens(): Generator
<any
, void
, unknown
>
Generator
<any
, void
, unknown
>
src/modules/tokens/modules/retrieval/sagas/retrieveTokens.ts:88
▸ withAuthSession<Fn
>(task
): Generator
<any
, void
, unknown
>
A generator function that receives any function as 1st parameter. The provided function will be launched on AUTH_SESSION_START
action and cancelled on AUTH_SESSION_END
.
Note that withAuthSession
is a blocking task (if you need to make it non-blocking one, use it with fork
effect).
example
import { withAuthSession } from '@ackee/petrus';
function* myAuthSaga() {}
export default function* () {
yield* withAuthSession(myAuthSaga);
// non-blocking version: yield fork(withAuthSession, myAuthSaga);
}
Name | Type |
---|---|
Fn |
extends DefaultFn
|
Name | Type |
---|---|
task |
Fn |
Generator
<any
, void
, unknown
>
src/services/sagas/withAuthSession.ts:40
▸ apiSelector<AppState
>(state
, apiKey
): ApiState
example
import { select } from 'redux-saga/effects';
import { createSelector } from 'reselect';
import { apiSelector, ApiKeys } from '@ackee/petrus';
const fetchUserSelector = createSelector(apiSelector, api => api[ApiKeys.FETCH_USER]);
function* selectFetchUser() {
const { inProgress, success, error } = yield select(fetchUserSelector);
// ...
}
Name |
---|
AppState |
Name | Type |
---|---|
state |
AppState |
apiKey |
ApiKeys |
ApiState
src/services/selectors/api.ts:21
▸ entitiesSelector<AppState
, User
>(state
): PetrusEntitiesState
<User
>
example
import { select } from 'redux-saga/effects';
import { createSelector } from 'reselect';
import { entitiesSelector } from '@ackee/petrus';
const authUserSelector = createSelector(entitiesSelector, entities => entities.user);
function* selectAuthUser() {
const authUser = yield select(authUserSelector);
// ...
}
Name | Type |
---|---|
AppState |
AppState |
User |
extends unknown = any
|
Name | Type |
---|---|
state |
AppState |
PetrusEntitiesState
<User
>
src/services/selectors/entities.ts:21
▸ createExpirationDate(expiresIn
): null
| string
Converts duration in ms to timestamp.
example
import { createExpirationDate } from '@ackee/petrus';
// expiratioDate will be in following format: "2019-02-19T21:02:57.970Z"
const expirationDate = createExpirationDate(3600 * 1000);
// VALID:
createExpirationDate('3600000');
createExpirationDate(null);
createExpirationDate(undefined);
// INVALID:
createExpirationDate('foo');
createExpirationDate('foo123');
Name | Type | Description |
---|---|---|
expiresIn |
undefined | null | string | number
|
value in ms when access token expires |
null
| string
Access token expiration date in ISO string format.