ノードjsにユーザーの認証機能があり、認証、パスポート、その他のライブラリを使用していないので、よく理解できなかったので、独自の認証機能を実行しました。ただし、私の関数はユーザーに対してのみ本物であり、Cookieを作成しません。「有効期限」ノードでCookieを作成する必要があり、待機するとすぐにログインルートにリダイレクトされます。これをこの関数に実装したい:
function verify(req,res,username,password){
db.serialize(function (){
const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
db.all(query,[username, password],function(err,rows){
if(err) {
console.log(err);
}
if(rows.length == 1){
console.log(rows);
console.log("Correct user");
res.render(__dirname + "/View/Home/index.handlebars");
}
else{
console.log("Incorrecto user!")
res.redirect('/login')
}
});
});
}
これはノードjsでの私のルートです
app.get("/login", (req,res) => {
res.render(__dirname + "/View/Home/login.handlebars");
});
app.post("/",(req,res) => {
const username = req.body.username
const password = req.body.password
verify(req,res,username,password)
});
ユーザーが有効で、Cookieの有効期限が切れると、ユーザーは「/ login」ルートに再度リダイレクトされる場合は、verify()関数内にCookieを作成する必要があります。
Expressサーバーを使用している場合は、を使用してCookieを設定できますres.cookie(name, value, options)
。options
はオブジェクトであり、maxAge
プロパティはおそらく必要なものです。つまり、有効期限が切れる前の数はミリ秒です。たとえば、ユーザーが有効な場合は、次のことができますres.cookie('username', username, {maxAge: 172800000 /* two days */})
。
リクエストのCookieにはreq.cookies
、Cookie名キーと文字列値のオブジェクトであるを使用してアクセスできます。'username'
キーが存在して有効かどうかを確認でき、存在しない場合は、を使用してリダイレクトできres.redirect
ます。
function verify(req,res,username,password){
// Place this block wherever you want it to check for a valid cookie
// Depending on the context when this function is called, that might not be at the start
if(typeof(req.cookies.username) != 'string')
res.redirect('/login');
db.serialize(function (){
const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
db.all(query,[username, password],function(err,rows){
if(err) {
console.log(err);
}
if(rows.length == 1){
console.log(rows);
console.log("Correct user");
// Set Cookie
res.cookie('username', username, {maxAge: 172800000 /* two days */});
res.render(__dirname + "/View/Home/index.handlebars");
}
else{
console.log("Incorrecto user!")
res.redirect('/login')
}
});
});
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加