Tabbatarwa da izini a cikin Express.js: Tsare Samun damar mai amfani

Tabbatarwa da izini abubuwa ne masu mahimmanci don tabbatar da tsaro na aikace-aikacen yanar gizo. A cikin Express.js mahalli, zaku iya aiwatar da ingantaccen amincin mai amfani da samun izini don amintaccen albarkatu. Ga jagora kan yadda ake cim ma wannan:

Tabbatar da mai amfani

Yi amfani da Tantancewa Middleware: Ƙirƙiri tabbaci middleware don bincika idan mai amfani ya shiga.

function isAuthenticated(req, res, next) {  
  if(req.isAuthenticated()) {  
    return next();  
  }  
  res.redirect('/login');  
}  
  
app.get('/profile', isAuthenticated,(req, res) => {  
  // Access profile page when logged in  
});  

 

Samun Izini don Amintattun Albarkatu

Yi amfani da izini Middleware: Ƙirƙiri middleware don bincika izinin samun damar mai amfani don amintaccen albarkatu.

function hasPermission(req, res, next) {  
  if(req.user.role === 'admin') {  
    return next();  
  }  
  res.status(403).send('Access denied');  
}  
  
app.get('/admin', isAuthenticated, hasPermission,(req, res) => {  
  // Access admin page with proper permission  
});  

 

Amfani da Laburaren Tabbatarwa da Izini

Yi amfani Passport.js: Yi amfani da Passport.js ɗakin karatu don sauƙaƙe ƙwarewa da izini.

const passport = require('passport');  
app.use(passport.initialize());  
  
app.post('/login', passport.authenticate('local', {  
  successRedirect: '/profile',  
  failureRedirect: '/login'  
}));  
  
app.get('/admin', isAuthenticated, hasPermission,(req, res) => {  
  // Access admin page with proper permission  
});  

 

Kammalawa

Tabbatarwa da izini suna taka muhimmiyar rawa wajen kiyaye aikace-aikacen gidan yanar gizo daga barazanar tsaro. Ta amfani da middleware, dakunan karatu kamar Passport.js, da binciken izini, za ku iya tabbatar da cewa masu amfani kawai za su iya samun damar dacewa da albarkatu masu aminci.