ar-saas 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +62 -0
  2. package/dist/cli.js +67 -0
  3. package/dist/generator.js +242 -0
  4. package/dist/index.js +13 -0
  5. package/dist/license.js +71 -0
  6. package/package.json +46 -0
  7. package/templates/backend/.env.example +67 -0
  8. package/templates/backend/.prettierrc +4 -0
  9. package/templates/backend/README.md +168 -0
  10. package/templates/backend/eslint.config.mjs +35 -0
  11. package/templates/backend/nest-cli.json +8 -0
  12. package/templates/backend/package-lock.json +10979 -0
  13. package/templates/backend/package.json +88 -0
  14. package/templates/backend/src/app.controller.spec.ts +24 -0
  15. package/templates/backend/src/app.controller.ts +15 -0
  16. package/templates/backend/src/app.module.ts +40 -0
  17. package/templates/backend/src/app.service.ts +11 -0
  18. package/templates/backend/src/common/base/base.repository.ts +221 -0
  19. package/templates/backend/src/common/base/base.schema.ts +24 -0
  20. package/templates/backend/src/common/decorators/cookie.decorator.ts +9 -0
  21. package/templates/backend/src/common/decorators/current-user.decorator.ts +20 -0
  22. package/templates/backend/src/common/decorators/workspace-id.decorator.ts +14 -0
  23. package/templates/backend/src/common/filters/global-exception.filter.ts +61 -0
  24. package/templates/backend/src/common/guards/jwt-auth.guard.ts +5 -0
  25. package/templates/backend/src/common/interceptors/workspace-tenant.interceptor.ts +45 -0
  26. package/templates/backend/src/main.ts +51 -0
  27. package/templates/backend/src/modules/auth/auth.controller.ts +158 -0
  28. package/templates/backend/src/modules/auth/auth.module.ts +20 -0
  29. package/templates/backend/src/modules/auth/auth.service.ts +257 -0
  30. package/templates/backend/src/modules/auth/dto/forgot-password.dto.ts +9 -0
  31. package/templates/backend/src/modules/auth/dto/login.dto.ts +14 -0
  32. package/templates/backend/src/modules/auth/dto/refresh-token.dto.ts +12 -0
  33. package/templates/backend/src/modules/auth/dto/register.dto.ts +26 -0
  34. package/templates/backend/src/modules/auth/dto/reset-password.dto.ts +16 -0
  35. package/templates/backend/src/modules/auth/dto/verify-email.dto.ts +9 -0
  36. package/templates/backend/src/modules/auth/strategies/jwt.strategy.ts +43 -0
  37. package/templates/backend/src/modules/mail/mail.module.ts +9 -0
  38. package/templates/backend/src/modules/mail/mail.service.ts +141 -0
  39. package/templates/backend/src/modules/users/schemas/user.schema.ts +54 -0
  40. package/templates/backend/src/modules/users/users.module.ts +14 -0
  41. package/templates/backend/src/modules/users/users.repository.ts +51 -0
  42. package/templates/backend/src/modules/users/users.service.ts +104 -0
  43. package/templates/backend/src/modules/workspaces/schemas/workspace.schema.ts +26 -0
  44. package/templates/backend/src/modules/workspaces/workspaces.module.ts +16 -0
  45. package/templates/backend/src/modules/workspaces/workspaces.repository.ts +34 -0
  46. package/templates/backend/src/modules/workspaces/workspaces.service.ts +42 -0
  47. package/templates/backend/test/app.e2e-spec.ts +25 -0
  48. package/templates/backend/test/jest-e2e.json +9 -0
  49. package/templates/backend/tsconfig.build.json +4 -0
  50. package/templates/backend/tsconfig.json +26 -0
  51. package/templates/frontend/.env.local.example +1 -0
  52. package/templates/frontend/components.json +20 -0
  53. package/templates/frontend/eslint.config.mjs +14 -0
  54. package/templates/frontend/next.config.ts +5 -0
  55. package/templates/frontend/package-lock.json +6722 -0
  56. package/templates/frontend/package.json +40 -0
  57. package/templates/frontend/postcss.config.mjs +7 -0
  58. package/templates/frontend/src/app/(auth)/forgot-password/page.tsx +84 -0
  59. package/templates/frontend/src/app/(auth)/layout.tsx +28 -0
  60. package/templates/frontend/src/app/(auth)/login/page.tsx +111 -0
  61. package/templates/frontend/src/app/(auth)/register/page.tsx +119 -0
  62. package/templates/frontend/src/app/(auth)/reset-password/page.tsx +120 -0
  63. package/templates/frontend/src/app/(auth)/verify-email/page.tsx +78 -0
  64. package/templates/frontend/src/app/(dashboard)/dashboard/page.tsx +36 -0
  65. package/templates/frontend/src/app/(dashboard)/layout.tsx +59 -0
  66. package/templates/frontend/src/app/globals.css +81 -0
  67. package/templates/frontend/src/app/layout.tsx +26 -0
  68. package/templates/frontend/src/app/page.tsx +5 -0
  69. package/templates/frontend/src/app/setup/page.tsx +278 -0
  70. package/templates/frontend/src/components/ui/button.tsx +52 -0
  71. package/templates/frontend/src/components/ui/card.tsx +50 -0
  72. package/templates/frontend/src/components/ui/form.tsx +158 -0
  73. package/templates/frontend/src/components/ui/input.tsx +21 -0
  74. package/templates/frontend/src/components/ui/label.tsx +22 -0
  75. package/templates/frontend/src/components/ui/toast.tsx +109 -0
  76. package/templates/frontend/src/components/ui/toaster.tsx +30 -0
  77. package/templates/frontend/src/hooks/use-toast.ts +116 -0
  78. package/templates/frontend/src/lib/api/auth.ts +39 -0
  79. package/templates/frontend/src/lib/api/client.ts +66 -0
  80. package/templates/frontend/src/lib/hooks/use-auth.ts +1 -0
  81. package/templates/frontend/src/lib/utils.ts +6 -0
  82. package/templates/frontend/src/providers/auth-provider.tsx +60 -0
  83. package/templates/frontend/src/types/api.ts +12 -0
  84. package/templates/frontend/src/types/auth.ts +27 -0
  85. package/templates/frontend/tsconfig.json +23 -0
@@ -0,0 +1,158 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import * as LabelPrimitive from '@radix-ui/react-label'
5
+ import { Slot } from '@radix-ui/react-slot'
6
+ import {
7
+ Controller,
8
+ FormProvider,
9
+ useFormContext,
10
+ type ControllerProps,
11
+ type FieldPath,
12
+ type FieldValues,
13
+ } from 'react-hook-form'
14
+ import { cn } from '@/lib/utils'
15
+ import { Label } from '@/components/ui/label'
16
+
17
+ const Form = FormProvider
18
+
19
+ type FormFieldContextValue<
20
+ TFieldValues extends FieldValues = FieldValues,
21
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
22
+ > = { name: TName }
23
+
24
+ const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue)
25
+
26
+ const FormField = <
27
+ TFieldValues extends FieldValues = FieldValues,
28
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
29
+ >({
30
+ ...props
31
+ }: ControllerProps<TFieldValues, TName>) => {
32
+ return (
33
+ <FormFieldContext.Provider value={{ name: props.name }}>
34
+ <Controller {...props} />
35
+ </FormFieldContext.Provider>
36
+ )
37
+ }
38
+
39
+ const useFormField = () => {
40
+ const fieldContext = React.useContext(FormFieldContext)
41
+ const itemContext = React.useContext(FormItemContext)
42
+ const { getFieldState, formState } = useFormContext()
43
+
44
+ const fieldState = getFieldState(fieldContext.name, formState)
45
+
46
+ if (!fieldContext) {
47
+ throw new Error('useFormField debe usarse dentro de <FormField>')
48
+ }
49
+
50
+ const { id } = itemContext
51
+
52
+ return {
53
+ id,
54
+ name: fieldContext.name,
55
+ formItemId: `${id}-form-item`,
56
+ formDescriptionId: `${id}-form-item-description`,
57
+ formMessageId: `${id}-form-item-message`,
58
+ ...fieldState,
59
+ }
60
+ }
61
+
62
+ type FormItemContextValue = { id: string }
63
+
64
+ const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue)
65
+
66
+ const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
67
+ ({ className, ...props }, ref) => {
68
+ const id = React.useId()
69
+ return (
70
+ <FormItemContext.Provider value={{ id }}>
71
+ <div ref={ref} className={cn('space-y-2', className)} {...props} />
72
+ </FormItemContext.Provider>
73
+ )
74
+ },
75
+ )
76
+ FormItem.displayName = 'FormItem'
77
+
78
+ const FormLabel = React.forwardRef<
79
+ React.ElementRef<typeof LabelPrimitive.Root>,
80
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
81
+ >(({ className, ...props }, ref) => {
82
+ const { error, formItemId } = useFormField()
83
+ return (
84
+ <Label
85
+ ref={ref}
86
+ className={cn(error && 'text-destructive', className)}
87
+ htmlFor={formItemId}
88
+ {...props}
89
+ />
90
+ )
91
+ })
92
+ FormLabel.displayName = 'FormLabel'
93
+
94
+ const FormControl = React.forwardRef<
95
+ React.ElementRef<typeof Slot>,
96
+ React.ComponentPropsWithoutRef<typeof Slot>
97
+ >(({ ...props }, ref) => {
98
+ const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
99
+ return (
100
+ <Slot
101
+ ref={ref}
102
+ id={formItemId}
103
+ aria-describedby={!error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`}
104
+ aria-invalid={!!error}
105
+ {...props}
106
+ />
107
+ )
108
+ })
109
+ FormControl.displayName = 'FormControl'
110
+
111
+ const FormDescription = React.forwardRef<
112
+ HTMLParagraphElement,
113
+ React.HTMLAttributes<HTMLParagraphElement>
114
+ >(({ className, ...props }, ref) => {
115
+ const { formDescriptionId } = useFormField()
116
+ return (
117
+ <p
118
+ ref={ref}
119
+ id={formDescriptionId}
120
+ className={cn('text-[0.8rem] text-muted-foreground', className)}
121
+ {...props}
122
+ />
123
+ )
124
+ })
125
+ FormDescription.displayName = 'FormDescription'
126
+
127
+ const FormMessage = React.forwardRef<
128
+ HTMLParagraphElement,
129
+ React.HTMLAttributes<HTMLParagraphElement>
130
+ >(({ className, children, ...props }, ref) => {
131
+ const { error, formMessageId } = useFormField()
132
+ const body = error ? String(error?.message) : children
133
+
134
+ if (!body) return null
135
+
136
+ return (
137
+ <p
138
+ ref={ref}
139
+ id={formMessageId}
140
+ className={cn('text-[0.8rem] font-medium text-destructive', className)}
141
+ {...props}
142
+ >
143
+ {body}
144
+ </p>
145
+ )
146
+ })
147
+ FormMessage.displayName = 'FormMessage'
148
+
149
+ export {
150
+ useFormField,
151
+ Form,
152
+ FormItem,
153
+ FormLabel,
154
+ FormControl,
155
+ FormDescription,
156
+ FormMessage,
157
+ FormField,
158
+ }
@@ -0,0 +1,21 @@
1
+ import * as React from 'react'
2
+ import { cn } from '@/lib/utils'
3
+
4
+ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
5
+ ({ className, type, ...props }, ref) => {
6
+ return (
7
+ <input
8
+ type={type}
9
+ className={cn(
10
+ 'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
11
+ className,
12
+ )}
13
+ ref={ref}
14
+ {...props}
15
+ />
16
+ )
17
+ },
18
+ )
19
+ Input.displayName = 'Input'
20
+
21
+ export { Input }
@@ -0,0 +1,22 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import * as LabelPrimitive from '@radix-ui/react-label'
5
+ import { cn } from '@/lib/utils'
6
+
7
+ const Label = React.forwardRef<
8
+ React.ElementRef<typeof LabelPrimitive.Root>,
9
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
10
+ >(({ className, ...props }, ref) => (
11
+ <LabelPrimitive.Root
12
+ ref={ref}
13
+ className={cn(
14
+ 'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
15
+ className,
16
+ )}
17
+ {...props}
18
+ />
19
+ ))
20
+ Label.displayName = LabelPrimitive.Root.displayName
21
+
22
+ export { Label }
@@ -0,0 +1,109 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import * as ToastPrimitive from '@radix-ui/react-toast'
5
+ import { cva, type VariantProps } from 'class-variance-authority'
6
+ import { X } from 'lucide-react'
7
+ import { cn } from '@/lib/utils'
8
+
9
+ const ToastProvider = ToastPrimitive.Provider
10
+
11
+ const ToastViewport = React.forwardRef<
12
+ React.ElementRef<typeof ToastPrimitive.Viewport>,
13
+ React.ComponentPropsWithoutRef<typeof ToastPrimitive.Viewport>
14
+ >(({ className, ...props }, ref) => (
15
+ <ToastPrimitive.Viewport
16
+ ref={ref}
17
+ className={cn(
18
+ 'fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]',
19
+ className,
20
+ )}
21
+ {...props}
22
+ />
23
+ ))
24
+ ToastViewport.displayName = ToastPrimitive.Viewport.displayName
25
+
26
+ const toastVariants = cva(
27
+ 'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
28
+ {
29
+ variants: {
30
+ variant: {
31
+ default: 'border bg-background text-foreground',
32
+ destructive: 'destructive group border-destructive bg-destructive text-destructive-foreground',
33
+ },
34
+ },
35
+ defaultVariants: { variant: 'default' },
36
+ },
37
+ )
38
+
39
+ const Toast = React.forwardRef<
40
+ React.ElementRef<typeof ToastPrimitive.Root>,
41
+ React.ComponentPropsWithoutRef<typeof ToastPrimitive.Root> & VariantProps<typeof toastVariants>
42
+ >(({ className, variant, ...props }, ref) => (
43
+ <ToastPrimitive.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} />
44
+ ))
45
+ Toast.displayName = ToastPrimitive.Root.displayName
46
+
47
+ const ToastAction = React.forwardRef<
48
+ React.ElementRef<typeof ToastPrimitive.Action>,
49
+ React.ComponentPropsWithoutRef<typeof ToastPrimitive.Action>
50
+ >(({ className, ...props }, ref) => (
51
+ <ToastPrimitive.Action
52
+ ref={ref}
53
+ className={cn(
54
+ 'inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive',
55
+ className,
56
+ )}
57
+ {...props}
58
+ />
59
+ ))
60
+ ToastAction.displayName = ToastPrimitive.Action.displayName
61
+
62
+ const ToastClose = React.forwardRef<
63
+ React.ElementRef<typeof ToastPrimitive.Close>,
64
+ React.ComponentPropsWithoutRef<typeof ToastPrimitive.Close>
65
+ >(({ className, ...props }, ref) => (
66
+ <ToastPrimitive.Close
67
+ ref={ref}
68
+ className={cn(
69
+ 'absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
70
+ className,
71
+ )}
72
+ toast-close=""
73
+ {...props}
74
+ >
75
+ <X className="h-4 w-4" />
76
+ </ToastPrimitive.Close>
77
+ ))
78
+ ToastClose.displayName = ToastPrimitive.Close.displayName
79
+
80
+ const ToastTitle = React.forwardRef<
81
+ React.ElementRef<typeof ToastPrimitive.Title>,
82
+ React.ComponentPropsWithoutRef<typeof ToastPrimitive.Title>
83
+ >(({ className, ...props }, ref) => (
84
+ <ToastPrimitive.Title ref={ref} className={cn('text-sm font-semibold [&+div]:text-xs', className)} {...props} />
85
+ ))
86
+ ToastTitle.displayName = ToastPrimitive.Title.displayName
87
+
88
+ const ToastDescription = React.forwardRef<
89
+ React.ElementRef<typeof ToastPrimitive.Description>,
90
+ React.ComponentPropsWithoutRef<typeof ToastPrimitive.Description>
91
+ >(({ className, ...props }, ref) => (
92
+ <ToastPrimitive.Description ref={ref} className={cn('text-sm opacity-90', className)} {...props} />
93
+ ))
94
+ ToastDescription.displayName = ToastPrimitive.Description.displayName
95
+
96
+ type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
97
+ type ToastActionElement = React.ReactElement<typeof ToastAction>
98
+
99
+ export {
100
+ type ToastProps,
101
+ type ToastActionElement,
102
+ ToastProvider,
103
+ ToastViewport,
104
+ Toast,
105
+ ToastTitle,
106
+ ToastDescription,
107
+ ToastClose,
108
+ ToastAction,
109
+ }
@@ -0,0 +1,30 @@
1
+ 'use client'
2
+
3
+ import { useToast } from '@/hooks/use-toast'
4
+ import {
5
+ Toast,
6
+ ToastClose,
7
+ ToastDescription,
8
+ ToastProvider,
9
+ ToastTitle,
10
+ ToastViewport,
11
+ } from '@/components/ui/toast'
12
+
13
+ export function Toaster() {
14
+ const { toasts } = useToast()
15
+ return (
16
+ <ToastProvider>
17
+ {toasts.map(({ id, title, description, action, ...props }) => (
18
+ <Toast key={id} {...props}>
19
+ <div className="grid gap-1">
20
+ {title && <ToastTitle>{title}</ToastTitle>}
21
+ {description && <ToastDescription>{description}</ToastDescription>}
22
+ </div>
23
+ {action}
24
+ <ToastClose />
25
+ </Toast>
26
+ ))}
27
+ <ToastViewport />
28
+ </ToastProvider>
29
+ )
30
+ }
@@ -0,0 +1,116 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import type { ToastActionElement, ToastProps } from '@/components/ui/toast'
5
+
6
+ const TOAST_LIMIT = 3
7
+ const TOAST_REMOVE_DELAY = 4000
8
+
9
+ type ToasterToast = ToastProps & {
10
+ id: string
11
+ title?: React.ReactNode
12
+ description?: React.ReactNode
13
+ action?: ToastActionElement
14
+ }
15
+
16
+ type ActionType = {
17
+ ADD_TOAST: 'ADD_TOAST'
18
+ UPDATE_TOAST: 'UPDATE_TOAST'
19
+ DISMISS_TOAST: 'DISMISS_TOAST'
20
+ REMOVE_TOAST: 'REMOVE_TOAST'
21
+ }
22
+
23
+ type Action =
24
+ | { type: ActionType['ADD_TOAST']; toast: ToasterToast }
25
+ | { type: ActionType['UPDATE_TOAST']; toast: Partial<ToasterToast> }
26
+ | { type: ActionType['DISMISS_TOAST']; toastId?: ToasterToast['id'] }
27
+ | { type: ActionType['REMOVE_TOAST']; toastId?: ToasterToast['id'] }
28
+
29
+ interface State {
30
+ toasts: ToasterToast[]
31
+ }
32
+
33
+ const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
34
+
35
+ const addToRemoveQueue = (toastId: string) => {
36
+ if (toastTimeouts.has(toastId)) return
37
+ const timeout = setTimeout(() => {
38
+ toastTimeouts.delete(toastId)
39
+ dispatch({ type: 'REMOVE_TOAST', toastId })
40
+ }, TOAST_REMOVE_DELAY)
41
+ toastTimeouts.set(toastId, timeout)
42
+ }
43
+
44
+ export const reducer = (state: State, action: Action): State => {
45
+ switch (action.type) {
46
+ case 'ADD_TOAST':
47
+ return { ...state, toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT) }
48
+ case 'UPDATE_TOAST':
49
+ return {
50
+ ...state,
51
+ toasts: state.toasts.map((t) => (t.id === action.toast.id ? { ...t, ...action.toast } : t)),
52
+ }
53
+ case 'DISMISS_TOAST': {
54
+ const { toastId } = action
55
+ if (toastId) {
56
+ addToRemoveQueue(toastId)
57
+ } else {
58
+ state.toasts.forEach((toast) => addToRemoveQueue(toast.id))
59
+ }
60
+ return {
61
+ ...state,
62
+ toasts: state.toasts.map((t) =>
63
+ t.id === toastId || toastId === undefined ? { ...t, open: false } : t,
64
+ ),
65
+ }
66
+ }
67
+ case 'REMOVE_TOAST':
68
+ return {
69
+ ...state,
70
+ toasts: action.toastId === undefined
71
+ ? []
72
+ : state.toasts.filter((t) => t.id !== action.toastId),
73
+ }
74
+ }
75
+ }
76
+
77
+ const listeners: Array<(state: State) => void> = []
78
+ let memoryState: State = { toasts: [] }
79
+
80
+ function dispatch(action: Action) {
81
+ memoryState = reducer(memoryState, action)
82
+ listeners.forEach((listener) => listener(memoryState))
83
+ }
84
+
85
+ let count = 0
86
+ function genId() {
87
+ count = (count + 1) % Number.MAX_SAFE_INTEGER
88
+ return count.toString()
89
+ }
90
+
91
+ type Toast = Omit<ToasterToast, 'id'>
92
+
93
+ function toast({ ...props }: Toast) {
94
+ const id = genId()
95
+ const update = (props: ToasterToast) => dispatch({ type: 'UPDATE_TOAST', toast: { ...props, id } })
96
+ const dismiss = () => dispatch({ type: 'DISMISS_TOAST', toastId: id })
97
+ dispatch({
98
+ type: 'ADD_TOAST',
99
+ toast: { ...props, id, open: true, onOpenChange: (open) => { if (!open) dismiss() } },
100
+ })
101
+ return { id, dismiss, update }
102
+ }
103
+
104
+ function useToast() {
105
+ const [state, setState] = React.useState<State>(memoryState)
106
+ React.useEffect(() => {
107
+ listeners.push(setState)
108
+ return () => {
109
+ const index = listeners.indexOf(setState)
110
+ if (index > -1) listeners.splice(index, 1)
111
+ }
112
+ }, [])
113
+ return { ...state, toast, dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId }) }
114
+ }
115
+
116
+ export { useToast, toast }
@@ -0,0 +1,39 @@
1
+ import apiClient from './client'
2
+ import type { User } from '@/types/auth'
3
+
4
+ export const authApi = {
5
+ register(data: { name: string; email: string; password: string }) {
6
+ return apiClient.post<never, { message: string }>('/api/auth/register', data)
7
+ },
8
+
9
+ login(data: { email: string; password: string }) {
10
+ return apiClient.post<never, User>('/api/auth/login', data)
11
+ },
12
+
13
+ logout() {
14
+ return apiClient.post<never, { message: string }>('/api/auth/logout')
15
+ },
16
+
17
+ refresh() {
18
+ return apiClient.post<never, { message: string }>('/api/auth/refresh')
19
+ },
20
+
21
+ verifyEmail(token: string) {
22
+ return apiClient.get<never, { message: string }>(`/api/auth/verify-email?token=${token}`)
23
+ },
24
+
25
+ forgotPassword(email: string) {
26
+ return apiClient.post<never, { message: string }>('/api/auth/forgot-password', { email })
27
+ },
28
+
29
+ resetPassword(token: string, newPassword: string) {
30
+ return apiClient.post<never, { message: string }>('/api/auth/reset-password', {
31
+ token,
32
+ newPassword,
33
+ })
34
+ },
35
+
36
+ getMe() {
37
+ return apiClient.get<never, User>('/api/auth/me')
38
+ },
39
+ }
@@ -0,0 +1,66 @@
1
+ import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'
2
+ import type { ApiError } from '@/types/api'
3
+
4
+ const apiClient = axios.create({
5
+ baseURL: process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000',
6
+ withCredentials: true,
7
+ })
8
+
9
+ let isRefreshing = false
10
+ let failedQueue: Array<{
11
+ resolve: (value: unknown) => void
12
+ reject: (reason?: unknown) => void
13
+ }> = []
14
+
15
+ function processQueue(error: unknown) {
16
+ failedQueue.forEach(({ resolve, reject }) => {
17
+ if (error) {
18
+ reject(error)
19
+ } else {
20
+ resolve(undefined)
21
+ }
22
+ })
23
+ failedQueue = []
24
+ }
25
+
26
+ apiClient.interceptors.response.use(
27
+ (response) => response.data,
28
+ async (error: AxiosError<ApiError>) => {
29
+ const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean }
30
+
31
+ if (error.response?.status !== 401 || originalRequest._retry) {
32
+ return Promise.reject(error.response?.data ?? error)
33
+ }
34
+
35
+ if (isRefreshing) {
36
+ return new Promise((resolve, reject) => {
37
+ failedQueue.push({ resolve, reject })
38
+ })
39
+ .then(() => apiClient(originalRequest))
40
+ .catch((err) => Promise.reject(err))
41
+ }
42
+
43
+ originalRequest._retry = true
44
+ isRefreshing = true
45
+
46
+ try {
47
+ await axios.post(
48
+ `${process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000'}/api/auth/refresh`,
49
+ {},
50
+ { withCredentials: true },
51
+ )
52
+ processQueue(null)
53
+ return apiClient(originalRequest)
54
+ } catch (refreshError) {
55
+ processQueue(refreshError)
56
+ if (typeof window !== 'undefined') {
57
+ window.location.href = '/login'
58
+ }
59
+ return Promise.reject(refreshError)
60
+ } finally {
61
+ isRefreshing = false
62
+ }
63
+ },
64
+ )
65
+
66
+ export default apiClient
@@ -0,0 +1 @@
1
+ export { useAuth } from '@/providers/auth-provider'
@@ -0,0 +1,6 @@
1
+ import { type ClassValue, clsx } from 'clsx'
2
+ import { twMerge } from 'tailwind-merge'
3
+
4
+ export function cn(...inputs: ClassValue[]) {
5
+ return twMerge(clsx(inputs))
6
+ }
@@ -0,0 +1,60 @@
1
+ 'use client'
2
+
3
+ import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'
4
+ import { useRouter } from 'next/navigation'
5
+ import { authApi } from '@/lib/api/auth'
6
+ import type { AuthState, User } from '@/types/auth'
7
+
8
+ interface AuthContextValue extends AuthState {
9
+ login: (email: string, password: string) => Promise<void>
10
+ logout: () => Promise<void>
11
+ register: (name: string, email: string, password: string) => Promise<{ message: string }>
12
+ }
13
+
14
+ const AuthContext = createContext<AuthContextValue | null>(null)
15
+
16
+ export function AuthProvider({ children }: { children: React.ReactNode }) {
17
+ const router = useRouter()
18
+ const [state, setState] = useState<AuthState>({
19
+ user: null,
20
+ isLoading: true,
21
+ isAuthenticated: false,
22
+ })
23
+
24
+ useEffect(() => {
25
+ authApi
26
+ .getMe()
27
+ .then((user: User) => setState({ user, isLoading: false, isAuthenticated: true }))
28
+ .catch(() => setState({ user: null, isLoading: false, isAuthenticated: false }))
29
+ }, [])
30
+
31
+ const login = useCallback(async (email: string, password: string) => {
32
+ const user = await authApi.login({ email, password })
33
+ setState({ user, isLoading: false, isAuthenticated: true })
34
+ router.push('/dashboard')
35
+ }, [router])
36
+
37
+ const logout = useCallback(async () => {
38
+ await authApi.logout()
39
+ setState({ user: null, isLoading: false, isAuthenticated: false })
40
+ router.push('/login')
41
+ }, [router])
42
+
43
+ const register = useCallback(
44
+ (name: string, email: string, password: string) =>
45
+ authApi.register({ name, email, password }),
46
+ [],
47
+ )
48
+
49
+ return (
50
+ <AuthContext.Provider value={{ ...state, login, logout, register }}>
51
+ {children}
52
+ </AuthContext.Provider>
53
+ )
54
+ }
55
+
56
+ export function useAuth(): AuthContextValue {
57
+ const ctx = useContext(AuthContext)
58
+ if (!ctx) throw new Error('useAuth debe usarse dentro de <AuthProvider>')
59
+ return ctx
60
+ }
@@ -0,0 +1,12 @@
1
+ export interface ApiError {
2
+ statusCode: number
3
+ message: string
4
+ error: string
5
+ timestamp: string
6
+ path: string
7
+ }
8
+
9
+ export interface ApiResponse<T> {
10
+ data: T
11
+ message?: string
12
+ }
@@ -0,0 +1,27 @@
1
+ export interface User {
2
+ _id: string
3
+ name: string
4
+ email: string
5
+ emailVerified: boolean
6
+ role: 'owner' | 'admin' | 'member'
7
+ workspaceId: string
8
+ lastLoginAt?: string
9
+ createdAt: string
10
+ updatedAt: string
11
+ }
12
+
13
+ export interface Workspace {
14
+ _id: string
15
+ name: string
16
+ slug: string
17
+ ownerId: string
18
+ status: 'active' | 'suspended'
19
+ createdAt: string
20
+ updatedAt: string
21
+ }
22
+
23
+ export interface AuthState {
24
+ user: User | null
25
+ isLoading: boolean
26
+ isAuthenticated: boolean
27
+ }