Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- GitHub Actions
- serializeUser
- typescript #import #export #*
- insertone
- connect-mongo
- typescript #class #extends #public #private #protected #static
- git vscode
- TypeScript #문법
- github#githubpages#빈화면#basename
- typescript #constructor #class #public #private
- deserializeUser
- sendFile
- git#github#init#add#commit#restore#log#staging area#repository#git사용법
- expess
- typescript #class #constructor #public #private #static #extends #protected #typeof #in #instanceof #never
- CSS
- updateone
- Passport
- e.target
- Promise #async #await #try #catch
- ejs 문법
- github#로컬저장소#원격저장소
- typescript #unknown
- github#githubpages#gh-pages#deploy
- 정적 페이지
- react#로스트아크#mbti#테스트
- mongodb 입출력
- __dirname
- updatemany
- typescript #react #jsx #component #usestate
Archives
- Today
- Total
VaIice의 이야기
[Node.js] 비밀번호 암호화 (hashing) 및 회원가입 예제 본문
1. 종류
SHA3-256
SHA3-512
bcrypt
scrypt
argon2
...
2. bcrypt 사용법
npm install bctypt
// server.js
const bctypt = require('bcrypt')
3. hashing
app.post('/signUp/add', async (request, response) => {
try {
let hashing = await bcrypt.hash(request.body.password, 10)
console.log(hashing)
bcrypt.hash('해싱할 문자', 숫자)
숫자가 높을수록 보안 ↑ 시간 ↑
비밀번호만 해싱하는 것이 아닌, salt라고 불리는 랜덤한 문자열 추가
salt는 DB에 보관되는데, 별도의 DB나 하드웨어에 저장 가능, 이런 경우 pepper라고 불리운다.
4. 해싱된 문자열 비교
// ID, PW 검사
passport.use(new LocalStrategy(async (username, password, cb) => {
let result = await db.collection('user').findOne({ username : username});
if (!result) {
return cb(null, false, { message: '올바른 ID를 입력해주세요.' });
}
// 문자열 비교 => true / false
if (await bcrypt.compare(password, result.password)) {
return cb(null, result);
} else {
return cb(null, false, { message: '올바른 비밀번호를 입력해주세요.' });
}
}));
await bcrypt.compare(비교할 문자열, 해싱된 문자열)
5. connect-mongo
npm install connect-mongo
// server.js
const MongoStore = require('connect-mongo')
app.use(session({
secret: '암호화에 쓸 비밀번호',
resave : false,
saveUninitialized: false,
cookie: {maxAge: 60*60*1000},
// DB 연결 추가
store: MongoStore.create({
mongoUrl: 'mongoDB 주소',
dbName: 'DB 이름'
})
}))
세션을 저장할 DB와 연결
Q1. 중복 아이디 가입 방지
let existingUsername = await db.collection('user').findOne({ username: request.body.username })
if (existingUsername) {
response.send('중복된 아이디입니다.');
}
Q2. 비밀번호 입력란 2개
// signUp.ejs
<input type="password" name="password">
<input type="password" name="passwordCheck">
// server.js
} else if (request.body.password != request.body.passwordCheck) {
response.send('비밀번호가 일치하지 않습니다.')
}
Q3. 로그인 한 유저만 글쓰기
// server.js
app.get('/write', (request, response) => {
if (request.user) {
response.render('write.ejs')
}
else {
response.send('로그인을 해주세요.')
}
})
Q4. 마이 페이지 만들기
// server.js
app.get('/myPage', (request, response) => {
if (!request.user) {
response.send('로그인을 해주세요.')
}
else {
response.render('myPage.ejs', { user: request.user });
}
});
// myPage.ejs
<div class="list-box">
<h4>마이페이지</h4>
<p>아이디: <%-user.username%></p>
</div>
'[Node.js]' 카테고리의 다른 글
[Node.js] 이미지 보관 - AWS S3 (1) (2) | 2024.07.19 |
---|---|
[Node.js] 환경변수 관리 (3) | 2024.07.19 |
[Node.js] Session, Token, OAuth, passport (2) | 2024.07.16 |
[Node.js] 페이지 기능 만들기 (0) | 2024.07.16 |
[Node.js] 서버로 데이터 보내기, 게시글 삭제 만들기 (2) | 2024.07.16 |