The authentication strategy "github" is unrecognized

I am encountering an issue with online authentication on GitHub. Even after registering the new app on GitHub, the application continues to fail to redirect to OAuth.

I have written the following code and am receiving an error message stating: Error: Unknown authentication strategy "github"

const passport      = require('passport');
const bcrypt        = require('bcrypt');

module.exports = function (app, db) {

    app.route('/')
      .get((req, res) => { 
        res.render(process.cwd()+'/views/pug/index', {title: 'Hello', message: 'Please login',showLogin: true, showRegistration: true});
      });


    app.route('/login')
      .post(passport.authenticate('local',{ failureRedirect: '/' }),(req,res)=>{
         res.redirect('/profile');
      });

    function ensureAuthenticated(req, res, next) {
      if (req.isAuthenticated()) {
        return next();
      }
      res.redirect('/');
     }

    app.route('/profile')
      .get(ensureAuthenticated, (req,res) => {
         res.render(process.cwd() + '/views/pug/profile',{username:req.user.username});
      });

    app.route('/logout')
      .get((req, res) => {
        req.logout();
        res.redirect('/');
      });


    app.route('/register')
     .post((req, res, next) => {
        var hash = bcrypt.hashSync(req.body.password, 12);
        db.collection('users').findOne({ username: req.body.username }, function (err, user) {
          if(err) {
              next(err);
          } else if (user) {
              res.redirect('/');
          } else {
              db.collection('users').insertOne(
                {username: req.body.username,
                 password: hash},
                (err, doc) => {
                    if(err) {
                        res.redirect('/');
                    } else {
                        next(null, user);
                    }
                }
              )
          }
      })},
    passport.authenticate('local', { failureRedirect: '/' }),
    (req, res, next) => {
        res.redirect('/profile');
    }
    );

  /*GitHub OAuth*/

  app.route('/auth/github')
    .get(passport.authenticate('github'));

   app.route('/auth/github/callback')
    .get(passport.authenticate('github', { failureRedirect: '/' }), (req,res) => { 
    res.redirect('/profile'); 
  });

  /*End of GitHub OAuth*/

  app.use((req, res, next) => {
    res.status(404)
      .type('text')
      .send('Not Found');
  });
}

I appear to be missing something or possibly overlooking a step in setting up OAuth for GitHub. The default strategy for GitHub is being accessed without defining the strategy on my end.

Answer №1

To successfully implement passport github strategy, you will need to configure it in your script. Follow this link for detailed instructions: https://github.com/jaredhanson/passport-github var GitHubStrategy = require('passport-github').Strategy;

passport.use(new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ githubId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmit messages from server (via Expressjs routing) to the client

I am looking for guidance on how to effectively send messages from the server to the client and incorporate this functionality into routes/index.js within my mean stack project. Can anyone provide insights on using socket.io in this context?: router.post( ...

When utilizing Express and body-parser for parsing a DELETE request, the body may be found to be

Currently using expressjs along with the body-parser middleware. This is how it is set up: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); When a DELETE request is sent from the client, the server side is receiving an emp ...

Streaming with Node/Express does not support downloading files directly using stream.pipe()

Is there a method to trigger a download when I stream data to the response in Node.js? HTTP/1.1 200 OK Server: Cowboy Connection: keep-alive X-Powered-By: Express Content-Type: application/pdf Date: Mon, 10 Oct 2016 20:22:51 GMT Transfer-Encoding: chunked ...

The attempt to add a note with a POST request to the /api/notes/addnote endpoint resulted in a

I'm facing an issue while trying to send a POST request to the /api/notes/addnote endpoint. The server is returning a 404 Not Found error. I have checked the backend code and made sure that the endpoint is correctly defined. Here are the specifics of ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

Why are JavaScript errors constantly popping up when I use Django Pipeline?

After configuring Django Pipeline (version 1.3.15) for a specific group of JS files, I ensured they were in the correct order based on their appearance on my page. The collectstatic process went smoothly and when viewing the source, it looked like all th ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

Nodemon persisted in its search for the index.js file

My Nodemon continuously starts looking for index.js, but I prefer to use app.js like most people do nowadays. https://i.sstatic.net/GVcNk.png How can I configure nodemon to search for app.js instead? I have attempted uninstalling and reinstalling withou ...

Triggering an event for a div using Javascript, along with a Rails loop

I have a page showcasing a collection of listings that are displayed on the main page. <% @listings.each do |listing| %> # do something <% end %> Each listing now includes a data-toggle, essentially a button. <a id="chat-menu-toggle" h ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

Execute JavaScript script whenever the state changes

I have a large table with multiple HTML elements such as dropdowns, textboxes, radio buttons, and checkboxes. Additionally, I have a function that I want to execute whenever any of these items change. Whether it's a selection from a dropdown, typing i ...

Learning how to implement react-toastify promises with axios is a valuable skill to have

// I am trying to implement toastify promises to show a spinner while fetching data and then display a success or failed message // However, I am encountering an error in the code below const fetchData = () => { axios .get("https://restc ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

Using Django to Display a Line Chart with Data from a Dictionary in a Template

I have a dictionary that was generated in the views.py file. The structure of the dictionary is as follows, but it contains data for an unspecified number of enterprises: { enterprise1: {'Year': ['2014/2015', '2016/2017', &ap ...

Uncertainty arises from the information transmitted from the controller to the Ajax function

In one of my coffee scripts, I have an AJAX call that calls a method in a controller. The AJAX call is structured like this: auto = -> $.ajax url : '<method_name>' type : 'POST' data : <variable_name> ...

JQuery causing array to not update properly

I am attempting to splice an array to remove an object from it. My approach involves using angular-formly for form display, and AngularJs with JQuery to manage the data. Utilizing JQuery $(document).on("click", ".delete-me", function () { var id = $( ...

What is the process for displaying a PHP array in HTML5 audio and video players?

I am currently working with two PHP arrays. The first array, array "a," contains strings that represent paths for MP3 files on the server. The second array, array "b," contains strings representing paths for MP4 files. For example: $test = 'a.mp3&ap ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

Nodemon functioning inconsistently across various directories

As I begin working on a new project, I understand that some people may be frustrated when questions are asked repeatedly. However, the solutions provided in previous posts have not resolved my current issue. Upon entering the command 'nodemon server&a ...