Skip to content

Commit

Permalink
feat: Add connect-flash to handle error message in login and register
Browse files Browse the repository at this point in the history
  • Loading branch information
Kris3131 committed Aug 31, 2022
1 parent 3f392d7 commit 566cb1c
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 8 deletions.
5 changes: 4 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ const express = require('express')
const session = require('express-session')
const usePassport = require('./config/passport')
const exphbs = require('express-handlebars')

const methodOverride = require('method-override')
const flash = require('connect-flash')

const routes = require('./routes/index')

Expand All @@ -27,9 +27,12 @@ app.use(
app.use(express.urlencoded({ extended: true }))
app.use(methodOverride('_method'))
usePassport(app)
app.use(flash())
app.use((req, res, next) => {
res.locals.isAuthenticated = req.isAuthenticated()
res.locals.user = req.user
res.locals.success_msg = req.flash('success_msg')
res.locals.warning_msg = req.flash('warning_msg')
next()
})
app.use(routes)
Expand Down
6 changes: 4 additions & 2 deletions config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ module.exports = (app) => {
User.findOne({ email }) // 從資料庫找有沒有人
.then((user) => {
if (!user)
return done(null, false, { message: `Email is not register` }) // 假如沒有資料->結束程序,不用帶錯誤訊息/沒有用戶資料/顯示訊息
return done(null, false, {
message: req.flash('warning_msg', `Email 沒有註冊過`),
}) // 假如沒有資料->結束程序,不用帶錯誤訊息/沒有用戶資料/顯示訊息
if (user.password !== password)
return done(null, false, {
message: `Email or Password incorrect`,
message: req.flash('warning_msg', `Email Password 不正確`),
}) // 假如密碼不同->結束程序,不用帶錯誤訊息/沒有用戶資料/顯示訊息
return done(null, user) // 建立使用者
})
Expand Down
1 change: 1 addition & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module.exports = {
if (req.isAuthenticated()) {
return next()
}
req.flash('warning_msg', '請先登入')
res.redirect('/users/login')
},
}
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"connect-flash": "^0.1.1",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"express-handlebars": "^6.0.6",
Expand Down
6 changes: 5 additions & 1 deletion routes/modules/records.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,11 @@ routes.delete('/:id', (req, res) => {
const userId = req.user._id
const _id = req.params.id
Record.findOneAndRemove({ _id, userId })
.then(() => res.redirect('/'))

.then(() => {
req.flash('success_msg', '你已經成功登出。')
res.redirect('/')
})
.catch((err) => console.log(err))
})

Expand Down
20 changes: 19 additions & 1 deletion routes/modules/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,27 @@ routes.get('/register', (req, res) => {
})

routes.post('/register', (req, res) => {
const { name, email, password } = req.body
const { name, email, password, confirmPassword } = req.body
const errors = []
if (!name || !email || !password || !confirmPassword) {
errors.push({ message: '所有欄位都是必填' })
}
if (password !== confirmPassword) {
errors.push({ message: '密碼與確認密碼不同' })
}
if (errors.length) {
res.render('register', {
errors,
name,
email,
password,
confirmPassword,
})
}
User.findOne({ email })
.then((user) => {
if (user) {
errors.push({ message: '這個 Email 已經註冊過了' })
res.render('login', { email: user.email })
} else {
User.create({ name, email, password })
Expand All @@ -30,6 +47,7 @@ routes.post(
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login',
failureMessage: true,
})
)
routes.get('/logout', (req, res) => {
Expand Down
1 change: 1 addition & 0 deletions views/login.hbs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<div class='container mx-auto mt-3'>
{{>message}}
<form action='/users/login' method='POST' class='mb-3'>
<div>
<label for='email' class='form-label'>Email</label>
Expand Down
37 changes: 37 additions & 0 deletions views/partials/message.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{{#if success_msg}}
<div class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>{{success_msg}}</strong>
<button
type='button'
class='btn-close'
data-bs-dismiss='alert'
aria-label='Close'
></button>
</div>
{{/if}}

{{#if warning_msg}}
<div class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>{{warning_msg}}</strong>
<button
type='button'
class='btn-close'
data-bs-dismiss='alert'
aria-label='Close'
></button>
</div>
{{/if}}

{{#if errors}}
{{#each errors}}
<div class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>{{this.message}}</strong>
<button
type='button'
class='btn-close'
data-bs-dismiss='alert'
aria-label='Close'
></button>
</div>
{{/each}}
{{/if}}
8 changes: 5 additions & 3 deletions views/register.hbs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<div class='container mx-auto mt-3'>
{{>message}}
<form action='/users/register' method='POST' class='mb-3'>

<div>
<label for='name' class='form-label'>Name</label>
<input type='text' id='name' name='name' class='form-control' />
<input type='text' id='name' name='name' class='form-control' value="{{name}}"/>
</div>
<div>
<label for='email' class='form-label'>Email</label>
<input type='email' id='email' name='email' class='form-control' />
<input type='email' id='email' name='email' class='form-control' value="{{email}}"/>
</div>
<div>
<label for='password' class='form-label'>Password</label>
Expand All @@ -16,6 +16,7 @@
id='password'
name='password'
class='form-control'
value="{{password}}"
/>
</div>
<div>
Expand All @@ -25,6 +26,7 @@
id='confirmPassword'
name='confirmPassword'
class='form-control'
value="{{confirmPassword}}"
/>
</div>
<div>
Expand Down

0 comments on commit 566cb1c

Please sign in to comment.