Суппорт jwt на фронте

This commit is contained in:
SleepWalker 2016-02-26 08:25:47 +02:00
parent 404684b8d9
commit 14d2d8eac4
4 changed files with 60 additions and 8 deletions

View File

@ -1,6 +1,6 @@
import { routeActions } from 'react-router-redux';
import { updateUser, logout as logoutUser } from 'components/user/actions';
import { updateUser, logout as logoutUser, fetchUserData } from 'components/user/actions';
import request from 'services/request';
export function login({login = '', password = '', rememberMe = false}) {
@ -12,11 +12,15 @@ export function login({login = '', password = '', rememberMe = false}) {
'/api/authentication/login',
{login, password, rememberMe}
)
.then(() => {
.then((resp) => {
dispatch(updateUser({
isGuest: false
isGuest: false,
token: resp.jwt
}));
request.setAuthToken(resp.jwt);
dispatch(fetchUserData());
dispatch(redirectToGoal());
})
.catch((resp) => {

View File

@ -1,3 +1,5 @@
import request from 'services/request';
export const UPDATE = 'USER_UPDATE';
/**
* @param {string|Object} payload jwt token or user object
@ -21,3 +23,24 @@ export function setUser(payload) {
export function logout() {
return setUser({isGuest: true});
}
export function fetchUserData() {
return (dispatch) =>
request.get('/api/users/current')
.then((resp) => {
dispatch(updateUser(resp));
})
.catch((resp) => {
/*
{
"name": "Unauthorized",
"message": "You are requesting with an invalid credential.",
"code": 0,
"status": 401,
"type": "yii\\web\\UnauthorizedHttpException"
}
*/
console.log(resp);
});
}

View File

@ -5,6 +5,9 @@ import RootPage from 'pages/root/RootPage';
import IndexPage from 'pages/index/IndexPage';
import AuthPage from 'pages/auth/AuthPage';
import request from 'services/request';
import { fetchUserData } from 'components/user/actions';
import OAuthInit from 'components/auth/OAuthInit';
import Register from 'components/auth/Register';
import Login from 'components/auth/Login';
@ -38,6 +41,13 @@ export default function routesFactory(store) {
}
}
const state = store.getState();
if (state.user.token) {
// authorizing user if it is possible
request.setAuthToken(state.user.token);
store.dispatch(fetchUserData());
}
return (
<Route path="/" component={RootPage}>
<IndexRoute component={IndexPage} onEnter={checkAuth} />

View File

@ -10,15 +10,27 @@ function serialize(data) {
;
}
let authToken;
const toJSON = (resp) => resp.json();
const handleResponse = (resp) => Promise[resp.success ? 'resolve' : 'reject'](resp);
// if resp.success does not exist - degradating to HTTP status codes
const handleResponse = (resp) => Promise[resp.success || typeof resp.success === 'undefined' ? 'resolve' : 'reject'](resp);
const getDefaultHeaders = () => {
const header = {Accept: 'application/json'};
if (authToken) {
header.Authorization = `Bearer ${authToken}`;
}
return header;
};
export default {
post(url, data) {
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
...getDefaultHeaders(),
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: serialize(data)
@ -27,6 +39,7 @@ export default {
.then(handleResponse)
;
},
get(url, data) {
if (typeof data === 'object') {
const separator = url.indexOf('?') === -1 ? '?' : '&';
@ -34,12 +47,14 @@ export default {
}
return fetch(url, {
headers: {
Accept: 'application/json'
}
headers: getDefaultHeaders()
})
.then(toJSON)
.then(handleResponse)
;
},
setAuthToken(tkn) {
authToken = tkn;
}
};