Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validasi body #13

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions controllers/v1/crowdfundings.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,19 @@ module.exports = {
},
crowdfundingsEdit: async (req, res) => {
try {
if (!req.params.id) res.status(400).json({ message: "Id Required" });

if (!req.body) res.status(400).json({ message: "body Required" });

const crowd = await Crowd.findOneAndUpdate(
{ _id: req.params.id },
req.body
req.body,
{ new: true }
);

res.send({ crowd, msg: "Berhasil diubah!" });
} catch (error) {
res.send(error);
res.status(400).json({ message: error });
}
},
};
2 changes: 2 additions & 0 deletions controllers/v1/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ module.exports = {

login: async (req, res) => {
try {
if (!req.body.email || !req.body.password)
res.status(400).json({ message: "Please Input Email/Password" });
const user = await User.cekUser(req.body.email, req.body.password);
const token = await user.generateAuthToken();

Expand Down
27 changes: 17 additions & 10 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const jwt = require("jsonwebtoken");
const { HttpStatusCode } = require("../constant/httpStatusCodes");
const User = require("../models/user");

const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer ', '');
const decoded = jwt.verify(token, process.env.SECRET);
const user = await User.findOne({ _id: decoded._id, 'tokens.token': token });
const header = req.header("Authorization");
const token = header.split(" ");

if (!user) {
throw new Error('User tidak ditemukan!');
}
if (token[0] != "Bearer") throw new Error("Invalid Format");

const decoded = jwt.verify(token[1], process.env.SECRET);
const user = await User.findOne({
_id: decoded._id,
"tokens.token": token,
});

if (!user) throw new Error("User Not Found");

req.token = token;
req.user = user;

next();
} catch (error) {
res.status(401).send({ message: 'Anda belum login!' });
} catch (err) {
// res.status(401).send({ message: "Anda Belum Login" });
next({ status: HttpStatusCode.FORBIDDEN });
}
};

Expand Down
8 changes: 4 additions & 4 deletions models/crowdfundings.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const mongoose = require('mongoose');
const mongoose = require("mongoose");

const crowdfundingsSchema = new mongoose.Schema({
title: {
type: String,
required: true,
required: [true, "Must Have Title"],
trim: true,
},
category: {
type: String,
required: true,
required: [true, "Must Have Category"],
trim: true,
},
thumbnail: {
Expand Down Expand Up @@ -42,6 +42,6 @@ const crowdfundingsSchema = new mongoose.Schema({
},
});

const Crowdfundings = mongoose.model('crowdfundings', crowdfundingsSchema);
const Crowdfundings = mongoose.model("crowdfundings", crowdfundingsSchema);

module.exports = Crowdfundings;
36 changes: 19 additions & 17 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,41 @@
const mongoose = require('mongoose');
const bcryptjs = require('bcryptjs');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const mongoose = require("mongoose");
const bcryptjs = require("bcryptjs");
const validator = require("validator");
const jwt = require("jsonwebtoken");

const userSchema = new mongoose.Schema({
nama: {
name: {
type: String,
required: true,
required: [true, "User Must Have Name"],
trim: true,
},
email: {
type: String,
required: true,
unique: true,
required: [true, "User Must Have Email"],
unique: [true, "Email Already Exist"],
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw { message: 'Email tidak sah!' };
throw { message: "Email tidak sah!" };
}
},
},
password: {
type: String,
required: true,
required: [true, "User Must Have Password"],
trim: true,
validate(value) {
if (!validator.isLength(value, { min: 6 })) {
throw { message: 'Password minimal 6 karakter!' };
throw { message: "Password minimal 6 karakter!" };
}
},
},
tokens: [
{
token: {
type: String,
required: true,
required: [true, "Please Give The Token"],
},
},
],
Expand All @@ -52,29 +52,31 @@ userSchema.methods.generateAuthToken = async function () {
};

userSchema.statics.cekUser = async (email, pass) => {
if (!validator.isEmail(email)) throw { message: "Email Not Valid!" };

const user = await User.findOne({ email });

if (!user) {
throw { message: 'Email sudah terdaftar!' };
throw { message: "Email sudah terdaftar!" };
}

const matchPass = await bcryptjs.compare(pass, user.password);
if (!matchPass) {
throw { message: 'Password salah!' };
throw { message: "Password salah!" };
}
return user;
};

userSchema.pre('save', async function (next) {
userSchema.pre("save", async function (next) {
const user = this;

if (user.isModified('password')) {
if (user.isModified("password")) {
user.password = await bcryptjs.hash(user.password, 8);
}

next();
});

const User = mongoose.model('User', userSchema);
const User = mongoose.model("User", userSchema);

module.exports = User;