Skip to content

Commit

Permalink
added backend api methods createUser and login for new user to get token
Browse files Browse the repository at this point in the history
  • Loading branch information
vijay authored and vijay committed Apr 6, 2023
1 parent 2876fbc commit 737a485
Show file tree
Hide file tree
Showing 7 changed files with 153 additions and 36 deletions.
3 changes: 2 additions & 1 deletion pettopia-backend/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ app.use('/api/v1/products', require('./routes/product.routes'))
app.use('/api/v1/cart', require('./routes/cart.routes'))
app.use('/api/v1/favorites', require('./routes/favorites.routes'))
app.use('/api/v1/test', require('./routes/test.routes'))
app.use('/api/v1/user', require('./routes/user.routes'))
app.use('/api/v1/auth', require('./routes/auth.routes'))
// unused routes
app.use('/api/v1/orders', require('./routes/order.routes'))
app.use('/api/v1/clients', require('./routes/client.routes'))
app.use('/api/v1/users', require('./routes/user.routes'))
app.use('/api/v1/roles', require('./routes/role.routes'))
app.use('/api/v1/auth', require('./routes/auth.routes'))



Expand Down
8 changes: 6 additions & 2 deletions pettopia-backend/src/controllers/auth/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

CTRL.login = (req, res) => {
User.findOne({ username: req.body.username }, (err, user) => {
console.log(req.body.email)
// User.findOne({email:req.body.email})
// .then(user =>{
// console.log(`${JSON.stringify(user)}`)
// })
User.findOne({ email: req.body.email }, (err, user) => {
if (err) {
return res.status(500).json({
ok: false,
Expand Down Expand Up @@ -35,7 +40,6 @@ CTRL.login = (req, res) => {

return res.status(201).json({
ok: true,
user,
token,
});
});
Expand Down
49 changes: 27 additions & 22 deletions pettopia-backend/src/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,31 +36,36 @@ CTRL.getUser = (req, res) => {
});
};

CTRL.createUser = (req, res) => {
const newUser = new User({
displayName: req.body.displayName,
email: req.body.email,
username: req.body.username,
password: bcrypt.hashSync(req.body.password, 10),
avatar: req.body.avatar,
role: req.body.role,
status: req.body.status
});

console.log(newUser);
newUser.save((err, user) => {
if (err) {
return res.status(500).json({
ok: false,
err,
});
CTRL.createUser = async (req, res) => {
try{
const { email, password, username} = req.body;
console.log(`${email}, ${password}, ${username}`);
if (!(email && password && username)) {
res.status(400).send("All input is required");
}
// check if user already exist
// Validate if user exist in our database
const oldUser = await User.findOne({ email });

return res.status(201).json({
ok: true,
user,
if (oldUser) {
return res.status(409).send("User Already Exist. Please Login");
}
//Encrypt user password
encryptedPassword = await bcrypt.hash(password, 10);
// Create user in our database
const user = await User.create({
username:username,
email: email.toLowerCase(), // sanitize: convert email to lowercase
password: encryptedPassword,
});
});

res.status(201).json(user);
} catch (err) {
console.log(err);
res.status(500).json({
err: err});
}

};

CTRL.updateUser = (req, res) => {
Expand Down
22 changes: 13 additions & 9 deletions pettopia-backend/src/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const Schema = mongoose.Schema;
const UserSchema = new Schema({
displayName: {
type: String,
required: true,
//required: true,
},
email: {
type: String,
Expand All @@ -25,18 +25,22 @@ const UserSchema = new Schema({
type: String,
maxlength: 512,
},
role: {
type: Schema.Types.ObjectId,
ref: 'Role',
},
status: {
type: Boolean,
default: true,
},
// role: {
// type: Schema.Types.ObjectId,
// ref: 'Role',
// },
// status: {
// type: Boolean,
// default: true,
// },
created_at: {
type: Date,
default: Date.now,
},
});

UserSchema.pre('save', (next) => {
this.displayName = this.username; // considering _id is input by client
next();
})
module.exports = mongoose.model("User", UserSchema);
2 changes: 1 addition & 1 deletion pettopia-backend/src/routes/user.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { isAuth } = require('../middlewares/authentication')

router.get('/', userCTRL.getUsers)
router.get('/:userId', userCTRL.getUser)
router.post('/', isAuth, userCTRL.createUser)
router.post('/', userCTRL.createUser)
router.put('/:userId', isAuth, userCTRL.updateUser)
router.delete('/:userId', isAuth, userCTRL.deleteUser)

Expand Down
13 changes: 12 additions & 1 deletion pettopia-frontend/src/components/authentication/Signup.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,18 @@ export default function Signup(){

//handle Signup API Integration here
const createAccount=()=>{

let signUpFields = {
username:signupState['username'],
email:signupState['email'],
password:signupState['password']
}
fetch('https://pettopia-backend.onrender.com/api/v1/user', {
method:'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(signUpFields)
})
.then((res) => res.json())
.then(data => console.log(data.token));
}

return(
Expand Down
92 changes: 92 additions & 0 deletions pettopia-frontend/src/utilities/Forms.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
class Form {

/**
* Validate Login
* @param str
* @returns boolean
*/
static validEmail(str) {
let regex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
return regex.test(str);
}

/**
* Minimum length of string
* @param str
* @param length
* @returns
*/
static minLength(str, length) {
let isInvalid = false;

if (str.length < length) {
isInvalid = true;
}

return isInvalid;
}

/**
* Form Validator
* @param obj
* @returns
*/
static validator(obj) {
let keys = Object.entries(obj);
let results = [];
let validations = null;

keys.map((key) => {
if ('isRequired' in key[1] && key[1].isRequired) {
if (key[1].value.length === 0) {
results.push({
[key[0]]: [`The ${key[0]} is required.`]
});
} else {
if ('isEmail' in key[1] && key[1].isEmail) {
let isValidEmail = Form.validEmail(key[1].value);

if (!isValidEmail) {
results.push({
[key[0]]: [`The ${key[0]} must be valid email.`]
});
}
}

if ('minLength' in key[1] && Form.minLength(key[1].value, key[1].minLength)) {
results.push({
[key[0]]: [`The ${key[0]} must at least ${key[1].minLength} characters.`]
});
}
}
} else if ('isEmail' in key[1]) {
let isValidEmail = Form.validEmail(key[1].value);

if (!isValidEmail) {
results.push({
[key[0]]: [`The ${key[0]} must be valid email`]
});
}
} else if ('minLength' in key[1] && Form.minLength(key[1].value, key[1].minLength)) {
results.push({
[key[0]]: [`The ${key[0]} must at least ${key[1].minLength} characters.`]
});
}
return results
})

results = Object.assign({}, ...results.map((result) => result))

if (Object.keys(results).length > 0) {
validations = {
errors: results
}
} else {
validations = null
}

return validations;
}
}

export default Form

0 comments on commit 737a485

Please sign in to comment.