Skip to content

Commit

Permalink
feat: store last locale used
Browse files Browse the repository at this point in the history
  • Loading branch information
rharkor committed Dec 10, 2023
1 parent b6be641 commit 16e80e6
Show file tree
Hide file tree
Showing 10 changed files with 46 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ CREATE TABLE "User" (
"role" TEXT NOT NULL DEFAULT 'user',
"password" TEXT,
"hasPassword" BOOLEAN NOT NULL DEFAULT false,
"lastLocale" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

Expand Down
1 change: 1 addition & 0 deletions packages/app/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ model User {
hasPassword Boolean @default(false)
resetPasswordToken ResetPassordToken?
userEmailVerificationToken UserEmailVerificationToken?
lastLocale String?
// Timestamps
createdAt DateTime @default(now())
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/api/auth/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { hash } from "@/lib/bcrypt"
import { logger } from "@/lib/logger"
import { sendMail } from "@/lib/mailer"
import { prisma } from "@/lib/prisma"
import { redis } from "@/lib/redis"
import { signUpSchema } from "@/lib/schemas/auth"
import { html, plainText, subject } from "@/lib/templates/mail/verify-email"
import { ApiError, handleApiError, throwableErrorsMessages } from "@/lib/utils/server-utils"
Expand All @@ -25,8 +26,10 @@ export const register = async ({ input }: apiInputFromSchema<typeof signUpSchema
email: email.toLowerCase(),
username,
password: hashedPassword,
lastLocale: input.locale,
},
})
await redis.set(`lastLocale:${user.id}`, input.locale)

//* Send verification email
if (env.ENABLE_MAILING_SERVICE === true) {
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/api/me/email/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const sendVerificationEmail = async ({ input }: apiInputFromSchema<typeof
email: email.toLowerCase(),
},
})

if (!user) {
logger.debug("User not found")
return { email }
Expand Down
35 changes: 34 additions & 1 deletion packages/app/src/app/[lang]/(protected)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Locale } from "i18n-config"
import requireAuth from "@/components/auth/require-auth"
import LocaleSwitcher from "@/components/locale-switcher"
import { ThemeSwitch } from "@/components/theme/theme-switch"
import { prisma } from "@/lib/prisma"
import { redis } from "@/lib/redis"

export default async function ProtectedLayout({
children,
Expand All @@ -13,7 +15,38 @@ export default async function ProtectedLayout({
lang: Locale
}
}) {
await requireAuth()
const session = await requireAuth()

//* Set last locale
// Get last locale from redis or db
const getLastLocale = async () => {
const lastLocale = await redis.get(`lastLocale:${session.user.id}`)
if (lastLocale) {
return lastLocale
}
const lastLocaleFromDb = await prisma.user.findUnique({
where: { id: session.user.id },
select: { lastLocale: true },
})
if (lastLocaleFromDb && lastLocaleFromDb.lastLocale) {
await redis.set(`lastLocale:${session.user.id}`, lastLocaleFromDb.lastLocale)
return lastLocaleFromDb.lastLocale
}
return null
}
// Set last locale in redis and db
const setLastLocale = async (locale: Locale) => {
await redis.set(`lastLocale:${session.user.id}`, locale)
await prisma.user.update({
where: { id: session.user.id },
data: { lastLocale: locale },
})
}

const lastLocale = await getLastLocale()
if (lastLocale !== lang) {
await setLastLocale(lang)
}

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default async function SignupByCredentials({
<CardTitle>{dictionary.signUpPage.createAnAccount}</CardTitle>
</CardHeader>
<CardBody>
<RegisterUserAuthForm className="gap-3" searchParams={searchParams} dictionary={dictionary} />
<RegisterUserAuthForm className="gap-3" searchParams={searchParams} dictionary={dictionary} locale={lang} />
</CardBody>
</Card>
</main>
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/app/[lang]/(sys-auth)/sign-up/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default async function SignUpPage({
<p className="text-muted-foreground text-sm">{dictionary.signUpPage.enterEmail}</p>
</div>
<div className="grid gap-6">
<RegisterUserAuthForm isMinimized searchParams={searchParams} dictionary={dictionary} />
<RegisterUserAuthForm isMinimized searchParams={searchParams} dictionary={dictionary} locale={lang} />
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
Expand Down
4 changes: 3 additions & 1 deletion packages/app/src/components/auth/register-user-auth-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type UserAuthFormProps = React.HTMLAttributes<HTMLFormElement> & {
dictionary: TDictionary
isMinimized?: boolean
searchParams?: { [key: string]: string | string[] | undefined }
locale: string
}

export const formSchema = (dictionary: TDictionary) =>
Expand Down Expand Up @@ -52,7 +53,7 @@ export const getFormSchema = ({ dictionary, isMinimized }: { dictionary: TDictio
export type IForm = z.infer<ReturnType<typeof formSchema>>
export type IFormMinimized = z.infer<ReturnType<typeof formMinizedSchema>>

export function RegisterUserAuthForm({ dictionary, isMinimized, searchParams, ...props }: UserAuthFormProps) {
export function RegisterUserAuthForm({ dictionary, isMinimized, searchParams, locale, ...props }: UserAuthFormProps) {
const router = useRouter()

const registerMutation = trpc.auth.register.useMutation({
Expand Down Expand Up @@ -102,6 +103,7 @@ export function RegisterUserAuthForm({ dictionary, isMinimized, searchParams, ..
username: "",
password: "",
confirmPassword: "",
locale,
},
})

Expand Down
1 change: 1 addition & 0 deletions packages/app/src/lib/schemas/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const signUpSchema = (dictionary?: TDictionary) =>
signInSchema(dictionary).extend({
username: usernameSchema(dictionary),
password: passwordSchemaWithRegex(dictionary),
locale: z.string(),
})

export const signUpResponseSchema = (dictionary?: TDictionary) =>
Expand Down

0 comments on commit 16e80e6

Please sign in to comment.