Skip to content

Commit

Permalink
Add AWS Cognito authenticator for pages
Browse files Browse the repository at this point in the history
Add advanced login bar
  • Loading branch information
ianpark committed Jun 18, 2018
1 parent ae93c2a commit 134cabf
Show file tree
Hide file tree
Showing 26 changed files with 374 additions and 220 deletions.
8 changes: 6 additions & 2 deletions src/actions/ActionTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ export const USER_SIGNUP_CONFIRM_IN_PROGRESS = 'USER_SIGNUP_CONFIRM_IN_PROGRESS'
export const USER_SIGNUP_CONFIRM_SUCCEES = 'USER_SIGNUP_CONFIRM_SUCCEES';
export const USER_SIGNUP_CONFIRM_ERROR = 'USER_SIGNUP_CONFIRM_ERROR';

export const SETTING_SAVE_IN_PROGRESS = 'SETTING_SAVE_IN_PROGRESS';
export const SETTING_SAVE_SUCCESS = 'SETTING_SAVE_SUCCESS';
export const SETTING_SAVE_FAILED = 'SETTING_SAVE_FAILED';



export const SETTING_LOAD_IN_PROGRESS = 'SETTING_LOAD_IN_PROGRESS';
export const SETTING_LOAD_SUCCESS = 'SETTING_LOAD_SUCCESS';
export const SETTING_LOAD_FAILED = 'SETTING_LOAD_FAILED';
84 changes: 38 additions & 46 deletions src/actions/auth.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as types from './ActionTypes';

import { Auth, Storage } from 'aws-amplify';
import { Auth } from 'aws-amplify';
import * as setting from './setting';

export const setUserId = (userId) => {
localStorage.setItem("user_id", userId);
Expand All @@ -14,8 +15,8 @@ export const userLoginInProgress = () => {
return { type: types.USER_LOGIN_IN_PROGRESS }
}

export const userLoginStateUpdate = (auth) => {
return { type: types.USER_LOGIN_STATE_UPDATE, auth }
export const userLoginStateUpdate = () => {
return { type: types.USER_LOGIN_STATE_UPDATE }
}

export const userLoginSuccess = (auth) => {
Expand All @@ -26,55 +27,46 @@ export const userLoginFail = (error) => {
return { type: types.USER_LOGIN_ERROR, error }
}

export const initAuth = () => {
return (dispatch) => {
Auth.currentAuthenticatedUser()
.then((user) => {
if (user) {
dispatch(userLoginStateUpdate(user));
}

Storage.put('test.txt', 'Protected Content', {
level: 'protected',
contentType: 'text/plain'
})
.then (result => console.log(result))
.catch(err => console.log(err));

})
.catch((error) => {
dispatch(userLoginStateUpdate(false));
console.log("Error loading user: " + error);
});
export const initAuth = async (dispatch) => {
try {
let user = await Auth.currentAuthenticatedUser()
if (user) {
await setting.loadConfig(dispatch, false);
dispatch(userLoginStateUpdate(user));
}
} catch (error) {
console.log("Error loading user: " + error);
dispatch(userLoginStateUpdate(false));
}
}

export const loginRequest = (id, pass) => {
return (dispatch) => {
dispatch(userLoginInProgress());
Auth.signIn(id, pass)
.then((user) => {
if (user) {
setUserId(id);
dispatch(userLoginStateUpdate(user));
}
})
.catch((error) => {
if (error.code === "UserNotConfirmedException") {
dispatch(userSignupConfirmRequired());
}
console.log(error);
dispatch(userLoginFail(error.message));
});
export const loginRequest = async (dispatch, id, pass) => {
dispatch(userLoginInProgress());
try {
await Auth.signIn(id, pass);
let user_auth = await Auth.currentAuthenticatedUser()
localStorage.setItem("user_auth", JSON.stringify(user_auth));
localStorage.setItem("user_id", id);
//window.location.reload();
await setting.loadConfig(dispatch, true);
dispatch(userLoginStateUpdate());
} catch (error) {
console.log("Login error: " + error);
if (error.code === "UserNotConfirmedException") {
dispatch(userSignupConfirmRequired());
}
dispatch(userLoginFail(error.message));
}
}

export const logoutRequest = () => {
return (dispatch) => {
dispatch(userLoginStateUpdate(false));
Auth.signOut()
.catch((error) => {
});
export const logoutRequest = async (dispatch) => {
dispatch(userLoginStateUpdate(false));
try {
await Auth.signOut();
localStorage.removeItem("user_auth");
window.location.reload();
} catch (error) {
console.log("Logout failed " + error);
}
}

Expand Down
12 changes: 1 addition & 11 deletions src/actions/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import * as types from './ActionTypes';
import Amplify from 'aws-amplify';
import { Auth } from "aws-amplify";
import config from 'config';
export * from './auth.js';

Amplify.configure(config.aws);

export const updateConfig = () => ({
type: types.UPDATE_CONFIG
});

export const priceFeed = (feedData) => ({
type: types.PRICE_FEED,
feedData
});

export const authStatus = (authStatus) => ({
type: types.AUTH_STATUS,
authStatus
})
});
49 changes: 49 additions & 0 deletions src/actions/setting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import * as types from './ActionTypes';
import { Storage } from 'aws-amplify';

export const settingSaveInProgress = () => {
return { type: types.SETTING_SAVE_IN_PROGRESS }
}

export const settingSaveFailed = (error) => {
return { type: types.SETTING_SAVE_FAILED, error }
}

export const settingSaveSuccess= () => {
return { type: types.SETTING_SAVE_SUCCESS }
}

export const settingLoadInProgress= () => {
return { type: types.SETTING_LOAD_IN_PROGRESS }
}

export const settingLoadFailed = (error) => {
return { type: types.SETTING_LOAD_FAILED, error }
}

export const settingLoadSuccess = () => {
return { type: types.SETTING_LOAD_SUCCESS }
}

export const updateConfig = () => ({
type: types.UPDATE_CONFIG
});

export const loadConfig = async (dispatch, force) => {
let existingConfig = localStorage.getItem('config');
if (!existingConfig || force) {
try {
let url = await Storage.get('config.json', { level: 'private', contentType: 'text/json'})
let config = await (await fetch(url)).json()
localStorage.setItem('config', JSON.stringify(config))
} catch (error) {
console.log("Failed to load config: " + error)
const configTemplate = {
users: [],
exchanges: [],
}
localStorage.setItem('config', JSON.stringify(configTemplate));
}
}
dispatch(updateConfig());
}
2 changes: 1 addition & 1 deletion src/components/AppFrame.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { Component } from "react"
import { Link } from 'react-router-dom'
import { Icon, Menu, Sidebar, Container } from "semantic-ui-react"
import { Icon, Menu, Sidebar } from "semantic-ui-react"
import LoginPanelContainer from 'containers/LoginPanelContainer'
import Footer from 'components/Footer'

Expand Down
34 changes: 25 additions & 9 deletions src/components/InvoiceForm.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { Component } from "react";
import { Button, Segment, Form, Label, Dimmer, Loader, Input, Dropdown, Select, Statistic, TextArea } from 'semantic-ui-react'
import { Button, Form, Dimmer, Loader, Input, Dropdown, TextArea } from 'semantic-ui-react'
import { Redirect, withRouter } from 'react-router-dom';
import Api from 'shared/API';
import Utils from 'shared/Utils';
Expand Down Expand Up @@ -68,11 +68,28 @@ class InvoiceForm extends Component {
&& this.state.invoiceData.amount;
}

showInvoiceForm = () => {
const receivers = this.state.receivers;
const exchanges = this.state.exchanges;
getParameters = () => {
let config = this.props.config;

return config && {
receivers: config.users.map((user) => {
var key = JSON.stringify({account: user.account});
return {text: user.account, key: user.account, value: key}
}),
exchanges: config.exchanges.map((exchange) => {
var key = JSON.stringify({exchange: exchange.name, account: exchange.account, wallet: exchange.wallet, nickname: exchange.nickname});
return {text: exchange.nickname + ' (' + exchange.account + ')', value: key, key: key };
}),
currencies: Utils.getCurrencies().map((currency) => {
return {key: currency.code, text: currency.symbol, value: currency.code, content: currency.code + ", " + currency.name };
})
}
}

return (
showInvoiceForm = () => {
let param = this.getParameters();
console.log(param);
return ( param &&
<div>
<h2>Create Invoice</h2>
{this.state.fetching && (
Expand All @@ -83,15 +100,15 @@ class InvoiceForm extends Component {
<h3>Amount</h3>
<Input fluid name='amount' size='huge' type="number"
label={<Dropdown name='currency' defaultValue={this.state.invoiceData.currency}
options={this.state.currencies} onChange={this.handleChange} direction='left' />}
options={param.currencies} onChange={this.handleChange} direction='left' />}
labelPosition='right' placeholder='Price' onChange={this.handleChange}
/>
<h3>Receiver</h3>
<Dropdown placeholder='Choose Receiver' name='receiver' fluid selection options={[...receivers, ...exchanges]}
<Dropdown placeholder='Choose Receiver' name='receiver' fluid selection options={[...param.receivers, ...param.exchanges]}
onChange={this.handleChange} style={{fontSize: '16pt'}} />
<h3>Memo (optional)</h3>
<Form>
<TextArea fluid name='memo'
<TextArea name='memo'
placeholder='Transaction message'
onChange={this.handleChange}
style={{fontSize: '16pt'}}/>
Expand All @@ -105,7 +122,6 @@ class InvoiceForm extends Component {
}

render() {

return this.state.invoiceId ?
<Redirect push to={this.props.location.pathname + "/" + this.state.invoiceId} />
:
Expand Down
2 changes: 1 addition & 1 deletion src/components/PaymentView.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class PaymentView extends Component {
let amount = info.amount + " " + info.currency;
let amountSBD = (info.amount / rate.price).toFixed(3) + " SBD";
let message = "";
if (info.type == 'exchange') {
if (info.type === 'exchange') {
message = info.receiverDetail.wallet;
} else {
message = "[SteemPay] " + info.memo + " | " + amount + " | " + amountSBD;
Expand Down
37 changes: 24 additions & 13 deletions src/components/login/LoginPanel.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
import React, { Component } from 'react'
import { Button } from 'semantic-ui-react'
import { Button, Dropdown, Image } from 'semantic-ui-react'
import { Link } from 'react-router-dom';

class LoginPanel extends Component {
constructor(props) {
super(props);
}

render() {
console.log(this.props);
if (!this.props.loginStateChecked) {
return null;
}
return this.props.auth ?
renderAuthenticated = () => {
const trigger = (
<span>
Hello, aaaaadfs <Image avatar src={"http://localhost:3000/img/home.jpeg"} />
</span>
)
const options = [
{ key: 'user', text: 'Account', icon: 'user' },
{ key: 'settings', text: 'Settings', icon: 'settings' },
{ key: 'sign-out', text: 'Sign Out', icon: 'sign out', onClick: this.props.onLogoutRequest },
]
console.log(this.props.auth)
return (
<div>
<Button size="medium" compact onClick={this.props.onLogoutRequest}>Log off</Button>
<Dropdown trigger={trigger} options={options} icon={null} />
</div>
:
)
}

renderNotAuthenticated = () => {
return (
<div>
<Button basic color='teal' size="medium" compact as={Link} to="/auth/login">Log in</Button>
<Button color='teal' size="medium" compact as={Link} to="/auth/signup">Sign up</Button>
</div>
)
}
render() {
return this.props.auth ? this.renderAuthenticated() : this.renderNotAuthenticated()
}
}

Expand Down
Loading

0 comments on commit 134cabf

Please sign in to comment.