{"size": 1172, "ext": "js", "max_stars_repo_path": "src/auth/middleware/basic-auth-middleware.js", "max_stars_repo_name": "Abdallah-Obaid/aqar-team", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/auth/middleware/basic-auth-middleware.js", "max_issues_repo_name": "Abdallah-Obaid/aqar-team", "max_issues_repo_issues_event_min_datetime": "2021-09-02T13:43:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T13:43:54.000Z", "max_forks_repo_path": "routes/middleware/basic-auth-middleware.js", "max_forks_repo_name": "Abdallah-401-advanced-javascript/lab-32-api", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": null, "avg_line_length": 30.8421052632, "max_line_length": 76, "alphanum_fraction": 0.6706484642}
'use strict';

const users = require('../users');
const base64 = require('base-64');

module.exports = (req, res, next) => {
  // check username and password if we have them sent in the request
  // req : params body qs headers
  // req.headers.authorization, encoded username and password
  if (!req.headers.authorization) {
    console.log(req.headers.authorization);
    next('invalid Login');
    return;
  }
  //  headers value : 
  // authorization(key name) : Basic dGVzdEB0ZXN0LmNvbTp0ZXN0MTIz (value) 
  // Pull out this encoded part and split the header value
  console.log('req.headers.authorization >>>> ',req.headers.authorization); 
  let basic = req.headers.authorization.split(' ').pop();
  console.log(basic);

  // decode to user:pass
  let [user, pass] = base64.decode(basic).split(':'); // [user, pass];
  // let user = res[0];
  // let pass = res[1];
  console.log(user);
  console.log(pass);

  users.authenticateBasic(user, pass).then(async (validUser) => {
    req.token = await users.generateTokenIn(validUser);
    console.log('TOOOOOOOOOOOOOOOOOOOOOOOOOOOOOKTTKSDKF',req.token);
    next();
  })
    .catch(err => next('Invalid Login!!'));

};

