├── 22-error-handling ├── .env ├── config.js ├── controllers │ ├── controller.js │ └── userController.js ├── models │ └── user.js ├── package.json ├── public │ ├── css │ │ └── style.css │ └── video │ │ └── letitsnow.mp4 ├── routes │ ├── index.js │ └── user.js ├── server.js ├── validators │ ├── userValidator.js │ └── validator.js └── views │ ├── errors │ ├── 404.ejs │ ├── 500.ejs │ └── developer.ejs │ ├── index.ejs │ ├── user.ejs │ └── users.ejs ├── 23-authentication-create-routes └── codes │ ├── .env │ ├── config.js │ ├── controllers │ ├── authController.js │ ├── controller.js │ └── userController.js │ ├── models │ └── user.js │ ├── package.json │ ├── public │ ├── css │ │ └── style.css │ └── video │ │ └── letitsnow.mp4 │ ├── routes │ ├── auth.js │ ├── index.js │ └── user.js │ ├── server.js │ ├── validators │ ├── authValidator.js │ ├── userValidator.js │ └── validator.js │ └── views │ ├── auth │ ├── login.ejs │ └── register.ejs │ ├── components │ └── validation-error.ejs │ ├── errors │ ├── 404.ejs │ ├── 500.ejs │ └── developer.ejs │ ├── index.ejs │ ├── user.ejs │ └── users.ejs ├── 24-create-routes-part-two.trec └── codes │ ├── .env │ ├── config.js │ ├── controllers │ ├── authController.js │ ├── controller.js │ ├── dashboardController.js │ └── userController.js │ ├── models │ └── user.js │ ├── package.json │ ├── public │ ├── css │ │ └── style.css │ └── video │ │ └── letitsnow.mp4 │ ├── routes │ ├── auth.js │ ├── dashboard.js │ ├── index.js │ └── user.js │ ├── server.js │ ├── validators │ ├── authValidator.js │ ├── userValidator.js │ └── validator.js │ └── views │ ├── auth │ ├── login.ejs │ └── register.ejs │ ├── components │ └── validation-error.ejs │ ├── dashboard │ └── index.ejs │ ├── errors │ ├── 404.ejs │ ├── 500.ejs │ └── developer.ejs │ ├── index.ejs │ ├── user.ejs │ └── users.ejs ├── 26-register-login-routes └── codes │ ├── .env │ ├── config.js │ ├── controllers │ ├── authController.js │ ├── controller.js │ ├── dashboardController.js │ └── userController.js │ ├── models │ └── user.js │ ├── package.json │ ├── passport │ └── passport-local.js │ ├── public │ ├── css │ │ └── style.css │ └── video │ │ └── letitsnow.mp4 │ ├── routes │ ├── auth.js │ ├── dashboard.js │ ├── index.js │ └── user.js │ ├── server.js │ ├── validators │ ├── authValidator.js │ ├── userValidator.js │ └── validator.js │ └── views │ ├── auth │ ├── login.ejs │ └── register.ejs │ ├── components │ └── validation-error.ejs │ ├── dashboard │ └── index.ejs │ ├── errors │ ├── 404.ejs │ ├── 500.ejs │ └── developer.ejs │ ├── index.ejs │ ├── user.ejs │ └── users.ejs ├── 28-upload-file └── codes │ ├── .env │ ├── config.js │ ├── controllers │ ├── authController.js │ ├── controller.js │ ├── dashboardController.js │ └── userController.js │ ├── models │ └── user.js │ ├── package.json │ ├── passport │ └── passport-local.js │ ├── public │ ├── css │ │ └── style.css │ ├── uploads │ │ └── imgages │ │ │ ├── 1590666976914-profile.jpg │ │ │ ├── 1590667065506-profile.jpg │ │ │ ├── 1590667068594-profile.jpg │ │ │ ├── 1590667088561-profile.jpg │ │ │ ├── 1590667238000-profile.jpg │ │ │ ├── 1590667351445-profile.jpg │ │ │ ├── 1590667863646-New Text Document.txt │ │ │ ├── 1590667888025-New Text Document.txt │ │ │ ├── 1590667898926-profile.jpg │ │ │ ├── 1590667903570-New Text Document.txt │ │ │ └── profile.jpg-1590666897127 │ └── video │ │ └── letitsnow.mp4 │ ├── routes │ ├── auth.js │ ├── dashboard.js │ ├── index.js │ └── user.js │ ├── server.js │ ├── upload │ └── uploadUserProfile.js │ ├── validators │ ├── authValidator.js │ ├── editUserValidator.js │ ├── userValidator.js │ └── validator.js │ └── views │ ├── auth │ ├── login.ejs │ └── register.ejs │ ├── components │ └── validation-error.ejs │ ├── dashboard │ └── index.ejs │ ├── errors │ ├── 404.ejs │ ├── 500.ejs │ └── developer.ejs │ ├── index.ejs │ ├── user.ejs │ └── users.ejs ├── 29-recaptcha └── codes │ ├── .env │ ├── config.js │ ├── controllers │ ├── authController.js │ ├── controller.js │ ├── dashboardController.js │ └── userController.js │ ├── models │ └── user.js │ ├── package.json │ ├── passport │ └── passport-local.js │ ├── public │ ├── css │ │ └── style.css │ ├── uploads │ │ └── imgages │ │ │ ├── 1590666976914-profile.jpg │ │ │ ├── 1590667065506-profile.jpg │ │ │ ├── 1590667068594-profile.jpg │ │ │ ├── 1590667088561-profile.jpg │ │ │ ├── 1590667238000-profile.jpg │ │ │ ├── 1590667351445-profile.jpg │ │ │ ├── 1590667863646-New Text Document.txt │ │ │ ├── 1590667888025-New Text Document.txt │ │ │ ├── 1590667898926-profile.jpg │ │ │ ├── 1590667903570-New Text Document.txt │ │ │ └── profile.jpg-1590666897127 │ └── video │ │ └── letitsnow.mp4 │ ├── routes │ ├── auth.js │ ├── dashboard.js │ ├── index.js │ └── user.js │ ├── server.js │ ├── upload │ └── uploadUserProfile.js │ ├── validators │ ├── authValidator.js │ ├── editUserValidator.js │ ├── userValidator.js │ └── validator.js │ └── views │ ├── auth │ ├── login.ejs │ └── register.ejs │ ├── components │ └── validation-error.ejs │ ├── dashboard │ └── index.ejs │ ├── errors │ ├── 404.ejs │ ├── 500.ejs │ └── developer.ejs │ ├── index.ejs │ ├── user.ejs │ └── users.ejs ├── 30-payment └── codes │ ├── .env │ ├── config.js │ ├── controllers │ ├── authController.js │ ├── controller.js │ ├── dashboardController.js │ ├── homeController.js │ └── userController.js │ ├── models │ ├── payment.js │ └── user.js │ ├── package.json │ ├── passport │ └── passport-local.js │ ├── public │ ├── css │ │ └── style.css │ ├── uploads │ │ └── imgages │ │ │ ├── 1590666976914-profile.jpg │ │ │ ├── 1590667065506-profile.jpg │ │ │ ├── 1590667068594-profile.jpg │ │ │ ├── 1590667088561-profile.jpg │ │ │ ├── 1590667238000-profile.jpg │ │ │ ├── 1590667351445-profile.jpg │ │ │ ├── 1590667863646-New Text Document.txt │ │ │ ├── 1590667888025-New Text Document.txt │ │ │ ├── 1590667898926-profile.jpg │ │ │ ├── 1590667903570-New Text Document.txt │ │ │ └── profile.jpg-1590666897127 │ └── video │ │ └── letitsnow.mp4 │ ├── routes │ ├── auth.js │ ├── dashboard.js │ ├── index.js │ └── user.js │ ├── server.js │ ├── upload │ └── uploadUserProfile.js │ ├── validators │ ├── authValidator.js │ ├── editUserValidator.js │ ├── userValidator.js │ └── validator.js │ └── views │ ├── auth │ ├── login.ejs │ └── register.ejs │ ├── components │ └── validation-error.ejs │ ├── dashboard │ └── index.ejs │ ├── errors │ ├── 404.ejs │ ├── 500.ejs │ └── developer.ejs │ ├── index.ejs │ ├── user.ejs │ └── users.ejs └── 31-payment-emplement └── codes ├── .env ├── config.js ├── controllers ├── authController.js ├── controller.js ├── dashboardController.js ├── homeController.js └── userController.js ├── models ├── payment.js └── user.js ├── package-lock.json ├── package.json ├── passport └── passport-local.js ├── public ├── css │ └── style.css ├── uploads │ └── imgages │ │ ├── 1590666976914-profile.jpg │ │ ├── 1590667065506-profile.jpg │ │ ├── 1590667068594-profile.jpg │ │ ├── 1590667088561-profile.jpg │ │ ├── 1590667238000-profile.jpg │ │ ├── 1590667351445-profile.jpg │ │ ├── 1590667863646-New Text Document.txt │ │ ├── 1590667888025-New Text Document.txt │ │ ├── 1590667898926-profile.jpg │ │ ├── 1590667903570-New Text Document.txt │ │ ├── 1615370873668-pythonmail.jpg │ │ ├── 1615370912540-bootresponsive.jpg │ │ └── profile.jpg-1590666897127 └── video │ └── letitsnow.mp4 ├── routes ├── auth.js ├── dashboard.js ├── index.js └── user.js ├── server.js ├── upload └── uploadUserProfile.js ├── validators ├── authValidator.js ├── editUserValidator.js ├── userValidator.js └── validator.js └── views ├── auth ├── login.ejs └── register.ejs ├── components └── validation-error.ejs ├── dashboard └── index.ejs ├── errors ├── 404.ejs ├── 500.ejs └── developer.ejs ├── index.ejs ├── user.ejs └── users.ejs /22-error-handling/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /22-error-handling/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /22-error-handling/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /22-error-handling/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | req.flash("errors", errors.array()); 39 | return res.redirect("/user"); 40 | } 41 | 42 | req.body.id = parseInt(req.body.id); 43 | let newUser = new User({ 44 | email: req.body.email, 45 | first_name: req.body.first_name, 46 | password: req.body.password 47 | }); 48 | await newUser.save(); 49 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 50 | return res.redirect("/user"); 51 | } catch (err) { 52 | next(err); 53 | } 54 | } 55 | 56 | async updateUser(req, res, next) { 57 | try { 58 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 59 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 60 | return res.redirect("/user"); 61 | } catch (err) { 62 | next(err); 63 | } 64 | } 65 | 66 | async deleteUser(req, res, next) { 67 | try { 68 | } catch (err) { 69 | await User.deleteOne({ _id: req.params.id }); 70 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 71 | return res.redirect("/user"); 72 | } 73 | } 74 | } 75 | 76 | module.exports = new UserController(); 77 | -------------------------------------------------------------------------------- /22-error-handling/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | first_name : { type : String } , 6 | email : { type : String , required : true } , 7 | password : { type : String , required : true } 8 | }); 9 | 10 | module.exports = mongoose.model("User", userSchema , "User") ; 11 | -------------------------------------------------------------------------------- /22-error-handling/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "connect-flash": "^0.1.1", 16 | "cookie-parser": "^1.4.5", 17 | "dotenv": "^8.2.0", 18 | "ejs": "^3.0.1", 19 | "express": "^4.17.1", 20 | "express-session": "^1.17.0", 21 | "express-validator": "^6.4.0", 22 | "method-override": "^3.0.0", 23 | "mongoose": "^5.9.6" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /22-error-handling/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /22-error-handling/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/22-error-handling/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /22-error-handling/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | 5 | router.use('/user' , require('./user')) 6 | 7 | router.all('*' , async (req,res,next)=>{ 8 | try{ 9 | let err = new Error('چنین صفحه ای یافت نشد '); 10 | err.status = 404; 11 | throw err; 12 | }catch(err){ 13 | next(err); 14 | } 15 | }); 16 | 17 | router.use( (err,req,res,next)=>{ 18 | const code = err.status || 500 ; 19 | const message = err.message || ""; 20 | const stack = err.stack || ""; 21 | 22 | if(config.debug){ 23 | return res.render('errors/developer' , {message , stack}) 24 | }else{ 25 | return res.render(`errors/${code}` , {message}); 26 | } 27 | }) 28 | 29 | 30 | 31 | 32 | module.exports = router; -------------------------------------------------------------------------------- /22-error-handling/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /22-error-handling/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | require('app-module-path').addPath(__dirname); 9 | require('dotenv').config(); 10 | 11 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 12 | 13 | global.config = require('./config'); 14 | 15 | app.use(express.static(__dirname + "/public")); 16 | app.use(express.urlencoded({extended : false})); 17 | app.set('view engine' , 'ejs') ; 18 | app.use(methodOverride('method')); 19 | 20 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 21 | 22 | app.use(session({ 23 | secret: process.env.SESSION_SECRET , 24 | resave: true , 25 | saveUninitialized: true, 26 | })) 27 | 28 | app.use(flash()); 29 | 30 | app.get('/', (req,res)=>{ 31 | res.render('index'); 32 | }) 33 | 34 | 35 | app.use('/' , require('./routes/index')); 36 | 37 | app.listen( config.port , ()=>{ 38 | console.log(`server is running on port ${config.port}`); 39 | }) -------------------------------------------------------------------------------- /22-error-handling/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /22-error-handling/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /22-error-handling/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /22-error-handling/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /22-error-handling/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /22-error-handling/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |

hello world

7 | 8 | -------------------------------------------------------------------------------- /22-error-handling/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /22-error-handling/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <% if(errors.length){ %> 8 |
9 | 14 |
15 | <% } %> 16 | 17 | 18 | 19 | <% if(message){ %> 20 |

<%= message %>

21 | <% } %> 22 |
23 |
24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | <% users.forEach(user=>{ %> 43 | 44 | 45 | 46 | 47 | 48 | 54 | 55 | <% }) %> 56 | 57 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 49 |
50 | 51 |
52 | update 53 |
58 | 59 | 60 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/controllers/authController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async registerForm(req, res, next) { 8 | try { 9 | res.render('auth/register' ) 10 | 11 | } catch (err) { 12 | next(err); 13 | } 14 | } 15 | 16 | 17 | async loginForm(req, res, next) { 18 | try { 19 | res.render('auth/login' ) 20 | 21 | } catch (err) { 22 | next(err); 23 | } 24 | } 25 | 26 | async register(req, res, next) { 27 | try { 28 | const errors = validationResult(req); 29 | if (!errors.isEmpty()) { 30 | req.flash("errors", errors.array()); 31 | return res.redirect("/auth/register"); 32 | } 33 | console.log('register') 34 | } catch (err) { 35 | next(err); 36 | } 37 | } 38 | 39 | async login(req, res, next) { 40 | try { 41 | const errors = validationResult(req); 42 | if (!errors.isEmpty()) { 43 | req.flash("errors", errors.array()); 44 | return res.redirect("/auth/login"); 45 | } 46 | console.log('login') 47 | 48 | } catch (err) { 49 | next(err); 50 | } 51 | } 52 | 53 | 54 | } 55 | 56 | module.exports = new UserController(); 57 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | req.flash("errors", errors.array()); 39 | return res.redirect("/user"); 40 | } 41 | 42 | req.body.id = parseInt(req.body.id); 43 | let newUser = new User({ 44 | email: req.body.email, 45 | first_name: req.body.first_name, 46 | password: req.body.password 47 | }); 48 | await newUser.save(); 49 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 50 | return res.redirect("/user"); 51 | } catch (err) { 52 | next(err); 53 | } 54 | } 55 | 56 | async updateUser(req, res, next) { 57 | try { 58 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 59 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 60 | return res.redirect("/user"); 61 | } catch (err) { 62 | next(err); 63 | } 64 | } 65 | 66 | async deleteUser(req, res, next) { 67 | try { 68 | } catch (err) { 69 | await User.deleteOne({ _id: req.params.id }); 70 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 71 | return res.redirect("/user"); 72 | } 73 | } 74 | } 75 | 76 | module.exports = new UserController(); 77 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | first_name : { type : String } , 6 | email : { type : String , required : true } , 7 | password : { type : String , required : true } 8 | }); 9 | 10 | module.exports = mongoose.model("User", userSchema , "User") ; 11 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "connect-flash": "^0.1.1", 16 | "cookie-parser": "^1.4.5", 17 | "dotenv": "^8.2.0", 18 | "ejs": "^3.0.1", 19 | "express": "^4.17.1", 20 | "express-session": "^1.17.0", 21 | "express-validator": "^6.4.0", 22 | "method-override": "^3.0.0", 23 | "mongoose": "^5.9.6" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/23-authentication-create-routes/codes/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const authController = require('controllers/authController'); 6 | 7 | //validators 8 | const authValidator = require('validators/authValidator'); 9 | 10 | router.get("/login", authController.loginForm ); 11 | router.get("/register", authController.registerForm ); 12 | 13 | 14 | router.post("/login", authValidator.login(), authController.login ); 15 | router.post("/register",authValidator.register(), authController.register ); 16 | 17 | 18 | 19 | module.exports = router; 20 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | 5 | router.use('/user' , require('./user')) 6 | router.use('/auth' , require('./auth')) 7 | 8 | 9 | router.all('*' , async (req,res,next)=>{ 10 | try{ 11 | let err = new Error('چنین صفحه ای یافت نشد '); 12 | err.status = 404; 13 | throw err; 14 | }catch(err){ 15 | next(err); 16 | } 17 | }); 18 | 19 | router.use( (err,req,res,next)=>{ 20 | const code = err.status || 500 ; 21 | const message = err.message || ""; 22 | const stack = err.stack || ""; 23 | 24 | if(config.debug){ 25 | return res.render('errors/developer' , {message , stack}) 26 | }else{ 27 | return res.render(`errors/${code}` , {message}); 28 | } 29 | }) 30 | 31 | 32 | 33 | 34 | module.exports = router; -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | require('app-module-path').addPath(__dirname); 9 | require('dotenv').config(); 10 | 11 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 12 | 13 | global.config = require('./config'); 14 | 15 | app.use(express.static(__dirname + "/public")); 16 | app.use(express.urlencoded({extended : false})); 17 | app.set('view engine' , 'ejs') ; 18 | app.use(methodOverride('method')); 19 | 20 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 21 | 22 | app.use(session({ 23 | secret: process.env.SESSION_SECRET , 24 | resave: true , 25 | saveUninitialized: true, 26 | })) 27 | 28 | app.use(flash()); 29 | 30 | app.use((req,res,next)=>{ 31 | res.locals = {errors: req.flash("errors"),}; 32 | next(); 33 | }) 34 | app.get('/', (req,res)=>{ 35 | res.render('index'); 36 | }) 37 | 38 | 39 | app.use('/' , require('./routes/index')); 40 | 41 | app.listen( config.port , ()=>{ 42 | console.log(`server is running on port ${config.port}`); 43 | }) -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/validators/authValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | register(){ 6 | return [ 7 | check("name", "نام نمیتواند خالی باشد").not().isEmpty() , 8 | // username must be an email 9 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 10 | // password must be at least 5 chars long 11 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 12 | min: 5 13 | }) 14 | ] 15 | } 16 | 17 | login(){ 18 | return [ 19 | // username must be an email 20 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 21 | // password must be at least 5 chars long 22 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 23 | min: 5 24 | }) 25 | ] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/auth/login.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/auth/register.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 | 8 |
9 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/components/validation-error.ejs: -------------------------------------------------------------------------------- 1 | <% if(errors.length){ %> 2 |
3 | 8 |
9 | <% } %> 10 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= mymessage %> 5 | 6 | 7 |

hello world

8 | 9 | 10 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /23-authentication-create-routes/codes/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <%- include('components/validation-error') -%> 8 | <% if(message){ %> 9 |

<%= message %>

10 | <% } %> 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <% users.forEach(user=>{ %> 32 | 33 | 34 | 35 | 36 | 37 | 43 | 44 | <% }) %> 45 | 46 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 38 |
39 | 40 |
41 | update 42 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/controllers/authController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async registerForm(req, res, next) { 8 | try { 9 | res.render('auth/register' ) 10 | 11 | } catch (err) { 12 | next(err); 13 | } 14 | } 15 | 16 | 17 | async loginForm(req, res, next) { 18 | try { 19 | res.render('auth/login' ) 20 | 21 | } catch (err) { 22 | next(err); 23 | } 24 | } 25 | 26 | async register(req, res, next) { 27 | try { 28 | const errors = validationResult(req); 29 | if (!errors.isEmpty()) { 30 | let myErrors = errors.array().map(err=>err.msg); 31 | req.flash("errors", myErrors); 32 | return res.redirect("/auth/register"); 33 | } 34 | console.log('register') 35 | } catch (err) { 36 | next(err); 37 | } 38 | } 39 | 40 | async login(req, res, next) { 41 | try { 42 | const errors = validationResult(req); 43 | if (!errors.isEmpty()) { 44 | let myErrors = errors.array().map(err=>err.msg); 45 | req.flash("errors", myErrors); 46 | return res.redirect("/auth/login"); 47 | } 48 | console.log('login') 49 | 50 | } catch (err) { 51 | next(err); 52 | } 53 | } 54 | 55 | 56 | } 57 | 58 | module.exports = new UserController(); 59 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/controllers/dashboardController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | module.exports = new class dashboardController extends controller { 7 | async index(req, res, next) { 8 | try { 9 | res.render('dashboard/index') 10 | } catch (err) { 11 | next(err); 12 | } 13 | } 14 | 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | req.flash("errors", errors.array()); 39 | return res.redirect("/user"); 40 | } 41 | 42 | req.body.id = parseInt(req.body.id); 43 | let newUser = new User({ 44 | email: req.body.email, 45 | first_name: req.body.first_name, 46 | password: req.body.password 47 | }); 48 | await newUser.save(); 49 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 50 | return res.redirect("/user"); 51 | } catch (err) { 52 | next(err); 53 | } 54 | } 55 | 56 | async updateUser(req, res, next) { 57 | try { 58 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 59 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 60 | return res.redirect("/user"); 61 | } catch (err) { 62 | next(err); 63 | } 64 | } 65 | 66 | async deleteUser(req, res, next) { 67 | try { 68 | } catch (err) { 69 | await User.deleteOne({ _id: req.params.id }); 70 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 71 | return res.redirect("/user"); 72 | } 73 | } 74 | } 75 | 76 | module.exports = new UserController(); 77 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | name : { type : String } , 6 | email : { type : String , required : true } , 7 | password : { type : String , required : true } 8 | }); 9 | 10 | module.exports = mongoose.model("User", userSchema , "User") ; 11 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "connect-flash": "^0.1.1", 16 | "connect-mongo": "^3.2.0", 17 | "cookie-parser": "^1.4.5", 18 | "dotenv": "^8.2.0", 19 | "ejs": "^3.0.1", 20 | "express": "^4.17.1", 21 | "express-session": "^1.17.0", 22 | "express-validator": "^6.4.0", 23 | "method-override": "^3.0.0", 24 | "mongoose": "^5.9.6" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/24-create-routes-part-two.trec/codes/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const authController = require('controllers/authController'); 6 | 7 | //validators 8 | const authValidator = require('validators/authValidator'); 9 | 10 | router.use((req,res,next)=>{ 11 | if(true){ 12 | return res.redirect('/dashboard'); 13 | } 14 | next(); 15 | }) 16 | 17 | router.get("/login", authController.loginForm ); 18 | router.get("/register", authController.registerForm ); 19 | 20 | 21 | router.post("/login", authValidator.login(), authController.login ); 22 | router.post("/register",authValidator.register(), authController.register ); 23 | 24 | 25 | 26 | module.exports = router; 27 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/routes/dashboard.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const dashboardController = require('controllers/dashboardController'); 6 | 7 | router.use((req,res,next)=>{ 8 | if(true){ 9 | return next(); 10 | } 11 | res.redirect('/'); 12 | }) 13 | 14 | router.get("/", dashboardController.index ); 15 | 16 | 17 | 18 | 19 | module.exports = router; 20 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | 5 | router.use('/user' , require('./user')) 6 | router.use('/auth' , require('./auth')) 7 | router.use('/dashboard' , require('./dashboard')) 8 | 9 | router.get('/logout' , (req,res)=>{ 10 | console.log('logout'); 11 | }) 12 | 13 | 14 | router.all('*' , async (req,res,next)=>{ 15 | try{ 16 | let err = new Error('چنین صفحه ای یافت نشد '); 17 | err.status = 404; 18 | throw err; 19 | }catch(err){ 20 | next(err); 21 | } 22 | }); 23 | 24 | router.use( (err,req,res,next)=>{ 25 | const code = err.status || 500 ; 26 | const message = err.message || ""; 27 | const stack = err.stack || ""; 28 | 29 | if(config.debug){ 30 | return res.render('errors/developer' , {message , stack}) 31 | }else{ 32 | return res.render(`errors/${code}` , {message}); 33 | } 34 | }) 35 | 36 | 37 | 38 | 39 | module.exports = router; -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | const MongoStore = require('connect-mongo')(session) 9 | require('app-module-path').addPath(__dirname); 10 | require('dotenv').config(); 11 | 12 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 13 | 14 | global.config = require('./config'); 15 | 16 | app.use(express.static(__dirname + "/public")); 17 | app.use(express.urlencoded({extended : false})); 18 | app.set('view engine' , 'ejs') ; 19 | app.use(methodOverride('method')); 20 | 21 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 22 | 23 | app.use(session({ 24 | secret: process.env.SESSION_SECRET , 25 | resave: true , 26 | saveUninitialized: true, 27 | cookie : {expires : new Date( Date.now() + 1000 * 3600 *24 * 100) }, 28 | store : new MongoStore({mongooseConnection : mongoose.connection }) 29 | })) 30 | 31 | app.use(flash()); 32 | 33 | app.use((req,res,next)=>{ 34 | res.locals = {errors: req.flash("errors"),}; 35 | next(); 36 | }) 37 | app.get('/', (req,res)=>{ 38 | res.render('index'); 39 | }) 40 | 41 | 42 | app.use('/' , require('./routes/index')); 43 | 44 | app.listen( config.port , ()=>{ 45 | console.log(`server is running on port ${config.port}`); 46 | }) -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/validators/authValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | register(){ 6 | return [ 7 | check("name", "نام نمیتواند خالی باشد").not().isEmpty() , 8 | // username must be an email 9 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 10 | // password must be at least 5 chars long 11 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 12 | min: 5 13 | }) 14 | ] 15 | } 16 | 17 | login(){ 18 | return [ 19 | // username must be an email 20 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 21 | // password must be at least 5 chars long 22 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 23 | min: 5 24 | }) 25 | ] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/auth/login.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/auth/register.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 | 8 |
9 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/components/validation-error.ejs: -------------------------------------------------------------------------------- 1 | <% if(errors.length){ %> 2 |
3 | 8 |
9 | <% } %> 10 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/dashboard/index.ejs: -------------------------------------------------------------------------------- 1 |

dashboard

2 | 3 | logout -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |

hello world

7 | 8 | 9 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /24-create-routes-part-two.trec/codes/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <%- include('components/validation-error') -%> 8 | <% if(message){ %> 9 |

<%= message %>

10 | <% } %> 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <% users.forEach(user=>{ %> 32 | 33 | 34 | 35 | 36 | 37 | 43 | 44 | <% }) %> 45 | 46 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 38 |
39 | 40 |
41 | update 42 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /26-register-login-routes/codes/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /26-register-login-routes/codes/controllers/authController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | const passport = require('passport'); 4 | 5 | const { validationResult } = require("express-validator"); 6 | 7 | class UserController extends controller { 8 | async registerForm(req, res, next) { 9 | try { 10 | res.render('auth/register' ) 11 | 12 | } catch (err) { 13 | next(err); 14 | } 15 | } 16 | 17 | 18 | async loginForm(req, res, next) { 19 | try { 20 | res.render('auth/login' ) 21 | 22 | } catch (err) { 23 | next(err); 24 | } 25 | } 26 | 27 | async register(req, res, next) { 28 | try { 29 | const errors = validationResult(req); 30 | if (!errors.isEmpty()) { 31 | let myErrors = errors.array().map(err=>err.msg); 32 | req.flash("errors", myErrors); 33 | return res.redirect("/auth/register"); 34 | } 35 | passport.authenticate('local.register' , { 36 | successRedirect : '/dashboard', 37 | failureRedirect : '/auth/register' , 38 | failureFlash : true 39 | })(req,res,next) 40 | } catch (err) { 41 | next(err); 42 | } 43 | } 44 | 45 | async login(req, res, next) { 46 | try { 47 | const errors = validationResult(req); 48 | if (!errors.isEmpty()) { 49 | let myErrors = errors.array().map(err=>err.msg); 50 | req.flash("errors", myErrors); 51 | return res.redirect("/auth/login"); 52 | } 53 | passport.authenticate('local.login' , (err,user)=>{ 54 | if(!user) return res.redirect('/auth/login'); 55 | 56 | req.logIn(user,err=>{ 57 | return res.redirect('/dashboard'); 58 | }) 59 | })(req,res,next) 60 | 61 | } catch (err) { 62 | next(err); 63 | } 64 | } 65 | 66 | 67 | } 68 | 69 | module.exports = new UserController(); 70 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/controllers/dashboardController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | module.exports = new class dashboardController extends controller { 7 | async index(req, res, next) { 8 | try { 9 | res.render('dashboard/index') 10 | } catch (err) { 11 | next(err); 12 | } 13 | } 14 | 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | req.flash("errors", errors.array()); 39 | return res.redirect("/user"); 40 | } 41 | 42 | req.body.id = parseInt(req.body.id); 43 | let newUser = new User({ 44 | email: req.body.email, 45 | first_name: req.body.first_name, 46 | password: req.body.password 47 | }); 48 | await newUser.save(); 49 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 50 | return res.redirect("/user"); 51 | } catch (err) { 52 | next(err); 53 | } 54 | } 55 | 56 | async updateUser(req, res, next) { 57 | try { 58 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 59 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 60 | return res.redirect("/user"); 61 | } catch (err) { 62 | next(err); 63 | } 64 | } 65 | 66 | async deleteUser(req, res, next) { 67 | try { 68 | } catch (err) { 69 | await User.deleteOne({ _id: req.params.id }); 70 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 71 | return res.redirect("/user"); 72 | } 73 | } 74 | } 75 | 76 | module.exports = new UserController(); 77 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | name : { type : String } , 6 | email : { type : String , required : true } , 7 | password : { type : String , required : true } 8 | }); 9 | 10 | module.exports = mongoose.model("User", userSchema , "User") ; 11 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "connect-flash": "^0.1.1", 16 | "connect-mongo": "^3.2.0", 17 | "cookie-parser": "^1.4.5", 18 | "dotenv": "^8.2.0", 19 | "ejs": "^3.0.1", 20 | "express": "^4.17.1", 21 | "express-session": "^1.17.0", 22 | "express-validator": "^6.4.0", 23 | "method-override": "^3.0.0", 24 | "mongoose": "^5.9.6", 25 | "passport": "^0.4.1", 26 | "passport-local": "^1.0.0" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/passport/passport-local.js: -------------------------------------------------------------------------------- 1 | const passport = require('passport'); 2 | const localStrategy = require('passport-local').Strategy; 3 | const User = require('../models/user'); 4 | 5 | passport.serializeUser((user,done)=>{ 6 | done(null,user.id); 7 | }) 8 | 9 | passport.deserializeUser(async (id,done)=>{ 10 | let user = await User.findById(id); 11 | if(user) done(null,user); 12 | }) 13 | 14 | 15 | passport.use("local.register" , new localStrategy( 16 | { 17 | usernameField : 'email' , 18 | passwordField : 'password', 19 | passReqToCallback : true , 20 | } , async (req , email , passport , done)=>{ 21 | try { 22 | let user = await User.findOne({email : req.body.email}); 23 | if(user){ 24 | return done(null,false,req.flash('errors' , "چنین کاربری با این ایمیل وجود دارد")); 25 | } 26 | const newUser = new User({ 27 | name : req.body.name , 28 | email : req.body.email , 29 | password : req.body.password , 30 | }); 31 | 32 | await newUser.save(); 33 | done(null,newUser); 34 | } catch (error) { 35 | return done(error , false , {message : error}) 36 | } 37 | } 38 | 39 | )) 40 | 41 | passport.use('local.login' ,new localStrategy( 42 | { 43 | usernameField : 'email' , 44 | passwordField : 'password', 45 | passReqToCallback : true , 46 | } , async (req,email,password , done)=>{ 47 | try { 48 | let user = await User.findOne({email : req.body.email}); 49 | if(!user || user.password != req.body.password){ 50 | return done(null , false , req.flash('errors' , 'اطلاعات شما هماهنگی ندارد')); 51 | } 52 | done(null , user); 53 | } catch (error) { 54 | return done(error , false , {message : error}) 55 | } 56 | 57 | } )) -------------------------------------------------------------------------------- /26-register-login-routes/codes/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/26-register-login-routes/codes/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /26-register-login-routes/codes/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const authController = require('controllers/authController'); 6 | 7 | //validators 8 | const authValidator = require('validators/authValidator'); 9 | 10 | router.use((req,res,next)=>{ 11 | if(req.isAuthenticated()){ 12 | return res.redirect('/dashboard'); 13 | } 14 | next(); 15 | }) 16 | 17 | router.get("/login", authController.loginForm ); 18 | router.get("/register", authController.registerForm ); 19 | 20 | 21 | router.post("/login", authValidator.login(), authController.login ); 22 | router.post("/register",authValidator.register(), authController.register ); 23 | 24 | 25 | 26 | module.exports = router; 27 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/routes/dashboard.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const dashboardController = require('controllers/dashboardController'); 6 | 7 | router.use((req,res,next)=>{ 8 | if(req.isAuthenticated()){ 9 | return next(); 10 | } 11 | res.redirect('/'); 12 | }) 13 | 14 | router.get("/", dashboardController.index ); 15 | 16 | 17 | 18 | 19 | module.exports = router; 20 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | 5 | router.use('/user' , require('./user')) 6 | router.use('/auth' , require('./auth')) 7 | router.use('/dashboard' , require('./dashboard')) 8 | 9 | router.get('/logout' , (req,res)=>{ 10 | req.logout(); 11 | res.redirect('/'); 12 | }) 13 | 14 | 15 | router.all('*' , async (req,res,next)=>{ 16 | try{ 17 | let err = new Error('چنین صفحه ای یافت نشد '); 18 | err.status = 404; 19 | throw err; 20 | }catch(err){ 21 | next(err); 22 | } 23 | }); 24 | 25 | router.use( (err,req,res,next)=>{ 26 | const code = err.status || 500 ; 27 | const message = err.message || ""; 28 | const stack = err.stack || ""; 29 | 30 | if(config.debug){ 31 | return res.render('errors/developer' , {message , stack}) 32 | }else{ 33 | return res.render(`errors/${code}` , {message}); 34 | } 35 | }) 36 | 37 | 38 | 39 | 40 | module.exports = router; -------------------------------------------------------------------------------- /26-register-login-routes/codes/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | const passport = require('passport'); 9 | const MongoStore = require('connect-mongo')(session) 10 | require('app-module-path').addPath(__dirname); 11 | require('dotenv').config(); 12 | 13 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 14 | 15 | global.config = require('./config'); 16 | 17 | app.use(express.static(__dirname + "/public")); 18 | app.use(express.urlencoded({extended : false})); 19 | app.set('view engine' , 'ejs') ; 20 | app.use(methodOverride('method')); 21 | 22 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 23 | 24 | app.use(session({ 25 | secret: process.env.SESSION_SECRET , 26 | resave: true , 27 | saveUninitialized: true, 28 | cookie : {expires : new Date( Date.now() + 1000 * 3600 *24 * 100) }, 29 | store : new MongoStore({mongooseConnection : mongoose.connection }) 30 | })) 31 | 32 | 33 | 34 | app.use(flash()); 35 | 36 | require('./passport/passport-local'); 37 | app.use(passport.initialize()) 38 | app.use(passport.session()) 39 | 40 | 41 | 42 | app.use((req,res,next)=>{ 43 | res.locals = {errors: req.flash("errors"), req}; 44 | next(); 45 | }) 46 | app.get('/', (req,res)=>{ 47 | res.render('index'); 48 | }) 49 | 50 | 51 | app.use('/' , require('./routes/index')); 52 | 53 | app.listen( config.port , ()=>{ 54 | console.log(`server is running on port ${config.port}`); 55 | }) -------------------------------------------------------------------------------- /26-register-login-routes/codes/validators/authValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | register(){ 6 | return [ 7 | check("name", "نام نمیتواند خالی باشد").not().isEmpty() , 8 | // username must be an email 9 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 10 | // password must be at least 5 chars long 11 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 12 | min: 5 13 | }) 14 | ] 15 | } 16 | 17 | login(){ 18 | return [ 19 | // username must be an email 20 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 21 | // password must be at least 5 chars long 22 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 23 | min: 5 24 | }) 25 | ] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/auth/login.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/auth/register.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 | 8 |
9 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/components/validation-error.ejs: -------------------------------------------------------------------------------- 1 | <% if(errors.length){ %> 2 |
3 | 8 |
9 | <% } %> 10 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/dashboard/index.ejs: -------------------------------------------------------------------------------- 1 |

dashboard

2 |

hi <%= req.user.name %>

3 | logout -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <% if(req.isAuthenticated()){ %> 7 | dashaboard 8 | <% }else{ %> 9 | register 10 | <% } %> 11 |

hello world

12 | 13 | 14 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /26-register-login-routes/codes/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <%- include('components/validation-error') -%> 8 | <% if(message){ %> 9 |

<%= message %>

10 | <% } %> 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <% users.forEach(user=>{ %> 32 | 33 | 34 | 35 | 36 | 37 | 43 | 44 | <% }) %> 45 | 46 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 38 |
39 | 40 |
41 | update 42 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /28-upload-file/codes/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /28-upload-file/codes/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /28-upload-file/codes/controllers/authController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | const passport = require('passport'); 4 | 5 | const { validationResult } = require("express-validator"); 6 | 7 | class UserController extends controller { 8 | async registerForm(req, res, next) { 9 | try { 10 | res.render('auth/register' ) 11 | 12 | } catch (err) { 13 | next(err); 14 | } 15 | } 16 | 17 | 18 | async loginForm(req, res, next) { 19 | try { 20 | res.render('auth/login' ) 21 | 22 | } catch (err) { 23 | next(err); 24 | } 25 | } 26 | 27 | async register(req, res, next) { 28 | try { 29 | const errors = validationResult(req); 30 | if (!errors.isEmpty()) { 31 | let myErrors = errors.array().map(err=>err.msg); 32 | req.flash("errors", myErrors); 33 | return res.redirect("/auth/register"); 34 | } 35 | passport.authenticate('local.register' , { 36 | successRedirect : '/dashboard', 37 | failureRedirect : '/auth/register' , 38 | failureFlash : true 39 | })(req,res,next) 40 | } catch (err) { 41 | next(err); 42 | } 43 | } 44 | 45 | async login(req, res, next) { 46 | try { 47 | const errors = validationResult(req); 48 | if (!errors.isEmpty()) { 49 | let myErrors = errors.array().map(err=>err.msg); 50 | req.flash("errors", myErrors); 51 | return res.redirect("/auth/login"); 52 | } 53 | passport.authenticate('local.login' , (err,user)=>{ 54 | if(!user) return res.redirect('/auth/login'); 55 | 56 | req.logIn(user,err=>{ 57 | return res.redirect('/dashboard'); 58 | }) 59 | })(req,res,next) 60 | 61 | } catch (err) { 62 | next(err); 63 | } 64 | } 65 | 66 | 67 | } 68 | 69 | module.exports = new UserController(); 70 | -------------------------------------------------------------------------------- /28-upload-file/codes/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /28-upload-file/codes/controllers/dashboardController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | module.exports = new class dashboardController extends controller { 7 | async index(req, res, next) { 8 | try { 9 | res.render('dashboard/index') 10 | } catch (err) { 11 | next(err); 12 | } 13 | } 14 | 15 | async edituser(req, res, next) { 16 | try { 17 | const errors = validationResult(req); 18 | if (!errors.isEmpty()) { 19 | let myErrors = errors.array().map(err=>err.msg); 20 | req.flash("errors", myErrors); 21 | return res.redirect("/dashboard"); 22 | } 23 | let data ={ 24 | name : req.body.name, 25 | } 26 | console.log(req.file.path); 27 | if(req.file){ 28 | data.img = req.file.path.replace(/\\/g,'/').substring(6) 29 | } 30 | 31 | await User.updateOne({_id : req.user.id} , {$set : data}) 32 | res.redirect('/dashboard'); 33 | } catch (err) { 34 | next(err); 35 | } 36 | } 37 | 38 | 39 | 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /28-upload-file/codes/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | let myErrors = errors.array().map(err=>err.msg); 39 | req.flash("errors", myErrors); 40 | return res.redirect("/auth/login"); 41 | } 42 | 43 | req.body.id = parseInt(req.body.id); 44 | let newUser = new User({ 45 | email: req.body.email, 46 | first_name: req.body.first_name, 47 | password: req.body.password 48 | }); 49 | await newUser.save(); 50 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 51 | return res.redirect("/user"); 52 | } catch (err) { 53 | next(err); 54 | } 55 | } 56 | 57 | async updateUser(req, res, next) { 58 | try { 59 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 60 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 61 | return res.redirect("/user"); 62 | } catch (err) { 63 | next(err); 64 | } 65 | } 66 | 67 | async deleteUser(req, res, next) { 68 | try { 69 | } catch (err) { 70 | await User.deleteOne({ _id: req.params.id }); 71 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 72 | return res.redirect("/user"); 73 | } 74 | } 75 | } 76 | 77 | module.exports = new UserController(); 78 | -------------------------------------------------------------------------------- /28-upload-file/codes/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | name : { type : String } , 6 | img : { type : String } , 7 | 8 | email : { type : String , required : true } , 9 | password : { type : String , required : true } 10 | }); 11 | 12 | module.exports = mongoose.model("User", userSchema , "User") ; 13 | -------------------------------------------------------------------------------- /28-upload-file/codes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "bcryptjs": "^2.4.3", 16 | "connect-flash": "^0.1.1", 17 | "connect-mongo": "^3.2.0", 18 | "cookie-parser": "^1.4.5", 19 | "dotenv": "^8.2.0", 20 | "ejs": "^3.0.1", 21 | "express": "^4.17.1", 22 | "express-session": "^1.17.0", 23 | "express-validator": "^6.4.0", 24 | "method-override": "^3.0.0", 25 | "mkdirp": "^1.0.4", 26 | "mongoose": "^5.9.6", 27 | "multer": "^1.4.2", 28 | "passport": "^0.4.1", 29 | "passport-local": "^1.0.0" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /28-upload-file/codes/passport/passport-local.js: -------------------------------------------------------------------------------- 1 | const passport = require('passport'); 2 | const localStrategy = require('passport-local').Strategy; 3 | var bcrypt = require('bcryptjs'); 4 | const User = require('../models/user'); 5 | 6 | passport.serializeUser((user,done)=>{ 7 | done(null,user.id); 8 | }) 9 | 10 | passport.deserializeUser(async (id,done)=>{ 11 | let user = await User.findById(id); 12 | if(user) done(null,user); 13 | }) 14 | 15 | 16 | passport.use("local.register" , new localStrategy( 17 | { 18 | usernameField : 'email' , 19 | passwordField : 'password', 20 | passReqToCallback : true , 21 | } , async (req , email , passport , done)=>{ 22 | try { 23 | let user = await User.findOne({email : req.body.email}); 24 | if(user){ 25 | return done(null,false,req.flash('errors' , "چنین کاربری با این ایمیل وجود دارد")); 26 | } 27 | const newUser = new User({ 28 | name : req.body.name , 29 | email : req.body.email , 30 | password : bcrypt.hashSync(req.body.password, 8) , 31 | }); 32 | 33 | await newUser.save(); 34 | done(null,newUser); 35 | } catch (error) { 36 | return done(error , false , {message : error}) 37 | } 38 | } 39 | 40 | )) 41 | 42 | passport.use('local.login' ,new localStrategy( 43 | { 44 | usernameField : 'email' , 45 | passwordField : 'password', 46 | passReqToCallback : true , 47 | } , async (req,email,password , done)=>{ 48 | try { 49 | let user = await User.findOne({email : req.body.email}); 50 | if(!user || !bcrypt.compareSync(req.body.password , user.password) ){ 51 | return done(null , false , req.flash('errors' , 'اطلاعات شما هماهنگی ندارد')); 52 | } 53 | done(null , user); 54 | } catch (error) { 55 | return done(error , false , {message : error}) 56 | } 57 | 58 | } )) -------------------------------------------------------------------------------- /28-upload-file/codes/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590666976914-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590666976914-profile.jpg -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667065506-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667065506-profile.jpg -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667068594-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667068594-profile.jpg -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667088561-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667088561-profile.jpg -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667238000-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667238000-profile.jpg -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667351445-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667351445-profile.jpg -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667863646-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667863646-New Text Document.txt -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667888025-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667888025-New Text Document.txt -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667898926-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667898926-profile.jpg -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/1590667903570-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/1590667903570-New Text Document.txt -------------------------------------------------------------------------------- /28-upload-file/codes/public/uploads/imgages/profile.jpg-1590666897127: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/uploads/imgages/profile.jpg-1590666897127 -------------------------------------------------------------------------------- /28-upload-file/codes/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/28-upload-file/codes/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /28-upload-file/codes/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const authController = require('controllers/authController'); 6 | 7 | //validators 8 | const authValidator = require('validators/authValidator'); 9 | 10 | router.use((req,res,next)=>{ 11 | if(req.isAuthenticated()){ 12 | return res.redirect('/dashboard'); 13 | } 14 | next(); 15 | }) 16 | 17 | router.get("/login", authController.loginForm ); 18 | router.get("/register", authController.registerForm ); 19 | 20 | 21 | router.post("/login", authValidator.login(), authController.login ); 22 | router.post("/register",authValidator.register(), authController.register ); 23 | 24 | 25 | 26 | module.exports = router; 27 | -------------------------------------------------------------------------------- /28-upload-file/codes/routes/dashboard.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const dashboardController = require('controllers/dashboardController'); 6 | const editUserValidator = require('validators/editUserValidator'); 7 | const uploadUserProfile = require('upload/uploadUserProfile'); 8 | 9 | router.use((req,res,next)=>{ 10 | if(req.isAuthenticated()){ 11 | return next(); 12 | } 13 | res.redirect('/'); 14 | }) 15 | 16 | router.get("/", dashboardController.index ); 17 | router.post("/edituser", uploadUserProfile.single('img') , (req,res,next)=>{ 18 | if(!req.file){ 19 | req.body.img = null 20 | }else{ 21 | req.body.img = req.file.filename; 22 | } 23 | next() 24 | } , editUserValidator.handle() , dashboardController.edituser ); 25 | 26 | 27 | 28 | 29 | 30 | module.exports = router; 31 | -------------------------------------------------------------------------------- /28-upload-file/codes/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | 5 | router.use('/user' , require('./user')) 6 | router.use('/auth' , require('./auth')) 7 | router.use('/dashboard' , require('./dashboard')) 8 | 9 | router.get('/logout' , (req,res)=>{ 10 | req.logout(); 11 | res.redirect('/'); 12 | }) 13 | 14 | 15 | router.all('*' , async (req,res,next)=>{ 16 | try{ 17 | let err = new Error('چنین صفحه ای یافت نشد '); 18 | err.status = 404; 19 | throw err; 20 | }catch(err){ 21 | next(err); 22 | } 23 | }); 24 | 25 | router.use( (err,req,res,next)=>{ 26 | const code = err.status || 500 ; 27 | const message = err.message || ""; 28 | const stack = err.stack || ""; 29 | 30 | if(config.debug){ 31 | return res.render('errors/developer' , {message , stack}) 32 | }else{ 33 | return res.render(`errors/${code}` , {message}); 34 | } 35 | }) 36 | 37 | 38 | 39 | 40 | module.exports = router; -------------------------------------------------------------------------------- /28-upload-file/codes/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /28-upload-file/codes/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | const passport = require('passport'); 9 | const MongoStore = require('connect-mongo')(session) 10 | require('app-module-path').addPath(__dirname); 11 | require('dotenv').config(); 12 | 13 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 14 | 15 | global.config = require('./config'); 16 | 17 | app.use(express.static(__dirname + "/public")); 18 | app.use(express.urlencoded({extended : false})); 19 | app.set('view engine' , 'ejs') ; 20 | app.use(methodOverride('method')); 21 | 22 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 23 | 24 | app.use(session({ 25 | secret: process.env.SESSION_SECRET , 26 | resave: true , 27 | saveUninitialized: true, 28 | cookie : {expires : new Date( Date.now() + 1000 * 3600 *24 * 100) }, 29 | store : new MongoStore({mongooseConnection : mongoose.connection }) 30 | })) 31 | 32 | 33 | 34 | app.use(flash()); 35 | 36 | require('./passport/passport-local'); 37 | app.use(passport.initialize()) 38 | app.use(passport.session()) 39 | 40 | 41 | 42 | app.use((req,res,next)=>{ 43 | res.locals = {errors: req.flash("errors"), req}; 44 | next(); 45 | }) 46 | app.get('/', (req,res)=>{ 47 | res.render('index'); 48 | }) 49 | 50 | 51 | app.use('/' , require('./routes/index')); 52 | 53 | app.listen( config.port , ()=>{ 54 | console.log(`server is running on port ${config.port}`); 55 | }) -------------------------------------------------------------------------------- /28-upload-file/codes/upload/uploadUserProfile.js: -------------------------------------------------------------------------------- 1 | const multer = require('multer'); 2 | const mkdir = require('mkdirp'); 3 | 4 | 5 | const storage = multer.diskStorage({ 6 | destination: function (req, file, cb) { 7 | mkdir('./public/uploads/imgages').then(made=>{ 8 | cb(null, './public/uploads/imgages'); 9 | }) 10 | }, 11 | filename: function (req, file, cb) { 12 | cb(null, Date.now() + '-' + file.originalname ) 13 | } 14 | }) 15 | 16 | const upload = multer({ storage: storage }); 17 | 18 | module.exports = upload; 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /28-upload-file/codes/validators/authValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | register(){ 6 | return [ 7 | check("name", "نام نمیتواند خالی باشد").not().isEmpty() , 8 | // username must be an email 9 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 10 | // password must be at least 5 chars long 11 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 12 | min: 5 13 | }) 14 | ] 15 | } 16 | 17 | login(){ 18 | return [ 19 | // username must be an email 20 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 21 | // password must be at least 5 chars long 22 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 23 | min: 5 24 | }) 25 | ] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /28-upload-file/codes/validators/editUserValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | const path = require('path'); 4 | 5 | module.exports = new class UserValidator extends validator { 6 | handle(){ 7 | return [ 8 | check("name", "نام نمیتواند خالی باشد").not().isEmpty(), 9 | check("img", "وجود تصویر الزامیست").not().isEmpty(), 10 | check("img").custom(async value=>{ 11 | if(!value){ 12 | return 13 | } 14 | if(!['.jpg','jpeg','.png'].includes(path.extname(value))){ 15 | throw new Error('پسوند فایل آپلود شده صحیح نیست') 16 | } 17 | }) 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /28-upload-file/codes/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /28-upload-file/codes/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/auth/login.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/auth/register.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 | 8 |
9 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/components/validation-error.ejs: -------------------------------------------------------------------------------- 1 | <% if(errors.length){ %> 2 |
3 | 8 |
9 | <% } %> 10 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/dashboard/index.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |

dashboard

4 |

hi <%= req.user.name %>

5 | 6 |
7 | 8 | 9 | 10 |
11 | logout -------------------------------------------------------------------------------- /28-upload-file/codes/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <% if(req.isAuthenticated()){ %> 7 | dashaboard 8 | <% }else{ %> 9 | register 10 | <% } %> 11 |

hello world

12 | 13 | 14 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /28-upload-file/codes/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <%- include('components/validation-error') -%> 8 | <% if(message){ %> 9 |

<%= message %>

10 | <% } %> 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <% users.forEach(user=>{ %> 32 | 33 | 34 | 35 | 36 | 37 | 43 | 44 | <% }) %> 45 | 46 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 38 |
39 | 40 |
41 | update 42 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /29-recaptcha/codes/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /29-recaptcha/codes/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /29-recaptcha/codes/controllers/authController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | const passport = require('passport'); 4 | var Recaptcha = require('express-recaptcha').RecaptchaV2; 5 | const options = {'hl':'fa'}; 6 | const recaptcha = new Recaptcha('6LffQv0UAAAAAPMCl2b8B1tgwXGHqzjNUMiUg7qf', '6LffQv0UAAAAAKydjq0fJc52IcsimzLaiEET8741', options); 7 | const { validationResult } = require("express-validator"); 8 | 9 | class UserController extends controller { 10 | async registerForm(req, res, next) { 11 | try { 12 | res.render('auth/register' , {recaptcha : recaptcha.render() } ) 13 | 14 | } catch (err) { 15 | next(err); 16 | } 17 | } 18 | 19 | 20 | async loginForm(req, res, next) { 21 | try { 22 | res.render('auth/login' ) 23 | 24 | } catch (err) { 25 | next(err); 26 | } 27 | } 28 | 29 | async register(req, res, next) { 30 | try { 31 | let recaptchaResult = await new Promise((resolve,reject)=>{ 32 | recaptcha.verify(req,(err,data)=>{ 33 | if(err){ 34 | req.flash('errors' , 'تیک گزینه امنیتی را بزنید'); 35 | res.redirect('/auth/register'); 36 | resolve(false) 37 | }else{ 38 | resolve(true) 39 | } 40 | }) 41 | }) 42 | 43 | if(!recaptchaResult){ 44 | return; 45 | } 46 | 47 | const errors = validationResult(req); 48 | if (!errors.isEmpty()) { 49 | let myErrors = errors.array().map(err=>err.msg); 50 | req.flash("errors", myErrors); 51 | return res.redirect("/auth/register" ); 52 | } 53 | passport.authenticate('local.register' , { 54 | successRedirect : '/dashboard', 55 | failureRedirect : '/auth/register' , 56 | failureFlash : true 57 | })(req,res,next) 58 | } catch (err) { 59 | next(err); 60 | } 61 | } 62 | 63 | async login(req, res, next) { 64 | try { 65 | const errors = validationResult(req); 66 | if (!errors.isEmpty()) { 67 | let myErrors = errors.array().map(err=>err.msg); 68 | req.flash("errors", myErrors); 69 | return res.redirect("/auth/login"); 70 | } 71 | passport.authenticate('local.login' , (err,user)=>{ 72 | if(!user) return res.redirect('/auth/login'); 73 | 74 | req.logIn(user,err=>{ 75 | return res.redirect('/dashboard'); 76 | }) 77 | })(req,res,next) 78 | 79 | } catch (err) { 80 | next(err); 81 | } 82 | } 83 | 84 | 85 | } 86 | 87 | module.exports = new UserController(); 88 | -------------------------------------------------------------------------------- /29-recaptcha/codes/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /29-recaptcha/codes/controllers/dashboardController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | module.exports = new class dashboardController extends controller { 7 | async index(req, res, next) { 8 | try { 9 | res.render('dashboard/index') 10 | } catch (err) { 11 | next(err); 12 | } 13 | } 14 | 15 | async edituser(req, res, next) { 16 | try { 17 | const errors = validationResult(req); 18 | if (!errors.isEmpty()) { 19 | let myErrors = errors.array().map(err=>err.msg); 20 | req.flash("errors", myErrors); 21 | return res.redirect("/dashboard"); 22 | } 23 | let data ={ 24 | name : req.body.name, 25 | } 26 | console.log(req.file.path); 27 | if(req.file){ 28 | data.img = req.file.path.replace(/\\/g,'/').substring(6) 29 | } 30 | 31 | await User.updateOne({_id : req.user.id} , {$set : data}) 32 | res.redirect('/dashboard'); 33 | } catch (err) { 34 | next(err); 35 | } 36 | } 37 | 38 | 39 | 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /29-recaptcha/codes/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | let myErrors = errors.array().map(err=>err.msg); 39 | req.flash("errors", myErrors); 40 | return res.redirect("/auth/login"); 41 | } 42 | 43 | req.body.id = parseInt(req.body.id); 44 | let newUser = new User({ 45 | email: req.body.email, 46 | first_name: req.body.first_name, 47 | password: req.body.password 48 | }); 49 | await newUser.save(); 50 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 51 | return res.redirect("/user"); 52 | } catch (err) { 53 | next(err); 54 | } 55 | } 56 | 57 | async updateUser(req, res, next) { 58 | try { 59 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 60 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 61 | return res.redirect("/user"); 62 | } catch (err) { 63 | next(err); 64 | } 65 | } 66 | 67 | async deleteUser(req, res, next) { 68 | try { 69 | } catch (err) { 70 | await User.deleteOne({ _id: req.params.id }); 71 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 72 | return res.redirect("/user"); 73 | } 74 | } 75 | } 76 | 77 | module.exports = new UserController(); 78 | -------------------------------------------------------------------------------- /29-recaptcha/codes/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | name : { type : String } , 6 | img : { type : String } , 7 | 8 | email : { type : String , required : true } , 9 | password : { type : String , required : true } 10 | }); 11 | 12 | module.exports = mongoose.model("User", userSchema , "User") ; 13 | -------------------------------------------------------------------------------- /29-recaptcha/codes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "bcryptjs": "^2.4.3", 16 | "connect-flash": "^0.1.1", 17 | "connect-mongo": "^3.2.0", 18 | "cookie-parser": "^1.4.5", 19 | "dotenv": "^8.2.0", 20 | "ejs": "^3.0.1", 21 | "express": "^4.17.1", 22 | "express-recaptcha": "^5.0.1", 23 | "express-session": "^1.17.0", 24 | "express-validator": "^6.4.0", 25 | "method-override": "^3.0.0", 26 | "mkdirp": "^1.0.4", 27 | "mongoose": "^5.9.6", 28 | "multer": "^1.4.2", 29 | "passport": "^0.4.1", 30 | "passport-local": "^1.0.0" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /29-recaptcha/codes/passport/passport-local.js: -------------------------------------------------------------------------------- 1 | const passport = require('passport'); 2 | const localStrategy = require('passport-local').Strategy; 3 | var bcrypt = require('bcryptjs'); 4 | const User = require('../models/user'); 5 | 6 | passport.serializeUser((user,done)=>{ 7 | done(null,user.id); 8 | }) 9 | 10 | passport.deserializeUser(async (id,done)=>{ 11 | let user = await User.findById(id); 12 | if(user) done(null,user); 13 | }) 14 | 15 | 16 | passport.use("local.register" , new localStrategy( 17 | { 18 | usernameField : 'email' , 19 | passwordField : 'password', 20 | passReqToCallback : true , 21 | } , async (req , email , passport , done)=>{ 22 | try { 23 | let user = await User.findOne({email : req.body.email}); 24 | if(user){ 25 | return done(null,false,req.flash('errors' , "چنین کاربری با این ایمیل وجود دارد")); 26 | } 27 | const newUser = new User({ 28 | name : req.body.name , 29 | email : req.body.email , 30 | password : bcrypt.hashSync(req.body.password, 8) , 31 | }); 32 | 33 | await newUser.save(); 34 | done(null,newUser); 35 | } catch (error) { 36 | return done(error , false , {message : error}) 37 | } 38 | } 39 | 40 | )) 41 | 42 | passport.use('local.login' ,new localStrategy( 43 | { 44 | usernameField : 'email' , 45 | passwordField : 'password', 46 | passReqToCallback : true , 47 | } , async (req,email,password , done)=>{ 48 | try { 49 | let user = await User.findOne({email : req.body.email}); 50 | if(!user || !bcrypt.compareSync(req.body.password , user.password) ){ 51 | return done(null , false , req.flash('errors' , 'اطلاعات شما هماهنگی ندارد')); 52 | } 53 | done(null , user); 54 | } catch (error) { 55 | return done(error , false , {message : error}) 56 | } 57 | 58 | } )) -------------------------------------------------------------------------------- /29-recaptcha/codes/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590666976914-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590666976914-profile.jpg -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667065506-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667065506-profile.jpg -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667068594-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667068594-profile.jpg -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667088561-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667088561-profile.jpg -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667238000-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667238000-profile.jpg -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667351445-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667351445-profile.jpg -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667863646-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667863646-New Text Document.txt -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667888025-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667888025-New Text Document.txt -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667898926-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667898926-profile.jpg -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/1590667903570-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/1590667903570-New Text Document.txt -------------------------------------------------------------------------------- /29-recaptcha/codes/public/uploads/imgages/profile.jpg-1590666897127: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/uploads/imgages/profile.jpg-1590666897127 -------------------------------------------------------------------------------- /29-recaptcha/codes/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/29-recaptcha/codes/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /29-recaptcha/codes/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const authController = require('controllers/authController'); 6 | 7 | //validators 8 | const authValidator = require('validators/authValidator'); 9 | 10 | router.use((req,res,next)=>{ 11 | if(req.isAuthenticated()){ 12 | return res.redirect('/dashboard'); 13 | } 14 | next(); 15 | }) 16 | 17 | router.get("/login", authController.loginForm ); 18 | router.get("/register", authController.registerForm ); 19 | 20 | 21 | router.post("/login", authValidator.login(), authController.login ); 22 | router.post("/register",authValidator.register(), authController.register ); 23 | 24 | 25 | 26 | module.exports = router; 27 | -------------------------------------------------------------------------------- /29-recaptcha/codes/routes/dashboard.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const dashboardController = require('controllers/dashboardController'); 6 | const editUserValidator = require('validators/editUserValidator'); 7 | const uploadUserProfile = require('upload/uploadUserProfile'); 8 | 9 | router.use((req,res,next)=>{ 10 | if(req.isAuthenticated()){ 11 | return next(); 12 | } 13 | res.redirect('/'); 14 | }) 15 | 16 | router.get("/", dashboardController.index ); 17 | router.post("/edituser", uploadUserProfile.single('img') , (req,res,next)=>{ 18 | if(!req.file){ 19 | req.body.img = null 20 | }else{ 21 | req.body.img = req.file.filename; 22 | } 23 | next() 24 | } , editUserValidator.handle() , dashboardController.edituser ); 25 | 26 | 27 | 28 | 29 | 30 | module.exports = router; 31 | -------------------------------------------------------------------------------- /29-recaptcha/codes/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | 5 | router.use('/user' , require('./user')) 6 | router.use('/auth' , require('./auth')) 7 | router.use('/dashboard' , require('./dashboard')) 8 | 9 | router.get('/logout' , (req,res)=>{ 10 | req.logout(); 11 | res.redirect('/'); 12 | }) 13 | 14 | 15 | router.all('*' , async (req,res,next)=>{ 16 | try{ 17 | let err = new Error('چنین صفحه ای یافت نشد '); 18 | err.status = 404; 19 | throw err; 20 | }catch(err){ 21 | next(err); 22 | } 23 | }); 24 | 25 | router.use( (err,req,res,next)=>{ 26 | const code = err.status || 500 ; 27 | const message = err.message || ""; 28 | const stack = err.stack || ""; 29 | 30 | if(config.debug){ 31 | return res.render('errors/developer' , {message , stack}) 32 | }else{ 33 | return res.render(`errors/${code}` , {message}); 34 | } 35 | }) 36 | 37 | 38 | 39 | 40 | module.exports = router; -------------------------------------------------------------------------------- /29-recaptcha/codes/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /29-recaptcha/codes/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | const passport = require('passport'); 9 | const MongoStore = require('connect-mongo')(session) 10 | require('app-module-path').addPath(__dirname); 11 | require('dotenv').config(); 12 | 13 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 14 | 15 | global.config = require('./config'); 16 | 17 | app.use(express.static(__dirname + "/public")); 18 | app.use(express.urlencoded({extended : false})); 19 | app.set('view engine' , 'ejs') ; 20 | app.use(methodOverride('method')); 21 | 22 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 23 | 24 | app.use(session({ 25 | secret: process.env.SESSION_SECRET , 26 | resave: true , 27 | saveUninitialized: true, 28 | cookie : {expires : new Date( Date.now() + 1000 * 3600 *24 * 100) }, 29 | store : new MongoStore({mongooseConnection : mongoose.connection }) 30 | })) 31 | 32 | 33 | 34 | app.use(flash()); 35 | 36 | require('./passport/passport-local'); 37 | app.use(passport.initialize()) 38 | app.use(passport.session()) 39 | 40 | 41 | 42 | app.use((req,res,next)=>{ 43 | res.locals = {errors: req.flash("errors"), req}; 44 | next(); 45 | }) 46 | app.get('/', (req,res)=>{ 47 | res.render('index'); 48 | }) 49 | 50 | 51 | app.use('/' , require('./routes/index')); 52 | 53 | app.listen( config.port , ()=>{ 54 | console.log(`server is running on port ${config.port}`); 55 | }) -------------------------------------------------------------------------------- /29-recaptcha/codes/upload/uploadUserProfile.js: -------------------------------------------------------------------------------- 1 | const multer = require('multer'); 2 | const mkdir = require('mkdirp'); 3 | 4 | 5 | const storage = multer.diskStorage({ 6 | destination: function (req, file, cb) { 7 | mkdir('./public/uploads/imgages').then(made=>{ 8 | cb(null, './public/uploads/imgages'); 9 | }) 10 | }, 11 | filename: function (req, file, cb) { 12 | cb(null, Date.now() + '-' + file.originalname ) 13 | } 14 | }) 15 | 16 | const upload = multer({ storage: storage }); 17 | 18 | module.exports = upload; 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /29-recaptcha/codes/validators/authValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | register(){ 6 | return [ 7 | check("name", "نام نمیتواند خالی باشد").not().isEmpty() , 8 | // username must be an email 9 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 10 | // password must be at least 5 chars long 11 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 12 | min: 5 13 | }) 14 | ] 15 | } 16 | 17 | login(){ 18 | return [ 19 | // username must be an email 20 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 21 | // password must be at least 5 chars long 22 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 23 | min: 5 24 | }) 25 | ] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /29-recaptcha/codes/validators/editUserValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | const path = require('path'); 4 | 5 | module.exports = new class UserValidator extends validator { 6 | handle(){ 7 | return [ 8 | check("name", "نام نمیتواند خالی باشد").not().isEmpty(), 9 | check("img", "وجود تصویر الزامیست").not().isEmpty(), 10 | check("img").custom(async value=>{ 11 | if(!value){ 12 | return 13 | } 14 | if(!['.jpg','jpeg','.png'].includes(path.extname(value))){ 15 | throw new Error('پسوند فایل آپلود شده صحیح نیست') 16 | } 17 | }) 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /29-recaptcha/codes/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /29-recaptcha/codes/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/auth/login.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/auth/register.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 | <%- recaptcha %> 8 | 9 |
10 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/components/validation-error.ejs: -------------------------------------------------------------------------------- 1 | <% if(errors.length){ %> 2 |
3 | 8 |
9 | <% } %> 10 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/dashboard/index.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |

dashboard

4 |

hi <%= req.user.name %>

5 | 6 |
7 | 8 | 9 | 10 |
11 | logout -------------------------------------------------------------------------------- /29-recaptcha/codes/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <% if(req.isAuthenticated()){ %> 7 | dashaboard 8 | <% }else{ %> 9 | register 10 | <% } %> 11 |

hello world

12 | 13 | 14 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /29-recaptcha/codes/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <%- include('components/validation-error') -%> 8 | <% if(message){ %> 9 |

<%= message %>

10 | <% } %> 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <% users.forEach(user=>{ %> 32 | 33 | 34 | 35 | 36 | 37 | 43 | 44 | <% }) %> 45 | 46 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 38 |
39 | 40 |
41 | update 42 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /30-payment/codes/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /30-payment/codes/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /30-payment/codes/controllers/authController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | const passport = require("passport"); 4 | var Recaptcha = require("express-recaptcha").RecaptchaV2; 5 | const options = { hl: "fa" }; 6 | const recaptcha = new Recaptcha( 7 | "6LffQv0UAAAAAPMCl2b8B1tgwXGHqzjNUMiUg7qf", 8 | "6LffQv0UAAAAAKydjq0fJc52IcsimzLaiEET8741", 9 | options 10 | ); 11 | const { validationResult } = require("express-validator"); 12 | 13 | class UserController extends controller { 14 | async registerForm(req, res, next) { 15 | try { 16 | res.render("auth/register", { recaptcha: recaptcha.render() }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async loginForm(req, res, next) { 23 | try { 24 | res.render("auth/login"); 25 | } catch (err) { 26 | next(err); 27 | } 28 | } 29 | 30 | async register(req, res, next) { 31 | try { 32 | let recaptchaResult = await new Promise((resolve, reject) => { 33 | recaptcha.verify(req, (err, data) => { 34 | if (err) { 35 | req.flash("errors", "تیک گزینه امنیتی را بزنید"); 36 | res.redirect("/auth/register"); 37 | resolve(false); 38 | } else { 39 | resolve(true); 40 | } 41 | }); 42 | }); 43 | 44 | if (!recaptchaResult) { 45 | return; 46 | } 47 | 48 | const errors = validationResult(req); 49 | if (!errors.isEmpty()) { 50 | let myErrors = errors.array().map((err) => err.msg); 51 | req.flash("errors", myErrors); 52 | return res.redirect("/auth/register"); 53 | } 54 | passport.authenticate("local.register", { 55 | successRedirect: "/dashboard", 56 | failureRedirect: "/auth/register", 57 | failureFlash: true, 58 | })(req, res, next); 59 | } catch (err) { 60 | next(err); 61 | } 62 | } 63 | 64 | async login(req, res, next) { 65 | try { 66 | const errors = validationResult(req); 67 | if (!errors.isEmpty()) { 68 | let myErrors = errors.array().map((err) => err.msg); 69 | req.flash("errors", myErrors); 70 | return res.redirect("/auth/login"); 71 | } 72 | passport.authenticate("local.login", (err, user) => { 73 | if (!user) return res.redirect("/auth/login"); 74 | 75 | req.logIn(user, (err) => { 76 | return res.redirect("/dashboard"); 77 | }); 78 | })(req, res, next); 79 | } catch (err) { 80 | next(err); 81 | } 82 | } 83 | } 84 | 85 | module.exports = new UserController(); 86 | -------------------------------------------------------------------------------- /30-payment/codes/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /30-payment/codes/controllers/dashboardController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | module.exports = new class dashboardController extends controller { 7 | async index(req, res, next) { 8 | try { 9 | res.render('dashboard/index') 10 | } catch (err) { 11 | next(err); 12 | } 13 | } 14 | 15 | async pay(req, res, next) { 16 | try { 17 | console.log('pay') 18 | } catch (err) { 19 | next(err); 20 | } 21 | } 22 | 23 | async edituser(req, res, next) { 24 | try { 25 | const errors = validationResult(req); 26 | if (!errors.isEmpty()) { 27 | let myErrors = errors.array().map(err=>err.msg); 28 | req.flash("errors", myErrors); 29 | return res.redirect("/dashboard"); 30 | } 31 | let data ={ 32 | name : req.body.name, 33 | } 34 | console.log(req.file.path); 35 | if(req.file){ 36 | data.img = req.file.path.replace(/\\/g,'/').substring(6) 37 | } 38 | 39 | await User.updateOne({_id : req.user.id} , {$set : data}) 40 | res.redirect('/dashboard'); 41 | } catch (err) { 42 | next(err); 43 | } 44 | } 45 | 46 | 47 | 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /30-payment/codes/controllers/homeController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | module.exports = new class dashboardController extends controller { 7 | async paycallback(req, res, next) { 8 | try { 9 | console.log('callback') 10 | } catch (err) { 11 | next(err); 12 | } 13 | } 14 | 15 | 16 | 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /30-payment/codes/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | let myErrors = errors.array().map(err=>err.msg); 39 | req.flash("errors", myErrors); 40 | return res.redirect("/auth/login"); 41 | } 42 | 43 | req.body.id = parseInt(req.body.id); 44 | let newUser = new User({ 45 | email: req.body.email, 46 | first_name: req.body.first_name, 47 | password: req.body.password 48 | }); 49 | await newUser.save(); 50 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 51 | return res.redirect("/user"); 52 | } catch (err) { 53 | next(err); 54 | } 55 | } 56 | 57 | async updateUser(req, res, next) { 58 | try { 59 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 60 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 61 | return res.redirect("/user"); 62 | } catch (err) { 63 | next(err); 64 | } 65 | } 66 | 67 | async deleteUser(req, res, next) { 68 | try { 69 | } catch (err) { 70 | await User.deleteOne({ _id: req.params.id }); 71 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 72 | return res.redirect("/user"); 73 | } 74 | } 75 | } 76 | 77 | module.exports = new UserController(); 78 | -------------------------------------------------------------------------------- /30-payment/codes/models/payment.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | user : {type : Schema.Types.ObjectId , ref : 'User'} , 6 | resnumber : {type : String , required : true } , 7 | amount : {type : Number , required : true} , 8 | payment : {type : Boolean , default : false } 9 | }); 10 | 11 | module.exports = mongoose.model("User", userSchema , "User") ; 12 | -------------------------------------------------------------------------------- /30-payment/codes/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | name : { type : String } , 6 | img : { type : String } , 7 | balance : {type : Number , default : 0 } , 8 | email : { type : String , required : true } , 9 | password : { type : String , required : true } 10 | }); 11 | 12 | module.exports = mongoose.model("User", userSchema , "User") ; 13 | -------------------------------------------------------------------------------- /30-payment/codes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "bcryptjs": "^2.4.3", 16 | "connect-flash": "^0.1.1", 17 | "connect-mongo": "^3.2.0", 18 | "cookie-parser": "^1.4.5", 19 | "dotenv": "^8.2.0", 20 | "ejs": "^3.0.1", 21 | "express": "^4.17.1", 22 | "express-recaptcha": "^5.0.1", 23 | "express-session": "^1.17.0", 24 | "express-validator": "^6.4.0", 25 | "method-override": "^3.0.0", 26 | "mkdirp": "^1.0.4", 27 | "mongoose": "^5.9.6", 28 | "multer": "^1.4.2", 29 | "passport": "^0.4.1", 30 | "passport-local": "^1.0.0" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /30-payment/codes/passport/passport-local.js: -------------------------------------------------------------------------------- 1 | const passport = require('passport'); 2 | const localStrategy = require('passport-local').Strategy; 3 | var bcrypt = require('bcryptjs'); 4 | const User = require('../models/user'); 5 | 6 | passport.serializeUser((user,done)=>{ 7 | done(null,user.id); 8 | }) 9 | 10 | passport.deserializeUser(async (id,done)=>{ 11 | let user = await User.findById(id); 12 | if(user) done(null,user); 13 | }) 14 | 15 | 16 | passport.use("local.register" , new localStrategy( 17 | { 18 | usernameField : 'email' , 19 | passwordField : 'password', 20 | passReqToCallback : true , 21 | } , async (req , email , passport , done)=>{ 22 | try { 23 | let user = await User.findOne({email : req.body.email}); 24 | if(user){ 25 | return done(null,false,req.flash('errors' , "چنین کاربری با این ایمیل وجود دارد")); 26 | } 27 | const newUser = new User({ 28 | name : req.body.name , 29 | email : req.body.email , 30 | password : bcrypt.hashSync(req.body.password, 8) , 31 | }); 32 | 33 | await newUser.save(); 34 | done(null,newUser); 35 | } catch (error) { 36 | return done(error , false , {message : error}) 37 | } 38 | } 39 | 40 | )) 41 | 42 | passport.use('local.login' ,new localStrategy( 43 | { 44 | usernameField : 'email' , 45 | passwordField : 'password', 46 | passReqToCallback : true , 47 | } , async (req,email,password , done)=>{ 48 | try { 49 | let user = await User.findOne({email : req.body.email}); 50 | if(!user || !bcrypt.compareSync(req.body.password , user.password) ){ 51 | return done(null , false , req.flash('errors' , 'اطلاعات شما هماهنگی ندارد')); 52 | } 53 | done(null , user); 54 | } catch (error) { 55 | return done(error , false , {message : error}) 56 | } 57 | 58 | } )) -------------------------------------------------------------------------------- /30-payment/codes/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590666976914-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590666976914-profile.jpg -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667065506-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667065506-profile.jpg -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667068594-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667068594-profile.jpg -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667088561-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667088561-profile.jpg -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667238000-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667238000-profile.jpg -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667351445-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667351445-profile.jpg -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667863646-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667863646-New Text Document.txt -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667888025-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667888025-New Text Document.txt -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667898926-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667898926-profile.jpg -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/1590667903570-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/1590667903570-New Text Document.txt -------------------------------------------------------------------------------- /30-payment/codes/public/uploads/imgages/profile.jpg-1590666897127: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/uploads/imgages/profile.jpg-1590666897127 -------------------------------------------------------------------------------- /30-payment/codes/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/30-payment/codes/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /30-payment/codes/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const authController = require('controllers/authController'); 6 | 7 | //validators 8 | const authValidator = require('validators/authValidator'); 9 | 10 | router.use((req,res,next)=>{ 11 | if(req.isAuthenticated()){ 12 | return res.redirect('/dashboard'); 13 | } 14 | next(); 15 | }) 16 | 17 | router.get("/login", authController.loginForm ); 18 | router.get("/register", authController.registerForm ); 19 | 20 | 21 | router.post("/login", authValidator.login(), authController.login ); 22 | router.post("/register",authValidator.register(), authController.register ); 23 | 24 | 25 | 26 | module.exports = router; 27 | -------------------------------------------------------------------------------- /30-payment/codes/routes/dashboard.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const dashboardController = require('controllers/dashboardController'); 6 | const editUserValidator = require('validators/editUserValidator'); 7 | const uploadUserProfile = require('upload/uploadUserProfile'); 8 | 9 | router.use((req,res,next)=>{ 10 | if(req.isAuthenticated()){ 11 | return next(); 12 | } 13 | res.redirect('/'); 14 | }) 15 | 16 | router.get("/", dashboardController.index ); 17 | router.post("/pay", dashboardController.pay ); 18 | 19 | router.post("/edituser", uploadUserProfile.single('img') , (req,res,next)=>{ 20 | if(!req.file){ 21 | req.body.img = null 22 | }else{ 23 | req.body.img = req.file.filename; 24 | } 25 | next() 26 | } , editUserValidator.handle() , dashboardController.edituser ); 27 | 28 | 29 | 30 | 31 | 32 | module.exports = router; 33 | -------------------------------------------------------------------------------- /30-payment/codes/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | const homeController = require('controllers/homeController'); 5 | 6 | 7 | 8 | router.use('/user' , require('./user')) 9 | router.use('/auth' , require('./auth')) 10 | router.use('/dashboard' , require('./dashboard')) 11 | router.get('/paycallback' , homeController.paycallback) 12 | 13 | router.get('/logout' , (req,res)=>{ 14 | req.logout(); 15 | res.redirect('/'); 16 | }) 17 | 18 | 19 | router.all('*' , async (req,res,next)=>{ 20 | try{ 21 | let err = new Error('چنین صفحه ای یافت نشد '); 22 | err.status = 404; 23 | throw err; 24 | }catch(err){ 25 | next(err); 26 | } 27 | }); 28 | 29 | router.use( (err,req,res,next)=>{ 30 | const code = err.status || 500 ; 31 | const message = err.message || ""; 32 | const stack = err.stack || ""; 33 | 34 | if(config.debug){ 35 | return res.render('errors/developer' , {message , stack}) 36 | }else{ 37 | return res.render(`errors/${code}` , {message}); 38 | } 39 | }) 40 | 41 | 42 | 43 | 44 | module.exports = router; -------------------------------------------------------------------------------- /30-payment/codes/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /30-payment/codes/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | const passport = require('passport'); 9 | const MongoStore = require('connect-mongo')(session) 10 | require('app-module-path').addPath(__dirname); 11 | require('dotenv').config(); 12 | 13 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 14 | 15 | global.config = require('./config'); 16 | 17 | app.use(express.static(__dirname + "/public")); 18 | app.use(express.urlencoded({extended : false})); 19 | app.set('view engine' , 'ejs') ; 20 | app.use(methodOverride('method')); 21 | 22 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 23 | 24 | app.use(session({ 25 | secret: process.env.SESSION_SECRET , 26 | resave: true , 27 | saveUninitialized: true, 28 | cookie : {expires : new Date( Date.now() + 1000 * 3600 *24 * 100) }, 29 | store : new MongoStore({mongooseConnection : mongoose.connection }) 30 | })) 31 | 32 | 33 | 34 | app.use(flash()); 35 | 36 | require('./passport/passport-local'); 37 | app.use(passport.initialize()) 38 | app.use(passport.session()) 39 | 40 | 41 | 42 | app.use((req,res,next)=>{ 43 | res.locals = {errors: req.flash("errors"), req}; 44 | next(); 45 | }) 46 | app.get('/', (req,res)=>{ 47 | res.render('index'); 48 | }) 49 | 50 | 51 | app.use('/' , require('./routes/index')); 52 | 53 | app.listen( config.port , ()=>{ 54 | console.log(`server is running on port ${config.port}`); 55 | }) -------------------------------------------------------------------------------- /30-payment/codes/upload/uploadUserProfile.js: -------------------------------------------------------------------------------- 1 | const multer = require('multer'); 2 | const mkdir = require('mkdirp'); 3 | 4 | 5 | const storage = multer.diskStorage({ 6 | destination: function (req, file, cb) { 7 | mkdir('./public/uploads/imgages').then(made=>{ 8 | cb(null, './public/uploads/imgages'); 9 | }) 10 | }, 11 | filename: function (req, file, cb) { 12 | cb(null, Date.now() + '-' + file.originalname ) 13 | } 14 | }) 15 | 16 | const upload = multer({ storage: storage }); 17 | 18 | module.exports = upload; 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /30-payment/codes/validators/authValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | register(){ 6 | return [ 7 | check("name", "نام نمیتواند خالی باشد").not().isEmpty() , 8 | // username must be an email 9 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 10 | // password must be at least 5 chars long 11 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 12 | min: 5 13 | }) 14 | ] 15 | } 16 | 17 | login(){ 18 | return [ 19 | // username must be an email 20 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 21 | // password must be at least 5 chars long 22 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 23 | min: 5 24 | }) 25 | ] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /30-payment/codes/validators/editUserValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | const path = require('path'); 4 | 5 | module.exports = new class UserValidator extends validator { 6 | handle(){ 7 | return [ 8 | check("name", "نام نمیتواند خالی باشد").not().isEmpty(), 9 | check("img", "وجود تصویر الزامیست").not().isEmpty(), 10 | check("img").custom(async value=>{ 11 | if(!value){ 12 | return 13 | } 14 | if(!['.jpg','jpeg','.png'].includes(path.extname(value))){ 15 | throw new Error('پسوند فایل آپلود شده صحیح نیست') 16 | } 17 | }) 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /30-payment/codes/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /30-payment/codes/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /30-payment/codes/views/auth/login.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /30-payment/codes/views/auth/register.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 | <%- recaptcha %> 8 | 9 |
10 | -------------------------------------------------------------------------------- /30-payment/codes/views/components/validation-error.ejs: -------------------------------------------------------------------------------- 1 | <% if(errors.length){ %> 2 |
3 | 8 |
9 | <% } %> 10 | -------------------------------------------------------------------------------- /30-payment/codes/views/dashboard/index.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |

dashboard

4 |

hi <%= req.user.name %>

5 | 6 |
7 | 8 | 9 | 10 |
11 | 12 |
13 |

اعتبار حساب کاربری خود را به مقدار دلخواه افزایش دهید

14 | 15 | 16 |
17 | logout -------------------------------------------------------------------------------- /30-payment/codes/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /30-payment/codes/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /30-payment/codes/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /30-payment/codes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <% if(req.isAuthenticated()){ %> 7 | dashaboard 8 | <% }else{ %> 9 | register 10 | <% } %> 11 |

hello world

12 | 13 | 14 | -------------------------------------------------------------------------------- /30-payment/codes/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /30-payment/codes/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <%- include('components/validation-error') -%> 8 | <% if(message){ %> 9 |

<%= message %>

10 | <% } %> 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <% users.forEach(user=>{ %> 32 | 33 | 34 | 35 | 36 | 37 | 43 | 44 | <% }) %> 45 | 46 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 38 |
39 | 40 |
41 | update 42 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/.env: -------------------------------------------------------------------------------- 1 | 2 | COOKIE_SECRET= 'jsgaoijrg825w8gds2gddfs' 3 | SESSION_SECRET= 'asdfasdf65f6sdfwe' -------------------------------------------------------------------------------- /31-payment-emplement/codes/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | port : 3000 , 3 | debug : true , 4 | } -------------------------------------------------------------------------------- /31-payment-emplement/codes/controllers/authController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | const passport = require("passport"); 4 | var Recaptcha = require("express-recaptcha").RecaptchaV2; 5 | const options = { hl: "fa" }; 6 | const recaptcha = new Recaptcha( 7 | "6LffQv0UAAAAAPMCl2b8B1tgwXGHqzjNUMiUg7qf", 8 | "6LffQv0UAAAAAKydjq0fJc52IcsimzLaiEET8741", 9 | options 10 | ); 11 | const { validationResult } = require("express-validator"); 12 | 13 | class UserController extends controller { 14 | async registerForm(req, res, next) { 15 | try { 16 | res.render("auth/register", { recaptcha: recaptcha.render() }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async loginForm(req, res, next) { 23 | try { 24 | res.render("auth/login"); 25 | } catch (err) { 26 | next(err); 27 | } 28 | } 29 | 30 | async register(req, res, next) { 31 | try { 32 | // let recaptchaResult = await new Promise((resolve, reject) => { 33 | // recaptcha.verify(req, (err, data) => { 34 | // if (err) { 35 | // req.flash("errors", "تیک گزینه امنیتی را بزنید"); 36 | // res.redirect("/auth/register"); 37 | // resolve(false); 38 | // } else { 39 | // resolve(true); 40 | // } 41 | // }); 42 | // }); 43 | 44 | // if (!recaptchaResult) { 45 | // return; 46 | // } 47 | 48 | const errors = validationResult(req); 49 | if (!errors.isEmpty()) { 50 | let myErrors = errors.array().map((err) => err.msg); 51 | req.flash("errors", myErrors); 52 | return res.redirect("/auth/register"); 53 | } 54 | passport.authenticate("local.register", { 55 | successRedirect: "/dashboard", 56 | failureRedirect: "/auth/register", 57 | failureFlash: true, 58 | })(req, res, next); 59 | } catch (err) { 60 | next(err); 61 | } 62 | } 63 | 64 | async login(req, res, next) { 65 | try { 66 | const errors = validationResult(req); 67 | if (!errors.isEmpty()) { 68 | let myErrors = errors.array().map((err) => err.msg); 69 | req.flash("errors", myErrors); 70 | return res.redirect("/auth/login"); 71 | } 72 | passport.authenticate("local.login", (err, user) => { 73 | if (!user) return res.redirect("/auth/login"); 74 | 75 | req.logIn(user, (err) => { 76 | return res.redirect("/dashboard"); 77 | }); 78 | })(req, res, next); 79 | } catch (err) { 80 | next(err); 81 | } 82 | } 83 | } 84 | 85 | module.exports = new UserController(); 86 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Controller{ 4 | constructor(){ 5 | autoBind(this); 6 | } 7 | 8 | error(message , status = 500){ 9 | let err = new Error(message); 10 | err.status = status; 11 | throw err; 12 | } 13 | } 14 | 15 | module.exports = Controller; 16 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/controllers/dashboardController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | const Payment = require("./../models/payment"); 4 | 5 | const axios = require('axios'); 6 | 7 | const { validationResult } = require("express-validator"); 8 | 9 | module.exports = new (class dashboardController extends controller { 10 | async index(req, res, next) { 11 | try { 12 | res.render("dashboard/index"); 13 | } catch (err) { 14 | next(err); 15 | } 16 | } 17 | 18 | async pay(req, res, next) { 19 | try { 20 | let params = { 21 | MerchantID: "6cded376-3063-11e9-a98e-005056a205be" , 22 | Amount: req.body.amount , 23 | CallbackURL: "http://45.149.79.205/paycallback", 24 | Description: "افزایش اعتبار حساب کاربری ", 25 | }; 26 | 27 | const response = await axios.post( "https://www.zarinpal.com/pg/rest/WebGate/PaymentRequest.json" , params); 28 | console.log(response); 29 | if(response.data.Status == 100 ){ 30 | let newPayment = new Payment({ 31 | user : req.user.id , 32 | amount : req.body.amount , 33 | resnumber : response.data.Authority 34 | }) 35 | await newPayment.save(); 36 | res.redirect(`https://www.zarinpal.com/pg/StartPay/${response.data.Authority}`); 37 | }else res.redirect('/dashboard') 38 | 39 | } catch (err) { 40 | next(err); 41 | } 42 | } 43 | 44 | async edituser(req, res, next) { 45 | try { 46 | const errors = validationResult(req); 47 | if (!errors.isEmpty()) { 48 | let myErrors = errors.array().map((err) => err.msg); 49 | req.flash("errors", myErrors); 50 | return res.redirect("/dashboard"); 51 | } 52 | let data = { 53 | name: req.body.name, 54 | }; 55 | console.log(req.file.path); 56 | if (req.file) { 57 | data.img = req.file.path.replace(/\\/g, "/").substring(6); 58 | } 59 | 60 | await User.updateOne({ _id: req.user.id }, { $set: data }); 61 | res.redirect("/dashboard"); 62 | } catch (err) { 63 | next(err); 64 | } 65 | } 66 | })(); 67 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/controllers/homeController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | const Payment = require("./../models/payment"); 4 | const axios = require('axios'); 5 | 6 | 7 | const { validationResult } = require("express-validator"); 8 | 9 | module.exports = new class dashboardController extends controller { 10 | async paycallback(req, res, next) { 11 | try { 12 | // if(req.query.Status && req.query.Status !== "OK"){ 13 | // return res.send('تراکنش ناموفق'); 14 | // } 15 | let payment = await Payment.findOne({resnumber : req.query.Authority}); 16 | if(!payment) return res.send('همچین تراکنشی وجود ندارد'); 17 | let params = { 18 | MerchantID: "6cded376-3063-11e9-a98e-005056a205be" , 19 | Amount: payment.amount , 20 | Authority: req.query.Authority, 21 | }; 22 | 23 | const response = await axios.post( "https://www.zarinpal.com/pg/rest/WebGate/PaymentVerification.json" , params); 24 | if(response.data.Status != 100){ 25 | let balance = payment.amount; 26 | let user = await User.findById(payment.user); 27 | if(user.balance){ 28 | balance += user.balance; 29 | } 30 | user.balance = balance; 31 | payment.payment = true; 32 | await user.save(); 33 | await payment.save(); 34 | res.redirect('/dashboard'); 35 | 36 | }else{ 37 | return res.send('تراکنش ناموفق'); 38 | } 39 | 40 | 41 | } catch (err) { 42 | next(err); 43 | } 44 | } 45 | 46 | 47 | 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/controllers/userController.js: -------------------------------------------------------------------------------- 1 | let controller = require("./controller"); 2 | const User = require("./../models/user"); 3 | 4 | const { validationResult } = require("express-validator"); 5 | 6 | class UserController extends controller { 7 | async getAllUsers(req, res, next) { 8 | try { 9 | 10 | let users = await User.find({}); 11 | res.render("users", { 12 | users: users, 13 | title: "همه کاربران", 14 | errors: req.flash("errors"), 15 | message: req.flash("message") 16 | }); 17 | } catch (err) { 18 | next(err); 19 | } 20 | } 21 | 22 | async seeOneUser(req, res, next) { 23 | try { 24 | let user = await User.findById(req.params.id); 25 | if(!user){ 26 | this.error('چنین کاربری یافت نشد' , 404 ); 27 | } 28 | res.render("user", { user: user }); 29 | } catch (err) { 30 | next(err); 31 | } 32 | } 33 | 34 | async createUser(req, res, next) { 35 | try { 36 | const errors = validationResult(req); 37 | if (!errors.isEmpty()) { 38 | let myErrors = errors.array().map(err=>err.msg); 39 | req.flash("errors", myErrors); 40 | return res.redirect("/auth/login"); 41 | } 42 | 43 | req.body.id = parseInt(req.body.id); 44 | let newUser = new User({ 45 | email: req.body.email, 46 | first_name: req.body.first_name, 47 | password: req.body.password 48 | }); 49 | await newUser.save(); 50 | req.flash("message", "کاربر مورد نظر با موفقیت ایجاد شد"); 51 | return res.redirect("/user"); 52 | } catch (err) { 53 | next(err); 54 | } 55 | } 56 | 57 | async updateUser(req, res, next) { 58 | try { 59 | await User.updateMany({ _id: req.params.id }, { $set: req.body }); 60 | req.flash("message", "کاربر مورد نظر با موفقیت به روز رسانی شد شد"); 61 | return res.redirect("/user"); 62 | } catch (err) { 63 | next(err); 64 | } 65 | } 66 | 67 | async deleteUser(req, res, next) { 68 | try { 69 | } catch (err) { 70 | await User.deleteOne({ _id: req.params.id }); 71 | req.flash("message", "کاربر مورد نظر با موفقیت حذف شد"); 72 | return res.redirect("/user"); 73 | } 74 | } 75 | } 76 | 77 | module.exports = new UserController(); 78 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/models/payment.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | user : {type : Schema.Types.ObjectId , ref : 'User'} , 6 | resnumber : {type : String , required : true } , 7 | amount : {type : Number , required : true} , 8 | payment : {type : Boolean , default : false } 9 | }); 10 | 11 | module.exports = mongoose.model("Payment", userSchema , "Payment") ; 12 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | 4 | const userSchema = new Schema({ 5 | name : { type : String } , 6 | img : { type : String } , 7 | balance : {type : Number , default : 0 } , 8 | email : { type : String , required : true } , 9 | password : { type : String , required : true } 10 | }); 11 | 12 | module.exports = mongoose.model("User", userSchema , "User") ; 13 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodestart", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "nodemon server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "app-module-path": "^2.2.0", 14 | "auto-bind": "^4.0.0", 15 | "axios": "^0.19.2", 16 | "bcryptjs": "^2.4.3", 17 | "connect-flash": "^0.1.1", 18 | "connect-mongo": "^3.2.0", 19 | "cookie-parser": "^1.4.5", 20 | "dotenv": "^8.2.0", 21 | "ejs": "^3.0.1", 22 | "express": "^4.17.1", 23 | "express-recaptcha": "^5.0.1", 24 | "express-session": "^1.17.0", 25 | "express-validator": "^6.4.0", 26 | "method-override": "^3.0.0", 27 | "mkdirp": "^1.0.4", 28 | "mongoose": "^5.9.6", 29 | "multer": "^1.4.2", 30 | "passport": "^0.4.1", 31 | "passport-local": "^1.0.0" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/passport/passport-local.js: -------------------------------------------------------------------------------- 1 | const passport = require('passport'); 2 | const localStrategy = require('passport-local').Strategy; 3 | var bcrypt = require('bcryptjs'); 4 | const User = require('../models/user'); 5 | 6 | passport.serializeUser((user,done)=>{ 7 | done(null,user.id); 8 | }) 9 | 10 | passport.deserializeUser(async (id,done)=>{ 11 | let user = await User.findById(id); 12 | if(user) done(null,user); 13 | }) 14 | 15 | 16 | passport.use("local.register" , new localStrategy( 17 | { 18 | usernameField : 'email' , 19 | passwordField : 'password', 20 | passReqToCallback : true , 21 | } , async (req , email , passport , done)=>{ 22 | try { 23 | let user = await User.findOne({email : req.body.email}); 24 | if(user){ 25 | return done(null,false,req.flash('errors' , "چنین کاربری با این ایمیل وجود دارد")); 26 | } 27 | const newUser = new User({ 28 | name : req.body.name , 29 | email : req.body.email , 30 | password : bcrypt.hashSync(req.body.password, 8) , 31 | }); 32 | 33 | await newUser.save(); 34 | done(null,newUser); 35 | } catch (error) { 36 | return done(error , false , {message : error}) 37 | } 38 | } 39 | 40 | )) 41 | 42 | passport.use('local.login' ,new localStrategy( 43 | { 44 | usernameField : 'email' , 45 | passwordField : 'password', 46 | passReqToCallback : true , 47 | } , async (req,email,password , done)=>{ 48 | try { 49 | let user = await User.findOne({email : req.body.email}); 50 | if(!user || !bcrypt.compareSync(req.body.password , user.password) ){ 51 | return done(null , false , req.flash('errors' , 'اطلاعات شما هماهنگی ندارد')); 52 | } 53 | done(null , user); 54 | } catch (error) { 55 | return done(error , false , {message : error}) 56 | } 57 | 58 | } )) -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/css/style.css: -------------------------------------------------------------------------------- 1 | table{ 2 | border: 1px solid #444; 3 | 4 | } 5 | 6 | table td{ 7 | border: 1px solid #444; 8 | padding: 3px 5px; 9 | } 10 | 11 | div{ 12 | padding: 30px 10px; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590666976914-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590666976914-profile.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667065506-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667065506-profile.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667068594-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667068594-profile.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667088561-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667088561-profile.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667238000-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667238000-profile.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667351445-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667351445-profile.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667863646-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667863646-New Text Document.txt -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667888025-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667888025-New Text Document.txt -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667898926-profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667898926-profile.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1590667903570-New Text Document.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1590667903570-New Text Document.txt -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1615370873668-pythonmail.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1615370873668-pythonmail.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/1615370912540-bootresponsive.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/1615370912540-bootresponsive.jpg -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/uploads/imgages/profile.jpg-1590666897127: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/uploads/imgages/profile.jpg-1590666897127 -------------------------------------------------------------------------------- /31-payment-emplement/codes/public/video/letitsnow.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohamad-sw/node/2d5ad3a62776ff1ff1140c41f3b0feb7aaf67d9e/31-payment-emplement/codes/public/video/letitsnow.mp4 -------------------------------------------------------------------------------- /31-payment-emplement/codes/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const authController = require('controllers/authController'); 6 | 7 | //validators 8 | const authValidator = require('validators/authValidator'); 9 | 10 | router.use((req,res,next)=>{ 11 | if(req.isAuthenticated()){ 12 | return res.redirect('/dashboard'); 13 | } 14 | next(); 15 | }) 16 | 17 | router.get("/login", authController.loginForm ); 18 | router.get("/register", authController.registerForm ); 19 | 20 | 21 | router.post("/login", authValidator.login(), authController.login ); 22 | router.post("/register",authValidator.register(), authController.register ); 23 | 24 | 25 | 26 | module.exports = router; 27 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/routes/dashboard.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const dashboardController = require('controllers/dashboardController'); 6 | const editUserValidator = require('validators/editUserValidator'); 7 | const uploadUserProfile = require('upload/uploadUserProfile'); 8 | 9 | router.use((req,res,next)=>{ 10 | if(req.isAuthenticated()){ 11 | return next(); 12 | } 13 | res.redirect('/'); 14 | }) 15 | 16 | router.get("/", dashboardController.index ); 17 | router.post("/pay", dashboardController.pay ); 18 | 19 | router.post("/edituser", uploadUserProfile.single('img') , (req,res,next)=>{ 20 | if(!req.file){ 21 | req.body.img = null 22 | }else{ 23 | req.body.img = req.file.filename; 24 | } 25 | next() 26 | } , editUserValidator.handle() , dashboardController.edituser ); 27 | 28 | 29 | 30 | 31 | 32 | module.exports = router; 33 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | const homeController = require('controllers/homeController'); 5 | 6 | 7 | 8 | router.use('/user' , require('./user')) 9 | router.use('/auth' , require('./auth')) 10 | router.use('/dashboard' , require('./dashboard')) 11 | router.get('/paycallback' , homeController.paycallback) 12 | 13 | router.get('/logout' , (req,res)=>{ 14 | req.logout(); 15 | res.redirect('/'); 16 | }) 17 | 18 | 19 | router.all('*' , async (req,res,next)=>{ 20 | try{ 21 | let err = new Error('چنین صفحه ای یافت نشد '); 22 | err.status = 404; 23 | throw err; 24 | }catch(err){ 25 | next(err); 26 | } 27 | }); 28 | 29 | router.use( (err,req,res,next)=>{ 30 | const code = err.status || 500 ; 31 | const message = err.message || ""; 32 | const stack = err.stack || ""; 33 | 34 | if(config.debug){ 35 | return res.render('errors/developer' , {message , stack}) 36 | }else{ 37 | return res.render(`errors/${code}` , {message}); 38 | } 39 | }) 40 | 41 | 42 | 43 | 44 | module.exports = router; -------------------------------------------------------------------------------- /31-payment-emplement/codes/routes/user.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | //controllers 5 | const userController = require('controllers/userController'); 6 | 7 | //validators 8 | const userValidator = require('validators/userValidator'); 9 | 10 | router.get("/", userController.getAllUsers ); 11 | router.get("/:id", userController.seeOneUser); 12 | router.post( "/", userValidator.handle() , userController.createUser ); 13 | router.put("/:id", userController.updateUser ); 14 | router.delete("/:id", userController.deleteUser ); 15 | 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | const methodOverride = require('method-override') 4 | const cookieParser = require('cookie-parser') 5 | const session = require('express-session') 6 | const flash = require('connect-flash'); 7 | const mongoose = require('mongoose'); 8 | const passport = require('passport'); 9 | const MongoStore = require('connect-mongo')(session) 10 | require('app-module-path').addPath(__dirname); 11 | require('dotenv').config(); 12 | 13 | mongoose.connect('mongodb://localhost:27017/nodestart', {useNewUrlParser: true, useUnifiedTopology: true}); 14 | 15 | global.config = require('./config'); 16 | 17 | app.use(express.static(__dirname + "/public")); 18 | app.use(express.urlencoded({extended : false})); 19 | app.set('view engine' , 'ejs') ; 20 | app.use(methodOverride('method')); 21 | 22 | app.use(cookieParser(process.env.COOKIE_SECRET)) ; 23 | 24 | app.use(session({ 25 | secret: process.env.SESSION_SECRET , 26 | resave: true , 27 | saveUninitialized: true, 28 | cookie : {expires : new Date( Date.now() + 1000 * 3600 *24 * 100) }, 29 | store : new MongoStore({mongooseConnection : mongoose.connection }) 30 | })) 31 | 32 | 33 | 34 | app.use(flash()); 35 | 36 | require('./passport/passport-local'); 37 | app.use(passport.initialize()) 38 | app.use(passport.session()) 39 | 40 | 41 | 42 | app.use((req,res,next)=>{ 43 | res.locals = {errors: req.flash("errors"), req}; 44 | next(); 45 | }) 46 | app.get('/', (req,res)=>{ 47 | res.render('index'); 48 | }) 49 | 50 | 51 | app.use('/' , require('./routes/index')); 52 | 53 | app.listen( config.port , ()=>{ 54 | console.log(`server is running on port ${config.port}`); 55 | }) -------------------------------------------------------------------------------- /31-payment-emplement/codes/upload/uploadUserProfile.js: -------------------------------------------------------------------------------- 1 | const multer = require('multer'); 2 | const mkdir = require('mkdirp'); 3 | 4 | 5 | const storage = multer.diskStorage({ 6 | destination: function (req, file, cb) { 7 | mkdir('./public/uploads/imgages').then(made=>{ 8 | cb(null, './public/uploads/imgages'); 9 | }) 10 | }, 11 | filename: function (req, file, cb) { 12 | cb(null, Date.now() + '-' + file.originalname ) 13 | } 14 | }) 15 | 16 | const upload = multer({ storage: storage }); 17 | 18 | module.exports = upload; 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/validators/authValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | register(){ 6 | return [ 7 | check("name", "نام نمیتواند خالی باشد").not().isEmpty() , 8 | // username must be an email 9 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 10 | // password must be at least 5 chars long 11 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 12 | min: 5 13 | }) 14 | ] 15 | } 16 | 17 | login(){ 18 | return [ 19 | // username must be an email 20 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 21 | // password must be at least 5 chars long 22 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 23 | min: 5 24 | }) 25 | ] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/validators/editUserValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | const path = require('path'); 4 | 5 | module.exports = new class UserValidator extends validator { 6 | handle(){ 7 | return [ 8 | check("name", "نام نمیتواند خالی باشد").not().isEmpty(), 9 | check("img", "وجود تصویر الزامیست").not().isEmpty(), 10 | check("img").custom(async value=>{ 11 | if(!value){ 12 | return 13 | } 14 | if(!['.jpg','jpeg','.png'].includes(path.extname(value))){ 15 | throw new Error('پسوند فایل آپلود شده صحیح نیست') 16 | } 17 | }) 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/validators/userValidator.js: -------------------------------------------------------------------------------- 1 | const validator = require('./validator'); 2 | const { check } = require("express-validator"); 3 | 4 | module.exports = new class UserValidator extends validator { 5 | handle(){ 6 | return [ 7 | // username must be an email 8 | check("email", "فرمت ایمیل صحیح نست").isEmail(), 9 | // password must be at least 5 chars long 10 | check("password", "طول پسورد بایستی حداقل 5 کاراکتر باشد").isLength({ 11 | min: 5 12 | }) 13 | ] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/validators/validator.js: -------------------------------------------------------------------------------- 1 | const autoBind = require('auto-bind'); 2 | 3 | class Validator{ 4 | constructor(){ 5 | 6 | autoBind(this); 7 | } 8 | } 9 | 10 | module.exports = Validator; 11 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/auth/login.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 |
8 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/auth/register.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |
4 | 5 | 6 | 7 | <%- recaptcha %> 8 | 9 |
10 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/components/validation-error.ejs: -------------------------------------------------------------------------------- 1 | <% if(errors.length){ %> 2 |
3 | 8 |
9 | <% } %> 10 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/dashboard/index.ejs: -------------------------------------------------------------------------------- 1 | <%- include('../components/validation-error') -%> 2 | 3 |

dashboard

4 |

hi <%= req.user.name %>

5 | 6 |
7 | 8 | 9 | 10 |
11 |

اعتبار کنونی شما <%= req.user.balance %>

12 |
13 |

اعتبار حساب کاربری خود را به مقدار دلخواه افزایش دهید

14 | 15 | 16 |
17 | logout -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/errors/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

چنین صفحه ای یافت نشد

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/errors/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

ارور از سمت سرور

11 |

<%= message %>

12 | 13 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/errors/developer.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 |

12 | <%= message %> 13 |

14 |
15 |         <%= stack %>
16 |     
17 | 18 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <% if(req.isAuthenticated()){ %> 7 | dashaboard 8 | <% }else{ %> 9 | register 10 | <% } %> 11 |

hello world

12 | 13 | 14 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/user.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | -------------------------------------------------------------------------------- /31-payment-emplement/codes/views/users.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | <%- include('components/validation-error') -%> 8 | <% if(message){ %> 9 |

<%= message %>

10 | <% } %> 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | <% users.forEach(user=>{ %> 32 | 33 | 34 | 35 | 36 | 37 | 43 | 44 | <% }) %> 45 | 46 |
idfirst_nameemailpasswordoperation
<%= user.id %><%= user.first_name %><%= user.email %><%= user.password %> 38 |
39 | 40 |
41 | update 42 |
47 | 48 | 49 | --------------------------------------------------------------------------------