Привет, ребята, я создаю API с Typescript, Express, Passport и JWT, но я также хочу интегрировать Facebook и Google OAuth.
Я проверял c на Passport, но я Я не уверен, как добавить Facebook и Google OAuth, чтобы пользователи могли регистрироваться и входить в систему.
Не могли бы вы мне помочь, вот мой код и благодарность:
user.controller.ts
import {Request, Response} from 'express';
import User, {IUser} from '../models/user';
import jwt from 'jsonwebtoken';
import config from '../config/config'
function createToken(user: IUser) {
return jwt.sign({id: user.id, email: user.email}, config.jwtSecret, {
expiresIn: 86400
});
}
export const registrar = async (req: Request, res: Response): Promise<Response> => {
if (!req.body.email || !req.body.password) {
return res.status(400).json({msg: 'Por favor envia tu correo y contraseña'});
}
const user = await User.findOne({email: req.body.email});
if (user) {
return res.status(400).json({msg: 'El usuario ya existe'});
}
const newUser = new User(req.body);
await newUser.save();
return res.status(201).json(newUser);
}
export const conectar = async (req: Request, res: Response): Promise<Response> => {
if (!req.body.email || !req.body.password) {
return res.status(400).json({msg: 'Por favor envia tu correo y contraseña'});
}
const user = await User.findOne({email: req.body.email});
if (!user) {
return res.status(400).json({msg: 'El usuario no existe'});
}
const isMatch = await user.comparePassword(req.body.password);
if (isMatch) {
return res.status(200).json({token: createToken(user) });
}
return res.status(400).json({msg: 'El correo o la contraseña son incorrectos'});
}
паспорт.ts
import {Strategy, ExtractJwt, StrategyOptions} from 'passport-jwt'
import config from '../config/config';
import User from '../models/user';
import passport from 'passport';
var GoogleStrategy = require('passport-google-oauth20').Strategy;
const opts: StrategyOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.jwtSecret
}
export default new Strategy(opts, async (payload, done) => {
try {
const user = await User.findById(payload.id);
if (user) {
return done(null, user);
}
return done(null, false);
} catch (error) {
console.log(error);
}
});
models / user.ts
import { model, Schema, Document } from 'mongoose';
import bcrypt from 'bcrypt';
export interface IUser extends Document {
email: string;
password: string;
comparePassword: (password: string) => Promise<boolean>;
}
const userSchema = new Schema({
email: {
type: String,
unique: true,
required: true,
lowercase: true,
trim: true
},
password: {
type: String,
required: true
}
});
userSchema.pre<IUser>('save', async function (next) {
const user = this;
if(!user.isModified('password')) return next();
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);
user.password = hash;
next();
});
userSchema.methods.comparePassword = async function (password: string): Promise<boolean> {
return await bcrypt.compare(password, this.password);
}
export default model<IUser>('User', userSchema);
app.ts
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import authRoutes from './routes/auth.routes';
import privateRoutes from './routes/private.routes';
import passport from 'passport';
import passportMiddleware from './middlewares/passport';
// Inicializaciones
const app = express();
// Configuraciones
app.set('port', process.env.PORT || 3000);
// Middlewares
app.use(morgan('dev'));
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(passport.initialize());
passport.use(passportMiddleware);
// Rutas
app.get('/', (req, res) => {
res.send(`El api esta en http://localhost:${app.get('port')}`);
});
app.use(authRoutes);
app.use(privateRoutes);
export default app;