-
Notifications
You must be signed in to change notification settings - Fork 0
/
Auth-lame.tsx
233 lines (214 loc) · 5.11 KB
/
Auth-lame.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import * as React from 'react';
import * as auth0 from 'auth0-js';
import { withApollo } from 'react-apollo';
import { AuthProvider } from './authContext';
import gql from 'graphql-tag';
//COMMENT
interface AuthProps {
client: any;
children: any;
domain: string;
clientId: string;
callbackUrl: string;
}
interface AuthState {
authenticated: boolean;
user: {
role: string;
};
accessToken: string;
}
interface SessionDatatype {
user: { id: string };
token: string;
login: { token: string };
}
class Auth extends React.Component<AuthProps, AuthState> {
public state = {
authenticated:
typeof window === 'undefined' || window.localStorage.getItem('token')
? true
: false,
user: {
role: 'visitor',
},
accessToken: '',
};
private auth = new auth0.WebAuth({
domain: this.props.domain,
clientID: this.props.clientId,
redirectUri: this.props.callbackUrl,
responseType: 'token id_token',
});
handleAuthentication = ({ email, password }) => {
this.auth.login(
{
realm: 'Username-Password-Authentication',
email,
password,
},
(e: any) => console.log(e)
);
};
handleSignUp = ({ email, password }: any) => {
console.log('started signup');
this.auth.signup(
{
email,
password,
connection: 'Username-Password-Authentication',
},
(error, userPayload) => {
console.log(error, userPayload);
if (error) {
return;
}
this.auth.login(
{
email,
password,
realm: 'Username-Password-Authentication',
},
e => {
console.log(e);
this.setSession({
user: { id: userPayload.sub || '' },
token: userPayload.accessToken,
login: { token: userPayload.idToken },
});
}
);
// @todo find if sub is the ID of user
}
);
};
loginWithGoogle(): void {
this.auth.authorize({
connection: 'google-oauth2',
});
}
loginWithlinkedIn(): void {
this.auth.authorize({
connection: 'linkedin',
});
}
setSession = (data: SessionDatatype) => {
const user = {
// @todo Add correct user details here
id: data.user.id,
role: 'JOBSEEKER',
};
this.setState({
authenticated: true,
accessToken: data.token,
user,
});
// @todo check if localstorage is available or not and if it isn't use
// cookies to set session instead.
const isBrowser = typeof window !== 'undefined';
if (isBrowser) {
window.localStorage.setItem('token', data.login.token);
}
};
handleCallback = async () => {
console.log('callbacked');
const SIGNUP_MUTATION = gql`
# Write your query or mutation here
mutation(
$email: String!
$name: String!
$authid: String!
$authmethod: String!
) {
createUser(
firstName: $name
email: $email
authid: $authid
authmethod: $authmethod
) {
id
}
}
`;
// don't parse twice because setSession is doing a re-render
if (!this.state.authenticated) {
console.log('state is not authenticated');
this.auth.parseHash((err, authResult) => {
console.log('auth is parsed');
if (authResult && authResult.accessToken && authResult.idToken) {
console.log('parseHash started');
// 1. mutate the backend
this.props.client
.mutate({
mutation: SIGNUP_MUTATION,
variables: {
authid: authResult.idTokenPayload.sub,
// we only allow local now
authmethod: 'local',
name: authResult.idTokenPayload.nickname,
email: authResult.idTokenPayload.email,
},
})
.catch((error: any) => console.log(error));
// 2. set the sessions
this.setSession({
user: { id: authResult.idTokenPayload.sub },
token: authResult.accessToken,
login: { token: authResult.idToken },
});
} else if (err) {
console.log(err);
}
history.back();
});
}
};
logout = () => {
this.setState({
authenticated: false,
user: {
role: 'visitor',
},
accessToken: '',
});
// Remove localstorage token
const isBrowser = typeof window !== 'undefined';
if (isBrowser) {
window.localStorage.removeItem('token'); // @todo Get a better token name LOL
}
// clear apollo store
this.props.client.clearStore();
};
render() {
const authProviderValue = {
...this.state,
handleAuthentication: this.handleAuthentication,
handleSignUp: this.handleSignUp,
logout: this.logout,
loginWithGoogle: this.loginWithGoogle,
loginWithlinkedIn: this.loginWithlinkedIn,
handleCallback: this.handleCallback,
};
setInterval(() => {
// return if not in browser
if (typeof window === 'undefined') {
return;
}
console.log('timer running');
// if they deleted the token but they are shown authenicated in UI
if (!localStorage.getItem('token') && this.state.authenticated) {
this.setState({ authenticated: false });
}
// if they have copy pasted token but they aren't shown authenticated in UI
else if (localStorage.getItem('token') && !this.state.authenticated) {
this.setState({ authenticated: true });
}
}, 1000 * 60);
return (
<AuthProvider value={authProviderValue}>
{this.props.children}
</AuthProvider>
);
}
}
export default withApollo(Auth);