Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

node.js - Authentication API in nodejs and angular using passport

I am building a web app using Angular, Express, Node JS, and I am using JSON files as a Database. I want to achieve User login authentication. I want when the user logs in the app using their username and passport, the app fetches the user_ID from the express/passport session according to which the user specific data is fetched in the following routes.. If the username and passport match then only the routes get authenticated otherwise we get redirected to the login page itself.

I am facing a problem in the implementation of the authentication API. How should I retrieve the credentials like User_ID in the other routes/pages of a particular session. I want to use Passport middleware. Kindly help.

//main router

app.use(
  session({
    secret: "dcdkkej8cue8fhn36q21",
    resave: false,
    saveUninitialized: true,
  })
);
app.use(passport.initialize());
app.use(passport.session({
  secret: 'cookie_secret',
  name: 'cookie_name',
  proxy: true,
  resave: true,
  saveUninitialized: true
}));

// app.use(cors());
app.use(cors({origin: [
  "http://localhost:4200"
], credentials: true}));
app.use("/", require("./routes/api/users"));
assport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(User, done) {
    User.loadOne({ _id: id }).then(function(user) {
        done(null, user);
    }).catch(function(err) {
        done(err, null);
    });
});

//Login middleware

router.get("/login" , (req, res) => {
  try {
    console.log("Checking Users");
    fs.readFile(registeredUsers, "utf8", (err, data) => {
      if (err) {
        console.log(err);
      }
      console.log("queries" + JSON.stringify(req.query));
      let id = req.query.name;
      let pass = req.query.password;
      let users = JSON.parse(data);
      const found = users.some(
        (user) => user.name === id && user.password == pass
      );
      // console.log("59", found);
      if (found) {
        console.log("found");
        const user = users.filter(
          (user) => user.name === id && user.password == pass
        );
        req.login(user[0], function (err) {
          if (err) {
            return next(err);
          }

        // return res.redirect('/playlist/' + req.session.passport.user);

          // console.log("user " + req.user.name);
          // console.log("Auth " + req.isAuthenticated());

          // passport.authenticate("local", {
          //   successRedirect: "/",
          //   failureRedirect: "/login",
          //   failureFlash: "Invalid username or password.",
          // })

          return res.json(user);
        });
      } else {
        res.status(400).json({
          msg: `User not found with name = ${id} and password = ${pass}`,
        });
      }
    });
  } catch (err) {
    console.log(err);
  }
});

//User Service

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(public httpClient: HttpClient) { }
  getUser(user: { name: string; password: string; }): Observable<any>{
    // return this.httpClient.get('http://localhost:3001/login', { params: { name:user.name,password:user.password }});
    return this.httpClient.get('http://localhost:3001/login', { withCredentials: true , params: { name:user.name,password:user.password }});
  }
   
  addUser(user: { name: string; email: string; password: string; confirmPassword: string; phone: number; }): Observable<any>{
    return this.httpClient.post('http://localhost:3001/signup' , user);
  }
}

There is another route for playlists where I want to show the playlists created by the user who has logged in by fetching the userID of the current user. I want to implement that.

Link to code https://github.com/Sakshi-Aggarwal25/Spotify-Clone

question from:https://stackoverflow.com/questions/65950459/authentication-api-in-nodejs-and-angular-using-passport

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...