Skip to content
Snippets Groups Projects
Commit 0e111d29 authored by Kirby, Matt J (UG - Comp Sci & Elec Eng)'s avatar Kirby, Matt J (UG - Comp Sci & Elec Eng)
Browse files

Merge branch '24-create-endpoint-for-user-registration' into 'main'

Create endpoint for user-registration

See merge request !9
parents 1ae36797 320aa7af
No related branches found
No related tags found
1 merge request!9Create endpoint for user-registration
Showing
with 3854 additions and 1 deletion
node_modules
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/.pnp
.pnp.js
/node_modules
.config.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
FROM node:latest as base
# Create app directory
WORKDIR /user-service/app
COPY package*.json ./
RUN npm install
# Bundle app source
COPY . .
EXPOSE 9000
CMD [ "npm", "run", "start" ]
\ No newline at end of file
export default {
JWT_SECRET : "yB/uX5KdyjHN9P34IE49HxAcrlQ4gfvpVJEzGbo5E/I="
}
\ No newline at end of file
import UserModel from '../model/User.model.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import ENV from '../config.js'
// Middleware
export async function verifyUser(req,res, next){
try{
const { username } = req.method == 'GET' ? req.query : req.body;
// Check if user exists
let exist = await UserModel.findOne( {username } );
if(!exist) return res.status(404).send({ error: "Can't find User"});
next();
} catch (error) {
return res.status(404).send({ error: "Authentication Error"})
}
}
/** POST: http://localhost:8080/api/register
* @param : {
"username" : "example123",
"password" : "admin123",
"email": "example@gmail.com",
"profile": ""
}
*/
export async function register(req,res){
try {
const { username, password, profile, email } = req.body;
// Checking existing Username
const existUsername = new Promise((resolve, reject) => {
UserModel.findOne({ username }, function(err, user){
if(err) reject(new Error(err))
if(user) reject({ error : "Please use unique username"});
resolve();
})
});
// Checking existing Email
const existEmail = new Promise((resolve, reject) => {
UserModel.findOne({ email }, function(err, email){
if(err) reject(new Error(err))
if(email) reject({ error : "Please use unique Email"});
resolve();
})
});
Promise.all([existUsername, existEmail])
.then(() => {
if(password){
bcrypt.hash(password, 10)
.then( hashedPassword => {
const user = new UserModel({
username,
password: hashedPassword,
profile: profile || '',
email
});
// return save result as a response
user.save()
.then(result => res.status(201).send({ msg: "User Registered Successfully"}))
.catch(error => res.status(500).send({error}))
}).catch(error => {
return res.status(500).send({
error : "Enable to hash password"
})
})
}
}).catch(error => {
return res.status(500).send({ error })
})
} catch (error) {
return res.status(500).send(error);
}
}
/** POST: http://localhost:8080/api/login
* @param: {
"username" : "example123",
"password" : "admin123"
}
*/
export async function login(req,res){
const { username, password } = req.body;
try {
UserModel.findOne({ username })
.then(user => {
bcrypt.compare(password, user.password)
.then(passwordCheck => {
if(!passwordCheck) return res.status(400).send({ error: "Don't have Password"});
// create jwt token
const token = jwt.sign({
userId: user._id,
username : user.username
}, ENV.JWT_SECRET , { expiresIn : "24h"});
return res.status(200).send({
msg: "Login Successful...!",
username: user.username,
token
});
})
.catch(error =>{
return res.status(400).send({ error: "Password does not Match"})
})
})
.catch( error => {
return res.status(404).send({ error : "Username not Found"});
})
} catch (error) {
return res.status(500).send({ error});
}
}
export async function getUser(req,res){
const { username } = req.params;
try {
if(!username) return res.status(401).send({error: "Invalid Username"});
UserModel.findOne({username}, function(err, user){
if(err) return res.status(500).send({err});
if(!user) return res.status(501).send({ error: "Couldn't find the User"});
const { password, ...rest } = Object.assign({}, user.toJSON());
return res.status(201).send(rest)
})
}catch(err) {
return res.status(404).send({ error: "Cannot find User Data"});
}
}
/** PUT: http://localhost:8080/api/updateuser
*
. * @param: {
"header" : "<token>"
}
body: {
firstName: '',
address : '',
profile : ''
}
*/
export async function updateUser(req,res){
try {
const {userId} = req.user;
if(userId){
const body = req.body;
// update the data
UserModel.updateOne({ _id : userId }, body, function(err, data){
if(err) throw err;
return res.status(201).send({ msg : "Record Updated...!"});
})
}else{
return res.status(401).send({ error : "User Not Found...!"});
}
} catch (error) {
return res.status(401).send({ error });
}
}
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";
async function connect(){
// const mongod = await MongoMemoryServer.create();
// const getUri = mongod.getUri();
const uri = process.env.MONGO_URI
console.log(uri)
const db = await mongoose.connect(uri);
console.log("Database Connected")
return db;
}
export default connect;
\ No newline at end of file
import jwt from 'jsonwebtoken';
import ENV from '../config.js'
export default async function Auth(req, res, next){
try {
const token = req.headers.authorization.split(" ")[1];
const decodedToken = await jwt.verify(token, ENV.JWT_SECRET);
req.user = decodedToken;
next();
} catch (error) {
res.status(401).json({ error : "Authentication Failed!"})
}
}
\ No newline at end of file
import mongoose from "mongoose";
export const UserSchema = new mongoose.Schema({
username : {
type: String,
required : [true, "Please provide unique Username"],
unique: [true, "Username Exist"]
},
password: {
type: String,
required: [true, "Please provide a password"],
unique : false,
},
email: {
type: String,
required : [true, "Please provide a unique email"],
unique: true,
},
firstName: { type: String},
lastName: { type: String},
mobile : { type : Number},
profile: { type: String}
});
export default mongoose.model.Users || mongoose.model('User', UserSchema);
\ No newline at end of file
This diff is collapsed.
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.0",
"cors": "^2.8.5",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",
"mongodb-memory-server": "^8.10.2",
"mongoose": "^6.8.0",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"nodemon": "^2.0.21"
}
}
import { Router } from "express";
import * as controller from '../controllers/appController.js';
import Auth from '../middleware/auth.js';
const router = Router();
/** POST Methods */
router.route('/register').post(controller.register); // Register
router.route('/login').post(controller.verifyUser, controller.login); // Login
/** GET Methods */
router.route('/user/:username').get(controller.getUser); // GetUser
/** PUT Methods */
router.route('/updateuser').put(Auth, controller.updateUser); // is use to update the user profile
export default router;
\ No newline at end of file
import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import connect from './database/conn.js'
import router from './router/route.js'
const app = express();
app.use(express.json());
app.use(cors());
app.use(morgan('tiny'));
app.disable('x-powered-by');
const port = 9000;
// HTTP GET
app.get('/', (req, res) => {
res.status(201).json("Home GET Request")
});
// API Routes
app.use('/api', router)
// Start server only when we have valid connection
connect().then(() => {
try {
app.listen(port, () => {
console.log(`Server connected to http://localhost:${port}`);
})
} catch (error) {
console.log('Cannot connect to the server')
}
}).catch(error => {
console.log("Invalid database connection...!");
})
\ No newline at end of file
......@@ -10,9 +10,31 @@ services:
environment:
- MONGO_URI=mongodb://feed-mongo:27017/
mongo:
user-service:
build:
context: './backend-services/user-service'
dockerfile: Dockerfile
restart: unless-stopped
ports:
- "9002:9000"
environment:
- MONGO_URI=mongodb://user-mongo:27017/userdb
feed-mongo:
image: mongo
container_name: feed-mongo
ports:
- "27017:27017"
user-mongo:
image: mongo
container_name: user-mongo
volumes:
- "./mongo/db:/data/db"
ports:
- "27018:27017"
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment