import * as jwtDecode from 'jwt-decode' import { ThunkAction } from 'redux-thunk' import { createTokens } from './createTokens' import { getTokens, removeTokens } from './localStorage' import { refreshTokens } from './refreshTokens' export const AUTH_INIT = 'AUTH_INIT' export const AUTH_LOGIN = 'AUTH_LOGIN' export const AUTH_LOGOUT = 'AUTH_LOGOUT' export const AUTH_REFRESH = 'AUTH_REFRESH' export function authInit() { return { type: AUTH_INIT } } export function authLogin(username: string, password: string): ThunkAction, any, any> { return async dispatch => { const result = await createTokens(username, password) const tokens = getTokens() if (result && tokens.access) { const nextPrincipal = jwtDecode(tokens.access) dispatch({ type: AUTH_LOGIN, principal: nextPrincipal, tokens }) } return result } } export function authLogout(): ThunkAction { return async dispatch => { removeTokens() dispatch({ type: AUTH_LOGOUT }) } } export function authRefresh(): ThunkAction, any, any> { return async dispatch => { const result = await refreshTokens() const tokens = getTokens() if (result && tokens.access) { const nextPrincipal = jwtDecode(tokens.access) dispatch({ type: AUTH_REFRESH, principal: nextPrincipal, tokens }) } return result } }