Skip to content

Commit 1e5b3d6

Browse files
committed
Refactored Auth and added Api
1 parent d00ffd0 commit 1e5b3d6

File tree

5 files changed

+226
-39
lines changed

5 files changed

+226
-39
lines changed

src/App.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import { Login, Page404, Page500, Register } from './views/Pages';
2222
// auth0
2323
import { Redirect} from 'react-router-dom';
2424
import Callback from './Callback/Callback';
25-
import Auth from './Auth/Auth';
25+
import Auth from './middleware/Auth/Auth';
2626
import history from './history';
2727

2828
const auth = new Auth();

src/containers/Full/Full.js

Lines changed: 41 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -21,55 +21,52 @@ import routes from '../../routes';
2121
import FullAside from './FullAside';
2222
import FullFooter from './FullFooter';
2323
import FullHeader from './FullHeader';
24-
25-
import { Auth0Lock} from 'auth0-lock';
26-
import history from '../../history';
27-
import Auth from "../../Auth/Auth";
24+
import {EngineApi} from './../../middleware/EngineAPI/Api';
2825

2926
class Full extends Component {
3027
constructor(props){
3128
super(props);
3229
console.log('Full constructor');
33-
this.lock = new Auth0Lock(
34-
'pfLIwsWrtUoFg63I5o7k3JPS7hOAB1cf',
35-
'drivemotors.auth0.com',{
36-
theme:{
37-
logo: 'https://www.drivemotors.com/assets/logos/drive_logo_march_14.svg'
38-
},
39-
allowSignUp: false,
40-
allowedConnections: ['Username-Password-Authentication']
41-
}
42-
);
43-
this.lock.on("authenticated", function(authResult) {
44-
// Use the token in authResult to getUserInfo() and save it to localStorage
45-
console.log('called loked.on');
46-
console.log(this);
47-
this.getUserInfo(authResult.accessToken, function(error, profile) {
48-
if (error) {
49-
// Handle error
50-
console.log('error');
51-
console.log(error);
52-
return;
53-
}
54-
console.log(authResult);
55-
console.log(profile);
56-
localStorage.setItem('accessToken', authResult.accessToken);
57-
localStorage.setItem('profile', JSON.stringify(profile));
5830

59-
const auth = new Auth();
60-
auth.setSession(authResult);
61-
console.log(auth.isAuthenticated());
62-
});
63-
});
31+
this.state = {
32+
privateMessage: '',
33+
publicMessage: ''
34+
};
35+
if(!this.props.auth.isAuthenticated()){
36+
this.props.auth.lock.show();
37+
}
6438
}
6539

6640
login() {
6741
// this.props.auth.login();
68-
this.lock.show();
42+
this.props.auth.lock.show();
6943
}
44+
45+
componentDidMount(){
46+
console.log('called full.js componentdidmount');
47+
EngineApi.getTestPublicApi( (message) =>{
48+
this.setState({ publicMessage:message });
49+
});
50+
EngineApi.getTestPrivateApi(this.props.auth, (message) => {
51+
this.setState({ privateMessage:message });
52+
});
53+
}
54+
55+
componentDidUpdate(prevProps, prevState){
56+
console.log('componentDidUpdate');
57+
console.log(prevProps.auth.loggedin);
58+
console.log(this.props.auth.loggedin);
59+
if(prevProps.auth.loggedin !== this.props.auth.loggedin){
60+
// EngineApi.getTestPrivateApi(this.props.auth, (message) => {
61+
// this.setState({ privateMessage:message });
62+
// });
63+
}
64+
}
65+
7066
render() {
7167
const { isAuthenticated } = this.props.auth;
72-
console.log('render');
68+
const { privateMessage, publicMessage } = this.state;
69+
console.log('called full.js render');
7370
console.log(this.props.auth.isAuthenticated());
7471
let displayHtml = null;
7572
if (isAuthenticated()){
@@ -91,8 +88,8 @@ class Full extends Component {
9188
<Container fluid>
9289
<Switch>
9390
{routes.map((route, idx) => {
94-
return route.component ? (<Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => (
95-
<route.component {...props} />
91+
return route.component ? (<Route key={idx} path={route.path} exact={route.exact} name={route.name} render={ props => (
92+
<route.component {...props} auth={this.props.auth} />
9693
)} />)
9794
: (null);
9895
},
@@ -106,6 +103,12 @@ class Full extends Component {
106103
</AppAside>
107104
</div>
108105
<AppFooter>
106+
<div>
107+
{privateMessage}
108+
</div>
109+
<div>
110+
{publicMessage}
111+
</div>
109112
<FullFooter />
110113
</AppFooter>
111114
</div>

src/middleware/Auth/Auth.js

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import auth0 from 'auth0-js';
2+
import { AUTH_CONFIG, EngineAPIUrl } from './auth0-variables';
3+
import history from '../../history';
4+
import {Auth0Lock} from "auth0-lock";
5+
6+
export default class Auth {
7+
auth0 = new auth0.WebAuth({
8+
___domain: AUTH_CONFIG.___domain,
9+
clientID: AUTH_CONFIG.clientId,
10+
// redirectUri: AUTH_CONFIG.callbackUrl,
11+
audience: EngineAPIUrl,
12+
responseType: AUTH_CONFIG.responseType,
13+
// responseType: 'code',
14+
scope: AUTH_CONFIG.exampleScope
15+
});
16+
17+
userProfile;
18+
19+
constructor() {
20+
this.login = this.login.bind(this);
21+
this.logout = this.logout.bind(this);
22+
this.handleAuthentication = this.handleAuthentication.bind(this);
23+
this.isAuthenticated = this.isAuthenticated.bind(this);
24+
this.getAccessToken = this.getAccessToken.bind(this);
25+
this.getProfile = this.getProfile.bind(this);
26+
this.loggedin = this.isAuthenticated();
27+
this.lock = this._InitializeLock();
28+
}
29+
30+
login() {
31+
this.auth0.authorize();
32+
this.loggedin = this.isAuthenticated();
33+
}
34+
35+
handleAuthentication() {
36+
console.log('called handleAuthentication');
37+
this.auth0.parseHash((err, authResult) => {
38+
if (authResult && authResult.accessToken && authResult.idToken) {
39+
this.setSession(authResult);
40+
history.replace('/');
41+
} else if (err) {
42+
history.replace('/');
43+
console.log(err);
44+
alert(`Error: ${err.error}. Check the console for further details.`);
45+
}
46+
});
47+
}
48+
49+
setSession(authResult) {
50+
console.log('called setSession');
51+
// Set the time that the access token will expire at
52+
let expiresAt = JSON.stringify(
53+
authResult.expiresIn * 1000 + new Date().getTime()
54+
);
55+
console.log(authResult);
56+
localStorage.setItem('access_token', authResult.accessToken);
57+
localStorage.setItem('id_token', authResult.idToken);
58+
localStorage.setItem('expires_at', expiresAt);
59+
this.loggedin = this.isAuthenticated();
60+
// navigate to the home route
61+
history.replace('/home');
62+
}
63+
64+
getAccessToken() {
65+
const accessToken = localStorage.getItem('access_token');
66+
if (!accessToken) {
67+
throw new Error('No access token found');
68+
}
69+
return accessToken;
70+
}
71+
72+
getProfile(cb) {
73+
let accessToken = this.getAccessToken();
74+
this.auth0.client.userInfo(accessToken, (err, profile) => {
75+
if (profile) {
76+
this.userProfile = profile;
77+
}
78+
cb(err, profile);
79+
});
80+
}
81+
82+
logout() {
83+
// Clear access token and ID token from local storage
84+
localStorage.removeItem('access_token');
85+
localStorage.removeItem('id_token');
86+
localStorage.removeItem('expires_at');
87+
this.userProfile = null;
88+
this.loggedin = this.isAuthenticated();
89+
// navigate to the home route
90+
history.replace('/home');
91+
}
92+
93+
isAuthenticated() {
94+
// Check whether the current time is past the
95+
// access token's expiry time
96+
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
97+
return new Date().getTime() < expiresAt;
98+
}
99+
100+
_InitializeLock(){
101+
let lock = new Auth0Lock(
102+
AUTH_CONFIG.clientId,
103+
AUTH_CONFIG.___domain,{
104+
theme:{
105+
logo: 'https://www.drivemotors.com/assets/logos/drive_logo_march_14.svg'
106+
},
107+
allowSignUp: false,
108+
allowedConnections: ['Username-Password-Authentication'],
109+
auth: {
110+
responseType: AUTH_CONFIG.responseType,
111+
redirectUrl: AUTH_CONFIG.callbackUrl,
112+
params: {
113+
scope: AUTH_CONFIG.exampleScope
114+
},
115+
audience: EngineAPIUrl
116+
}
117+
}
118+
);
119+
lock.on("authenticated", function(authResult) {
120+
// Use the token in authResult to getUserInfo() and save it to localStorage
121+
console.log('called locked.on');
122+
console.log(this);
123+
this.getUserInfo(authResult.accessToken, function(error, profile) {
124+
if (error) {
125+
// Handle error
126+
console.log('error');
127+
console.log(error);
128+
return;
129+
}
130+
131+
// console.log(authResult);
132+
// console.log('authResult');
133+
// console.log('profile');
134+
// console.log(profile);
135+
// localStorage.setItem('accessToken', authResult.accessToken);
136+
// localStorage.setItem('profile', JSON.stringify(profile));
137+
138+
// const auth = new Auth();
139+
// auth.setSession(authResult);
140+
// console.log(auth.isAuthenticated());
141+
});
142+
});
143+
144+
return lock;
145+
}
146+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export const AUTH_CONFIG = {
2+
___domain: 'drivemotors.auth0.com',
3+
clientId: 'pfLIwsWrtUoFg63I5o7k3JPS7hOAB1cf',
4+
callbackUrl: 'http://localhost:3013/callback',
5+
responseType: 'token id_token',
6+
exampleScope: 'openid profile read:messages'
7+
}
8+
9+
export const EngineAPIUrl = 'https://dev.drive:3000';

src/middleware/EngineAPI/Api.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import axios from 'axios';
2+
import { EngineAPIUrl } from './../Auth/auth0-variables';
3+
4+
export class EngineApi {
5+
6+
static getTestPublicApi(done) {
7+
axios.get(`${EngineAPIUrl}/api/public`)
8+
.then(response => done(response.data.message))
9+
.catch(error => done(error.message));
10+
}
11+
12+
static getTestPrivateApi(auth, done) {
13+
const { isAuthenticated, getAccessToken, } = auth;
14+
const headers = isAuthenticated() ? { 'Authorization' : `Bearer ${getAccessToken()}`}: null;
15+
console.log('called getTestPrivateApi');
16+
console.log('isAuthenticated ' + isAuthenticated());
17+
if(isAuthenticated()){
18+
console.log(getAccessToken());
19+
}
20+
21+
axios.get(`${EngineAPIUrl}/api/private`, { headers })
22+
.then(response => done(response.data.message))
23+
.catch(error => {
24+
console.log(JSON.stringify(error));
25+
done(error.message);
26+
});
27+
}
28+
}
29+

0 commit comments

Comments
 (0)