Skip to content

Commit

Permalink
Refactored authentication state management to the reducer, it was chi…
Browse files Browse the repository at this point in the history
…lling inside of the action
  • Loading branch information
anther committed Oct 12, 2018
1 parent 2ead03e commit 0c3a343
Show file tree
Hide file tree
Showing 6 changed files with 145 additions and 147 deletions.
47 changes: 10 additions & 37 deletions app/actions/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import electronSettings from 'electron-settings';
import { endpoints, SmashLadderAuthentication } from '../utils/SmashLadderAuthentication';
import getAuthenticationFromState from '../utils/getAuthenticationFromState';

export const SET_LOGIN_KEY = 'SET_LOGIN_KEY';
export const INVALID_LOGIN_KEY = 'INVALID_LOGIN_KEY';

export const LOGIN_BEGIN = 'LOGIN_BEGIN';
Expand All @@ -22,52 +21,32 @@ export const ENABLE_DEVELOPMENT_URLS = 'ENABLE_DEVELOPMENT_URLS';
export const setLoginKey = (loginCode) => {
return (dispatch, getState) => {
const currentState = getState();

const { productionUrls } = currentState.login;
dispatch({
type: LOGIN_BEGIN,
payload: loginCode
});
const authentication = SmashLadderAuthentication.create({
loginCode,
productionUrls: currentState.login.productionUrls
productionUrls
});
const state = {
loginCode: loginCode
};
if (!authentication.getAccessCode()) {
dispatch({
type: INVALID_LOGIN_KEY,
payload: {
...state,
loginErrors: ['Invalid Key']
}
payload: 'Invalid Key'
});
return;
}
dispatch({
type: LOGIN_BEGIN,
payload: {
...state,
player: null,
isLoggingIn: true,
loginErrors: []
}
});
authentication
.isAuthenticated()
.then(() => {
const saveDatas = {};
saveDatas.loginCode = loginCode;
saveDatas.sessionId = authentication.session_id;
saveDatas.player = authentication.player;
electronSettings.set('login', saveDatas);
dispatch({
type: LOGIN_SUCCESS,
payload: {
...state,
player: authentication.player,
isLoggingIn: false,
sessionId: authentication.session_id
}
payload: authentication
});
})
.catch(response => {
console.error(response);
let error = null;
if (response.statusCode === 401) {
error = 'Invalid Code, Maybe it expired?';
Expand All @@ -88,13 +67,7 @@ export const setLoginKey = (loginCode) => {
}
dispatch({
type: LOGIN_FAIL,
payload: {
...state,
player: null,
loginErrors: error,
isLoggingIn: false,
showLoginButton: true
}
payload: error
});
});
};
Expand Down
1 change: 0 additions & 1 deletion app/actions/replayWatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ export const beginWatchingForReplayChanges = () => (dispatch, getState) => {
paths.sort();

if (_.isEqual(replayWatchPaths, paths)) {
console.log('already wtaching same paths?', replayWatchPaths, paths);
return;
}

Expand Down
2 changes: 1 addition & 1 deletion app/containers/BuildsPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class BuildsPage extends Component<Props> {
productionUrls: props.productionUrls,
authentication: SmashLadderAuthentication.create({
loginCode: props.loginCode,
session_id: props.sessionId,
sessionId: props.sessionId,
productionUrls: props.productionUrls
})
};
Expand Down
36 changes: 31 additions & 5 deletions app/reducers/login.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import electronSettings from 'electron-settings';
import {
SET_LOGIN_KEY,
LOGIN_FAIL,
LOGIN_SUCCESS,
LOGIN_BEGIN,
Expand Down Expand Up @@ -60,14 +59,41 @@ export default (state = initialState, action) => {
...defaultLoginState,
productionUrls: state.productionUrls
};
case LOGIN_SUCCESS:
case SET_LOGIN_KEY:
case LOGIN_FAIL:
case INVALID_LOGIN_KEY:
return {
...state,
loginErrors: [action.payload],
isLoggingIn: false,
};
case LOGIN_BEGIN:
return {
...state,
...action.payload
loginCode: action.payload,
player: null,
isLoggingIn: true,
loginErrors: []
};
case LOGIN_SUCCESS: {
const { player, sessionId } = action.payload;
electronSettings.set('login', {
loginCode: state.loginCode,
sessionId: sessionId,
player: player
});
return {
...state,
player: player,
sessionId: sessionId,
isLoggingIn: false,
};
}
case LOGIN_FAIL:
return {
...state,
player: null,
loginErrors: [action.payload],
isLoggingIn: false,
showLoginButton: true
};
default:
return state;
Expand Down
204 changes: 102 additions & 102 deletions app/utils/SmashLadderAuthentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,119 +5,119 @@ const request = require('request-promise-native');
const ClientOAuth2 = require('client-oauth2');

export const endpoints = {
PLAYER_PROFILE: 'player/me',
SUBMIT_REPLAY_RESULT: 'dolphin/slippi_replay',
LOGIN: 'dolphin/credentials_link',
DOLPHIN_BUILDS: 'dolphin/all_builds',
CLOSED_DOLPHIN: 'dolphin/closed_host',
OPENED_DOLPHIN: 'dolphin/opened_dolphin',
UPDATE_BUILD_PREFERENCES: 'matchmaking/update_active_build_preferences',
DOLPHIN_HOST: 'dolphin/set_host_code',
REPORT_MATCH_GAME: 'dolphin/report_match_game',
RETRIEVE_MATCH_GAME_ID: 'dolphin/prepare_match_game',
DOLPHIN_PLAYER_JOINED: 'dolphin/player_list_update',
SET_ACTIVE_BUILDS: 'matchmaking/set_active_builds',
WEBSOCKET_URL: productionUrls =>
productionUrls === false
? 'ws://localhost:100'
: 'wss://www.smashladder.com',
LOGOUT: 'player/logout'
PLAYER_PROFILE: 'player/me',
SUBMIT_REPLAY_RESULT: 'dolphin/slippi_replay',
LOGIN: 'dolphin/credentials_link',
DOLPHIN_BUILDS: 'dolphin/all_builds',
CLOSED_DOLPHIN: 'dolphin/closed_host',
OPENED_DOLPHIN: 'dolphin/opened_dolphin',
UPDATE_BUILD_PREFERENCES: 'matchmaking/update_active_build_preferences',
DOLPHIN_HOST: 'dolphin/set_host_code',
REPORT_MATCH_GAME: 'dolphin/report_match_game',
RETRIEVE_MATCH_GAME_ID: 'dolphin/prepare_match_game',
DOLPHIN_PLAYER_JOINED: 'dolphin/player_list_update',
SET_ACTIVE_BUILDS: 'matchmaking/set_active_builds',
WEBSOCKET_URL: productionUrls =>
productionUrls === false
? 'ws://localhost:100'
: 'wss://www.smashladder.com',
LOGOUT: 'player/logout'
};

export class SmashLadderAuthentication extends CacheableDataObject {
beforeConstruct() {
this.player = null;
this.loginCode = null;
this.session_id = null;
this.productionUrls = null;
}
beforeConstruct() {
this.player = null;
this.loginCode = null;
this.sessionId = null;
this.productionUrls = null;
}

fullEndpointUrl(endpoint) {
let SITE_URL = 'https://www.smashladder.com';
if (this.productionUrls === false) {
SITE_URL = 'http://localhost/smashladder';
}
const API_URL = `${SITE_URL}/api/v1`;
if (typeof endpoint === 'string') {
return `${API_URL}/${endpoint}`;
}
fullEndpointUrl(endpoint) {
let SITE_URL = 'https://www.smashladder.com';
if (this.productionUrls === false) {
SITE_URL = 'http://localhost/smashladder';
}
const API_URL = `${SITE_URL}/api/v1`;
if (typeof endpoint === 'string') {
return `${API_URL}/${endpoint}`;
}

return endpoint(this.productionUrls);
}
return endpoint(this.productionUrls);
}

parseCredentials() {
let string = '';
try {
string = atob(this.loginCode);
} catch (error) {
return {
access: null
};
}
const split = string.split(':');
return {
access: split[1]
};
}
parseCredentials() {
let string = '';
try {
string = atob(this.loginCode);
} catch (error) {
return {
access: null
};
}
const split = string.split(':');
return {
access: split[1]
};
}

getAccessCode() {
const credentials = this.parseCredentials();
return credentials.access;
}
getAccessCode() {
const credentials = this.parseCredentials();
return credentials.access;
}

apiGet(endpoint) {
return this.request({
url: this.fullEndpointUrl(endpoint),
method: 'GET'
});
}
apiGet(endpoint) {
return this.request({
url: this.fullEndpointUrl(endpoint),
method: 'GET'
});
}

apiPost(endpoint, sendData) {
return this.request({
url: this.fullEndpointUrl(endpoint),
method: 'POST',
form: sendData
});
}
apiPost(endpoint, sendData) {
return this.request({
url: this.fullEndpointUrl(endpoint),
method: 'POST',
form: sendData
});
}

async request(requestData) {
if (!this.getAccessCode()) {
throw new Error('Invalid Login Credentials');
}
return this._sendRequest(requestData);
}
async request(requestData) {
if (!this.getAccessCode()) {
throw new Error('Invalid Login Credentials');
}
return this._sendRequest(requestData);
}

_sendRequest(requestData) {
const oauthAuth = new ClientOAuth2({});
console.log('[SEND REQUEST]', requestData);
if (!this.getAccessCode()) {
throw new Error('Invalid Login Code');
}
const token = oauthAuth.createToken(this.getAccessCode());
const signedRequest = token.sign(requestData);
// console.log('['+requestData.method+']', requestData);
return request(signedRequest).then(response => {
try {
return JSON.parse(response);
} catch (error) {
throw new Error(response);
}
});
}
_sendRequest(requestData) {
const oauthAuth = new ClientOAuth2({});
console.log('[SEND REQUEST]', requestData);
if (!this.getAccessCode()) {
throw new Error('Invalid Login Code');
}
const token = oauthAuth.createToken(this.getAccessCode());
const signedRequest = token.sign(requestData);
// console.log('['+requestData.method+']', requestData);
return request(signedRequest).then(response => {
try {
return JSON.parse(response);
} catch (error) {
throw new Error(response);
}
});
}

async isAuthenticated() {
if (this.checkValid) {
console.log('[SHORTCUT CHECK]');
return this;
}
async isAuthenticated() {
if (this.checkValid) {
console.log('[SHORTCUT CHECK]');
return this;
}

return this._sendRequest({
url: this.fullEndpointUrl(endpoints.PLAYER_PROFILE),
method: 'GET'
}).then(response => {
this.player = response.player;
this.session_id = response.session_id;
return this;
});
}
return this._sendRequest({
url: this.fullEndpointUrl(endpoints.PLAYER_PROFILE),
method: 'GET'
}).then(response => {
this.player = response.player;
this.sessionId = response.session_id;
return this;
});
}
}
2 changes: 1 addition & 1 deletion app/utils/getAuthenticationFromState.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export default function getAuthenticationFromState(getState) {
const state = getState();
return SmashLadderAuthentication.create({
loginCode: state.login.loginCode,
session_id: state.login.sessionId,
sessionId: state.login.sessionId,
productionUrls: state.login.productionUrls
});
}

0 comments on commit 0c3a343

Please sign in to comment.