-
Notifications
You must be signed in to change notification settings - Fork 1
Exports
- checkAccessTokenExpiration
- loginRequest
- logoutRequest
- setTokensPersistence
- setUserWithTokens
- terminate
- 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
- loginReset
Ƭ PetrusCredentials: Petrus.ConfigureCredentials
extends { value
: unknown
} ? Petrus.ConfigureCredentials
["value"
] : void
Ƭ PetrusLogger: Object
Name | Type |
---|---|
error |
Console ["error" ] |
warn |
Console ["warn" ] |
Ƭ PetrusOAuth: Object
Name | Type |
---|---|
searchParams |
Record <string , any > |
Ƭ PetrusRefreshTokens: Required
<PetrusTokens
>
Ƭ PetrusTokens: Petrus.ConfigureTokens
extends { value
: Tokens
} ? Petrus.ConfigureTokens
["value"
] : Tokens
Ƭ PetrusUser: Petrus.ConfigureUser
extends { value
: unknown
} ? Petrus.ConfigureUser
["value"
] : any
• 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.
example
import { put } from 'redux-saga/effects';
import { checkAccessTokenExpiration } from '@ackee/petrus';
export function* saga() {
yield put(checkAccessTokenExpiration());
}
modules/tokens/modules/refreshment/actions/general.ts:22
• Const
loginRequest: ActionCreatorWithoutPayload
<"@@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
}
}
})
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());
}
modules/auth-session/actions/logout.ts:35
• Const
setTokensPersistence: ActionCreatorWithPayload
<TokensPersistence
, "@@petrus/SET_TOKENS_PERSISTENCE"
>
example
1. Override the default tokensPersistence
value:
import { configure, TokensPersistence } from '@ackee/petrus';
const { saga, reducer } = configure({
// ...
initialState: {
tokensPersistence: TokensPersistence.NONE,
},
});
example
2. Set tokens persistence dynamically:
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));
}
modules/tokens/modules/storage/actions/index.ts:40
• Const
setUserWithTokens: ActionCreatorWithPreparedPayload
<[user: any, tokens: Tokens], { tokens
: Tokens
; 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,
},
}),
);
}
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.
services/actions/control.ts:14
• 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).
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
.
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
.
services/actions/authSession.ts:69
• Const
AUTH_SESSION_PAUSE: "@@petrus/AUTH_SESSION_PAUSE"
This action is triggered on the access token refreshment start.
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.
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) {
// ...
});
}
services/actions/authSession.ts:48
• Const
LOGIN_FAILURE: "@@petrus/LOGIN_FAILURE"
Triggered on failed login.
modules/auth-session/actions/login.ts:85
• 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)
}
modules/auth-session/actions/login.ts:78
• Const
RETRIEVE_TOKENS_REQUEST: "@@petrus/RETRIEVE_TOKENS_REQUEST"
This action is triggered right before tokens retrieval from a local storage begins.
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.
modules/tokens/modules/retrieval/actions/index.ts:33
• Const
loginReset: ActionCreatorWithoutPayload
<"@@petrus/LOGIN_RESET"
> = login.reset
modules/auth-session/actions/login.ts:55
▸ configure(customConfig
): Object
link
{TODO: link}
example
interface Credentials {
email: string;
password: string;
}
interface UserInfo {
id: string;
name: string;
}
type RootState = ReturnType<typeof rootReducer>;
declare global {
namespace Petrus {
interface ConfigureCredentials {
value: Credentials;
}
interface ConfigureUser {
value: UserInfo;
}
interface ConfigureAppRootState {
value: BackgroundRootState;
}
}
}
export const { reducer, saga } = configure({
selector: state => state.auth,
handlers: {
authenticate(credentials: PetrusCredentials) {
const user: PetrusUser | undefined = {
id: '1',
name: 'Bob',
};
const tokens: PetrusTokens = {
accessToken: {
token: '...',
expiration: '...',
},
refreshToken: {
token: '...',
},
};
return {
user,
tokens,
};
},
refreshTokens(tokens: PetrusRefreshTokens) {
const freshTokens: PetrusTokens = {
accessToken: {
token: '...',
expiration: '...',
},
refreshToken: {
token: '...',
},
};
return freshTokens;
},
getAuthUser(tokens: PetrusTokens) {
const user: PetrusUser = {
id: '1',
name: 'Bob',
};
return user;
},
},
});
Name | Type |
---|---|
customConfig |
PetrusCustomConfig <PetrusConfig > |
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
components/Authenticated/Authenticated.tsx:35
▸ useAuthenticated(): FlowType
▸ getAccessToken(): Generator
<any
, null
| { expiration?
: null
| string
; token
: string
}, 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
}, unknown
>
services/sagas/getAccessToken.ts:88
▸ retrieveTokens(): Generator
<any
, void
, unknown
>
Generator
<any
, void
, unknown
>
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
>
services/sagas/withAuthSession.ts:40
▸ accessTokenSelector(state
): null
| { expiration?
: null
| string
; token
: string
}
Name | Type |
---|---|
state |
any |
null
| { expiration?
: null
| string
; token
: string
}
services/selectors/tokens.ts:17
▸ apiSelector(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 | Type |
---|---|
state |
any |
apiKey |
ApiKeys |
ApiState
▸ entitiesSelector(state
): PetrusEntitiesState
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 |
---|---|
state |
any |
services/selectors/entities.ts:21
▸ tokensPersistenceSelector(state
): TokensPersistence
Name | Type |
---|---|
state |
any |
services/selectors/tokens.ts:12
▸ tokensSelector(state
): null
| Tokens
Name | Type |
---|---|
state |
any |
null
| Tokens
services/selectors/tokens.ts:7
▸ 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.