NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

require('dotenv').config();
const express = require('express');
const session = require('express-session');
const mysql = require('mysql2');
const bodyParser = require('body-parser');
const cors = require('cors');
const cloudinary = require('cloudinary').v2;
const crypto = require('crypto');

cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLIENT_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
});

const app = express();
app.use(cors());
app.use(bodyParser.json());

app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {secure: false}
}));

const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'items',
});

// Нэвтрэх зам
app.post('/login', (req, res) => {
const { phone, password } = req.body;
if (!password) {
return res.status(400).send('Password is required.');
}
const hashedPassword = hashPassword(password);
const sql = 'SELECT * FROM users WHERE phone = ? AND password = ?';
db.query(sql, [phone, hashedPassword], (err, results) => {
if (err) return res.status(500).send(err);
if (results.length > 0) {
req.session.userId = results[0].id; // Session дотор хэрэглэгчийн ID-г хадгална
res.send({ id: results[0].id, ...results[0] });
} else {
res.status(401).send('Invalid phone number or password');
}
});
});

function hashPassword(password) {
if (!password) {
throw new Error("Password is required for hashing.");
}
return crypto.createHash('sha256').update(password).digest('hex');
}

// Хэрэглэгч нэмэх
app.post('/users', (req, res) => {
const { firstName, lastName, password, email, phone, imgUrl, payPassword, age } = req.body;

// Check for duplicates
const checkDuplicateQuery = `SELECT * FROM users WHERE email = ? OR phone = ?`;
db.query(checkDuplicateQuery, [email, phone], (err, results) => {
if (err) return res.status(500).send(err);

if (results.length > 0) {
const duplicateType = results[0].email === email ? 'duplicate_email' : 'duplicate_phone';
return res.status(409).json({ error: duplicateType });
}

// Check for required login password only
if (!password) {
return res.status(400).send("Password is required.");
}

const hashedPassword = hashPassword(password);
const hashedPayPassword = payPassword ? hashPassword(payPassword) : null; // Optional transaction password

const sql = `INSERT INTO users (firstName, lastName, password, email, phone, imgUrl, payPassword, age)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
db.query(sql, [firstName, lastName, hashedPassword, email, phone, imgUrl, hashedPayPassword, age], (err, results) => {
if (err) return res.status(500).send(err);

const userId = results.insertId;
req.session.userId = userId;
res.status(201).send({ id: userId, ...req.body });
});
});
});



app.put('/profilesetup/:id', async (req, res) => {
const { firstName, lastName, age, payPassword, imgUrl, phone, email, password } = req.body;
const userId = req.params.id;

let imageUrl = imgUrl;
let hashedPayPassword = null;

if (payPassword) {
hashedPayPassword = hashPassword(payPassword); // Гүйлгээний нууц үгийг шифрлэх
}

// Хэрэв imgUrl нь base64 кодтой бол Cloudinary-д байршуулах
if (imgUrl && imgUrl.startsWith('data:image')) {
try {
const result = await cloudinary.uploader.upload(imgUrl, {
upload_preset: 'ml_default'
});
imageUrl = result.secure_url;
} catch (err) {
return res.status(500).send('Зургийг байршуулахад алдаа гарлаа');
}
}

// Хэрэглэгчийн өгөгдлийг шинэчлэх SQL асуулга
const sql = `
UPDATE users
SET firstName = ?,
lastName = ?,
age = ?,
payPassword = COALESCE(?, payPassword),
imgUrl = COALESCE(?, imgUrl),
phone = COALESCE(?, phone),
email = COALESCE(?, email),
password = COALESCE(?, password)
WHERE id = ?`;

db.query(sql, [firstName, lastName, age, hashedPayPassword, imageUrl, phone, email, password, userId], (err) => {
if (err) return res.status(500).send(err);
res.status(200).send("Тохиргоо амжилттай шинэчлэгдлээ");
});
});

app.put('/updatePassword/:id', async (req, res) => {
const { currentPassword, newPassword, confirmNewPassword, isPaymentPassword } = req.body;
const userId = req.params.id;

if (newPassword !== confirmNewPassword) {
return res.status(400).send({ message: 'Шинэ нууц үг болон баталгаажуулалт тохирохгүй байна.' });
}

const passwordField = isPaymentPassword ? 'payPassword' : 'password';
const hashedCurrentPassword = hashPassword(currentPassword);
const hashedNewPassword = hashPassword(newPassword);

// Одоогийн нууц үгийг шалгах SQL асуулга
const verifyPasswordSQL = `SELECT ${passwordField} FROM users WHERE id = ?`;
db.query(verifyPasswordSQL, [userId], (err, results) => {
if (err) return res.status(500).send({ message: 'Мэдээллийн сантай холбогдоход алдаа гарлаа' });
if (results.length === 0) return res.status(404).send({ message: 'Хэрэглэгч олдсонгүй' });

const storedPassword = results[0][passwordField];

// Алдаа гарч буй хэсгийг шалгах
console.log("Одоогийн шифрлэгдсэн нууц үг:", hashedCurrentPassword);
console.log("Хадгалагдсан шифрлэгдсэн нууц үг:", storedPassword);

if (storedPassword !== hashedCurrentPassword) {
return res.status(401).send({ message: 'Одоогийн нууц үг буруу байна.' });
}

const updatePasswordSQL = `UPDATE users SET ${passwordField} = ? WHERE id = ?`;
db.query(updatePasswordSQL, [hashedNewPassword, userId], (updateErr) => {
if (updateErr) return res.status(500).send({ message: 'Нууц үгийг шинэчлэхэд алдаа гарлаа' });
res.status(200).send({ message: 'Нууц үг амжилттай шинэчлэгдлээ.' });
});
});
});



// hereglegchiin medeelliig avah

// Хэрэглэгчийн мэдээллийг авах зам
app.get('/getUser/:id', (req, res) => {
const userId = req.params.id;
const sql = 'SELECT firstName, lastName, email, phone, imgUrl, age FROM users WHERE id = ?';

db.query(sql, [userId], (err, results) => {
if (err) return res.status(500).send(err);
if (results.length > 0) {
res.send(results[0]); // Хэрэглэгчийн мэдээллийг илгээнэ
} else {
res.status(404).send('User not found');
}
});
});


// Session-г шалгах зам
app.get('/check-session', (req, res) => {
if (req.session.userId) {
res.send({ loggedIn: true, userId: req.session.userId });
} else {
res.send({ loggedIn: false });
}
});

// banner get

app.get('/active-banners', (req, res) => {
const currentDate = new Date();
currentDate.setHours(currentDate.getUTCHours() + 8); // Монголын цагаар тохируулах

const sql = `
SELECT * FROM banner
WHERE startDate <= ? AND endDate >= ?
`;
db.query(sql, [currentDate, currentDate], (err, results) => {
if (err) return res.status(500).send(err);

// Зургийн замыг бүрэн URL болгон бүрдүүлэх
results = results.map(banner => {
banner.photo = `http://10.0.2.2:8000/storage/${banner.photo.replace(/\/g, '/')}`;
return banner;
});

res.send(results);
});
});

// Сервер талд оноо нэмэх API
app.post('/addPoints', (req, res) => {
const { userId, amount } = req.body;
const points = Math.floor(amount / 100); // 100 MNT = 1 оноо
const sql = 'UPDATE users SET points = points + ? WHERE id = ?';
db.query(sql, [points, userId], (err) => {
if (err) return res.status(500).send(err);
res.status(200).send({ message: 'Оноо амжилттай нэмэгдлээ', points });
});
});

// Оноо хасах API
app.post('/subtractPoints', (req, res) => {
const { userId, pointsToSubtract } = req.body;
const sql = 'UPDATE users SET points = points - ? WHERE id = ? AND points >= ?';
db.query(sql, [pointsToSubtract, userId, pointsToSubtract], (err, result) => {
if (err) return res.status(500).send(err);
if (result.affectedRows > 0) {
res.status(200).send({ message: 'Оноо хасагдлаа' });
} else {
res.status(400).send({ message: 'Оноо хангалтгүй байна.' });
}
});
});





app.get('/getUserPoints/:userId', (req, res) => {
const userId = req.params.userId;
const sql = 'SELECT points FROM users WHERE id = ?';

db.query(sql, [userId], (err, results) => {
if (err) return res.status(500).send(err);
if (results.length > 0) {
res.send({ points: results[0].points });
} else {
res.status(404).send('User not found');
}
});
});




// Logout хийх зам
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) return res.status(500).send(err);
res.send('Successfully logged out');
});
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.