Skip to content

Commit 1988cea

Browse files
committed
Refactor
1 parent 3e9be59 commit 1988cea

File tree

3 files changed

+148
-152
lines changed

3 files changed

+148
-152
lines changed

client/src/App.js

Lines changed: 6 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -1,161 +1,15 @@
1-
import React, { useState, useEffect } from 'react';
2-
import { PublicClientApplication } from '@azure/msal-browser';
1+
import React from 'react';
32
import { Buffer } from 'buffer';
3+
import { AuthProvider } from './AuthProvider';
4+
import CSVUploader from './CSVUploader';
45

56
window.Buffer = Buffer;
67

7-
// MSAL Configuration
8-
const msalConfig = {
9-
auth: {
10-
clientId: process.env.REACT_APP_STATIC_WEB_APP_CLIENT_ID,
11-
authority: `https://login.microsoftonline.com/${process.env.REACT_APP_AZURE_TENANT_ID}`,
12-
redirectUri: window.location.origin,
13-
},
14-
};
15-
16-
const msalInstance = new PublicClientApplication(msalConfig);
17-
188
const App = () => {
19-
const [file, setFile] = useState(null);
20-
const [error, setError] = useState('');
21-
const [modalVisible, setModalVisible] = useState(false);
22-
const [user, setUser] = useState(null);
23-
const [isInitialized, setIsInitialized] = useState(false);
24-
25-
const handleFileChange = (e) => {
26-
setError('');
27-
setFile(e.target.files[0]);
28-
};
29-
30-
const uploadFile = async (file) => {
31-
if (!file) {
32-
setError('Please select a file to upload');
33-
return;
34-
}
35-
36-
try {
37-
console.log('Authenticating and uploading file...');
38-
39-
// Acquire access token
40-
const account = msalInstance.getAllAccounts()[0];
41-
if (!account) {
42-
throw new Error('User is not signed in');
43-
}
44-
45-
const tokenResponse = await msalInstance.acquireTokenSilent({
46-
scopes: ['api://hvalfangst-function-app/Csv.Writer'],
47-
account
48-
});
49-
50-
console.log('Token response:', tokenResponse);
51-
52-
const token = tokenResponse.accessToken;
53-
54-
const endpoint = 'https://hvalfangstlinuxfunctionapp.azurewebsites.net/api/upload_csv';
55-
56-
// Read the file as a text string
57-
const fileContent = await file.text();
58-
59-
const response = await fetch(endpoint, {
60-
method: 'POST',
61-
headers: {
62-
'Content-Type': 'text/csv', // Set content type to CSV
63-
Authorization: `Bearer ${token}`, // Include OAuth token
64-
},
65-
body: fileContent, // Send the file content as the body
66-
});
67-
68-
if (!response.ok) {
69-
const errorMessage = await response.text();
70-
throw new Error(`Failed to upload: ${errorMessage}`);
71-
}
72-
73-
console.log('Response:', response)
74-
75-
console.log('File uploaded successfully');
76-
setModalVisible(true); // Show success modal
77-
} catch (error) {
78-
console.error('Error uploading file:', error);
79-
setError(`Error uploading file: ${error.message}`);
80-
}
81-
};
82-
83-
const handleFileUpload = () => {
84-
if (file) {
85-
uploadFile(file);
86-
} else {
87-
setError('Please select a file to upload');
88-
}
89-
};
90-
91-
const closeModal = () => {
92-
setModalVisible(false);
93-
};
94-
95-
const handleSignIn = async () => {
96-
try {
97-
await msalInstance.initialize();
98-
setIsInitialized(true);
99-
const response = await msalInstance.loginPopup({
100-
scopes: ['openid'],
101-
});
102-
console.log('Sign in response:', response);
103-
console.log('User signed in successfully');
104-
setUser(response.account);
105-
} catch (error) {
106-
console.error('Error signing in:', error);
107-
setError(`Error signing in: ${error.message}`);
108-
}
109-
};
110-
111-
const handleSignOut = async () => {
112-
if (!isInitialized) {
113-
console.error('MSAL instance is not initialized.');
114-
return;
115-
}
116-
await msalInstance.logoutPopup();
117-
setUser(null);
118-
};
119-
120-
useEffect(() => {
121-
const initializeMsal = async () => {
122-
await msalInstance.initialize();
123-
setIsInitialized(true);
124-
const accounts = msalInstance.getAllAccounts();
125-
if (accounts.length > 0) {
126-
setUser(accounts[0]);
127-
}
128-
};
129-
130-
initializeMsal();
131-
}, []);
132-
1339
return (
134-
<div className="csv-uploader">
135-
<h1>CSV Uploader</h1>
136-
{user ? (
137-
<div>
138-
<p>Welcome, {user.name}</p>
139-
<button onClick={handleSignOut}>Sign Out</button>
140-
</div>
141-
) : (
142-
<button onClick={handleSignIn}>Sign In</button>
143-
)}
144-
145-
<input type="file" accept=".csv" onChange={handleFileChange} />
146-
<button onClick={handleFileUpload}>Upload</button>
147-
{error && <p className="error">{error}</p>}
148-
149-
{modalVisible && (
150-
<div className="modal">
151-
<div className="modal-content">
152-
<h2>Upload Successful!</h2>
153-
<p>Your file has been uploaded to Azure Blob Storage via Azure Function.</p>
154-
<button onClick={closeModal}>Close</button>
155-
</div>
156-
</div>
157-
)}
158-
</div>
10+
<AuthProvider>
11+
<CSVUploader />
12+
</AuthProvider>
15913
);
16014
};
16115

client/src/AuthProvider.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import React, { createContext, useContext, useState, useEffect } from 'react';
2+
import { PublicClientApplication } from '@azure/msal-browser';
3+
4+
const AuthContext = createContext();
5+
6+
const msalConfig = {
7+
auth: {
8+
clientId: process.env.REACT_APP_STATIC_WEB_APP_CLIENT_ID,
9+
authority: `https://login.microsoftonline.com/${process.env.REACT_APP_AZURE_TENANT_ID}`,
10+
redirectUri: window.location.origin,
11+
},
12+
};
13+
14+
const msalInstance = new PublicClientApplication(msalConfig);
15+
16+
export const AuthProvider = ({ children }) => {
17+
const [user, setUser] = useState(null);
18+
const [isInitialized, setIsInitialized] = useState(false);
19+
20+
useEffect(() => {
21+
const initializeMsal = async () => {
22+
await msalInstance.initialize();
23+
setIsInitialized(true);
24+
const accounts = msalInstance.getAllAccounts();
25+
if (accounts.length > 0) {
26+
setUser(accounts[0]);
27+
}
28+
};
29+
30+
initializeMsal();
31+
}, []);
32+
33+
const handleSignIn = async () => {
34+
try {
35+
await msalInstance.initialize();
36+
setIsInitialized(true);
37+
const response = await msalInstance.loginPopup({
38+
scopes: ['openid'],
39+
});
40+
setUser(response.account);
41+
} catch (error) {
42+
console.error('Error signing in:', error);
43+
}
44+
};
45+
46+
const handleSignOut = async () => {
47+
if (!isInitialized) {
48+
console.error('MSAL instance is not initialized.');
49+
return;
50+
}
51+
await msalInstance.logoutPopup();
52+
setUser(null);
53+
};
54+
55+
return (
56+
<AuthContext.Provider value={{ user, handleSignIn, handleSignOut }}>
57+
{children}
58+
</AuthContext.Provider>
59+
);
60+
};
61+
62+
export const useAuth = () => useContext(AuthContext);

client/src/CsvUploader.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import React, { useState } from 'react';
2+
import { useAuth } from './AuthProvider';
3+
4+
const CSVUploader = () => {
5+
const { user, handleSignIn, handleSignOut } = useAuth();
6+
const [file, setFile] = useState(null);
7+
const [error, setError] = useState('');
8+
const [modalVisible, setModalVisible] = useState(false);
9+
10+
const handleFileChange = (e) => {
11+
setError('');
12+
setFile(e.target.files[0]);
13+
};
14+
15+
const uploadFile = async (file) => {
16+
if (!file) {
17+
setError('Please select a file to upload');
18+
return;
19+
}
20+
21+
try {
22+
console.log('Authenticating and uploading file...');
23+
24+
const account = msalInstance.getAllAccounts()[0];
25+
if (!account) {
26+
throw new Error('User is not signed in');
27+
}
28+
29+
const tokenResponse = await msalInstance.acquireTokenSilent({
30+
scopes: ['api://hvalfangst-function-app/Csv.Writer'],
31+
account
32+
});
33+
34+
const token = tokenResponse.accessToken;
35+
const endpoint = 'https://hvalfangstlinuxfunctionapp.azurewebsites.net/api/upload_csv';
36+
const fileContent = await file.text();
37+
38+
const response = await fetch(endpoint, {
39+
method: 'POST',
40+
headers: {
41+
'Content-Type': 'text/csv',
42+
Authorization: `Bearer ${token}`,
43+
},
44+
body: fileContent,
45+
});
46+
47+
if (!response.ok) {
48+
const errorMessage = await response.text();
49+
throw new Error(`Failed to upload: ${errorMessage}`);
50+
}
51+
52+
setModalVisible(true);
53+
} catch (error) {
54+
console.error('Error uploading file:', error);
55+
setError(`Error uploading file: ${error.message}`);
56+
}
57+
};
58+
59+
const handleFileUpload = () => {
60+
if (file) {
61+
uploadFile(file);
62+
} else {
63+
setError('Please select a file to upload');
64+
}
65+
};
66+
67+
const closeModal = () => {
68+
setModalVisible(false);
69+
};
70+
71+
return (
72+
<div className="csv-uploader">
73+
<Header user={user} handleSignOut={handleSignOut} handleSignIn={handleSignIn} />
74+
<FileUploader handleFileChange={handleFileChange} handleFileUpload={handleFileUpload} error={error} />
75+
<Modal modalVisible={modalVisible} closeModal={closeModal} />
76+
</div>
77+
);
78+
};
79+
80+
export default CSVUploader;

0 commit comments

Comments
 (0)