Skip to content

Instantly share code, notes, and snippets.

@OleksivO
Last active May 5, 2020 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OleksivO/171f51eac6ea2b280e6d21338051ac4c to your computer and use it in GitHub Desktop.
Save OleksivO/171f51eac6ea2b280e6d21338051ac4c to your computer and use it in GitHub Desktop.
the description for this gist
import {delay} from 'redux-saga';
import {put, call, takeEvery} from 'redux-saga/effects';
import axios from "axios";
import * as actions from '../actions/authorization'
export default function* watchAuthSaga() {...}
function* authUser(action) {
yield put(actions.authStart());
const url = action.signin ? 'SIGNIN_URL' : 'SIGNUP_URL';
try {
const response = yield call(() => axios.post(url, { email: action.email, password: action.password}));
const expirationDate = new Date(new Date().getTime() + response.data.expiresIn * 1000);
yield localStorage.setItem('token', response.data.token);
yield localStorage.setItem('expirationDate', expirationDate);
yield localStorage.setItem('userId', response.data.userId);
yield put(actions.authSuccess(response.data.token, response.data.userId));
yield put(actions.checkAuthTimeout(response.data.expiresIn));
} catch (error) {
yield put(actions.authFail(error))
}
}
function* checkAuthTimeout(action) {
yield delay(action.expirationTime * 1000);
yield put(actions.logout());
}
function* logout(action) {
yield localStorage.removeItem('token');
yield localStorage.removeItem('expirationDate');
yield localStorage.removeItem('userId');
yield put(actions.logoutSucceed())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment