I’m trying to build a login by Facebook through API endpoint ( My first time ) for mainly a mobile APP using NestJs framework and passport lib
I have followed this article here but I don’t know what next?! also when accessing the endpoint just says not authorized!
I need to register a user if not exist and login if it exists
My code so far ( FB strategy )
import { Injectable } from "@nestjs/common";
import { use } from "passport";
import { UsersService } from "../routes/users/users.service";
import PassportFacebookToken = require("passport-facebook-token");
@Injectable()
export class FacebookStrategy {
constructor(
private readonly userService: UsersService,
) {
this.init();
}
init() {
use(
new PassportFacebookToken(
{
clientID: '',
clientSecret: '',
fbGraphVersion: 'v3.0',
},
async (
accessToken: string,
refreshToken: string,
profile: any,
done: any,
) => {
const user = await this.userService.create(
{
username: profile.displayName,
email: profile.emails[0].value,
picture: profile.photos[0].value,
},
);
return done(null, user);
},
),
);
}
}
Service:
async create(
user: Partial<UserDTO>
): Promise<UserDTO> {
let userExist: UserDTO = await this.userRepository.findOne({ where: { username: user.username } });
if (userExist) {
throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
}
let createdUser = this.userRepository.create(user);
return (await this.userRepository.save(createdUser));
}
Controller
@UseGuards(AuthGuard('facebook-token'))
@Get('facebook')
async getTokenAfterFacebookSignIn(
@Req() req: any
) {
// return this
}
2
Answers
Your client will need to transmit the access_token that is received from Facebook after login, send the access_token as a query param to your Facebook auth endpoint.
You should check here for clarification
In case someone is new here or still following this question, There is an awesome npm package which provides various social login implementation in your NestJS application. You can login with google, facebook, twitter and many more.
https://github.com/mjangir/nestjs-hybrid-auth