Я хочу реализовать Google OAuthentication в моем приложении стека MEAN.
Я установил модуль аутентификации Google паспорта с помощью 'npm install passport-google-oauth20'. в бэкэнде
аутентификация работает правильно, пока я нажимаю api с использованием шаблона EJS.
Вот мой код:
app.js
const express = require('express');
const cookieSession = require('cookie-session');
const passport = require('passport');
const authRoutes = require('./routes/auth-routes');
const profileRoutes = require('./routes/profile-routes');
const passportSetup = require('./config/passport-setup');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const app = express();
// set view engine
app.set('view engine', 'ejs');
// set up session cookies
app.use(cookieSession({
maxAge: 24 * 60 * 60 * 1000,
keys: [keys.session.cookieKey]
}));
// initialize passport
app.use(passport.initialize());
app.use(passport.session());
// connect to mongodb
mongoose.connect(keys.mongodb.dbURI, () => {
console.info('connected to mongodb');
});
// set up routes
app.use('/auth', authRoutes);
app.use('/profile', profileRoutes);
// create home route
app.get('/', (req, res) => {
res.render('home', { user: req.user });
});
app.listen(4000, () => {
console.info('app now listening for requests on port 4000');
});
login.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Login</title>
</head>
<body>
<nav>
<ul>
<% if (user) { %>
<li><a href = "/auth/logout">Log out</a></li>
<% } else { %>
<li><a href = "/auth/login">Login</a></li>
<% } %>
<li><a href = "/">Homepage</a></li>
<li><a href = "/profile">Profile</a></li>
</ul>
</nav>
<header>
<h1>Login using...</h1>
</header>
<main>
<a class = "google-btn" href = "/auth/google">Google+</a>
</main>
</body>
</html>
auth-routes.js
const router = require('express').Router();
const passport = require('passport');
// auth login
router.get('/login', (req, res) => {
res.render('login', { user: req.user });
});
// auth logout
router.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
// auth with google+
router.get('/google', passport.authenticate('google', {
scope: ['profile']
}));
// callback route for google to redirect to
// hand control to passport to use code to grab profile info
router.get('/google/redirect', passport.authenticate('google'), (req, res) => {
// res.send(req.user);
res.redirect('/profile');
});
module.exports = router;
паспорт-setup.js
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('./keys');
const User = require('../models/user-model');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id).then((user) => {
done(null, user);
});
});
passport.use(
new GoogleStrategy({
// options for google strategy
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret,
callbackURL: '/auth/google/redirect'
}, (accessToken, refreshToken, profile, done) => {
// check if user already exists in our own db
User.findOne({googleId: profile.id}).then((currentUser) => {
if (currentUser){
// already have this user
console.info('user is: ', currentUser);
done(null, currentUser);
} else {
// if not, create user in our db
new User({
googleId: profile.id,
username: profile.displayName,
thumbnail: profile._json.image.url
}).save().then((newUser) => {
console.info('created new user: ', newUser);
done(null, newUser);
});
}
});
})
);
здесь мой код работает правильно, так как я вызываю api прямо из login.ejs как
<a class = "google-btn" href = "/auth/google">Google+</a>
Но мой вопрос в том, как вызвать Node api (то есть '/ auth / google') непосредственно из angular 5. или есть ли какой-либо другой способ вызвать google oauth с помощью angular 5+.
Заранее спасибо.
да. Я вызвал функцию в файле component.ts. но есть ли способ вызвать api прямо из component.html. или как вызывать маршруты api непосредственно из файла component.ts.
@DaImTo Спасибо за совет. Я его отредактировал.
@Deepakparamesh круто! Я удалил свой голос "против" в стек.
Надеюсь, вы понимаете мой вопрос. Если что-то непонятно, я могу отредактировать снова. @DaImTo
Мне это кажется довольно ясным, но я не нод или угловатый человек, поэтому не могу вам помочь, я уверен, что кто-то поможет.





вам нужно вызвать функцию из HTML в свой класс компонента, который вызывает у вас Nodejs API