Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
7ece79e
add R01.test.js && unit-test-helper.js
AmberYen Mar 2, 2022
79ff158
註解 typo 修正
zjzheng17 Jul 18, 2022
03c14c0
correcting typo in comment
zjzheng17 Jul 18, 2022
d5b1553
chore: init github workflow
eugenechen0514 Sep 9, 2023
fe01b7f
Update unit-test-helper.js
tuterwell Sep 12, 2023
e2665da
chore: format code
eugenechen0514 Sep 17, 2023
1be932b
test: fix update method
eugenechen0514 Sep 17, 2023
d12a942
Merge commit '1be932b9d1998168679d2cdf5a7a9e2f1d2bca91' into R01-test
eugenechen0514 Sep 17, 2023
fa173a7
chore: fix code format
eugenechen0514 Sep 17, 2023
1b8cd24
Delete .travis.yml
tuterwell Sep 18, 2023
3f6b855
feat: add handlebars
maomao0007 Jun 27, 2024
b24885e
feat: add index page
maomao0007 Jun 27, 2024
0715003
feat: add admin index page
maomao0007 Jun 27, 2024
043241c
feat: add user model
maomao0007 Jun 28, 2024
27b2d5c
feat: user signup
maomao0007 Jun 28, 2024
89cd7b5
feat: flash msg & signup verification
maomao0007 Jun 28, 2024
60f2bb0
feat: passport init & signin
maomao0007 Jun 28, 2024
4739e14
feat: add header & footer
maomao0007 Jun 28, 2024
0bcbc51
feat: user model add is_admin
maomao0007 Jun 28, 2024
ae800e7
feat: add restaurant model
maomao0007 Jun 28, 2024
d26ff04
feat: modify admin restaurants page
maomao0007 Jun 28, 2024
dfa657b
feat: create restaurant
maomao0007 Jun 28, 2024
9f75410
feat: admin restaurant page
maomao0007 Jun 28, 2024
04e51f7
feat: admin update restaurant
maomao0007 Jun 28, 2024
d2ca57d
feat: delete restaurant
maomao0007 Jun 28, 2024
2c0f403
feat: add restaurant image
maomao0007 Jun 30, 2024
2ddebce
fix commit
maomao0007 Jun 30, 2024
ae9e430
Import test file.
maomao0007 Jun 30, 2024
f7cb13f
Modify the functionality of postRestaurant feature.
maomao0007 Jun 30, 2024
3fd657d
Add a user role page.
maomao0007 Jul 1, 2024
aa63382
Add a User role page.
maomao0007 Jul 1, 2024
5b28288
Add a user role page.
maomao0007 Jul 2, 2024
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
13 changes: 13 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
name: Node.js test

on:
<<<<<<< HEAD
pull_request_target:
branches:
- main
Expand All @@ -11,6 +12,14 @@ on:
# - '*-test'
# pull_request:
# branches:
=======
push:
branches:
# - main
- '*-test'
pull_request:
branches:
>>>>>>> origin/R01-test
# - main

env:
Expand Down Expand Up @@ -38,11 +47,15 @@ jobs:
# mysql user: 'github' # Required if "mysql root password" is empty, default is empty. The superuser for the specified database. Can use secrets, too
# mysql password: 'password' # Required if "mysql user" exists. The password for the "mysql user"
- run: mysql --version
<<<<<<< HEAD
- run: echo "checkout head ${{ github.event.pull_request.head.sha }}"
- run: echo "base ${{ github.event.pull_request.base.sha }}"
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
=======
- uses: actions/checkout@v3
>>>>>>> origin/R01-test
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
Expand Down
45 changes: 37 additions & 8 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,42 @@
const express = require('express')
const routes = require('./routes')
const path = require("path"); // 引入 path 套件
const express = require("express");
const handlebars = require("express-handlebars"); // 引入 express-handlebars
const flash = require("connect-flash");
const methodOverride = require("method-override");
const session = require("express-session");
const passport = require("./config/passport");
const handlebarsHelpers = require("./helpers/handlebars-helpers"); // 引入 handlebars-helpers
const { getUser } = require("./helpers/auth-helpers");
const routes = require("./routes");

const app = express()
const port = process.env.PORT || 3000
const app = express();
const port = process.env.PORT || 3000;
const SESSION_SECRET = "secret";
const db = require("./models"); // 暫時新增這行,引入資料庫,檢查完可刪
// 註冊 Handlebars 樣板引擎,並指定副檔名為 .hbs
app.engine("hbs", handlebars({ extname: ".hbs", helpers: handlebarsHelpers }));
// 設定使用 Handlebars 做為樣板引擎
app.set("view engine", "hbs");
app.use(express.urlencoded({ extended: true }));
app.use(
session({ secret: SESSION_SECRET, resave: false, saveUninitialized: false })
);
app.use(passport.initialize()); // 增加這行,初始化 Passport
app.use(passport.session()); // 增加這行,啟動 session 功能
app.use(flash()); // 掛載套件
app.use(methodOverride("_method"));
app.use("/upload", express.static(path.join(__dirname, "upload")));
app.use((req, res, next) => {
res.locals.success_messages = req.flash("success_messages"); // 設定 success_msg 訊息
res.locals.error_messages = req.flash("error_messages"); // 設定 warning_msg 訊息
res.locals.user = getUser(req);
next();
});

app.use(routes)
app.use(routes);

app.listen(port, () => {
console.info(`Example app listening on port ${port}!`)
})
console.info(`Example app listening on port ${port}!`);
});

module.exports = app
module.exports = app;
47 changes: 47 additions & 0 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const passport = require("passport");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcryptjs");
const db = require("../models");
const User = db.User;
// set up Passport strategy
passport.use(
new LocalStrategy(
// customize user field
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true,
},
// authenticate user
(req, email, password, cb) => {
User.findOne({ where: { email } }).then((user) => {
if (!user)
return cb(
null,
false,
req.flash("error_messages", "帳號或密碼輸入錯誤!")
);
bcrypt.compare(password, user.password).then((res) => {
if (!res)
return cb(
null,
false,
req.flash("error_messages", "帳號或密碼輸入錯誤!")
);
return cb(null, user);
});
});
}
)
);
// serialize and deserialize user
passport.serializeUser((user, cb) => {
cb(null, user.id);
});
passport.deserializeUser((id, cb) => {
User.findByPk(id).then((user) => {
user = user.toJSON();
return cb(null, user);
});
});
module.exports = passport;
120 changes: 120 additions & 0 deletions controllers/admin-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
const { Restaurant, User } = require("../models");
const { localFileHandler } = require('../helpers/file-helpers') // 將 file-helper

const adminController = {
getRestaurants: (req, res, next) => {
return Restaurant.findAll({
raw: true,
})
.then((restaurants) => res.render("admin/restaurants", { restaurants }))
.catch((err) => next(err));
},
createRestaurant: (req, res) => {
return res.render("admin/create-restaurant");
},
postRestaurant: (req, res, next) => {
const { name, tel, address, openingHours, description } = req.body;
if (!name) throw new Error("Restaurant name is required!");
const { file } = req; // 把檔案取出來
return localFileHandler(file)
.then((filePath) =>
Restaurant.create({
name,
tel,
address,
openingHours,
description,
image: filePath || null,
})
)
.then(() => {
req.flash("success_messages", "restaurant was successfully created");
res.redirect("/admin/restaurants");
})
.catch((err) => next(err));
},
getRestaurant: (req, res, next) => {
return Restaurant.findByPk(req.params.id, {
//去資料庫用 id 找一筆資料
raw: true, // 找到以後整理格式再回傳
})
.then((restaurant) => {
if (!restaurant) throw new Error("Restaurant didn't exist!"); // 如果找不到,回傳錯誤訊息,後面不執行
res.render("admin/restaurant", { restaurant });
})
.catch((err) => next(err));
},
editRestaurant: (req, res, next) => {
return Restaurant.findByPk(req.params.id, {
raw: true,
})
.then((restaurant) => {
if (!restaurant) throw new Error("Restaurant didn't exist!");
res.render("admin/edit-restaurant", { restaurant });
})
.catch((err) => next(err));
},
putRestaurant: (req, res, next) => {
const { name, tel, address, openingHours, description } = req.body;
if (!name) throw new Error("Restaurant name is required!");
const { file } = req;

return Promise.all([
Restaurant.findByPk(req.params.id),
localFileHandler(file),
])
.then(([restaurant, filePath]) => {
if (!restaurant) throw new Error("Restaurant didn't exist!");

return restaurant.update({
name,
tel,
address,
openingHours,
description,
image: filePath || restaurant.image,
});
})
.then(() => {
req.flash("success_messages", "restaurant was successfully to update");
res.redirect("/admin/restaurants");
})
.catch((err) => next(err));
},

deleteRestaurant: (req, res, next) => {
return Restaurant.findByPk(req.params.id)
.then((restaurant) => {
if (!restaurant) throw new Error("Restaurant didn't exist!");
return restaurant.destroy();
})
.then(() => res.redirect("/admin/restaurants"))
.catch((err) => next(err));
},

getUsers: (req, res, next) => {
return User.findAll({ raw: true })
.then((users) => res.render("admin/users", { users }))
.catch((err) => next(err));
},

patchUser: (req, res, next) => {
return User.findByPk(req.params.id)
.then(user => {
if (!user) throw new Error("User didn't exist!")
if (user.email === 'root@example.com') {
req.flash('error_messages', '禁止變更 root 權限')
return res.redirect('back')
}

return user.update({ isAdmin: !user.isAdmin })
})
.then(() => {
req.flash('success_messages', '使用者權限變更成功')
res.redirect('/admin/users')
})
.catch(err => next(err))
}
}

module.exports = adminController;
6 changes: 6 additions & 0 deletions controllers/restaurant-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const restaurantController = {
getRestaurants: (req, res) => {
return res.render("restaurants");
},
};
module.exports = restaurantController;
47 changes: 47 additions & 0 deletions controllers/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const bcrypt = require("bcryptjs"); //載入 bcrypt
const db = require("../models");
const { User } = db;
const userController = {
signUpPage: (req, res) => {
res.render("signup");
},
signUp: (req, res, next) => {
//修改這裡
// 如果兩次輸入的密碼不同,就建立一個 Error 物件並拋出
if (req.body.password !== req.body.passwordCheck)
throw new Error("Passwords do not match!");

// 確認資料裡面沒有一樣的 email,若有,就建立一個 Error 物件並拋出
User.findOne({ where: { email: req.body.email } })
.then((user) => {
if (user) throw new Error("Email already exists!");
return bcrypt.hash(req.body.password, 10); // 前面加 return
})
.then((hash) =>
User.create({
//上面錯誤狀況都沒發生,就把使用者的資料寫入資料庫
name: req.body.name,
email: req.body.email,
password: hash,
})
)
.then(() => {
req.flash("success_messages", "Successfully registered!"); //並顯示成功訊息
res.redirect("/signin");
})
.catch((err) => next(err)); //接住前面拋出的錯誤,呼叫專門做錯誤處理的 middleware
},
signInPage: (req, res) => {
res.render("signin");
},
signIn: (req, res) => {
req.flash("success_messages", "Successfully logged in!");
res.redirect("/restaurants");
},
logout: (req, res) => {
req.flash("success_messages", "Successfully logged out!");
req.logout();
res.redirect("/signin");
},
};
module.exports = userController;
10 changes: 10 additions & 0 deletions helpers/auth-helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const getUser = (req) => {
return req.user || null;
};
const ensureAuthenticated = (req) => {
return req.isAuthenticated();
};
module.exports = {
getUser,
ensureAuthenticated,
};
16 changes: 16 additions & 0 deletions helpers/file-helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const fs = require("fs"); // 引入 fs 模組
const localFileHandler = (file) => {
// file 是 multer 處理完的檔案
return new Promise((resolve, reject) => {
if (!file) return resolve(null);
const fileName = `upload/${file.originalname}`;
return fs.promises
.readFile(file.path)
.then((data) => fs.promises.writeFile(fileName, data))
.then(() => resolve(`/${fileName}`))
.catch((err) => reject(err));
});
};
module.exports = {
localFileHandler,
};
4 changes: 4 additions & 0 deletions helpers/handlebars-helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const dayjs = require("dayjs"); //載入 dayjs 套件
module.exports = {
currentYear: () => dayjs().year(), //取得當年年份作為 currentYear 的屬性值,並導出
};
Loading