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

Remove errors from the user api #121

Open
wants to merge 1 commit into
base: master
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
22 changes: 14 additions & 8 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,23 @@ var http = require('http'),
errorhandler = require('errorhandler'),
mongoose = require('mongoose');

const connectDB = require('./config/db');

var isProduction = process.env.NODE_ENV === 'production';

// Create global app object
var app = express();

// Connect Database
connectDB();


app.use(cors());

// Normal express config defaults
app.use(require('morgan')('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json({ extended: false }));
// app.use(bodyParser.json());

app.use(require('method-override')());
app.use(express.static(__dirname + '/public'));
Expand All @@ -30,12 +36,12 @@ if (!isProduction) {
app.use(errorhandler());
}

if(isProduction){
mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.connect('mongodb://localhost/conduit');
mongoose.set('debug', true);
}
// if(isProduction){
// mongoose.connect(process.env.MONGODB_URI);
// } else {
// mongoose.connect('mongodb+srv://123:[email protected]/myFirstDatabase?retryWrites=true&w=majority');
// mongoose.set('debug', true);
// }

require('./models/User');
require('./models/Article');
Expand Down
22 changes: 22 additions & 0 deletions config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURL');

// Connect to the DB
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
console.log('MongoDB Connected');
} catch (error) {
console.error(error.message);
// Exist process with failure
process.exit(1);
}
};

module.exports = connectDB;

4 changes: 4 additions & 0 deletions config/default.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"mongoURL": "mongodb+srv://123:[email protected]/myFirstDatabase?retryWrites=true&w=majority",
"jwtSecret": "mysecrettoken"
}
28 changes: 28 additions & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const jwt = require('jsonwebtoken');
const config = require('config');

module.exports = function(req, res, next) {
// Get token from header
const token = req.header('x-auth-token');

// Check if not token
if(!token) {
// 401 - not found
return res.status(401).json({ msg: 'No token, authorization denied' });
}

// Verify token
try {
// When you register or try to login a user, a token is assigned to that user
// using the user ID, this is how a token is assigned to a specific user. On
// verifying the token, we just assign the requested user to the user in the
// requested token since that user would have been passed while creating the token
const decoded = jwt.verify(token, config.get('jwtSecret'));

req.user = decoded.user;
next();

} catch (res) {
res.status(401).json({ msg: 'Token is not valid' });
}
}
2 changes: 1 addition & 1 deletion models/Article.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var User = mongoose.model('User');
var User = require('./User');

var ArticleSchema = new mongoose.Schema({
slug: {type: String, lowercase: true, unique: true},
Expand Down
2 changes: 1 addition & 1 deletion models/Comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var mongoose = require('mongoose');

var CommentSchema = new mongoose.Schema({
body: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
article: { type: mongoose.Schema.Types.ObjectId, ref: 'Article' }
}, {timestamps: true});

Expand Down
47 changes: 18 additions & 29 deletions models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,18 @@ var jwt = require('jsonwebtoken');
var secret = require('../config').secret;

var UserSchema = new mongoose.Schema({
username: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/^[a-zA-Z0-9]+$/, 'is invalid'], index: true},
email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
username: {
type: String,
lowercase: true,
unique: true,
index: true
},
email: {
type: String,
lowercase: true,
unique: true,
index: true
},
bio: String,
image: String,
favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }],
Expand All @@ -15,38 +25,17 @@ var UserSchema = new mongoose.Schema({
salt: String
}, {timestamps: true});

UserSchema.plugin(uniqueValidator, {message: 'is already taken.'});

UserSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
return this.hash === hash;
};

UserSchema.methods.setPassword = function(password){
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
};

UserSchema.methods.generateJWT = function() {
var today = new Date();
var exp = new Date(today);
exp.setDate(today.getDate() + 60);

return jwt.sign({
id: this._id,
username: this.username,
exp: parseInt(exp.getTime() / 1000),
}, secret);
};

UserSchema.methods.toAuthJSON = function(){
return {
username: this.username,
email: this.email,
token: this.generateJWT(),
bio: this.bio,
image: this.image
};
UserSchema.methods.setPassword = async function(password){
// Using bcrpt instead
const salt = await bcrypt.genSalt(10);
password = await bcrypt.hash(password, salt);
return password;
};

UserSchema.methods.toProfileJSONFor = function(user){
Expand Down Expand Up @@ -96,4 +85,4 @@ UserSchema.methods.isFollowing = function(id){
});
};

mongoose.model('User', UserSchema);
module.exports = User = mongoose.model('User', UserSchema);
Loading