├── .gitignore.bak ├── routes └── authRoutes.js ├── schemas └── userSchema.js ├── package.json ├── app.js ├── controllers └── authController.js └── .gitignore /.gitignore.bak: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /routes/authRoutes.js: -------------------------------------------------------------------------------- 1 | import express from 'express' 2 | import { login, register } from '../controllers/authController.js' 3 | 4 | const router = express.Router(); 5 | 6 | router.post('/login', login); 7 | 8 | router.post('/register', register); 9 | 10 | export default router; -------------------------------------------------------------------------------- /schemas/userSchema.js: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose' 2 | 3 | const userSchema = mongoose.Schema({ 4 | email: { 5 | type: String, 6 | required: true 7 | }, 8 | password: { 9 | type: String, 10 | required: true 11 | } 12 | }) 13 | 14 | export default mongoose.model('User', userSchema); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "server", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "bcrypt": "^5.1.0", 14 | "cors": "^2.8.5", 15 | "dotenv": "^16.0.3", 16 | "express": "^4.18.2", 17 | "jsonwebtoken": "^9.0.0", 18 | "mongoose": "^6.8.1", 19 | "nodemon": "^2.0.20", 20 | "validator": "^13.7.0" 21 | }, 22 | "type": "module" 23 | } 24 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | import * as dotenv from 'dotenv' 2 | import express from 'express' 3 | import cors from 'cors' 4 | import mongoose from 'mongoose' 5 | import authRouter from './routes/authRoutes.js' 6 | 7 | dotenv.config(); 8 | const PORT = process.env.PORT || 3000; 9 | 10 | const app = express(); 11 | 12 | mongoose.set("strictQuery", false); 13 | // mongoose.connect("mongodb://127.0.0.1:27017/auth", () => console.log("Connected to MongoDB")); 14 | mongoose.connect(`mongodb+srv://ahkar33:A09599m376*@auth.deuhhaf.mongodb.net/?retryWrites=true&w=majority`, () => { 15 | console.log("Connected to MongoDB"); 16 | }); 17 | 18 | // app.use(cors({ 19 | // origin: 'http://localhost:5173' 20 | // })) 21 | 22 | app.use(cors()) 23 | 24 | app.use(express.json()); 25 | 26 | app.get('/', (req, res) => { 27 | res.status(200).json({message: 'hello world'}); 28 | }) 29 | 30 | app.use('/auth', authRouter); 31 | 32 | app.listen(PORT, () => console.log(`server is running on port ${PORT}`)); 33 | 34 | -------------------------------------------------------------------------------- /controllers/authController.js: -------------------------------------------------------------------------------- 1 | import * as dotenv from 'dotenv' 2 | import User from '../schemas/userSchema.js' 3 | import bcrypt from 'bcrypt' 4 | import validator from 'validator' 5 | import jwt from 'jsonwebtoken' 6 | 7 | dotenv.config(); 8 | 9 | const saltRounds = parseInt("10"); 10 | 11 | export const login = async (req, res) => { 12 | const { email, password } = req.body; 13 | if (!email || !password) { 14 | return res.status(400).json({ message: 'Both Email and Password are required.' }); 15 | } 16 | const user = await User.findOne({ email: email }); 17 | if(user == null) { 18 | return res.status(401).json({ message: 'Email or Password incorrect' }); 19 | } 20 | const isPasswordMatch = bcrypt.compareSync(password, user.password); 21 | if (!isPasswordMatch) { 22 | return res.status(401).json({ message: 'Email or Password incorrect' }); 23 | } 24 | const accessToken = jwt.sign( 25 | { id: user.id, email: user.email }, 26 | "234kjf(*)ui234r-09i<.,jfo;.2j3ljrlej02934o0wdhjlaosdjf[q2039845uodfja;lkdjf", 27 | { expiresIn: '3d' } 28 | ); 29 | return res.status(200).json({ user: { id: user.id, email: user.email }, accessToken: accessToken }); 30 | } 31 | 32 | export const register = async (req, res) => { 33 | const { email, password } = req.body; 34 | if (!email || !password) { 35 | return res.status(400).json({ message: 'Both Email and Password are required.' }); 36 | } 37 | if (!validator.isEmail(email)) { 38 | return res.status(400).json({ message: 'Invalid Email.' }); 39 | } 40 | const isUserExist = await User.findOne({ email: email }); 41 | if (isUserExist) { 42 | return res.status(400).json({ message: 'User already Exists' }); 43 | } 44 | if (!validator.isStrongPassword(password)) { 45 | return res.status(400).json({ message: 'Password not strong enough.' }); 46 | } 47 | const hashPassword = bcrypt.hashSync(password, saltRounds); 48 | const user = new User({ 49 | email: email, 50 | password: hashPassword 51 | }); 52 | try { 53 | await user.save(); 54 | } 55 | catch (err) { 56 | return res.status(500).json({ error: err.message }); 57 | } 58 | res.status(201).json({ message: 'Registered Successfully' }); 59 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* --------------------------------------------------------------------------------