Skip to content

Commit ab5825d

Browse files
committed
The project is up to date
0 parents  commit ab5825d

File tree

96 files changed

+26310
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

96 files changed

+26310
-0
lines changed

.env

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
SEARCH_ONLY_KEY=47b93bbf7ef18b8555f8516326074852
2+
APP_KEY=OGV7N0YFSM
3+
ADMIN_KEY=b6657e0ff7e883f3e7f2f2cb5797cb75
4+
SERVER_PORT=3341
5+
COOKIE_SECRET='MY_TINY_SECRET'
6+
MONGO_URI='mongodb+srv://kTap:[email protected]/user?retryWrites=true&w=majority'

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules/
2+
logs/
3+
package-lock

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Full Stack Project by Begzat Kidirbaev

config/Algolia.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import AlgoliaSearch from 'algoliasearch';
2+
import { config } from 'dotenv';
3+
config();
4+
5+
const APP_KEY = process.env.APP_KEY;
6+
const SEARCH_ONLY_KEY = process.env.SEARCH_ONLY_KEY;
7+
8+
export default function (search = {}) {
9+
return new Promise((resolve, reject) => {
10+
const client = new AlgoliaSearch(APP_KEY, SEARCH_ONLY_KEY);
11+
const index = client.initIndex('accounts');
12+
13+
if (search.searcher && search.searcher !== '') {
14+
index.search(search.query, {
15+
headers: { 'X-Algolia-UserToken': search.searcher },
16+
attributesToRetrieve: search.attributes
17+
})
18+
.then(({ hits }) => resolve({
19+
ok: true,
20+
hits
21+
}))
22+
// .catch(error => reject({error}))
23+
} else {
24+
const public_key = client.generateSecuredApiKey(SEARCH_ONLY_KEY, {
25+
filters: '_tags:user_42'
26+
});
27+
28+
index.search(
29+
search.query,
30+
{
31+
headers: { 'X-Algolia-UserToken': public_key},
32+
attributesToRetrieve: search.attributes
33+
})
34+
.then(({ hits }) => {
35+
resolve({
36+
ok: true,
37+
hits,
38+
public_key
39+
});
40+
})
41+
// .catch(error => reject({error}))
42+
}
43+
});
44+
}

config/Auth.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const JWT_PRIVATE_KEY = 'my_secret_key';

config/Database.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import mongoose from 'mongoose';
2+
import logger from '../helpers/utils/logger.js';
3+
4+
export default class ConnDB {
5+
static connInst = null;
6+
static conn;
7+
8+
constructor() {
9+
this.conn = mongoose.createConnection(process.env.MONGO_URI);
10+
}
11+
12+
static getConn() {
13+
if (ConnDB.connInst) {
14+
return ConnDB.connInst.conn;
15+
} else {
16+
ConnDB.connInst = new ConnDB();
17+
return ConnDB.connInst.conn;
18+
}
19+
}
20+
21+
initDB() {
22+
return new mongoose.Promise((resolve, reject) => {
23+
if (!this.conn) {
24+
this.conn = mongoose.createConnection(process.env.MONGO_URI);
25+
}
26+
27+
if (process.env.NODE_ENV === 'development') {
28+
mongoose.set('debug', true);
29+
}
30+
31+
this.conn.on('disconnected', () => {
32+
logger("alert", "MongoDB was disconnected, and trying to new connection instance...");
33+
mongoose.connect(process.env.MONGO_URI);
34+
});
35+
36+
this.conn.on('error', (err) => {
37+
reject(err);
38+
});
39+
40+
this.conn.on('open', () => {
41+
resolve(this.conn);
42+
});
43+
44+
this.conn.once('open', () => {
45+
logger.info('Succesfully connected to MongoDB');
46+
});
47+
});
48+
}
49+
}

controllers/auth.controller.js

+278
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
// import { authenticate } from '../helpers/validators/authenticate.js';
2+
import jwt from 'jsonwebtoken';
3+
import Joi from 'joi';
4+
import { UserSchema } from '../models/Schemas/UserSchema.js';
5+
import { User } from '../models/Database/UserModel.js';
6+
import { SERVER_MESSAGES } from '../utils/constants/server-messages.js';
7+
import { JWT_PRIVATE_KEY } from '../config/Auth.js';
8+
import { findOnePromise, comparePromise, hashPromise } from '../utils/helpers/CRUD.js';
9+
import logger from '../utils/helpers/logger.js';
10+
import { ErrorFor, Response } from '../utils/helpers/ErrorHandler.js';
11+
import { debug } from '../utils/helpers/debug.js';
12+
13+
{
14+
// const find_user_from_database = (username, db, callback) => {
15+
// (username && db) ? db.find(u => {
16+
// if (u.username === username)
17+
// return callback(null, u);
18+
// }) : callback('Userni topishda xatolik yuz berdi', false);
19+
// }
20+
21+
// // hash all passwords in database
22+
// const hash_all_passwords = (db, callback) => {
23+
24+
// if (!db)
25+
// return callback('Database bo\'sh', false);
26+
27+
// let hashed_db = [];
28+
// db.map((user) => {
29+
// hash(user.password, 10, (err, hash) => {
30+
31+
// hashed_db.push({
32+
// id: user.id,
33+
// username: user.username,
34+
// password: hash
35+
// });
36+
37+
// if (user.id === db.length)
38+
// callback(null, hashed_db);
39+
40+
// });
41+
// });
42+
// };
43+
44+
// export const homer = async (req, res) => {
45+
// res.render('pages/home');
46+
// // res.end();
47+
// }
48+
49+
// export const signup_get = async (req, res) => {
50+
// const result = await UserRegistrationSchema.validateAsync(req.query);
51+
// console.log(req.query);
52+
// const isValidUser = await UserRegistrationModel.find({
53+
// $or: [
54+
// { email: req.query.email },
55+
// { phone: req.query.phone_number }
56+
// ]
57+
// });
58+
59+
// if (isValidUser.length > 0) {
60+
// res.status(400).json({ success: false, message: 'Bu email yoki telefon raqami mavjud' });
61+
// } else if (result.error) {
62+
// res.status(400).json({ success: false, message: SERVER_MESSAGES.uzb.VALIDATION_ERROR });
63+
// } else {
64+
// let user = new UserRegistrationModel(req.query);
65+
66+
// hash(user.password, 10, (err, hash) => {
67+
// if (err) {
68+
// res.status(500).json({ success: false, message: SERVER_MESSAGES.uzb.INTERNAL_SERVER_ERROR });
69+
// } else { user.password = hash; }
70+
// });
71+
// user.save()
72+
// .then(() => {
73+
// const token = jwt.sign({ _id: user._id }, JWT_PRIVATE_KEY, {
74+
// expiresIn: '1h'
75+
// });
76+
// logger.info('[SIGNUP] You are signed up & in!');
77+
// res
78+
// .status(201)
79+
// .cookie('token', token, {
80+
// httpOnly: true,
81+
// expires: new Date(Date.now() + 60 * 60 * 1000),
82+
// secure: process.env.NODE_ENV === 'production'
83+
// })
84+
// .json({ success: true, message: SERVER_MESSAGES.uzb.USER_SIGNED_UP });
85+
// })
86+
// .catch(err => {
87+
// logger.error(err);
88+
// res.status(500).json({ success: false, message: SERVER_MESSAGES.uzb.INTERNAL_SERVER_ERROR });
89+
// });
90+
// }
91+
92+
// }
93+
94+
// export const home = (req, res) => {
95+
// res.locals.username = req.session.user;
96+
// res.render('login');
97+
// delete res.locals.username;
98+
// };
99+
100+
// export const login = (req, res) => {
101+
// return res.render('home');
102+
// };
103+
104+
// export const social = (req, res) => {
105+
// const username = req.query?.first_name;
106+
// const password = req.query?.hash;
107+
108+
// if (!req.query && !username && !password) {
109+
// res.status(400).json({ success: false, message: 'Barcha maydonlar to\'g\'ri to\'ldirilishi kerak' });
110+
// } else {
111+
// const result = UserSchema.validate({ username, password });
112+
// console.log('1')
113+
// hash_all_passwords(users, (err, db) => {
114+
// if (!err) {
115+
// console.log('2')
116+
// find_user_from_database(username, db, (err, user) => {
117+
// if (!err && user && !result.error) {
118+
// console.log('3')
119+
// compare(password, user.password, (err, result) => {
120+
// if (!err && result) {
121+
// console.log('4')
122+
// const token = jwt.sign({ _id: user.id }, JWT_PRIVATE_KEY, {
123+
// expiresIn: '1h'
124+
// });
125+
// logger.info('[SIGNIN] You are logged in!');
126+
// res.status(201).cookie('token', token, {
127+
// httpOnly: true,
128+
// expires: new Date(Date.now() + 60 * 60 * 1000),
129+
// secure: process.env.NODE_ENV === 'production'
130+
// })
131+
// .json({ success: true, message: 'Tizimga muvaffaqiyatli kirildi' })
132+
// } else {
133+
// res.status(401).json({ success: false, message: 'Parol xato' });
134+
// }
135+
// });
136+
// } else {
137+
// console.log('5')
138+
// res.status(401).json({ success: false, message: 'Parol yoki login no\'tog\'ri kiritilgan' });
139+
// }
140+
// });
141+
// } else {
142+
// console.log('6')
143+
// res.status(500).json({ success: false, message: 'Userlarni heshlashda xatolik yuz berdi' });
144+
// }
145+
// });
146+
// console.log('7')
147+
// }
148+
// }
149+
150+
// export const logout = (req, res) => {
151+
// return res.clearCookie('token')
152+
// .status(200)
153+
// .json({ success: true, message: 'Muvafaqqiyatli logout bajarildi' })
154+
// };
155+
156+
// export const restricted = (req, res) => {
157+
// res.send('Wahoo! restricted area, click to <a href="/auth/logout">logout</a>');
158+
// };
159+
}
160+
161+
export const signin = async (req, res) => {
162+
163+
debug(0, req.body);
164+
165+
const user = await findOnePromise(User, { email: req.body?.email });
166+
167+
if (!user.ok)
168+
return Response(new ErrorFor('Find User'), req, res);
169+
170+
debug(1, user.ok);
171+
172+
const decoded_password = await comparePromise(req.body.password, user.password);
173+
174+
debug(2, decoded_password);
175+
176+
if (!decoded_password.ok)
177+
return Response(new ErrorFor('Find User'), req, res);
178+
179+
debug(3, !decoded_password, !user);
180+
181+
const token = jwt.sign({ _id: user._id }, JWT_PRIVATE_KEY, {
182+
// expire in 1 minute
183+
expiresIn: '1m'
184+
});
185+
186+
debug(4, token);
187+
188+
req.session.user = {
189+
first_name: user.first_name,
190+
last_name: user.last_name
191+
}
192+
193+
debug(5, req.session.user);
194+
195+
req.session.token = token;
196+
197+
debug(6, req.session.token);
198+
199+
res.status(201)
200+
.json({ success: true, message: 'Foydalanuvchi muvaffaqiyatli login bo\'ldi', redirect: '/' });
201+
202+
debug(7, req.session);
203+
204+
Response(new ErrorFor(), req, res);
205+
206+
};
207+
208+
export const signup = async (req, res) => {
209+
210+
debug(0, req.body);
211+
212+
const val_res = UserSchema.validate(req.body);
213+
214+
debug(1, val_res);
215+
216+
if (val_res.error)
217+
return Response(new ErrorFor('Validation'), req, res);
218+
219+
debug(2, val_res.error);
220+
221+
const isExistUser = await findOnePromise(User, { email: req.body?.email });
222+
223+
debug(3, isExistUser);
224+
225+
if (isExistUser.ok)
226+
return Response(new ErrorFor('Exist User'), req, res);
227+
228+
debug(4, isExistUser.ok);
229+
230+
const hashv = await hashPromise(req.body.password, 10);
231+
232+
debug(5, hashv);
233+
234+
if (!hashv.ok)
235+
return Response(new ErrorFor(), req, res)
236+
237+
debug(6, hashv.ok);
238+
239+
const new_user = new User({
240+
email: req.body.email,
241+
first_name: req.body.first_name,
242+
last_name: req.body.last_name,
243+
password: hashv.hash,
244+
phone_number: req.body.phone_number.split(' ').join(''),
245+
});
246+
247+
debug(7, new_user);
248+
249+
await new_user.save()
250+
.then(() => {
251+
const token = jwt.sign({_id: new_user._id}, JWT_PRIVATE_KEY, {
252+
expiresIn: '1m'
253+
});
254+
255+
debug(8, token);
256+
257+
logger.info('[SIGNUP] You are signed up & in!');
258+
req.session.user = {
259+
first_name: new_user.first_name,
260+
last_name: new_user.last_name
261+
}
262+
263+
debug(9, req.session.user);
264+
265+
req.session.token = token;
266+
267+
debug(10, req.session.token);
268+
269+
res
270+
.status(201)
271+
.json({ success: true, message: SERVER_MESSAGES.uzb.USER_SIGNED_UP, redirect: '/' });
272+
})
273+
.catch(err => {
274+
console.log('Userni saqlashda xatolik: ', err);
275+
Response(new ErrorFor(), req, res);
276+
});
277+
278+
}

0 commit comments

Comments
 (0)