2016-09-26 65 views
0

這是一個nodejs設置。我們的目標是防止執行代碼的某些部分,如果用戶不是在管理員組:從外部文件調用執行停止代碼

這是file1.js:

export function adminAuthRequired(req, res) { 
if (req.session.user_group !== "admin") { 
    const message = "You are not authorized to access this content." 

    boundaries.redirectToPage(res, message, "redirect-default-page.ejs") 

} 

}

這是file2.js調用該函數from file1.js:

public destroy(slug) { 
    utils.adminAuthRequired(this.req, this.res) // Here we include file1 function 
    // Code needs to stop execution here if user is not admin 

    // Query db for user details 
    db.deleteSingleRecord(this.res, "links", `WHERE link_slug = ${slug}`, callback) 

    // ... rest of code.... 
} 

是否有無論如何在file2的adminAuthRequired調用後停止代碼執行?在file1中處理執行停止?

我可以簡單地在file2中從文件1返回的bool中執行if語句,但是我想知道是否有方法將它全部嵌入到file1中?

+0

你可以創建一個file2.js函數,就是所謂的「executeAsAdmin」,並通過功能作爲在file1.js定義,但執行的參數在file2.js中,並且只有當用戶是管理員時。 – Glubus

回答

0

您可以使用回撥方法..

例如,

export function adminAuthRequired(req, res, cb) { 
    if (req.session.user_group !== "admin") { 
     const message = "You are not authorized to access this content." 
     boundaries.redirectToPage(res, message, "redirect-default-page.ejs") 
    } else cb(); 
} 

,然後調用類似 - >

public destroy(slug) { 
    utils.adminAuthRequired(this.req, this.res, function() { 
     db.deleteSingleRecord(this.res, "links", `WHERE link_slug = ${slug}`, callback); 
     // ... rest of code.... 
    }); 
}