Spaces:
Runtime error
Runtime error
File size: 8,203 Bytes
4782147 | 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | "use server";
import {
validatedActionWithAdminPermission,
validatedActionWithUserManagePermission,
} from "lib/action-utils";
import { headers } from "next/headers";
import { auth } from "auth/server";
import {
UpdateUserDetailsSchema,
DeleteUserSchema,
UpdateUserPasswordSchema,
UpdateUserActionState,
DeleteUserActionState,
UpdateUserPasswordActionState,
} from "./validations";
import { getUser, getUserAccounts, updateUserDetails } from "lib/user/server";
import { getTranslations } from "next-intl/server";
import { logger } from "better-auth";
import {
generateImageWithOpenAI,
generateImageWithXAI,
GeneratedImageResult,
generateImageWithNanoBanana,
} from "lib/ai/image/generate-image";
export const updateUserImageAction = validatedActionWithUserManagePermission(
UpdateUserDetailsSchema.pick({ userId: true, image: true }),
async (
data,
userId,
userSession,
isOwnResource,
): Promise<UpdateUserActionState> => {
const t = await getTranslations("User.Profile.common");
try {
const { image } = data;
if (isOwnResource) {
await auth.api.updateUser({
returnHeaders: true,
body: { image },
headers: await headers(),
});
} else {
await updateUserDetails(
userId,
userSession.user.name,
userSession.user.email || "",
image,
);
}
const user = await getUser(userId);
if (!user) {
return {
success: false,
message: t("userNotFound"),
};
}
return {
success: true,
message: "Profile photo updated successfully",
user,
currentUserUpdated: isOwnResource,
};
} catch (error) {
logger.error("Failed to update user image:", error);
return {
success: false,
message: "Failed to update profile photo",
};
}
},
);
export const updateUserDetailsAction = validatedActionWithUserManagePermission(
UpdateUserDetailsSchema,
async (
data,
userId,
userSession,
isOwnResource,
_formData,
): Promise<UpdateUserActionState> => {
const t = await getTranslations("User.Profile.common");
try {
const { name, email, image } = data;
const user = await getUser(userId);
if (!user) {
return {
success: false,
message: t("userNotFound"),
};
}
const isDifferentEmail = email && email !== userSession.user.email;
const isDifferentName = name && name !== userSession.user.name;
const isDifferentImage = image && image !== userSession.user.image;
// this forces a session update for the current user, getting the latest data
if (isOwnResource) {
if (isDifferentName || isDifferentImage) {
await auth.api.updateUser({
returnHeaders: true,
body: { name, ...(image && { image }) },
headers: await headers(),
});
}
if (isDifferentEmail) {
await auth.api.changeEmail({
returnHeaders: true,
body: { newEmail: email },
headers: await headers(),
});
}
} else {
await updateUserDetails(userId, name, email);
}
if (isDifferentEmail) user.email = email;
if (isDifferentName) user.name = name;
if (isDifferentImage) user.image = image;
return {
success: true,
message: t("userDetailsUpdatedSuccessfully"),
user,
currentUserUpdated: isOwnResource,
};
} catch (error) {
logger.error("Failed to update user details:", error);
return {
success: false,
message: t("failedToUpdateUserDetails"),
};
}
},
);
export const deleteUserAction = validatedActionWithAdminPermission(
DeleteUserSchema,
async (data, _formData, _userSession): Promise<DeleteUserActionState> => {
const t = await getTranslations("Admin.UserDelete");
const { userId } = data;
try {
await auth.api.removeUser({
body: { userId },
headers: await headers(),
});
} catch (error) {
console.error("Failed to delete user:", error);
return {
success: false,
message: t("failedToDeleteUser"),
};
}
return {
success: true,
message: t("userDeletedSuccessfully"),
redirect: "/admin",
};
},
);
export const updateUserPasswordAction = validatedActionWithUserManagePermission(
UpdateUserPasswordSchema,
async (
data,
userId,
_userSession,
isOwnResource,
_formData,
): Promise<UpdateUserPasswordActionState> => {
const t = await getTranslations("User.Profile.common");
const { newPassword, currentPassword } = data;
const { hasPassword } = await getUserAccounts(userId);
if (!hasPassword) {
return {
success: false,
message: t("userHasNoPasswordAccount"),
};
}
try {
if (isOwnResource) {
if (!currentPassword) {
return {
success: false,
message: t("failedToUpdatePassword"),
};
}
await auth.api.changePassword({
body: { currentPassword, newPassword, revokeOtherSessions: true },
headers: await headers(),
});
} else {
await auth.api.setUserPassword({
body: { userId, newPassword },
headers: await headers(),
});
await auth.api.revokeUserSessions({
body: { userId },
headers: await headers(),
});
}
return {
success: true,
message: t("passwordUpdatedSuccessfully"),
};
} catch (_error) {
console.error("Failed to update user password:", _error);
return {
success: false,
message: t("failedToUpdatePassword"),
};
}
},
);
type ImageProvider = "openai" | "xai" | "google";
interface GenerateAvatarResult {
success: boolean;
base64?: string;
mimeType?: string;
error?: string;
}
/**
* Server Action to generate avatar image using AI
*/
export async function generateAvatarImageAction(
provider: ImageProvider,
prompt: string,
): Promise<GenerateAvatarResult> {
try {
if (!prompt.trim()) {
return {
success: false,
error: "Prompt is required",
};
}
// Wrap user prompt with avatar-specific instructions
const enhancedPrompt = `You are tasked with creating a professional profile picture for a user.
Requirements:
- Portrait style with centered face
- Clear, high-quality image suitable for profile/avatar use
- Friendly and approachable expression
- Professional yet personable appearance
- Clean background that doesn't distract from the subject
- Well-lit with good contrast
User's request:
"${prompt}"
Generate a profile picture that fulfills the user's request while maintaining the professional portrait quality requirements above.`;
let response: GeneratedImageResult;
switch (provider) {
case "openai":
response = await generateImageWithOpenAI({
prompt: enhancedPrompt,
});
break;
case "xai":
response = await generateImageWithXAI({
prompt: enhancedPrompt,
});
break;
case "google":
response = await generateImageWithNanoBanana({
prompt: enhancedPrompt,
});
break;
default:
return {
success: false,
error: "Invalid provider",
};
}
if (!response || response.images.length === 0) {
return {
success: false,
error: "No image generated",
};
}
const image = response.images[0];
if (!image.base64) {
return {
success: false,
error: "No image data received",
};
}
return {
success: true,
base64: image.base64,
mimeType: image.mimeType || "image/png",
};
} catch (error) {
logger.error("Failed to generate avatar image:", error);
return {
success: false,
error:
error instanceof Error ? error.message : "Failed to generate image",
};
}
}
|