0% found this document useful (0 votes)
13 views24 pages

Codes

The document outlines a web application for a freelancing platform, including HTML files for login, registration, and user dashboards, along with corresponding JavaScript files for handling form submissions and profile creation. It features user authentication, profile management for freelancers and job providers, and integrates with a MySQL database using Express.js. The application allows users to register, log in, and create profiles with various details, while managing user sessions with JWT tokens.

Uploaded by

lavyapunjabi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views24 pages

Codes

The document outlines a web application for a freelancing platform, including HTML files for login, registration, and user dashboards, along with corresponding JavaScript files for handling form submissions and profile creation. It features user authentication, profile management for freelancers and job providers, and integrates with a MySQL database using Express.js. The application allows users to register, log in, and create profiles with various details, while managing user sessions with JWT tokens.

Uploaded by

lavyapunjabi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

login.

html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Login - Freelancing Website</title>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<div class="container">

<h1>Login</h1>

<form id="loginForm">

<input type="email" id="email" name="email" placeholder="Email" required>

<input type="password" id="password" name="password" placeholder="Password" required>

<button type="submit">Login</button>

</form>

<p>Don't have an account? <a href="[Link]">Register here</a></p>

</div>

<script src="[Link]"></script>

</body>

</html>

[Link] file
[Link]('loginForm').addEventListener('submit', async (e) => {

[Link]();

const formData = new FormData([Link]);

const userData = [Link]([Link]());

try {

const response = await fetch('/login', {


method: 'POST',

headers: {

'Content-Type': 'application/json',

},

body: [Link](userData),

});

const data = await [Link]();

if ([Link]) {

// Store the token in localStorage

[Link]('token', [Link]);

[Link]('userType', [Link]);

// Redirect based on user type

if ([Link] === 'Freelancer') {

[Link] = '/[Link]';

} else if ([Link] === 'Job Provider') {

[Link] = '/[Link]';

} else {

alert([Link] || 'Error logging in');

} catch (error) {

[Link]('Error:', error);

alert('An error occurred while logging in');

});

[Link] file
<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Register - Freelancing Website</title>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<div class="container">

<h1>Register</h1>

<form id="registerForm">

<input type="email" id="email" name="email" placeholder="Email" required>

<input type="password" id="password" name="password" placeholder="Password" required>

<select id="userType" name="userType" required>

<option value="">Select User Type</option>

<option value="Freelancer">Freelancer</option>

<option value="Job Provider">Job Provider</option>

</select>

<input type="text" id="firstName" name="firstName" placeholder="First Name" required>

<input type="text" id="lastName" name="lastName" placeholder="Last Name" required>

<input type="date" id="dateOfBirth" name="dateOfBirth" required>

<input type="text" id="country" name="country" placeholder="Country" required>

<input type="tel" id="phoneNumber" name="phoneNumber" placeholder="Phone Number"


required>

<button type="submit">Register</button>

<p>Already have an account? <a href="[Link]">Login here</a></p>

</form>

</div>

<script src="[Link]"></script>

</body>

</html>
[Link] file
[Link]('registerForm').addEventListener('submit', async (e) => {

[Link]();

const formData = new FormData([Link]);

const userData = [Link]([Link]());

try {

const response = await fetch('/register', {

method: 'POST',

headers: {

'Content-Type': 'application/json',

},

body: [Link](userData),

});

const data = await [Link]();

if ([Link]) {

alert([Link]);

// Store the JWT token and user type in local storage

[Link]('token', [Link]);

[Link]('userType', [Link]);

// Redirect based on user type

if ([Link] === 'Freelancer') {

[Link] = '/[Link]';

} else if ([Link] === 'Job Provider') {

[Link] = '/[Link]';

} else {
alert([Link] || 'Error registering user');

} catch (error) {

[Link]('Error:', error);

alert('An error occurred while registering');

});

[Link] file

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Create Freelancer Profile</title>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<div class="container">

<h1>Create Freelancer Profile</h1>

<form id="freelancerProfileForm">

<input type="text" id="profileTitle" name="profileTitle" placeholder="Profile Title" required>

<textarea id="techStack" name="techStack" placeholder="Tech Stack (comma-separated)"


required></textarea>

<input type="number" id="yearsOfExperience" name="yearsOfExperience"


placeholder="Years of Experience" required>

<textarea id="bio" name="bio" placeholder="Bio" required></textarea>

<textarea id="skills" name="skills" placeholder="Skills (comma-separated)"


required></textarea>

<h3>Education</h3>

<div id="educationContainer">
<div class="education-entry">

<input type="text" name="degree" placeholder="Degree">

<input type="text" name="institution" placeholder="Institution">

<input type="number" name="yearOfCompletion" placeholder="Year of Completion">

</div>

</div>

<button type="button" id="addEducation">Add Education</button>

<h3>Work Experience</h3>

<div id="workExperienceContainer">

<div class="work-experience-entry">

<input type="text" name="companyName" placeholder="Company Name">

<input type="text" name="position" placeholder="Position">

<input type="date" name="startDate" placeholder="Start Date">

<input type="date" name="endDate" placeholder="End Date">

<textarea name="description" placeholder="Description"></textarea>

</div>

</div>

<button type="button" id="addWorkExperience">Add Work Experience</button>

<h3>Portfolio Projects</h3>

<div id="portfolioProjectsContainer">

<div class="portfolio-project-entry">

<input type="text" name="projectTitle" placeholder="Project Title">

<textarea name="projectDescription" placeholder="Project Description"></textarea>

<input type="url" name="projectUrl" placeholder="Project URL">

<input type="text" name="technologiesUsed" placeholder="Technologies Used (comma-


separated)">

</div>

</div>

<button type="button" id="addPortfolioProject">Add Portfolio Project</button>


<button type="submit">Create Profile</button>

</form>

</div>

<script src="[Link]"></script>

</body>

</html>

[Link] file

[Link]('DOMContentLoaded', () => {

const form = [Link]('freelancerProfileForm');

const addEducationBtn = [Link]('addEducation');

const addWorkExperienceBtn = [Link]('addWorkExperience');

const addPortfolioProjectBtn = [Link]('addPortfolioProject');

[Link]('click', addEducationEntry);

[Link]('click', addWorkExperienceEntry);

[Link]('click', addPortfolioProjectEntry);

[Link]('submit', handleSubmit);

});

function addEducationEntry() {

const container = [Link]('educationContainer');

const entry = [Link]('div');

[Link] = 'education-entry';

[Link] = `

<input type="text" name="degree" placeholder="Degree">

<input type="text" name="institution" placeholder="Institution">

<input type="number" name="yearOfCompletion" placeholder="Year of Completion">

`;
[Link](entry);

function addWorkExperienceEntry() {

const container = [Link]('workExperienceContainer');

const entry = [Link]('div');

[Link] = 'work-experience-entry';

[Link] = `

<input type="text" name="companyName" placeholder="Company Name">

<input type="text" name="position" placeholder="Position">

<input type="date" name="startDate" placeholder="Start Date">

<input type="date" name="endDate" placeholder="End Date">

<textarea name="description" placeholder="Description"></textarea>

`;

[Link](entry);

function addPortfolioProjectEntry() {

const container = [Link]('portfolioProjectsContainer');

const entry = [Link]('div');

[Link] = 'portfolio-project-entry';

[Link] = `

<input type="text" name="projectTitle" placeholder="Project Title">

<textarea name="projectDescription" placeholder="Project Description"></textarea>

<input type="url" name="projectUrl" placeholder="Project URL">

<input type="text" name="technologiesUsed" placeholder="Technologies Used (comma-


separated)">

`;

[Link](entry);

}
async function handleSubmit(event) {

[Link]();

const formData = new FormData([Link]);

const profileData = {

profileTitle: [Link]('profileTitle'),

techStack: [Link]('techStack').split(',').map(item => [Link]()),

yearsOfExperience: parseInt([Link]('yearsOfExperience')),

bio: [Link]('bio'),

skills: [Link]('skills').split(',').map(item => [Link]()),

education: getEducationData(),

workExperience: getWorkExperienceData(),

portfolioProjects: getPortfolioProjectsData()

};

try {

const response = await fetch('/create-freelancer-profile', {

method: 'POST',

headers: {

'Content-Type': 'application/json',

'Authorization': 'Bearer ' + [Link]('token')

},

body: [Link](profileData)

});

const data = await [Link]();

if ([Link]) {

alert([Link]);

// Redirect to [Link] after successful profile creation

[Link] = '/[Link]';
} else {

alert([Link] || 'Error creating freelancer profile');

} catch (error) {

[Link]('Error:', error);

alert('An error occurred while creating the profile');

function getEducationData() {

const educationEntries = [Link]('.education-entry');

return [Link](educationEntries).map(entry => ({

degree: [Link]('input[name="degree"]').value,

institution: [Link]('input[name="institution"]').value,

yearOfCompletion: parseInt([Link]('input[name="yearOfCompletion"]').value)

}));

function getWorkExperienceData() {

const workExperienceEntries = [Link]('.work-experience-entry');

return [Link](workExperienceEntries).map(entry => ({

companyName: [Link]('input[name="companyName"]').value,

position: [Link]('input[name="position"]').value,

startDate: [Link]('input[name="startDate"]').value,

endDate: [Link]('input[name="endDate"]').value,

description: [Link]('textarea[name="description"]').value

}));

function getPortfolioProjectsData() {

const portfolioProjectEntries = [Link]('.portfolio-project-entry');


return [Link](portfolioProjectEntries).map(entry => ({

projectTitle: [Link]('input[name="projectTitle"]').value,

projectDescription: [Link]('textarea[name="projectDescription"]').value,

projectUrl: [Link]('input[name="projectUrl"]').value,

technologiesUsed:
[Link]('input[name="technologiesUsed"]').[Link](',').map(item => [Link]())

}));

[Link] file

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Create Client Profile</title>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<div class="container">

<h1>Create Client Profile</h1>

<form id="clientProfileForm">

<input type="text" id="companyName" name="companyName" placeholder="Company


Name" required>

<select id="companySize" name="companySize" required>

<option value="">Select Company Size</option>

<option value="1-10">1-10 employees</option>

<option value="11-50">11-50 employees</option>

<option value="51-200">51-200 employees</option>

<option value="201-500">201-500 employees</option>

<option value="501+">501+ employees</option>

</select>
<input type="text" id="industry" name="industry" placeholder="Industry" required>

<input type="url" id="website" name="website" placeholder="Company Website">

<textarea id="companyDescription" name="companyDescription" placeholder="Company


Description" required></textarea>

<button type="submit">Create Profile</button>

</form>

</div>

<script src="[Link]"></script>

</body>

</html>

[Link] file

[Link]('DOMContentLoaded', () => {

const form = [Link]('clientProfileForm');

[Link]('submit', handleSubmit);

});

async function handleSubmit(event) {

[Link]();

const formData = new FormData([Link]);

const profileData = [Link]([Link]());

try {

const response = await fetch('/create-client-profile', {

method: 'POST',

headers: {

'Content-Type': 'application/json',

'Authorization': 'Bearer ' + [Link]('token')

},

body: [Link](profileData)
});

const data = await [Link]();

if ([Link]) {

alert([Link]);

[Link] = '/[Link]'; // Redirect to client portal

} else {

alert([Link] || 'Error creating client profile');

} catch (error) {

[Link]('Error:', error);

alert('An error occurred while creating the profile');

[Link] file

const express = require('express');

const mysql = require('mysql2');

const dotenv = require('dotenv');

const bcrypt = require('bcrypt');

const jwt = require('jsonwebtoken');

const path = require('path');

const { promisify } = require('util');

// Load environment variables

[Link]();

// Create Express app

const app = express();

const port = [Link] || 3000;


// Middleware

[Link]([Link]());

[Link]([Link]({ extended: true }));

[Link]([Link]('public'));

// Database connection

const db = [Link]({

host: [Link].DB_HOST,

user: [Link].DB_USER,

password: [Link].DB_PASSWORD,

database: [Link].DB_NAME,

});

[Link]((err) => {

if (err) {

[Link]('Error connecting to the database:', err);

return;

[Link]('Connected to the database');

});

// Promisify [Link] for async/await usage

const queryAsync = promisify([Link]).bind(db);

// Routes

[Link]('/', (req, res) => {

[Link]([Link](__dirname, 'public', '[Link]'));

});

[Link]('/login', (req, res) => {


[Link]([Link](__dirname, 'public', '[Link]'));

});

[Link]('/client-profile', (req, res) => {

[Link]([Link](__dirname, 'public', '[Link]'));

});

[Link]('/client-portal', (req, res) => {

[Link]([Link](__dirname, 'public', '[Link]'));

});

// Registration route

[Link]('/register', async (req, res) => {

const { email, password, userType, firstName, lastName, dateOfBirth, country, phoneNumber } =


[Link];

try {

const hashedPassword = await [Link](password, 10);

const query = 'INSERT INTO Users (email, password, user_type, first_name, last_name,
date_of_birth, country, phone_number) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';

const values = [email, hashedPassword, userType, firstName, lastName, dateOfBirth, country,


phoneNumber];

await queryAsync(query, values);

[Link](201).json({ message: 'User registered successfully' });

} catch (error) {

[Link]('Error registering user:', error);

[Link](500).json({ error: 'Error registering user' });

});
// Login route

[Link]('/login', async (req, res) => {

const { email, password } = [Link];

try {

const query = 'SELECT * FROM Users WHERE email = ?';

const results = await queryAsync(query, [email]);

if ([Link] === 0) {

return [Link](401).json({ error: 'Invalid email or password' });

const user = results[0];

const passwordMatch = await [Link](password, [Link]);

if (!passwordMatch) {

return [Link](401).json({ error: 'Invalid email or password' });

const token = [Link](

{ userId: user.user_id, email: [Link], userType: user.user_type },

[Link].JWT_SECRET,

{ expiresIn: '1h' }

);

[Link]({ token, userType: user.user_type });

} catch (error) {

[Link]('Error during login:', error);

[Link](500).json({ error: 'Internal server error' });

});
// Route: Create freelancer profile

[Link]('/create-freelancer-profile', authenticateToken, async (req, res) => {

if ([Link] !== 'Freelancer') {

return [Link](403).json({ error: 'Only freelancers can create a profile' });

const { profileTitle, techStack, yearsOfExperience, bio, skills, education, workExperience,


portfolioProjects } = [Link];

try {

const query = `

INSERT INTO FreelancerProfiles

(user_id, profile_title, tech_stack, years_of_experience, bio, skills, education, work_experience,


portfolio_projects)

VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

`;

const values = [

[Link],

profileTitle,

[Link](techStack),

yearsOfExperience,

bio,

[Link](skills),

[Link](education),

[Link](workExperience),

[Link](portfolioProjects)

];

await queryAsync(query, values);

[Link](201).json({ message: 'Freelancer profile created successfully' });

} catch (error) {
[Link]('Error creating freelancer profile:', error);

[Link](500).json({ error: 'Error creating freelancer profile' });

});

// Route: Create client profile

[Link]('/create-client-profile', authenticateToken, async (req, res) => {

if ([Link] !== 'Job Provider') {

return [Link](403).json({ error: 'Only job providers can create a client profile' });

const { companyName, companySize, industry, website, companyDescription } = [Link];

try {

const query = `

INSERT INTO ClientProfiles

(user_id, company_name, company_size, industry, website, company_description)

VALUES (?, ?, ?, ?, ?, ?)

`;

const values = [

[Link],

companyName,

companySize,

industry,

website,

companyDescription

];

await queryAsync(query, values);

[Link](201).json({ message: 'Client profile created successfully' });

} catch (error) {
[Link]('Error creating client profile:', error);

[Link](500).json({ error: 'Error creating client profile' });

});

// Route: Add a new project

[Link]('/add-project', authenticateToken, async (req, res) => {

if ([Link] !== 'Job Provider') {

return [Link](403).json({ error: 'Only job providers can add projects' });

const { title, description, requiredSkills, budget, deadline } = [Link];

try {

const query = `

INSERT INTO Projects

(client_id, title, description, required_skills, budget, deadline)

VALUES (?, ?, ?, ?, ?, ?)

`;

const values = [

[Link],

title,

description,

[Link](requiredSkills),

budget,

deadline

];

await queryAsync(query, values);

[Link](201).json({ message: 'Project added successfully' });

} catch (error) {
[Link]('Error adding project:', error);

[Link](500).json({ error: 'Error adding project' });

});

// Route: Fetch all projects

[Link]('/projects', authenticateToken, async (req, res) => {

try {

const query = `

SELECT p.*, u.first_name, u.last_name

FROM Projects p

JOIN Users u ON p.client_id = u.user_id

WHERE [Link] = 'Open'

ORDER BY p.created_at DESC

`;

const projects = await queryAsync(query);

[Link](projects);

} catch (error) {

[Link]('Error fetching projects:', error);

[Link](500).json({ error: 'Error fetching projects' });

});

// Route: Fetch user profile

[Link]('/user-profile', authenticateToken, async (req, res) => {

try {

const userQuery = `SELECT * FROM Users WHERE user_id = ?`;

const [user] = await queryAsync(userQuery, [[Link]]);

if (!user) {

return [Link](404).json({ error: 'User not found' });


}

delete [Link];

let profile = null;

if ([Link] === 'Freelancer') {

const profileQuery = `SELECT * FROM FreelancerProfiles WHERE user_id = ?`;

[profile] = await queryAsync(profileQuery, [[Link]]);

} else if ([Link] === 'Job Provider') {

const profileQuery = `SELECT * FROM ClientProfiles WHERE user_id = ?`;

[profile] = await queryAsync(profileQuery, [[Link]]);

[Link]({ user, profile });

} catch (error) {

[Link]('Error fetching user profile:', error);

[Link](500).json({ error: 'Error fetching user profile' });

});

// Route: Fetch client projects

[Link]('/client-projects', authenticateToken, async (req, res) => {

if ([Link] !== 'Job Provider') {

return [Link](403).json({ error: 'Access denied' });

try {

const query = `

SELECT * FROM Projects

WHERE client_id = ?

ORDER BY created_at DESC


`;

const projects = await queryAsync(query, [[Link]]);

[Link](projects);

} catch (error) {

[Link]('Error fetching client projects:', error);

[Link](500).json({ error: 'Error fetching client projects' });

});

// Route: Fetch freelancer projects

[Link]('/freelancer-projects', authenticateToken, async (req, res) => {

if ([Link] !== 'Freelancer') {

return [Link](403).json({ error: 'Access denied' });

try {

const query = `

SELECT p.*, u.first_name, u.last_name

FROM Projects p

JOIN Users u ON p.client_id = u.user_id

WHERE [Link] = 'Open'

ORDER BY p.created_at DESC

`;

const projects = await queryAsync(query);

[Link](projects);

} catch (error) {

[Link]('Error fetching freelancer projects:', error);

[Link](500).json({ error: 'Error fetching freelancer projects' });

});
// Route: Logout

[Link]('/logout', (req, res) => {

[Link]({ message: 'Logged out successfully' });

});

// Middleware to authenticate token

function authenticateToken(req, res, next) {

const authHeader = [Link]['authorization'];

const token = authHeader && [Link](' ')[1];

if (!token) {

return [Link](401).json({ error: 'No token provided' });

[Link](token, [Link].JWT_SECRET, (err, user) => {

if (err) {

return [Link](403).json({ error: 'Invalid token' });

[Link] = user;

next();

});

// Start server

[Link](port, () => {

[Link](`Server is running on port ${port}`);

});

You might also like