diff --git a/app.js b/app.js index 46f10df..59e9bea 100644 --- a/app.js +++ b/app.js @@ -121,19 +121,48 @@ global.syzoj = { app.use((req, res, next) => { // req.session.user_id = 1; + let User = syzoj.model('user'); if (req.session.user_id) { - let User = syzoj.model('user'); User.fromID(req.session.user_id).then((user) => { res.locals.user = user; next(); }).catch((err) => { this.log(err); - res.locals.user = req.session.user_id = null; + res.locals.user = null; + req.session.user_id = null; next(); }) } else { - res.locals.user = req.session.user_id = null; - next(); + if (req.cookies.login) { + let obj; + try { + obj = JSON.parse(req.cookies.login); + User.findOne({ + where: { + username: obj[0], + password: obj[1] + } + }).then(user => { + if (!user) throw null; + res.locals.user = user; + req.session.user_id = user.id; + next(); + }).catch(err => { + console.log(err); + res.locals.user = null; + req.session.user_id = null; + next(); + }); + } catch (e) { + res.locals.user = null; + req.session.user_id = null; + next(); + } + } else { + res.locals.user = null; + req.session.user_id = null; + next(); + } } }); diff --git a/modules/api.js b/modules/api.js index 140644c..5c660e4 100644 --- a/modules/api.js +++ b/modules/api.js @@ -25,6 +25,10 @@ let WaitingJudge = syzoj.model('waiting_judge'); let JudgeState = syzoj.model('judge_state'); let TestData = syzoj.model('testdata'); +function setLoginCookie(username, password, res) { + res.cookie('login', JSON.stringify([username, password])); +} + // Login app.post('/api/login', async (req, res) => { try { @@ -35,6 +39,7 @@ app.post('/api/login', async (req, res) => { else if (user.password !== req.body.password) res.send({ error_code: 1002 }); else { req.session.user_id = user.id; + setLoginCookie(user.username, user.password, res); res.send({ error_code: 1 }); } } catch (e) { @@ -65,6 +70,8 @@ app.post('/api/sign_up', async (req, res) => { await user.save(); req.session.user_id = user.id; + setLoginCookie(user.username, user.password, res); + res.send(JSON.stringify({ error_code: 1 })); } catch (e) { syzoj.log(e); diff --git a/modules/user.js b/modules/user.js index de02e65..b80d4ef 100644 --- a/modules/user.js +++ b/modules/user.js @@ -78,6 +78,7 @@ app.get('/sign_up', async (req, res) => { // Logout app.get('/logout', async (req, res) => { req.session.user_id = null; + res.clearCookie('login'); res.redirect(req.query.url || '/'); });