added username change
This commit is contained in:
parent
27bc2f4e70
commit
8da2ffb4f1
6 changed files with 327 additions and 6 deletions
|
@ -19,7 +19,7 @@ const safeLogtoAppSecret = logtoAppSecret || "missing_app_secret";
|
|||
const safeLogtoEndpoint = logtoEndpoint || "https://auth.ieeeucsd.org";
|
||||
const safeLogtoTokenEndpoint =
|
||||
logtoTokenEndpoint || "https://auth.ieeeucsd.org/oidc/token";
|
||||
const safeLogtoApiEndpoint = logtoApiEndpoint || "https://auth.ieeeucsd.org";
|
||||
const safeLogtoApiEndpoint = logtoApiEndpoint || "";
|
||||
---
|
||||
|
||||
<div id="settings-section" class="">
|
||||
|
@ -95,7 +95,7 @@ const safeLogtoApiEndpoint = logtoApiEndpoint || "https://auth.ieeeucsd.org";
|
|||
Update your personal information and profile details
|
||||
</p>
|
||||
<div class="divider"></div>
|
||||
<UserProfileSettings client:load />
|
||||
<UserProfileSettings client:load logtoApiEndpoint={logtoApiEndpoint} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
@ -5,15 +5,23 @@ import { Collections, type User } from '../../../schemas/pocketbase/schema';
|
|||
import allMajors from '../../../data/allUCSDMajors.txt?raw';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
export default function UserProfileSettings() {
|
||||
interface UserProfileSettingsProps {
|
||||
logtoApiEndpoint?: string;
|
||||
}
|
||||
|
||||
export default function UserProfileSettings({
|
||||
logtoApiEndpoint: propLogtoApiEndpoint
|
||||
}: UserProfileSettingsProps) {
|
||||
const auth = Authentication.getInstance();
|
||||
const update = Update.getInstance();
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [logtoUserId, setLogtoUserId] = useState('');
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
email: '',
|
||||
username: '',
|
||||
major: '',
|
||||
graduation_year: '',
|
||||
zelle_information: '',
|
||||
|
@ -21,6 +29,12 @@ export default function UserProfileSettings() {
|
|||
member_id: ''
|
||||
});
|
||||
|
||||
// Access environment variables directly
|
||||
const envLogtoApiEndpoint = import.meta.env.LOGTO_API_ENDPOINT;
|
||||
|
||||
// Use environment variables or props (fallback)
|
||||
const logtoApiEndpoint = envLogtoApiEndpoint || propLogtoApiEndpoint;
|
||||
|
||||
// Parse the majors list from the text file and sort alphabetically
|
||||
const majorsList = allMajors
|
||||
.split('\n')
|
||||
|
@ -31,17 +45,64 @@ export default function UserProfileSettings() {
|
|||
const loadUserData = async () => {
|
||||
try {
|
||||
const currentUser = auth.getCurrentUser();
|
||||
if (currentUser) {
|
||||
if (!currentUser) {
|
||||
throw new Error('User not authenticated');
|
||||
}
|
||||
|
||||
// Get the Logto user ID from PocketBase's external auth collection
|
||||
const pb = auth.getPocketBase();
|
||||
try {
|
||||
const externalAuthRecord = await pb.collection('_externalAuths').getFirstListItem(`recordRef="${currentUser.id}" && provider="oidc"`);
|
||||
const logtoId = externalAuthRecord.providerId;
|
||||
if (!logtoId) {
|
||||
throw new Error('No Logto ID found in external auth record');
|
||||
}
|
||||
setLogtoUserId(logtoId);
|
||||
|
||||
// Fetch user data from Logto through our server-side API
|
||||
const logtoResponse = await fetch('/api/get-logto-user', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userId: logtoId,
|
||||
logtoApiEndpoint: logtoApiEndpoint
|
||||
})
|
||||
});
|
||||
|
||||
if (!logtoResponse.ok) {
|
||||
throw new Error('Failed to fetch Logto user data');
|
||||
}
|
||||
|
||||
const logtoUser = await logtoResponse.json();
|
||||
// Extract username from Logto data or email if not set
|
||||
const defaultUsername = logtoUser.data?.username || currentUser.email?.split('@')[0] || '';
|
||||
|
||||
setUser(currentUser);
|
||||
setFormData({
|
||||
name: currentUser.name || '',
|
||||
email: currentUser.email || '',
|
||||
username: defaultUsername,
|
||||
major: currentUser.major || '',
|
||||
graduation_year: currentUser.graduation_year?.toString() || '',
|
||||
zelle_information: currentUser.zelle_information || '',
|
||||
pid: currentUser.pid || '',
|
||||
member_id: currentUser.member_id || ''
|
||||
});
|
||||
|
||||
// If username is blank in Logto, update it
|
||||
if (!logtoUser.data?.username && currentUser.email) {
|
||||
try {
|
||||
const emailUsername = currentUser.email.split('@')[0];
|
||||
await updateLogtoUser(logtoId, emailUsername);
|
||||
} catch (error) {
|
||||
console.error('Error setting default username:', error);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching external auth record:', error);
|
||||
toast.error('Could not determine your user ID. Please try again later or contact support.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading user data:', error);
|
||||
|
@ -52,7 +113,54 @@ export default function UserProfileSettings() {
|
|||
};
|
||||
|
||||
loadUserData();
|
||||
}, []);
|
||||
}, [logtoApiEndpoint]);
|
||||
|
||||
const updateLogtoUser = async (userId: string, username: string) => {
|
||||
try {
|
||||
// First get the current user data from Logto through our server-side API
|
||||
const getCurrentResponse = await fetch('/api/get-logto-user', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userId,
|
||||
logtoApiEndpoint
|
||||
})
|
||||
});
|
||||
|
||||
if (!getCurrentResponse.ok) {
|
||||
throw new Error('Failed to fetch current Logto user data');
|
||||
}
|
||||
|
||||
const currentLogtoUser = await getCurrentResponse.json();
|
||||
|
||||
// Now update the user with new username through our server-side API
|
||||
const response = await fetch('/api/update-logto-user', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userId,
|
||||
username,
|
||||
logtoApiEndpoint,
|
||||
profile: {
|
||||
...currentLogtoUser.data?.profile,
|
||||
preferredUsername: username
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || 'Failed to update Logto username');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating Logto username:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target;
|
||||
|
@ -68,6 +176,12 @@ export default function UserProfileSettings() {
|
|||
|
||||
try {
|
||||
if (!user) throw new Error('User not authenticated');
|
||||
if (!logtoUserId) throw new Error('Could not determine your user ID');
|
||||
|
||||
// Update username in Logto if changed
|
||||
if (formData.username !== user.username) {
|
||||
await updateLogtoUser(logtoUserId, formData.username);
|
||||
}
|
||||
|
||||
const updateData: Partial<User> = {
|
||||
name: formData.name,
|
||||
|
@ -131,6 +245,22 @@ export default function UserProfileSettings() {
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-control">
|
||||
<label className="label">
|
||||
<span className="label-text">Username</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
name="username"
|
||||
value={formData.username}
|
||||
onChange={handleInputChange}
|
||||
className="input input-bordered w-full"
|
||||
pattern="^[A-Z_a-z]\w*$"
|
||||
title="Username must start with a letter or underscore and can contain only letters, numbers, and underscores"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-control">
|
||||
<label className="label">
|
||||
<span className="label-text">Email Address</span>
|
||||
|
|
88
src/pages/api/get-logto-user.ts
Normal file
88
src/pages/api/get-logto-user.ts
Normal file
|
@ -0,0 +1,88 @@
|
|||
import type { APIRoute } from "astro";
|
||||
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
try {
|
||||
const { userId, logtoApiEndpoint } = await request.json();
|
||||
|
||||
if (!userId || !logtoApiEndpoint) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "Missing required parameters",
|
||||
}),
|
||||
{
|
||||
status: 400,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Get access token for Logto API
|
||||
const tokenResponse = await fetch(`${logtoApiEndpoint}/oidc/token`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: "client_credentials",
|
||||
client_id: import.meta.env.LOGTO_APP_ID || "",
|
||||
client_secret: import.meta.env.LOGTO_APP_SECRET || "",
|
||||
scope: "all",
|
||||
resource: "https://default.logto.app/api",
|
||||
organization: "ieeeucsd",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
throw new Error("Failed to get access token");
|
||||
}
|
||||
|
||||
const tokenData = await tokenResponse.json();
|
||||
const accessToken = tokenData.access_token;
|
||||
|
||||
// Get user data from Logto
|
||||
const userResponse = await fetch(
|
||||
`${logtoApiEndpoint}/api/users/${userId}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error("Failed to fetch user data from Logto");
|
||||
}
|
||||
|
||||
const userData = await userResponse.json();
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
data: userData,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error in get-logto-user:", error);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : "An error occurred",
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
95
src/pages/api/update-logto-user.ts
Normal file
95
src/pages/api/update-logto-user.ts
Normal file
|
@ -0,0 +1,95 @@
|
|||
import type { APIRoute } from "astro";
|
||||
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
try {
|
||||
const { userId, username, logtoApiEndpoint, profile } =
|
||||
await request.json();
|
||||
|
||||
if (!userId || !username || !logtoApiEndpoint) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "Missing required parameters",
|
||||
}),
|
||||
{
|
||||
status: 400,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Get access token for Logto API
|
||||
const tokenResponse = await fetch(`${logtoApiEndpoint}/oidc/token`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: "client_credentials",
|
||||
client_id: import.meta.env.LOGTO_APP_ID || "",
|
||||
client_secret: import.meta.env.LOGTO_APP_SECRET || "",
|
||||
scope: "all",
|
||||
resource: "https://default.logto.app/api",
|
||||
organization: "ieeeucsd",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
throw new Error("Failed to get access token");
|
||||
}
|
||||
|
||||
const tokenData = await tokenResponse.json();
|
||||
const accessToken = tokenData.access_token;
|
||||
|
||||
// Update user data in Logto
|
||||
const updateResponse = await fetch(
|
||||
`${logtoApiEndpoint}/api/users/${userId}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
profile,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!updateResponse.ok) {
|
||||
throw new Error("Failed to update user data in Logto");
|
||||
}
|
||||
|
||||
const updatedData = await updateResponse.json();
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
data: updatedData,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error in update-logto-user:", error);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : "An error occurred",
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
|
@ -24,6 +24,7 @@ export interface User extends BaseRecord {
|
|||
emailVisibility: boolean;
|
||||
verified: boolean;
|
||||
name: string;
|
||||
username?: string;
|
||||
avatar?: string;
|
||||
pid?: string;
|
||||
member_id?: string;
|
||||
|
@ -35,7 +36,7 @@ export interface User extends BaseRecord {
|
|||
notification_preferences?: string; // JSON string of notification settings
|
||||
display_preferences?: string; // JSON string of display settings (theme, font size, etc.)
|
||||
accessibility_settings?: string; // JSON string of accessibility settings (color blind mode, reduced motion)
|
||||
resume?: string;
|
||||
resume?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -127,6 +127,13 @@ export class Authentication {
|
|||
return this.pb.authStore.model?.id || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current auth token
|
||||
*/
|
||||
public getAuthToken(): string | null {
|
||||
return this.pb.authStore.token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to auth state changes
|
||||
* @param callback Function to call when auth state changes
|
||||
|
|
Loading…
Reference in a new issue