๋ณต์ต - MONGODB AND MONGOOSE
๋ณต์ต - USER AUTHENTICATION
์ค์ ์ฝ๋๋ github์ ์ฌ๋ฆผ(wetube_v2)
๐ก ํด์ํ๊ทธ ํฌ๋งท
- ๋ฐฉ๋ฒ 1 (pre hook ์ด์ฉ)
DB update ์์๋ ์ฌ์ฉ ๋ชป ํจ// Video.js videoSchema.pre("save", async function () { // form์์ ๋ฐ์์จ hashtags๊ฐ ์๋๋ผ schema์ hashtags๋ผ์ ๋ฌธ์์ด ์๋๊ณ ๋ฐฐ์ด ํํ โ this.hashtags = await this.hashtags[0] .split(",") .map((word) => (word.startsWith("#") ? word : `#${word}`)); });
- ๋ฐฉ๋ฒ 2 (formatHashtags ํจ์ export & import)
// Video.js export const formatHashtags = (hashtags) => hashtags.split(",").map((word) => (word.startsWith("#") ? word : `#${word}`));
// videoController.js import Video, { formatHashtags } from "../models/Video"; export const postEdit = async (req, res) => { // ์ค๋ต await Video.findByIdAndUpdate(id, { title, description, hashtags: formatHashtags(hashtags), }); // ์ค๋ต };
- ๋ฐฉ๋ฒ3 (query ์ง์ ๋ง๋ค๊ธฐ)
// Video.js videoSchema.static("formatHashtags", function(hashtags) { return hashtags.split(",").map((word) => (word.startsWith("#") ? word : `#${word}`)); })
// videoController.js export const postEdit = async (req, res) => { // ์ค๋ต await Video.findByIdAndUpdate(id, { title, description, hashtags: Video.formatHashtags(hashtags), }); // ์ค๋ต };
[TIL] 211130 ๐ฅ
[TIL] 211201 ๐ฅ
[TIL] 211202 ๐ฅ
[TIL] 211203 ๐ฅ
๐ก github ๋ก๊ทธ์ธ ์์
[ startGithubLogin ]
github ๋ก๊ทธ์ธ ๋งํฌ ํด๋ฆญ
http:// localhost:7000/users/github/start
https:// github.com/login/oauth/authorize?client_id=...[ finishGithubLogin ]
user๊ฐ ์ฑ์ผ๋ก ํ์ฌ๊ธ github user ์ ๋ณด์ ์ ๊ทผํ ์ ์๋๋ก ๊ถํ์ ์น์ธํด์ค
http:// localhost:7000/users/github/finish?code=... (redirect)https:// github.com/login/oauth/access_token?client_id... (fetch ์ด์ฉ)
code๋ฅผ access token์ผ๋ก ๋ฐ๊ฟhttps:// api.github.com/user (fetch ์ด์ฉ)
github api์ ์ ๊ทผํด์ user data์ user email ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ดprimary & verified email์ ์ฐพ์
github email์ด DB์ ์๋ค๋ฉด login ์ํด
github email์ด DB์ ์๋ค๋ฉด, ๊ทธ user์ ๊ณ์ ์ ์์ฑํจ
๐ก github email์ด DB์ ์๋ค๋ฉด, ๊ทธ user์ ๊ณ์ ์ ์์ฑํ๋ค
์ด๋ (๋น๋ก userSchema์์ password๊ฐ ํ์ ๊ฐ์ด ์๋๋๋ผ๋) User.create({ })์๋password: ""
๋ ์ ์ด์ค์ผ ํ๋ค.
ํจ์ค์๋๋ฅผ ํด์ฑํ๋ bcrypt๊ฐ password ๊ฐ์ ํ์๋ก ํ๊ธฐ ๋๋ฌธ์ด๋ค.
์ด ๊ฒฝ์ฐ ๋น ๋ฌธ์์ด์ ํด์ฑํ์ฌ DB์ ์ ์ฅํ๊ฒ ๋๋ค.๋์ , github ์ ๋ณด๋ฅผ ์ด์ฉํด ๊ณ์ ์์ฑ์ ์ํด User.create({ })๋ฅผ ์คํํ ๋ password ํ๋๋ ์์ ์ฐ์ง ๋ง๊ณ , ํจ์ค์๋๋ฅผ ํด์ฑํ๋ pre hook์
if (!this.socialOnly && this.isModified("password"))
๋ฅผ ์ถ๊ฐํ ์๋ ์๋ค. [TIL] 211226 ์ฐธ๊ณ