Guest User

Untitled

a guest
Jun 8th, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.20 KB | None | 0 0
  1. 'use strict';
  2. const Joi = require('joi');
  3. Joi.objectId = require('joi-objectid')(Joi);
  4. const config = require('config');
  5. const mongoose = require('mongoose');
  6. const debug = require('debug')('app:api');
  7. const express = require('express');
  8. const path = require('path');
  9. const morgan = require('morgan');
  10. const bodyParser = require('body-parser');
  11. const { isNotFound, errorHandlerDev, errorHandlerPro } = require('./middleware/handlers');
  12.  
  13. const index = require('./routes/index');
  14. const auth = require('./routes/auth');
  15. const users = require('./routes/users');
  16.  
  17. const app = express();
  18.  
  19. if(!config.get('jwtPrivateKey')) {
  20. console.log('KRİTİK HATA: JWT Private Key Tanımlanmadı!');
  21. process.exit(1);
  22. }
  23. if(!config.get('connectionString')) {
  24. console.log('KRİTİK HATA: Connection String Tanımlanmadı!');
  25. process.exit(1);
  26. }
  27. if(!process.env.USERNAME || !process.env.PASSWORD) {
  28. console.log('KRİTİK HATA: MongoDB Kullanıcı Bilgileri Eksik!');
  29. process.exit(1);
  30. }
  31.  
  32. mongoose.connect(config.get('connectionString').replace(/({{USERNAME}}|{{PASSWORD}})/gi, match => { match = match.replace(/({|})/gi, symbol => ''); return process.env[match]; }))
  33. .then(() => debug('MongoDB > Uptime-Monitor Başarıyla Bağlandı!'))
  34. .catch(error => debug('MongoDB > Uptime-Monitor Bağlanırken Hata Oluştu! Hata Bilgisi:', error));
  35.  
  36. app.use(morgan('dev'));
  37. app.use(bodyParser.json());
  38. app.use(bodyParser.urlencoded({ extended: false }));
  39.  
  40. app.use('/api/', index);
  41. app.use('/api/auth', auth);
  42. app.use('/api/users', users);
  43.  
  44. app.use(isNotFound);
  45.  
  46. if (app.get('env') === 'development') {
  47. app.use(errorHandlerDev);
  48. }
  49.  
  50. app.use(errorHandlerPro);
  51.  
  52. app.set('port', process.env.PORT || 5000);
  53.  
  54. app.listen(app.get('port'), function () {
  55. debug(`Express Sunucusu Port ${app.get('port')} Üzerinde Çalışıyor!`);
  56. });
  57.  
  58. 'use strict';
  59. const config = require('config');
  60. const jwt = require('jsonwebtoken');
  61. const Joi = require('joi');
  62. Joi.objectId = require('joi-objectid')(Joi);
  63. const mongoose = require('mongoose');
  64.  
  65. var model = {};
  66.  
  67. // Required Data: username, email, phone, password
  68. // Optional Data: name, lastname, tosAgreement, isAdmin
  69. model.userSchema = new mongoose.Schema({
  70. name: {
  71. type: String,
  72. trim: true,
  73. minlength: [3, 'Adınızın Karakter Sayısı Uygun Değildir. Minimum 3, Maksimum 50 Adet Karakterden Oluşabilir.'],
  74. maxlength: [50, 'Adınızın Karakter Sayısı Uygun Değildir. Minimum 3, Maksimum 50 Adet Karakterden Oluşabilir.']
  75. },
  76. lastname: {
  77. type: String,
  78. trim: true,
  79. minlength: [3, 'Soyadınızın Karakter Sayısı Uygun Değildir. Minimum 3, Maksimum 50 Adet Karakterden Oluşabilir.'],
  80. maxlength: [50, 'Adınızın Karakter Sayısı Uygun Değildir. Minimum 3, Maksimum 50 Adet Karakterden Oluşabilir.']
  81. },
  82. username: {
  83. type: String,
  84. trim: true,
  85. minlength: [3, 'Kullanıcı Adınızın Karakter Sayısı Uygun Değildir. Minimum 3, Maksimum 30 Adet Karakterden Oluşabilir.'],
  86. maxlength: [20, 'Kullanıcı Adınızın Karakter Sayısı Uygun Değildir. Minimum 3, Maksimum 30 Adet Karakterden Oluşabilir.'],
  87. //unique: [true, 'İstenilen Kullanıcı Adı Daha Önce Kullanılmış.'],
  88. validate: {
  89. validator: function(v) {
  90. let re = /^w+$/;
  91. return re.test(v);
  92. },
  93. message: 'Uygun Kullanıcı Adı Giriniz.'
  94. },
  95. match: [/^w+$/, 'Uygun Kullanıcı Adı Giriniz.']
  96. },
  97. email: {
  98. type: String,
  99. trim: true,
  100. //unique: [true, 'İstenilen E-Posta Adresi Daha Önce Kullanılmış.'],
  101. lowercase: true,
  102. validate: {
  103. validator: function(v) {
  104. let re = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
  105. return re.test(v);
  106. },
  107. message: 'Uygun E-Posta Adresi Giriniz.'
  108. },
  109. match: [/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/, 'Uygun E-Posta Adresi Giriniz.']
  110. },
  111. phone: {
  112. type: Number,
  113. required: [true, 'Telefon Numaranızı Girmeniz Gerekmektedir.'],
  114. //unique: [true, 'İstenilen Telefon Numarası Daha Önce Kullanılmış.'],
  115. min: [10, 'Telefon Numaranızın Uzunluğu Uygun Değildir. 10 Haneden Oluşmalıdır.'],
  116. },
  117. password: {
  118. type: String,
  119. trim: true,
  120. required: [true, 'Şifrenizi Girmeniz Gerekmektedir.'],
  121. minlength: 5,
  122. maxlength: 1024
  123. },
  124. registerDate: {
  125. type: Date,
  126. default: Date.now
  127. },
  128. tosAgreement: {
  129. type: Boolean,
  130. default: true
  131. },
  132. isAdmin: {
  133. type: Boolean,
  134. required: true,
  135. default: false
  136. }
  137. });
  138.  
  139. model.userSchema.methods.generateToken = function() {
  140. return jwt.sign({ _id: this._id, isAdmin: this.isAdmin}, config.get('jwtPrivateKey'));
  141. };
  142.  
  143. model.User = mongoose.model('User', model.userSchema);
  144.  
  145. model.validate = user => {
  146. const Schema = {
  147. name: Joi.string().min(3).max(50),
  148. lastname: Joi.string().min(3).max(50),
  149. username: Joi.string().required().regex(/^w+$/).min(3).max(20),
  150. email: Joi.string().required().min(3).email(),
  151. phone: Joi.number().required().min(10),
  152. password: Joi.string().required().min(5).max(255),
  153. tosAgreement: Joi.boolean().default(true),
  154. isAdmin: Joi.boolean().default(false)
  155. };
  156.  
  157. return Joi.validate(user, Schema);
  158. };
  159.  
  160. model.validateId = id => {
  161. return Joi.validate(id, Joi.objectId().required());
  162. };
  163.  
  164. module.exports.model = model;
  165.  
  166. 'use strict';
  167. const auth = require('./../middleware/auth');
  168. const admin = require('./../middleware/admin');
  169. const bcyript = require('bcrypt');
  170. const _ = require('lodash');
  171. const mongoose = require('mongoose');
  172. const { userSchema, User, validate, validateId } = require('./../models/user');
  173. const express = require('express');
  174. const router = express.Router();
  175.  
  176. router.get('/', [auth, admin], async (req, res) => {
  177. const users = await User.find().select({ _id: 1, name: 1, email: 1, tosAgreement: 1}).sort({ name: 1 });
  178. if(!users) return res.status(200).send({'BİLGİ': 'Hiç Kullanıcı Bulunamadı.'});
  179. res.status(200).send(users);
  180. });
  181.  
  182. router.get('/me', auth, async (req, res) => {
  183. const user = await User.findById(req.user._id).select('-password -phone');
  184. res.status(200).send(user);
  185. });
  186.  
  187. router.get('/:id', [auth, admin], async (req, res) => {
  188. const user = await User.findById(req.params.id).select({ _id: 1, name: 1, email: 1, tosAgreement: 1, isAdmin: true});
  189. if(!user) return res.status(404).send({'HATA': 'Belirtilen ID'ye Sahip Kullanıcı Bulunamadı.'});
  190. res.status(200).send(user);
  191. });
  192.  
  193. router.post('/', /*[auth, admin],*/async (req, res) => {
  194. const { error } = validate(req.body);
  195. if(error) return res.status(400).send({'Hata': error.details[0].message});
  196. let isAnyUserWithThatEmail = await User.findOne({ email: req.body.email });
  197. if(isAnyUserWithThatEmail) return res.status(400).send({'Hata': 'Belirtilen E-Posta Adresi Kullanımda.'});
  198. let isAnyUserWithThatPhone = await User.findOne({ phone: req.body.phone });
  199. if(isAnyUserWithThatPhone) return res.status(400).send({'Hata': 'Belirtilen Telefon Numarası Kullanımda.'});
  200. const user = new User(req.body);
  201. const salt = await bcyript.genSalt(10);
  202. user.password = await bcyript.hash(user.password, salt);
  203. await user.save();
  204. const token = user.generateToken();
  205. res.header('x-auth-token', token).status(201).send(_.pick(user, ['_id', 'name', 'email', 'tosAgreement', 'isAdmin']));
  206. });
  207.  
  208. router.put('/:id', auth, async (req, res) => {
  209. const errorId = validateId(req.params.id).error;
  210. if(errorId) return res.status(400).json({'Hata': errorId.details[0].message});
  211. const { error } = validate(req.body);
  212. if(error) return res.status(400).send({'Hata': error.details[0].message});
  213. const salt = await bcyript.genSalt(10);
  214. const user = await User.findByIdAndUpdate(req.params.id, {
  215. name: req.body.name,
  216. lastname: req.body.lastname,
  217. email: req.body.email,
  218. phone: req.body.phone,
  219. password: await bcyript.hash(req.body.password, salt),
  220. tosAgreement: req.body.tosAgreement,
  221. isAdmin: req.body.isAdmin
  222. }, { new: true, runValidators: true });
  223. if(!user) return res.status(404).send({'Hata': 'Belirtilen ID'ye Sahip Kullanıcı Bulunamadı.'});
  224. res.status(200).send(_.pick(user, ['_id', 'name', 'email', 'tosAgreement', 'isAdmin']));
  225. });
  226.  
  227. router.delete('/:id', [auth, admin], async (req, res) => {
  228. const { error } = validateId(req.params.id);
  229. if(error) return res.status(400).json({'Hata': error.details[0].message});
  230. const user = await User.findByIdAndRemove(req.params.id);
  231. if(!user) return res.status(404).send({'Hata': 'Belirtilen ID'ye Sahip Kullanıcı Bulunamadı.'});
  232. res.status(200).send(_.pick(user, ['_id', 'name', 'email', 'tosAgreement', 'isAdmin']));
  233. });
  234.  
  235. module.exports = router;
  236.  
  237. //@@@ NO ERROR WHEN COMMENT OUT THESE 'unique' IDENTIFIERS @@@
  238. ...
  239. username: {
  240. ...
  241. //unique: [true, 'İstenilen Kullanıcı Adı Daha Önce Kullanılmış.'],
  242. ...
  243. },
  244. email: {
  245. ...
  246. //unique: [true, 'İstenilen E-Posta Adresi Daha Önce Kullanılmış.'],
  247. ...
  248. },
  249. phone: {
  250. ...
  251. //unique: [true, 'İstenilen Kullanıcı Adı Daha Önce Kullanılmış.'],
  252. ...
  253. }
  254. ...
Add Comment
Please, Sign In to add comment