refactor: improve user retrieval and formatting in auth component

- Enhanced the getCurrentUser function to include the user's profile picture URL.
- Cleaned up formatting for better readability and consistency across the auth.ts file.
- Maintained existing functionality while improving code organization.
This commit is contained in:
2025-11-12 12:15:43 -03:00
parent da26a21f7e
commit 6087990eaf

View File

@@ -1,10 +1,9 @@
import { createClient, type GenericCtx } from "@convex-dev/better-auth"; import { createClient, type GenericCtx } from '@convex-dev/better-auth';
import { convex } from "@convex-dev/better-auth/plugins"; import { convex } from '@convex-dev/better-auth/plugins';
import { components } from "./_generated/api"; import { components } from './_generated/api';
import { type DataModel } from "./_generated/dataModel"; import { type DataModel } from './_generated/dataModel';
import { mutation, MutationCtx, query, QueryCtx } from "./_generated/server"; import { MutationCtx, query, QueryCtx } from './_generated/server';
import { betterAuth } from "better-auth"; import { betterAuth } from 'better-auth';
import { v } from "convex/values";
const siteUrl = process.env.SITE_URL!; const siteUrl = process.env.SITE_URL!;
@@ -13,106 +12,108 @@ const siteUrl = process.env.SITE_URL!;
export const authComponent = createClient<DataModel>(components.betterAuth); export const authComponent = createClient<DataModel>(components.betterAuth);
export const createAuth = ( export const createAuth = (
ctx: GenericCtx<DataModel>, ctx: GenericCtx<DataModel>,
{ optionsOnly } = { optionsOnly: false } { optionsOnly } = { optionsOnly: false }
) => { ) => {
return betterAuth({ return betterAuth({
// disable logging when createAuth is called just to generate options. // disable logging when createAuth is called just to generate options.
// this is not required, but there's a lot of noise in logs without it. // this is not required, but there's a lot of noise in logs without it.
logger: { logger: {
disabled: optionsOnly, disabled: optionsOnly
}, },
baseURL: siteUrl, baseURL: siteUrl,
database: authComponent.adapter(ctx), database: authComponent.adapter(ctx),
// Configure simple, non-verified email/password to get started // Configure simple, non-verified email/password to get started
emailAndPassword: { emailAndPassword: {
enabled: true, enabled: true,
requireEmailVerification: false, requireEmailVerification: false
}, },
plugins: [ plugins: [
// The Convex plugin is required for Convex compatibility // The Convex plugin is required for Convex compatibility
convex(), convex()
], ]
}); });
}; };
// Example function for getting the current user // Example function for getting the current user
// Feel free to edit, omit, etc. // Feel free to edit, omit, etc.
export const getCurrentUser = query({ export const getCurrentUser = query({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
const authUser = await authComponent.safeGetAuthUser(ctx as any); const authUser = await authComponent.safeGetAuthUser(ctx as any);
if (!authUser) { if (!authUser) {
return; return;
} }
const user = await ctx.db const user = await ctx.db
.query("usuarios") .query('usuarios')
.withIndex("authId", (q) => q.eq("authId", authUser._id)) .withIndex('authId', (q) => q.eq('authId', authUser._id))
.unique(); .unique();
if (!user) { if (!user) {
return; return;
} }
if (!user.roleId) { const fotoPerfilUrl = user.fotoPerfil ? await ctx.storage.getUrl(user.fotoPerfil) : null;
return { ...user, role: null };
}
const role = await ctx.db if (!user.roleId) {
.query("roles") return { ...user, role: null, fotoPerfilUrl };
.withIndex("by_id", (q) => q.eq("_id", user.roleId)) }
.unique();
return { ...user, role }; const role = await ctx.db
}, .query('roles')
.withIndex('by_id', (q) => q.eq('_id', user.roleId))
.unique();
return { ...user, role, fotoPerfilUrl };
}
}); });
export const getCurrentUserFunction = async (ctx: QueryCtx | MutationCtx) => { export const getCurrentUserFunction = async (ctx: QueryCtx | MutationCtx) => {
const authUser = await authComponent.safeGetAuthUser(ctx as any); const authUser = await authComponent.safeGetAuthUser(ctx as any);
if (!authUser) { if (!authUser) {
return; return;
} }
const user = await ctx.db const user = await ctx.db
.query("usuarios") .query('usuarios')
.withIndex("authId", (q) => q.eq("authId", authUser._id)) .withIndex('authId', (q) => q.eq('authId', authUser._id))
.unique(); .unique();
if (!user) { if (!user) {
return; return;
} }
return user; return user;
}; };
export const createAuthUser = async ( export const createAuthUser = async (
ctx: MutationCtx, ctx: MutationCtx,
args: { nome: string; email: string; password: string } args: { nome: string; email: string; password: string }
) => { ) => {
const { auth, headers } = await authComponent.getAuth(createAuth, ctx as any); const { auth, headers } = await authComponent.getAuth(createAuth, ctx as any);
const result = await auth.api.signUpEmail({ const result = await auth.api.signUpEmail({
headers, headers,
body: { body: {
name: args.nome, name: args.nome,
email: args.email, email: args.email,
password: args.password, password: args.password
}, }
}); });
return result.user.id; return result.user.id;
}; };
export const updatePassword = async ( export const updatePassword = async (
ctx: MutationCtx, ctx: MutationCtx,
args: { newPassword: string; currentPassword: string } args: { newPassword: string; currentPassword: string }
) => { ) => {
const { auth, headers } = await authComponent.getAuth(createAuth, ctx as any); const { auth, headers } = await authComponent.getAuth(createAuth, ctx as any);
await auth.api.changePassword({ await auth.api.changePassword({
headers, headers,
body: { body: {
currentPassword: args.currentPassword, currentPassword: args.currentPassword,
newPassword: args.newPassword, newPassword: args.newPassword
}, }
}); });
}; };