entryPoint.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. //---------------------------------------//LOAD TOOLS//---------------------------------------//
  2. const express = require('express');
  3. const mongoose = require('mongoose');
  4. const jwt = require('jsonwebtoken');
  5. const bcrypt = require('bcryptjs');
  6. const app = express();
  7. app.use(express.json());
  8. //---------------------------------------//CONNECT TO SCHOOL DATABASE//---------------------------------------//
  9. //const dbServerAddress = "mongodb://192.168.131.172:27017/manfa940_database";
  10. const dbServerAddress = "mongodb://manfa940:Dm29070@$@192.168.131.172:27017/manfa940_database?authSource=admin";
  11. const dbLocalAddress = "mongodb://127.0.0.1:27017/manfa940_database";
  12. const mySecretKey = "super_secret_key_123";
  13. mongoose.connect(dbServerAddress)
  14. .then(() => console.log("Success: Connected to School Server!"))
  15. .catch(err => console.log("Error: Could not connect", err));
  16. //---------------------------------------//SCHEMAS//---------------------------------------//
  17. // User (Name, Password, and Money)
  18. const userSchema = new mongoose.Schema({
  19. username: { type: String, required: true },
  20. password: { type: String, required: true },
  21. balance: { type: Number, default: 50 }
  22. });
  23. // Plant
  24. const plantSchema = new mongoose.Schema({
  25. owner: mongoose.Schema.Types.ObjectId,
  26. type: String,
  27. sequence: String, // Random code to remember
  28. quality: { type: Number, default: 0 }
  29. });
  30. const User = mongoose.model('User', userSchema);
  31. const Plant = mongoose.model('Plant', plantSchema);
  32. //---------------------------------------//SECURITY CHECK//---------------------------------------//
  33. // Checks if user is logged in
  34. const checkLogin = (req, res, next) => {
  35. const token = req.headers['authorization']?.split(' ')[1];
  36. if (!token) return res.send("You are not logged in!");
  37. jwt.verify(token, mySecretKey, (err, data) => {
  38. if (err) return res.send("Token is bad!");
  39. req.userId = data.id;
  40. next();
  41. });
  42. };
  43. //---------------------------------------//GAME ACTIONS//---------------------------------------//
  44. // Create Account
  45. app.post('/register', async (req, res) => {
  46. const pass = await bcrypt.hash(req.body.password, 10);
  47. const newUser = new User({ username: req.body.username, password: pass });
  48. await newUser.save();
  49. res.send("Account created!");
  50. });
  51. // Login
  52. app.post('/login', async (req, res) => {
  53. const findUser = await User.findOne({ username: req.body.username });
  54. if (!findUser) return res.send("User not found");
  55. const checkPass = await bcrypt.compare(req.body.password, findUser.password);
  56. if (!checkPass) return res.send("Wrong password");
  57. const myToken = jwt.sign({ id: findUser._id }, mySecretKey);
  58. res.json({ token: myToken });
  59. });
  60. // Plant a flower (Costs $10)
  61. app.post('/plant', checkLogin, async (req, res) => {
  62. const player = await User.findById(req.userId);
  63. if (player.balance < 10) return res.send("You are too poor!");
  64. // Random 6 letter code
  65. let code = "";
  66. let letters = "1234";
  67. for (let i = 0; i < 7; i++) {
  68. code += letters.charAt(Math.floor(Math.random() * 7));
  69. }
  70. const newPlant = new Plant({ owner: req.userId, type: "Fern", sequence: code });
  71. player.balance = player.balance - 10;
  72. await player.save();
  73. await newPlant.save();
  74. res.json({ msg: "Planted! Remember this code:", code: code });
  75. });
  76. // Grow plant by typing code
  77. app.post('/grow/:id', checkLogin, async (req, res) => {
  78. const myPlant = await Plant.findById(req.params.id);
  79. const userTyped = req.body.typedCode;
  80. // Check how many letters are correct
  81. let score = 0;
  82. if (userTyped[0] === myPlant.sequence[0]) score++;
  83. if (userTyped[1] === myPlant.sequence[1]) score++;
  84. if (userTyped[2] === myPlant.sequence[2]) score++;
  85. if (userTyped[3] === myPlant.sequence[3]) score++;
  86. if (userTyped[4] === myPlant.sequence[4]) score++;
  87. if (userTyped[5] === myPlant.sequence[5]) score++;
  88. if (userTyped[6] === myPlant.sequence[6]) score++;
  89. myPlant.quality = score / 7;
  90. await myPlant.save();
  91. res.send("Growth finished! Quality is: " + myPlant.quality);
  92. });
  93. // Sell plant for money
  94. app.post('/sell/:id', checkLogin, async (req, res) => {
  95. const myPlant = await Plant.findById(req.params.id);
  96. // Money earned is $20 (profit from base price) * quality
  97. let moneyEarned = 20 * myPlant.quality;
  98. const player = await User.findById(req.userId);
  99. player.balance = player.balance + moneyEarned;
  100. await player.save();
  101. await Plant.deleteOne({ _id: req.params.id });
  102. res.send("Sold! You got $" + moneyEarned);
  103. });
  104. //---------------------------------------//START SERVER//---------------------------------------//
  105. app.listen(3000, () => {
  106. console.log("Game is running on port 3000");
  107. });