Guest User

Untitled

a guest
Jan 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.59 KB | None | 0 0
  1. //Daniel Monera Postman book service
  2.  
  3. //Connections and general lines
  4. const mongoose = require('mongoose');
  5. const express = require('express');
  6. const uniqueValidator = require('mongoose-unique-validator');
  7. const validate = require('mongoose-validator');
  8. const bodyParser = require('body-parser');
  9. const jwt = require('jsonwebtoken');
  10. const sha256 = require('sha256');
  11. const fs = require('fs');
  12.  
  13. const secretWord = "SecretWord";
  14.  
  15. mongoose.Promise = global.Promise;
  16. mongoose.connect('mongodb://localhost:27017/book-services', {useMongoClient: true});
  17.  
  18. //Schemas
  19. let userSchema = new mongoose.Schema({
  20. name: {
  21. type: String,
  22. required: true,
  23. minlength: 1,
  24. trim: true,
  25. unique: true,
  26. validate: [
  27. validate({
  28. validator : 'isAlphanumeric',
  29. message : 'caps must be numbers and letters only'
  30. })
  31. ]
  32. //I prefer to use packages, easier and cleaner ;)
  33. /*validate : [{
  34. msg : 'only alphanumeric characters',
  35. validator : function (value) {
  36. return /^[a-z0-9]+$/i.test(value);
  37. }
  38. }]*/
  39. },
  40. password: {
  41. type: String,
  42. required: true,
  43. minlength: 4
  44. }
  45. });
  46.  
  47. let bookSchema = new mongoose.Schema({
  48. author:{
  49. type: String,
  50. required: true,
  51. trim: true,
  52. minlength: 4
  53. },
  54. title:{
  55. type: String,
  56. required: true,
  57. trime: true,
  58. minlength: 1
  59. },
  60. published:{
  61. type: Date,
  62. required: true
  63. },
  64. price:{
  65. type: Number,
  66. required: true,
  67. min: 0,
  68. max: 5000
  69. },
  70. image:{
  71. type: String,
  72. required: false
  73. }
  74. });
  75.  
  76. let commentSchema = new mongoose.Schema({
  77. book:{
  78. type: mongoose.Schema.Types.ObjectId,
  79. ref: 'books',
  80. required: true
  81. },
  82. user:{
  83. type: mongoose.Schema.Types.ObjectId,
  84. ref: 'users',
  85. required: true
  86. },
  87. text:{
  88. type: String,
  89. required:true,
  90. trim:true,
  91. minlength: 5
  92. },
  93. score:{
  94. type: Number,
  95. min: 1,
  96. max: 5,
  97. default:3
  98. }
  99. });
  100.  
  101. let User = mongoose.model('users', userSchema);
  102. let Book = mongoose.model('books', bookSchema);
  103. let Comment = mongoose.model('comments', commentSchema);
  104.  
  105. //REST service
  106. let app = express();
  107. app.use(bodyParser.json());
  108.  
  109. //Generate token with the secret word
  110. let generateToken = login => {
  111. let token = jwt.sign({login: login}, secretWord,
  112. {expiresIn:"365 days"});
  113. return token;
  114. };
  115.  
  116. //Function to validate the token
  117. let validateToken = token => {
  118. try {
  119. let result = jwt.verify(token, secretWord);
  120. return result;
  121. } catch (e) {
  122. }
  123. }
  124.  
  125.  
  126.  
  127.  
  128. //POST /REGISTER Register a new user
  129. app.post('/register', (req, res) => {
  130. let newUser = new User({
  131. name: req.body.name,
  132. password: sha256(req.body.password) //Encrypt the password with SHA256
  133. });
  134. newUser.save().then(result => {
  135. let data = {error: false, result: result};
  136. res.send(data);
  137. }).catch(error => {
  138. console.log(error);
  139. let data = {error: true,
  140. errorMessage:"User couldn't be registered"};
  141. res.send(data);
  142. });
  143. });
  144.  
  145. //POST /LOGIN Login with the username using a encrypted password
  146. app.post('/login', (req, res) => {
  147. // Get user credentials from the request
  148. let userClient = {
  149. name: req.body.name,
  150. password: req.body.password
  151. };
  152. // Look for user in the User collection
  153. User.find({name: userClient.name,
  154. password: sha256(userClient.password)})
  155. .then(data => {
  156. // User is valid. Generate token
  157. if (data) {
  158. let token = generateToken(userClient.name);
  159. let result = {error: false, token: token};
  160. res.send(result);
  161. // User not found. Generate error message
  162. } else {
  163. let result = {error: true,
  164. errorMessage: "Invalid user"};
  165. res.send(result);
  166. }
  167. }).catch (error => {
  168. // Error searching user. Generate error message
  169. console.log(error);
  170. let result = {error: true, errorMessage: "Error validating user"};
  171. res.send(result);
  172. });
  173. });
  174.  
  175. //GET /BOOKS Get the complete books array
  176. app.get('/books', (req, res) => {
  177. //Check if the token is valid or not
  178. let token = req.headers['authorization'];
  179. let result = validateToken(token);
  180. //If the token is valid we continue with the request
  181. if (result) {
  182. Book.find().then(result => {
  183. res.send(result);
  184. })
  185. } else{
  186. res.sendStatus(401);
  187. }
  188.  
  189. });
  190.  
  191.  
  192. //POST /BOOKS Publicate a new book
  193. app.post('/books', (req, res)=> {
  194. //Check if the token is valid or not
  195. let token = req.headers['authorization'];
  196. let result = validateToken(token);
  197. //If the token is valid we continue with the request
  198. if (result) {
  199. let imageName = 'img/' + Date.now() + '.jpg';
  200. let imageJPG = fs.writeFileSync(imageName, Buffer.from(req.body.image, 'base64'));
  201. let newBook = new Book({
  202. author: req.body.author,
  203. title: req.body.title,
  204. price: req.body.price,
  205. published: req.body.published,
  206. image: imageName
  207. });
  208. newBook.save().then(result=>{
  209. let data = {error: false, result: result};
  210. res.send(data);
  211. }).catch(error => {
  212. console.log(error);
  213. let data = {error: true, errorMessage: "Error adding new book"};
  214. res.send(data);
  215. });
  216. } else{
  217. res.sendStatus(401);
  218. }
  219. });
  220.  
  221.  
  222. //DELETE /BOOKS/:ID Delete the book and his comments.
  223. app.delete('/books/:id', (req, res) =>{
  224. //Check if the token is valid or not
  225. let token = req.headers['authorization'];
  226. let result = validateToken(token);
  227. //If the token is valid we continue with the request
  228. if (result) {
  229. //Comment.remove({book: request.params.id}).then(() => {
  230. Book.findByIdAndRemove(req.params.id).then(result => {
  231. let data = {error: false, result: result};
  232. res.send(data);
  233. }).catch(error =>{
  234. console.log(error);
  235. let data = {error: true, errorMessage: "Error deleting book"};
  236. });
  237. //});
  238. } else{
  239. res.sendStatus(401);
  240. }
  241. });
  242.  
  243. //I don't know how to do it in this way////////////////////////////////////////////////////////////////
  244. //PUT /BOOKS/:ID Update a current book
  245. app.put('/books:id', (req, res) =>{
  246. //Check if the token is valid or not
  247. let token = req.headers['authorization'];
  248. let result = validateToken(token);
  249. //If the token is valid we continue with the request
  250. if (result) {
  251. Book.findById(req.params.id).then(book => {
  252. $set: {
  253. author: req.body.author,
  254. title: req.body.title,
  255. published: req.body.age,
  256. price: req.body.price,
  257. image: req.body.image
  258. }
  259. book.save().then(book => {
  260. let data = {error: false, result: result};
  261. res.send(data);
  262. }).catch(error => {
  263. console.log(error);
  264. let data = {error: true, errorMessage: "Error updating book"};
  265. });
  266. }).catch(error => {
  267. console.log(error);
  268. let data = {error: true, errorMessage: "Book not found"};
  269. });
  270. } else{
  271. res.sendStatus(401);
  272. }
  273. })
  274.  
  275. //GET /COMMENTS/:BOOKID
  276. app.get('/comments/:bookId', (req,res) =>{
  277. //Check if the token is valid or not
  278. let token = req.headers['authorization'];
  279. let result = validateToken(token);
  280. if (result) {
  281. Book.findById().populate('comments').populate('users').then(result => {
  282. res.send(result);
  283. })
  284. } else{
  285. res.sendStatus(401);
  286. }
  287. })
  288.  
  289.  
  290. //POST /COMMENTS/:BOOKID//////////////////////////////////////////////////////////////////////////////////
  291. app.post('/comments/:bookId', (req, res) => {
  292. //Check if the token is valid or not
  293. let token = req.headers['authorization'];
  294. let result = validateToken(token);
  295. if (result) {
  296. var payload = jwt.decode(token, {complete: true});
  297. console.log("point 1");
  298. let newComment = new Comment({
  299. book: req.params.bookId,
  300. user: payload.id, //////I don't know how to get the user ID here
  301. text: req.body.text,
  302. score: req.body.score
  303. });
  304. newComment.save().then(result => {
  305. console.log("point 2");
  306. let data = {error: false, result: result};
  307. res.send(data);
  308. }).catch(error => {
  309. console.log(error);
  310. let data = {error: true,
  311. errorMessage:"Error adding comment"};
  312. res.send(data);
  313. });
  314. } else{
  315. res.sendStatus(401);
  316. }
  317. });
  318.  
  319.  
  320. app.listen(8080);
Add Comment
Please, Sign In to add comment