Add dockre file

This commit is contained in:
Aditya Siregar
2025-08-15 23:03:15 +07:00
commit 486f45bb92
106 changed files with 18736 additions and 0 deletions
+194
View File
@@ -0,0 +1,194 @@
"use client"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { API_CONFIG } from "@/lib/config"
import apiClient from "@/lib/api-client"
interface User {
id: string
name: string
email: string
is_active: boolean
created_at: string
updated_at: string
department_response?: any
}
interface Role {
id: string
name: string
code: string
}
interface LoginResponse {
success: boolean
data: {
token: string
expires_at: string
user: User
roles: Role[]
permissions: any[]
departments: any
}
errors: any
}
export function useAuth() {
const [user, setUser] = useState<User | null>(null)
const [loading, setLoading] = useState(true)
const [token, setToken] = useState<string | null>(null)
const [roles, setRoles] = useState<Role[]>([])
const router = useRouter()
useEffect(() => {
checkAuth()
}, [])
const checkAuth = async () => {
try {
const storedToken = localStorage.getItem("auth_token")
const storedUser = localStorage.getItem("auth_user")
const storedRoles = localStorage.getItem("auth_roles")
if (!storedToken || !storedUser) {
setLoading(false)
// Redirect to login page when no session exists
router.push("/login")
return
}
// Set the stored data
setToken(storedToken)
setUser(JSON.parse(storedUser))
if (storedRoles) {
const parsedRoles = JSON.parse(storedRoles)
// console.log('🔄 Loading roles from localStorage:', parsedRoles)
setRoles(parsedRoles)
}
} catch (error) {
console.error("Auth check failed:", error)
// Clear invalid data and redirect to login
localStorage.removeItem("auth_token")
localStorage.removeItem("auth_user")
localStorage.removeItem("auth_roles")
setUser(null)
setToken(null)
setRoles([])
router.push("/login")
} finally {
setLoading(false)
}
}
const login = async (email: string, password: string) => {
try {
console.log('Attempting login with Axios...')
const response = await apiClient.post<LoginResponse>('/api/v1/auth/login', {
email,
password,
})
console.log('Login successful:', response.data)
if (response.data.success && response.data.data) {
const { token, user, roles, expires_at } = response.data.data
// Store session data in localStorage
localStorage.setItem("auth_token", token)
localStorage.setItem("auth_user", JSON.stringify(user))
localStorage.setItem("auth_roles", JSON.stringify(roles))
localStorage.setItem("auth_expires_at", expires_at)
// console.log('💾 Storing roles in localStorage:', roles)
// Update state
setToken(token)
setUser(user)
setRoles(roles)
return { success: true, user, roles, token }
} else {
return { success: false, message: response.data.errors || "Login failed" }
}
} catch (error: any) {
console.error("Login error:", error)
// Handle different types of errors
if (error.response) {
// Server responded with error status
const errorMessage = error.response.data?.errors || `Server error: ${error.response.status}`
return { success: false, message: errorMessage }
} else if (error.request) {
// Request was made but no response received
return { success: false, message: "No response from server. Please check your connection." }
} else {
// Something else happened
return { success: false, message: "Terjadi kesalahan sistem" }
}
}
}
const logout = async () => {
try {
// Call external logout endpoint if available
if (token) {
await apiClient.post('/api/v1/auth/logout', {}, {
headers: {
Authorization: `Bearer ${token}`,
},
})
}
} catch (error) {
console.error("Logout error:", error)
// Continue with logout even if API call fails
} finally {
// Clear all session data
localStorage.removeItem("auth_token")
localStorage.removeItem("auth_user")
localStorage.removeItem("auth_roles")
localStorage.removeItem("auth_expires_at")
// Clear state
setToken(null)
setUser(null)
setRoles([])
// Redirect to login
router.push("/login")
}
}
const isAuthenticated = !!user && !!token
const isAdmin = roles.some(role => role.code === "superadmin" || role.code === "admin")
const isVoter = roles.some(role => role.code === "voter")
const isSuperAdmin = roles.some(role => role.code === "superadmin")
// Debug logging for role checking (commented out to reduce console spam)
// console.log('🔐 Auth Debug:', {
// user: !!user,
// token: !!token,
// rolesCount: roles.length,
// roles: roles,
// isAuthenticated,
// isAdmin,
// isVoter,
// isSuperAdmin
// })
return {
user,
token,
roles,
loading,
isAuthenticated,
isAdmin,
isVoter,
isSuperAdmin,
login,
logout,
checkAuth,
}
}
+19
View File
@@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}
+194
View File
@@ -0,0 +1,194 @@
"use client"
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }