generated from nhcarrigan/template
feat: auto-assign Discord role to library members
Implemented automatic Discord role assignment for users who are members of the NHCarrigan server. This happens on every login: - Check if user is in Discord server (ID: 1354624415861833870) - Fetch user's current roles via Discord API - Assign library member role if they don't have it yet - Graceful error handling without blocking login Uses Discord Bot API with proper permissions to manage roles. Similar pattern to badge refresh on login. Environment variables added: - DISCORD_BOT_TOKEN: Bot token for Discord API calls - LIBRARY_ROLE_ID: Role ID to assign (1474616681023279236)
This commit is contained in:
@@ -102,6 +102,53 @@ const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
request
|
||||
);
|
||||
|
||||
// Assign library member role if user is in Discord server but doesn't have it
|
||||
const libraryRoleId = process.env.LIBRARY_ROLE_ID;
|
||||
if (inDiscord && guildId && libraryRoleId) {
|
||||
try {
|
||||
const memberResponse = await fetch(
|
||||
`https://discord.com/api/users/@me/guilds/${guildId}/member`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokenResult.token.access_token}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (memberResponse.ok) {
|
||||
const memberData = await memberResponse.json() as { roles: string[] };
|
||||
const hasLibraryRole = memberData.roles.includes(libraryRoleId);
|
||||
|
||||
if (!hasLibraryRole) {
|
||||
const botToken = process.env.DISCORD_BOT_TOKEN;
|
||||
if (botToken) {
|
||||
const assignRoleResponse = await fetch(
|
||||
`https://discord.com/api/v10/guilds/${guildId}/members/${userData.id}/roles/${libraryRoleId}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bot ${botToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (assignRoleResponse.ok || assignRoleResponse.status === 204) {
|
||||
app.log.info(`Assigned library role to user ${user.username} (${user.id})`);
|
||||
} else {
|
||||
app.log.error(
|
||||
`Failed to assign library role to user ${user.username}: ${assignRoleResponse.status}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Don't fail the login if role assignment fails
|
||||
app.log.error({ err: error }, "Error assigning library role");
|
||||
}
|
||||
}
|
||||
|
||||
// Set signed cookies and redirect to frontend
|
||||
reply
|
||||
.setCookie("auth-token", accessToken, {
|
||||
|
||||
Reference in New Issue
Block a user