diff --git a/src/redux/actions.js b/src/redux/actions.js index 740a951ee..c82973ef0 100644 --- a/src/redux/actions.js +++ b/src/redux/actions.js @@ -1,10 +1,13 @@ var keyMirror = require('keymirror'); var api = require('../mixins/api.jsx').api; +var jar = require('../lib/jar.js'); var Types = keyMirror({ - REFRESH_SESSION: null, SET_SESSION: null, - SET_SESSION_ERROR: null + SET_SESSION_ERROR: null, + SET_TOKEN: null, + SET_TOKEN_ERROR: null, + USE_TOKEN: null }); var Actions = { @@ -36,12 +39,45 @@ var Actions = { if (body.banned) { return window.location = url; } else { - return dispatch(Actions.setSession(body)); + dispatch(Actions.getToken()); + dispatch(Actions.setSession(body)); + return; } } }); }; }, + + getToken: function () { + return function (dispatch) { + jar.get('scratchsessionsid', function (err, value) { + if (err) return dispatch(Actions.setTokenError(err)); + jar.unsign(value, function (err, contents) { + if (err) return dispatch(Actions.setTokenError(err)); + try { + var sessionData = JSON.parse(contents); + } catch (err) { + return dispatch(Actions.setTokenError(err)); + } + return dispatch(Actions.setToken(sessionData.token)); + }); + }); + } + }, + + setToken: function (token) { + return { + type: Types.SET_TOKEN, + token: token + }; + }, + + setTokenError: function (error) { + return { + type: Types.SET_SESSION_ERROR, + error: error + }; + } }; module.exports = Actions; diff --git a/src/redux/reducer.js b/src/redux/reducer.js index 2ae881afe..d9b522677 100644 --- a/src/redux/reducer.js +++ b/src/redux/reducer.js @@ -5,7 +5,6 @@ var actionTypes = require('./actions.js').types; var sessionReducer = function (state, action) { // Reducer for handling changes to session state - if (typeof state === 'undefined') { state = {}; } @@ -20,8 +19,25 @@ var sessionReducer = function (state, action) { } }; +var tokenReducer = function (state, action) { + // Reducer for updating the api token + if (typeof state === 'undefined') { + state = ''; + } + switch (action.type) { + case actionTypes.SET_TOKEN: + return action.token; + case actionTypes.SET_TOKEN_ERROR: + // TODO: do something with the error + return state; + default: + return state; + } +}; + var appReducer = combineReducers({ - session: sessionReducer + session: sessionReducer, + token: tokenReducer }); module.exports = appReducer;