Related
I am using Express and node for the session management with https. I want to create a session using express so that authentication and the session is made before accessing the data. So I want only admin who can access the books, but the session is undefined. here is my code :
AuthUser.js
export const adminOnly = async (req, res, next) => {
if (!req.session.userId) {
return res.status(401).json({ msg: "You must be logged in" });
}
const admin = await Admin.findOne({
where: {
uuid: req.session.userId,
},
});
if (!admin) return res.status(404).json({ msg: "Akses Terlarang" });
next();
};
Auth.js
export const LoginAdmin = async (req, res) => {
const admin = await Admin.findOne({
where: {
username: req.body.username,
},
});
if (!admin) return res.status(404).json({ msg: "Data not found" });
const match = await argon2.verify(admin.password, req.body.password);
if (!match) return res.status(400).json({ msg: "Wrong Password" });
req.session.userId = admin.uuid;
const uuid = admin.uuid;
const username = admin.username;
const role = admin.role;
res.status(200).json({ uuid, username, role });
};
index.js
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import db from "./config/Database.js";
import {
BookRoute,
BookTypeRoute,
CategoryRoute,
Denda,
PeminjamanRoute,
PengembalianRoute,
UserRoute,
AdminRoute,
} from "./routes/index.js";
import AuthRoute from "./routes/AuthRoute.js";
import SequelizeStore from "connect-session-sequelize";
import session from "express-session";
dotenv.config();
const app = express();
const sessionStore = SequelizeStore(session.Store);
const store = new sessionStore({
db: db,
});
app.use(
session({
secret: process.env.SESS_SECRET,
resave: false,
saveUninitialized: true,
store: store,
cookie: {
secure: "auto",
},
})
);
app.use(
cors({
credentials: true,
origin: "https://localhost:3000",
})
);
app.use(express.json());
app.use(UserRoute);
app.use(AdminRoute);
app.use(BookRoute);
app.use(AuthRoute);
app.use(CategoryRoute);
app.use(BookTypeRoute);
app.use(Denda);
app.use(PeminjamanRoute);
app.use(PengembalianRoute);
// store.sync();
app.listen(process.env.APP_PORT, () => {
console.log("Server is listening on port 5000");
});
I have tried logging console.log('req.session.userId') and it returns undefined value and when I delete if (!req.session.userId) return res.status(401).json({ msg: "You must be logged in" }); the error is Error: WHERE parameter "uuid" has invalid "undefined" value.
I am trying to implement google auth using passportjs, logic works fine in development mode but in development, whenever my frontend interact with my backend, it can't find req.session.user, but when I interact with my backend api directly in the browser, req.session.user was printed in heroku console.
What I want to achieve:
I want to save req.user as req.session.user so I can use it to authenticate a user.
Here is what my code looks like:
------------Configuration of express-session and passportjs--------------
const store = new PgStore({ conString: connection, schemaName: "hidden", createTableIfMissing: true })
app.use(express.json())
app.use(cookieParser(process.env.SESSION_SECRET))
app.set("trust proxy", 1)
app.use(
session({
store: store,
secret: process.env.SESSION_SECRET,
saveUninitialized: true,
resave: true,
proxy: true,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
httpOnly: true,
sameSite: process.env.NODE_ENV === "production" ? 'none' : 'lax',
secure: process.env.NODE_ENV === "production" ? true : false,
},
})
)
app.use(passport.initialize())
app.use(passport.session())
------------------Google auth strategy------------------------
import passport from "passport"
import theGoogleStrategy from "passport-google-oauth2"
import bcrypt from "bcryptjs"
import { v4 as uuidv4 } from 'uuid';
import pool from "../LIB/DB-Client.js"
const GoogleStrategy = theGoogleStrategy.Strategy
/**
* #TODO Work on referral in google signin
*/
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: `${process.env.BACKEND_URL}/auth/google/callback`,
passReqToCallback: true,
},
async (request, accessToken, refreshToken, profile, done) => {
try {
let user
const account = profile._json
console.log(account)
const userWhoWantToSignin = await pool.query("SELECT email, google_user FROM users WHERE email = $1", [
account.email,
])
if (userWhoWantToSignin.rowCount > 0 && userWhoWantToSignin.rows[0].google_user === false) {
return done(null, false)
}
const userTokenAlreadyExist = await pool.query("SELECT token FROM verify_token WHERE token = $1", [account.sub])
const hashedPassword = bcrypt.hashSync(process.env.GOOGLE_USER_PASSWORD, 10)
if (userTokenAlreadyExist.rowCount < 1 && userWhoWantToSignin.rowCount < 1) {
const NewUser = await pool.query(
"INSERT INTO users (first_name, last_name, email, profile_image, profile_image_id, password, verified, google_user) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *",
[
account.given_name ?? account.family_name,
account.family_name ?? account.given_name,
account.email,
account.picture,
process.env.DEFAULT_PROFILE_IMAGE_ID,
hashedPassword,
true,
true,
]
)
const uniqueToken = uuidv4();
await pool.query("INSERT INTO verify_token ( user_id, token) VALUES ($1, $2) RETURNING *", [
NewUser.rows[0].id,
uniqueToken,
])
user = NewUser.rows[0].id
console.log(user)
return done(null, user)
} else {
const updatedUser = await pool.query("SELECT email, id FROM users WHERE email = $1", [account.email])
await pool.query("UPDATE verify_token SET token = $1 WHERE user_id = $2", [
account.sub,
updatedUser.rows[0].id,
])
user = updatedUser.rows[0].id
return done(null, user)
}
} catch (error) {
console.log(error)
done(error)
}
}
)
)
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser((user, done) => {
done(null, user)
})
-----------------------Google auth route---------------------------
import express from "express"
import passport from "passport"
const router = express.Router()
router.get(
"/auth/google",
passport.authenticate("google", {
scope: ["email", "profile"],
})
)
router.get(
"/auth/google/callback",
passport.authenticate("google", {
successRedirect: "/auth/google/success",
failureRedirect: "/auth/google/failed"
})
)
router.get("/auth/google/success", async (req, res) => {
if (!req.user) return res.redirect(`${process.env.FRONTEND_URL}/auth/login`)
req.session.regenerate(async () => {
req.session.user = req.user
return res.redirect(`${process.env.FRONTEND_URL}/profile`)
})
})
router.get("/auth/google/failed", (req, res) => {
return res.redirect(`${process.env.FRONTEND_URL}/auth/login`)
})
export default router
The problem is that I cannot get the cookie in the server. It is set in the browser (I can see it in devtools). When using Postman it works fine (including the middleware). But for some reason when making the request from the browser to the middleware (authMiddleware) the token comes back undefined.
Anyone with any ideas would be great. I have been stuck on this for days! :O
App.js (server)
const express = require('express');
const cookieParser = require('cookie-parser');
const authRouter = require('./routes/authRoutes');
const cocktailRouter = require('./routes/cocktailRoutes');
require('dotenv').config();
const cors = require('cors');
const app = express();
mongoose.connect(process.env.DBURI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then((result) => {
console.log('listening');
app.listen(5000)
})
.catch((err) => console.log(err));
//middleware
app.use(express.static('public'));
app.use(express.json());
app.use(cookieParser());
app.use(cors({ origin: true, credentials: true }));
// ROUTER MIDDLEWARE
app.use('/api/cocktails', cocktailRouter);
app.use('/auth', authRouter);
authMiddleware
const User = require('../models/User');
require('dotenv').config();
//check user is authorized
const requireAuth = (req, res, next) => {
const token = req.cookies.jwt;
console.log('TOKEN', token)
//check json web token exists and is verified
if (token) {
jwt.verify(token, process.env.SECRET_KEY, (err, decodedToken) => {
if (err) {
// res.redirect('/auth/login');
console.log('not logged in')
} else {
console.log('logged in ')
next();
}
})
} else {
// res.redirect('/auth/login');
console.log('not logged in again')
}
};
module.exports = { requireAuth };
cocktailRoute
This is where I am implementing the requireAuth middleware:
const router = Router();
const { requireAuth } = require('../middleware/authMiddleware');
const { cocktail_get, cocktail_post, cocktail_put, cocktail_delete } = require('../controllers/cocktailController');
router.get('/', requireAuth, cocktail_get);
router.post('/', cocktail_post);
router.put('/:cocktailId', cocktail_put);
router.delete('/:cocktailId', cocktail_delete);
module.exports = router;
authController
const jwt = require('jsonwebtoken');
//handle errors function
const handleErrors = (err) => {
const { message } = err;
const errors = { email: '', password: '' }
//incorrect email
if (message === 'Incorrect email') {
errors.email = 'Invalid email';
};
//incorrect password
if (message === 'Incorrect password') {
errors.password = 'Invalid password';
};
//duplicate error = 11000
if (err.code === 11000) {
errors.email = 'That email is already registered';
return errors;
}
//validation errors
if (message.includes('user validation failed')) {
Object.values(err.errors).forEach(({ properties }) => {
errors[properties.path] = properties.message;
})
};
return errors;
}
//create jwt token
const maxAge = 3 * 24 * 60 * 60; // 3 days in seconds
const createToken = (id) => {
return jwt.sign({ id }, process.env.SECRET_KEY, { expiresIn: maxAge })
};
module.exports.register_post = async (req, res) => {
const { name, email, password } = req.body;
try {
const user = await User.create({ name, email, password });
const token = createToken(user._id);
res.cookie('jwt', token, { httpOnly: false, maxAge: maxAge * 1000 });
res.status(201).json({ user: user._id, token });
} catch (err) {
const errors = handleErrors(err);
res.status(400).json({ errors });
}
};
module.exports.login_post = async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.login(email, password);
const token = createToken(user._id);
res.cookie('jwt', token, { httpOnly: false, maxAge: maxAge * 1000, secure: false });
res.status(200).json({ user: user._id });
} catch (err) {
const errors = handleErrors(err);
res.status(400).json({ errors });
}
};
module.exports.logout_get = (req, res) => {
console.log(res.cookie('jwt', '', { maxAge: 1 }))
res.cookie('jwt', '', { maxAge: 1 });
res.redirect('/');
}
FRONTEND (React)
LoginPage
const LoginPage = () => {
const [values, setValues] = useState({ email: '', password: '' });
const handleChange = (event) => {
const { name, value } = event.target;
setValues({ ...values, [name]: value });
};
const handleLoginFormSubmit = (event) => {
event.preventDefault();
const { email, password } = values;
try {
fetch(`${process.env.REACT_APP_API_URL}/auth/login`, {
method: "POST",
withCredentials: true,
credentials: 'include',
headers: { "Content-Type": "application/json", "Accept": "application/json" },
body: JSON.stringify({
email, password
})
})
} catch (err) { if (err.request) { console.log('REQUEST', err.request) } if (err.response) { console.log('RESPONSE', err.response) } }
};
return (
<div>
<h1>Login</h1>
<form onSubmit={handleLoginFormSubmit}>
<input type="text" value={values.email} name="email" placeholder="Enter your email" onChange={handleChange} />
<input type="password" value={values.password} name="password" placeholder="Enter your password" onChange={handleChange} />
<button>Login</button>
</form>
</div>
)
}
export default LoginPage
I am making full stack app and learn from tutorials and videos . I have a problem with GET request to get information about user which is login in the system. I use Postman to check the requests. When I add user with /login , the Postman look user's accesstoken code. I copy his code and paste it in authorization key in headers in Postman and when I change the URL in localhost to /infor to get information about this user and send it. But it say me "Invalid Authentication". I can't find the wrong. I think the problem is in controllers/userCtrl.js in getUser function. Can you help me?
I put the code:
server.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())
// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
useTempFiles: true
}))
// Routes
app.use('/user', require('./routes/userRouter'))
// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
}, err =>{
if(err) throw err;
console.log('Connected to MongoDB')
})
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
.env
MONGO_URL = ***********
ACCESS_TOKEN_SECRET = ***********
REFRESH_TOKEN_SECRET = *************
routes/userRouter.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())
// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
useTempFiles: true
}))
// Routes
app.use('/user', require('./routes/userRouter'))
// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
}, err =>{
if(err) throw err;
console.log('Connected to MongoDB')
})
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
models/userModel.js
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
role: {
type: Number,
default: 0
},
cart: {
type: Array,
default: []
}
}, {
timestamps: true
})
module.exports = mongoose.model('Users', userSchema)
middleware/auth.js
const jwt = require('jsonwebtoken')
const auth = (req, res, next) => {
try{
const token = req.header("Authorization")
if(!token) return res.status(400).json({ msg: "Invalid Authentication" })
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if(!err) return res.status(400).json({msg: "Invalid Authentication" })
req.user = user
next()
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
}
module.exports = auth
controllers/userCtrl.js
const Users = require('../models/userModel')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const userCtrl = {
register: async (req, res) => { // async before a function means one simple thing: a function always returns a promise.
try{
const { name, email, password } = req.body
const user = await Users.findOne({ email }) // wait until the promise resolves
if(user) return res.status(400).json({msg: "The email already exists"})
if(password.length < 6)
return res.status(400).json({msg: "Password is at least 6 characteres long."})
//Password encryption
const passwordHash = await bcrypt.hash(password, 10)
const newUser = new Users({
name, email, password: passwordHash
})
// save mongodb
await newUser.save()
//then create jsonwebtoken to authentication
const accesstoken = createAccessToken({ id: newUser._id })
const refreshtoken = createRefreshToken({ id: newUser._id })
res.cookie('refreshtoken', refreshtoken, {
httpOnly: true,
path: '/user/refresh_token'
});
res.json({accesstoken})
} catch(err){
return res.status(500).json({msg: err.message})
}
},
login: async (req, res) => {
try{
const {email, password} = req.body;
const user = await Users.findOne({email})
if(!user) return res.status(400).json({msg: "User does not exist."})
const isMatch = await bcrypt.compare(password, user.password)
if(!isMatch) return res.status(400).json({msg: "Incorrect password"})
// if login success, create access token and refresh token
const accesstoken = createAccessToken({ id: user._id })
const refreshtoken = createRefreshToken({ id: user._id })
res.cookie('refreshtoken', refreshtoken, {
httpOnly: true,
path: '/user/refresh_token'
});
res.json({accesstoken})
} catch(err){
return res.status(500).json({msg: err.message})
}
},
logout: async (req, res)=> {
try{
res.clearCookie('refreshtoken', {path: '/user/refresh_token'})
return res.json({msg: "Logged out"})
}catch(err){
return res.status(500).json({msg: err.message})
}
},
refreshToken: (req, res) => {
try{
const rftoken = req.cookies.refreshtoken
if(!rftoken) return res.status(400).json({msg: "Please login or Register"})
jwt.verify(rftoken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if(err) return res.status(400).json({msg: "Please login or Register"})
const accesstoken = createAccessToken({id: user.id})
res.json({ accesstoken })
})
}catch (err) {
return res.status(500).json({msg: err.message})
}
},
getUser: async (req, res) => { // problem
try{
const user = await (await Users.findById(req.user.id)).isSelected('-password')
if(!user) return res.status(400).json({ msg: "Useer does not exist."})
res.json(req.user)
}catch (err) {
return res.status(500).json({msg: err.message})
}
}
}
const createAccessToken = (user) => {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
}
const createRefreshToken = (user) => {
return jwt.sign(user, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '7d' })
}
module.exports = userCtrl
For your middle ware for getting the token (auth function)
const { authorization } = req.headers
if (!authorization) {
console.log('[No Authorization Code]');
return res.status(401).send({ message: 'Unauthorized' });
}
if (!authorization.startsWith('Bearer')) {
console.log('[Authorization need to start with Bearer]')
return res.status(401).send({ message: 'Unauthorized' });
}
const split = authorization.split('Bearer ')
if (split.length !== 2) {
console.log('[Invalid Authorization Param')
return res.status(401).send({ message: 'Unauthorized' });
}
const token = split[1] //this is your token to use with jwt.verify
When you sending the token in postman, select Bearer Token
When you start creating your frontend, the codes should be equivalent to the following fetch request
fetch('/api/path', { method: 'GET', headers: { "Authorization": `Bearer ${token}`}}).(res => res.json())
May change method to your desire method (e.g get or post), and the token will be the the jwt token
In localhost, deserializeUser is being called, and there was no problem.
But after we deploy our app to ec2 using nginx(react), deserializeUser is never called.
const express = require("express");
const cors = require("cors");
const path = require("path");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const passport = require("passport");
const flash = require("connect-flash");
const authRouter = require("./routes/auth");
const calendarRouter = require("./routes/calendar");
const healthPillRouter = require("./routes/healthPill");
const { sequelize } = require("./models");
const passportConfig = require("./passport");
dotenv.config();
const app = express();
sequelize
.sync()
.then(() => {
console.log("db 연결 성공");
})
.catch(console.error);
passportConfig(passport);
app.set("view engine", "pug");
app.use(morgan("combined"));
app.use(cors({ origin: "http://13.124.67.98", credentials: true }));
app.use("/", express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
resave: false,
saveUninitialized: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true,
secure: false,
},
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use("/", authRouter);
app.use("/", calendarRouter);
app.use("/", healthPillRouter);
app.listen(4000, () => {
console.log("실행중");
});
app.set("port", process.env.PORT || 8001);
// if (process.env.NODE_ENV === "production") {
// app.use(morgan("combined"));
// } else {
// app.use(morgan("dev"));
// }
app.use(express.static(path.join(__dirname, "public")));
app.use(cookieParser(process.env.COOKIE_SECRET));
const sessionOption = {
resave: false,
saveUninitialized: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true,
secure: false,
},
};
// if (process.env.NODE_ENV === "production") {
// sessionOption.proxy = true;
// sessionOption.cookie.secure = true;
// }
app.use(session(sessionOption));
app.use(flash());
this is our app.js
and the bottom is our router code.
<auth.js>
const express = require("express");
const passport = require("passport");
const bcrypt = require("bcrypt");
const { isLoggedIn, isNotLoggedIn } = require("./middlewares");
const { User, Cycle } = require("../models");
const router = express.Router();
//회원가입
router.post("/api/auth/register", isNotLoggedIn, async (req, res) => {
const {
userName,
userEmail,
userPassword,
userBirth,
userWeight,
userHeight,
firCycleStart,
firCycleEnd,
meanCycle,
meanPeriod,
userAlcohol,
} = req.body;
try {
//exUser 존재 시
const exUser = await User.findOne({ where: { userEmail } });
if (exUser) {
return res.send("이미 가입된 이메일입니다");
}
//비밀번호 암호화
const hash = await bcrypt.hash(userPassword, 12);
//users 테이블에 사용자 정보 저장
await User.create({
userName: userName,
userEmail: userEmail,
userPassword: hash,
userBirth: userBirth,
userWeight: userWeight,
userHeight: userHeight,
meanCycle: meanCycle,
meanPeriod: meanPeriod,
userAlcohol: userAlcohol,
});
const loginUser = await User.findOne({
attributes: ["id"],
where: {
userEmail: userEmail,
},
});
//시작일 정보를 입력했을 때만 주기정보 저장
if (firCycleStart) {
await Cycle.create({
bleedStart: firCycleStart,
bleedEnd: firCycleEnd,
userId: loginUser.id,
});
}
return res.status(201).json({ completed: true });
} catch (error) {
console.error(error);
return next(error);
}
});
//로그인 성공 시 json 형식으로 사용자 이름 send
router.post("/api/auth/login", isNotLoggedIn, async (req, res, next) => {
passport.authenticate("local", (authError, user, info) => {
if (authError) {
console.log(authError);
return next(authError);
}
if (!user) {
return res.send(info.message);
}
return req.login(user, (loginError) => {
if (loginError) {
console.error(loginError);
return next(loginError);
}
return res.json({id: user.id, name: user.userName});
});
})(req, res, next);
});
//로그아웃
router.get("/api/auth/logout", isLoggedIn, async (req, res) => {
console.log(req.user.id);
req.logout();
req.session.destroy();
console.log("로그아웃");
return res.status(200).send("로그아웃 되었습니다");
});
module.exports = router;
<calendar.js>
const express = require("express");
const { isLoggedIn } = require("./middlewares");
const { User, Date, Cycle } = require("../models");
const router = express.Router();
const moment = require("moment");
const Sequelize = require("sequelize");
const Op = Sequelize.Op;
//캘린더 디테일 페이지 POST
//로그인한 사용자의 id는 req.user.id로 가져올 수 있다
router.post("/api/main/date", isLoggedIn, async (req, res) => {
const {
date,
cycleStart,
cycleEnd,
isSex,
isProtection,
isControl,
dateMood,
//★ 프런트 처리 미완 ★
dateCondition,
dateMemo,
} = req.body;
try {
//사용자가 입력한 정보를 dates 테이블에 입력
//upsert 기준이 (date+userId)여야하는데 sequelize는 FK를 composite key로 사용 불가... if문 쓰는 수 밖에?
const exDate = await Date.findOne({
where: { date: date, userId: req.user.id },
});
//이미 존재하던 날짜 정보면 update
if (exDate) {
await Date.update(
{
date: date,
isSex: isSex,
isProtection: isProtection,
isControl: isControl,
dateMood: dateMood,
dateCondition1: dateCondition,
//★ 프런트 처리 미완 ★
dateCondition2: 0,
dateCondition3: 0,
dateMemo: dateMemo,
userId: req.user.id,
},
{
where: { date: date, userId: req.user.id },
}
);
} else {
//새로운 날짜 정보면 create
await Date.create({
date: date,
isSex: isSex,
isProtection: isProtection,
isControl: isControl,
dateMood: dateMood,
dateCondition1: dateCondition,
//★ 프런트 처리 미완 ★
dateCondition2: 0,
dateCondition3: 0,
dateMemo: dateMemo,
userId: req.user.id,
});
}
//사용자가 입력한 정보를 cycles 테이블에 입력
//cycleStart cycleEnd 동시에 존재하는 경우는 없게 프런트에서 처리 완료
const exCycle = await Cycle.findOne({
where: {
bleedStart: { [Op.ne]: null },
bleedEnd: null,
userId: req.user.id,
},
});
//bleedStart만 있고 bleedEnd는 없는 이전 기록이 존재하는 경우
if (exCycle) {
if (cycleStart) {
//잘못된 입력. 이전 기록의 cycleEnd를 미리 설정해야 함.
res.send("최근 생리 종료일을 먼저 입력해야 합니다.");
} else if (cycleEnd) {
//사용자가 cycleEnd를 설정: cycles 테이블 bleedEnd 업데이트
await Cycle.update(
{
bleedEnd: cycleEnd,
},
{
where: {
bleedStart: { [Op.ne]: null },
bleedEnd: null,
userId: req.user.id,
},
}
);
return res.status(200).json({ completed: true });
}
} else {
//이전 기록이 존재하지 않는 경우
if (cycleStart) {
//사용자가 cycleStart를 설정: cycles 테이블 bleedStart 저장
await Cycle.create({
bleedStart: cycleStart,
userId: req.user.id,
});
return res.status(200).json({ completed: true });
} else if (cycleEnd) {
//사용자가 cycleEnd를 설정: cycles 테이블 bleedEnd 저장, bleedStart = bleedEnd - cycles.meanPeriod로 계산 후 저장
const userInfo = await User.findOne({
attributes: ["meanPeriod"],
where: { id: req.user.id },
});
await Cycle.create({
//★ meanPeriod를 입력 안 한 사용자일때? ★
bleedStart: moment(cycleEnd, "YYYY-MM-DD")
.subtract(userInfo.meanPeriod, "d")
.format("YYYY-MM-DD"),
bleedEnd: cycleEnd,
userId: req.user.id,
});
return res.status(200).json({ completed: true });
} else {
return res.status(200).json({ completed: true });
}
}
} catch (error) {
console.error(error);
return next(error);
}
});
//캘린더 디테일 페이지 GET
//입력된 정보가 있으면 보내주고, 없으면 "입력된 정보가 없습니다."
router.get("/api/main/", isLoggedIn, async (req, res) => {
//날짜는 req.body로 받아옴
const date = req.query.Date_send;
try {
const exDate = await Date.findOne({
where: { date: date, userId: req.user.id },
});
if (exDate) {
res.send(exDate);
} else {
res.send("입력된 정보가 없습니다.");
}
} catch (error) {
console.error(error);
return next(error);
}
});
router.get("/api/main/today", isLoggedIn, async (req, res) => {
//날짜는 req.body로 받아옴
const date = req.query.Today_send;
try {
const exDate = await Date.findOne({
where: { date: date, userId: req.user.id },
});
if (exDate) {
res.send(exDate);
} else {
res.send("입력된 정보가 없습니다.");
}
} catch (error) {
console.error(error);
return next(error);
}
});
module.exports = router;
login and register have no problem, but I couldn't use any functions needed login session or cookies. How I solve this problem?
Since the release of Google Chrome 80 on February 4, 2020, the default value of Cookie's SameSite property has been changed from None to Lax.
In other words, if you send an intersection request, not the same domain address, the cookie will not work.
The solution was to change the cookie settings to sameSite none in backend app.js.
But if you change it, you have to put the attribute secure true, and it was only possible in https.
Even if it is not https, if front and backend are using the same domain, there is no problem.
I believe that applying the domain will not result in an error, because eventually you have to have a domain to apply for https