Compare commits

...

2 Commits

Author SHA1 Message Date
Ravindranbit
4b9797e368 feat: integrate frontend login form with backend API
- Migrated dummy login form submission to use Axios and correctly hit /api/auth/login
- Stored session tokens in universal-cookie upon successful authentication
- Added visually integrated 'show password' toggle functionality with custom eye icon
2026-04-28 16:44:54 +05:30
Ravindranbit
9f25fe3228 Refactor API URLs to use centralized buildApiUrl utility and environment variables 2026-04-28 16:31:48 +05:30
8 changed files with 69 additions and 19 deletions

1
.env.example Normal file
View File

@ -0,0 +1 @@
NEXT_PUBLIC_API_BASE_URL=http://localhost:3000/api/

View File

@ -1,8 +1,13 @@
'use client';
import IconLockDots from '@/components/icon/icon-lock-dots';
import IconMail from '@/components/icon/icon-mail';
import IconEye from '@/components/icon/icon-eye';
import { useRouter } from 'next/navigation';
import React, { useState } from 'react';
import axios from 'axios';
import Cookies from 'universal-cookie';
const cookies = new Cookies();
const LoginForm = () => {
const router = useRouter();
@ -13,7 +18,9 @@ const LoginForm = () => {
password: '',
});
// ✅ State for errors
// ✅ State for loading and errors
const [loading, setLoading] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const [errors, setErrors] = useState<{ email?: string; password?: string }>({});
// Generic handler for inputs
@ -43,7 +50,7 @@ const LoginForm = () => {
return newErrors;
};
const submitForm = (e: React.FormEvent) => {
const submitForm = async (e: React.FormEvent) => {
e.preventDefault();
const validationErrors = validate();
@ -52,8 +59,25 @@ const LoginForm = () => {
return;
}
console.log('Form Data:', formData);
router.push('/');
setLoading(true);
try {
const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3000/api/';
const response = await axios.post(`${baseUrl}auth/login`, formData);
if (response.data.success && response.data.data?.token) {
cookies.set('token', response.data.data.token, { path: '/' });
cookies.set('user', JSON.stringify(response.data.data.user), { path: '/' });
router.push('/');
}
} catch (error: any) {
console.error('Login error', error);
setErrors({
email: error.response?.data?.message || 'Invalid email or password',
password: '',
});
} finally {
setLoading(false);
}
};
return (
@ -85,15 +109,22 @@ const LoginForm = () => {
<input
id="Password"
name="password"
type="password"
type={showPassword ? "text" : "password"}
placeholder="Enter Password"
className="form-input ps-10 placeholder:text-white-dark"
className="form-input ps-10 pe-10 placeholder:text-white-dark"
value={formData.password}
onChange={handleChange}
/>
<span className="absolute start-4 top-1/2 -translate-y-1/2">
<IconLockDots fill={true} />
</span>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className={`absolute end-4 top-1/2 -translate-y-1/2 hover:text-black dark:hover:text-white ${showPassword ? 'text-black dark:text-white' : ''}`}
>
<IconEye />
</button>
</div>
{errors.password && (
<p className="text-red-500 text-sm mt-1">{errors.password}</p>
@ -103,8 +134,9 @@ const LoginForm = () => {
<button
type="submit"
className="btn btn-gradient !mt-6 w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(67,97,238,0.44)]"
disabled={loading}
>
Sign in
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
);

View File

@ -4,6 +4,7 @@ import IconTrashLines from '../icon/icon-trash-lines';
import axios from 'axios';
import { useRouter } from 'next/navigation';
import { showMessage } from '@/utils/CommonFunction.utils';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface FormValues {
year: string;
@ -85,7 +86,7 @@ const CreateEventForm: React.FC = () => {
}
try {
const ImageUpload = await axios.post(`https://api.tamilculturewaterloo.org/api/upload/single`, data, {
const ImageUpload = await axios.post(buildApiUrl('upload/single'), data, {
headers: {
"Content-Type": "multipart/form-data", // important for file upload
},
@ -99,7 +100,7 @@ const CreateEventForm: React.FC = () => {
eventimageurl: ImageUpload?.data?.data?.fullUrl
}
const res = await axios.post(`https://api.tamilculturewaterloo.org/api/events`, createData)
const res = await axios.post(buildApiUrl('events'), createData)
console.log("res", res)
showMessage("Event Created Successfully", "success")
router?.push(`/`)

View File

@ -3,6 +3,7 @@ import React, { useState, ChangeEvent, FormEvent } from 'react';
import IconTrashLines from '../icon/icon-trash-lines';
import axios from 'axios';
import { useRouter } from 'next/navigation';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface FormErrors {
[key: string]: string;
@ -61,7 +62,7 @@ const CreateEventGalleryForm: React.FC<EditEventFormProps> = ({ eventId }) => {
formData.append(`files`, file);
});
const uploadRes = await axios.post(`https://api.tamilculturewaterloo.org/api/upload/multiple`, formData)
const uploadRes = await axios.post(buildApiUrl('upload/multiple'), formData)
console.log("uploadres", uploadRes)
const uploadedUrls = uploadRes?.data?.data?.map((image: any) => image?.fullUrl) || [];
@ -75,7 +76,7 @@ const CreateEventGalleryForm: React.FC<EditEventFormProps> = ({ eventId }) => {
// Step 3: Call bulk API
await axios.post(
`https://api.tamilculturewaterloo.org/api/event-images/bulk`,
buildApiUrl('event-images/bulk'),
body
);

View File

@ -3,6 +3,7 @@ import React, { useState, useEffect, ChangeEvent, FormEvent } from 'react';
import IconTrashLines from '../icon/icon-trash-lines';
import axios from 'axios';
import { useRouter } from 'next/navigation';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface FormValues {
year: string;
@ -43,7 +44,7 @@ const EditEventForm: React.FC<EditEventFormProps> = ({ eventId }) => {
const getEvent = async () => {
try {
const res = await axios.get(`https://api.tamilculturewaterloo.org/api/events/${eventId}`);
const res = await axios.get(buildApiUrl(`events/${eventId}`));
const data = res?.data?.data;
setFormData({
@ -124,7 +125,7 @@ const EditEventForm: React.FC<EditEventFormProps> = ({ eventId }) => {
imgFormData.append('file', formData.eventimageurl);
const uploadRes = await axios.post(
'https://api.tamilculturewaterloo.org/api/upload/single',
buildApiUrl('upload/single'),
imgFormData,
{ headers: { 'Content-Type': 'multipart/form-data' } }
);
@ -140,7 +141,7 @@ const EditEventForm: React.FC<EditEventFormProps> = ({ eventId }) => {
eventimageurl: imageUrl,
};
const res = await axios.put(`https://api.tamilculturewaterloo.org/api/events/${eventId}`, updatedData, );
const res = await axios.put(buildApiUrl(`events/${eventId}`), updatedData, );
console.log('Event updated:', res.data);
router.push('/');

View File

@ -9,6 +9,7 @@ import axios from 'axios';
import { useRouter } from 'next/navigation';
import IconTrashLines from '../icon/icon-trash-lines';
import Swal from 'sweetalert2';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
interface EditEventFormProps {
eventId: string | null;
@ -29,7 +30,7 @@ const ListOfEventsGallery: React.FC<EditEventFormProps> = ({ eventId }) => {
const getEventGallery = async () => {
try {
const res = await axios.get(`https://api.tamilculturewaterloo.org/api/event-images/event/${eventId}`);
const res = await axios.get(buildApiUrl(`event-images/event/${eventId}`));
const formatted = res.data?.data?.map((img: any) => ({
id: img.id, // ensure ID is preserved for deletion
src: img.imageurl,
@ -58,7 +59,7 @@ const ListOfEventsGallery: React.FC<EditEventFormProps> = ({ eventId }) => {
}).then(async (result) => {
if (result.isConfirmed) {
try {
await axios.delete(`https://api.tamilculturewaterloo.org/api/event-images/${item.id}`);
await axios.delete(buildApiUrl(`event-images/${item.id}`));
Swal.fire({
title: 'Deleted!',
text: 'Your file has been deleted.',

View File

@ -7,6 +7,7 @@ import IconTrashLines from '../icon/icon-trash-lines';
import IconPencil from '../icon/icon-pencil';
import Swal from 'sweetalert2';
import { useRouter } from 'next/navigation';
import { buildApiUrl } from '@/utils/BaseUrl.utils';
export const metadata: Metadata = {
title: 'Knowledge Base',
@ -23,7 +24,7 @@ const ListOfEvents = () => {
const getEvents = async () => {
try {
const eventRes: any = await axios?.get(`https://api.tamilculturewaterloo.org/api/events`)
const eventRes: any = await axios?.get(buildApiUrl('events'))
console.log("eventRes", eventRes)
setEvents(eventRes?.data?.data)
} catch (error) {
@ -61,7 +62,7 @@ const ListOfEvents = () => {
}).then(async (result) => {
if (result.isConfirmed) {
try {
await axios.delete(`https://api.tamilculturewaterloo.org/api/events/${event.id}`);
await axios.delete(buildApiUrl(`events/${event.id}`));
Swal.fire({
title: 'Deleted!',
text: 'Your file has been deleted.',

View File

@ -1 +1,13 @@
export const Baseurl = "https://api.tamilculturewaterloo.org/api/"
const DEFAULT_BASE_URL = 'https://api.tamilculturewaterloo.org/api/';
const configuredBaseUrl =
typeof process !== 'undefined' && process.env.NEXT_PUBLIC_API_BASE_URL
? process.env.NEXT_PUBLIC_API_BASE_URL
: DEFAULT_BASE_URL;
export const Baseurl = configuredBaseUrl.endsWith('/') ? configuredBaseUrl : `${configuredBaseUrl}/`;
export const buildApiUrl = (path) => {
const normalizedPath = String(path).replace(/^\/+/, '');
return `${Baseurl}${normalizedPath}`;
};