Get Provider UID in Firebase using Angular2 - facebook

Im trying to access the facebook uid using firebase providers in Angular2, but I can´t get the user uid from the facebook provider.
When I use authState.uid It shows me the firebase uid and not the facebook uid, the documentation is outdated and the authState.facebook.uid is deprecated so I don´t know the right way to get the facebook user id.
Through internet I saw that it´s a new way to get the facebook user id using something like authState.providerData.uid but in the console I get undefined.
Here is my code:
export class AppComponent {
user: Observable<firebase.User>;
displayName;
photoURL;
constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase, private http: Http) {
this.user = afAuth.authState;
}
ngOnInit() {
this.afAuth.authState.subscribe(authState => {
if (!authState) {
console.log('NOT LOGGED IN');
this.displayName = null;
this.photoURL = null;
return;
}
let userRef = this.db.object('/users/' + authState.uid)
userRef.subscribe(user => {
let url = `https://graph.facebook.com/v2.8/${authState.uid}?fields=first_name,last_name&access_token=${user.accessToken}`;
this.http.get(url).subscribe(response => {
let user = response.json();
userRef.update({
firstName: user.first_name,
lastName: user.last_name
});
});
});
this.displayName = authState.displayName;
this.photoURL = authState.photoURL;
console.log(authState.uid);
});
}
Thanks for your time and help :)

Ok so I solved this way, I don´t know if it is the best way to do it but It works for me...
To get the Facebook uid instead of used authState.facebook.uid (I think this is deprecated) I´m now using authState.providerData[0].uid
I´ve tried with authState.providerData.uid but it didnt work so I put the [0] to get into the array and get the uid.

Related

Facebook complains that the app is not secure

When I try to login via Facebook, it throws the following error;
facebook has detected app isn't using a secure connection to transfer information
But I'm pretty sure that it is secured via 'Let's encrypt'.
I have checked Web and Client OAuth login boxes and set the corresponding redirect uris on developer facebook.
On maui side, I am calling the following code piece and AppSettings.BaseUrl is correct, I have checked that;
WebAuthenticatorResult authResult = await WebAuthenticator.Default.AuthenticateAsync(
new WebAuthenticatorOptions()
{
Url = new Uri($"{AppSettings.BaseUrl}account/authentication/{scheme}"),
CallbackUrl = new Uri("tibi://"),
PrefersEphemeralWebBrowserSession = true
});
And on backend side, the following api is requested;
[HttpGet("authentication/{scheme}")]
[AllowAnonymous]
public async Task Get([FromRoute] string scheme)
{
var auth = await Request.HttpContext.AuthenticateAsync(scheme);
if (!auth.Succeeded
|| auth?.Principal == null
|| !auth.Principal.Identities.Any(id => id.IsAuthenticated)
|| string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
{
// Not authenticated, challenge
await Request.HttpContext.ChallengeAsync(scheme);
}
else
{
var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
var email = string.Empty;
email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
// Get parameters to send back to the callback
var qs = new Dictionary<string, string>
{
{ "access_token", auth.Properties.GetTokenValue("access_token") },
{ "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },
{ "expires_in", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },
{ "email", email }
};
// Build the result url
var url = callbackScheme + "://#" + string.Join(
"&",
qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
.Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));
// Redirect to final url
Request.Host = HostString.FromUriComponent(AppSettingsProvider.GatewayUrl);
Request.HttpContext.Response.Redirect(url);
}
}
Challenge is invoked successfully and redirects me to the Facebook login but when I sign in, I get the error above.

NextJS fetching DATA from MongoDB using getServerSideProps [duplicate]

This question already has an answer here:
How to access route parameter inside getServerSideProps in Next.js?
(1 answer)
Closed 1 year ago.
I am tryin to fetch user data from MongoDB database using getServerSideProps with dynamic path. Here is my code.
import dbConnect from 'lib/dbConnect'
import User from 'models/User'
export default function refID({user}){
return(
<>
<p>USERID:{user.userID}</p>
<p>USERNAME:{user.userName}</p>
</>
);
}
export async function getServerSideProps({ params }) {
await dbConnect()
const user = await User.findOne({userID}).lean()
user._id = user._id.toString()
return { props: { user } }
}
I have tried using hardcoded data.ie 'userID:S7L4SU' which works fine except that for only that one user.
How can I define the userID such that it fetches data for that ID ?I have tried couple of methods which resulted to errors..
Sample path:http://localhost:3000/p/[userID]
How will i get around for dynamic path to work for all users in the DATABASE??Help here
Try this:
export async function getServerSideProps(ctx) {
const { userID } = ctx.query;
await dbConnect()
const user = await User.findOne({userID}).lean()
if (user !== null) {
user._id = user._id.toString()
}
return { props: { user } }
}

Http get request URL shows [object promise]

I am trying to use web api call get method to access data and display in my page. My url would be something like: https://localhost:44399/api/APIOrder/GetUserOrder?email=xxx#gmail.com to be able to display the data.
However, when I combine my url with a variable,it doesn't display anything and console log shows the url in https://localhost:44399/api/APIOrder/GetUserOrder?email=[object Promise]. Is there any way to let the url read my this.User variable?
please review my getUserOrder()
User = this.storage.get('currentUser');
constructor(private http:Http,public storage: Storage){
}
public getUserOrder()
{
var url="https://localhost:44399/api/APIOrder/GetUserOrder?email=";
console.log(url+this.User);
return this.http.get(url+this.User).map(res=>res.json());
}
I am really new to this. Pls tell me if i am unclear. Any help would be much appreciated..
UPDATE
It shows undefined because it accessed the variable value on top but not from ionViewWillEnter
User:string;
constructor(private http:Http,public storage: Storage){
}
async ionViewWillEnter()
{
this.User = await this.storage.get('currentUser');
}
public getUserOrder()
{
var url="https://localhost:44399/api/APIOrder/GetUserOrder?email=";
console.log(url+ this.User);
return this.http.get(url+this.User).map(res=>res.json());
}
You should await the return of the Promise. You can do this inside the constructor or inside a lifecyle like ionViewWillEnter()
User: string;
async ionViewWillEnter() {
this.User = await this.storage.get('currentUser');
}
Answer here: "This is the expected result."
UPDATE
This is a different approach: if your function is directly called somehow, you can create a function which returns the variable from storage. If the data is found, proceed with the http request.
async getUserOrder() {
const user = await this.getUserFromStorage();
if (user) {
var url="https://localhost:44399/api/APIOrder/GetUserOrder?email=";
return this.http.get(url + user).map(res=>res.json());
}
}
async getUserFromStorage(): Promise<string> {
return await this.storage.get('currentUser');
}

Waterlocks authentication from server side form

I am having a problem with waterlock-local-auth. Basically I've been playing around with waterlock all day trying to figure out how to create a new user (with hashed password and all), and also how to authenticate the user from a form on a server side sails.js view. But have been completely unsuccessful. Below is the code in my LoginController that my login form is posting to. Any help will be greatly appreciated. Thanks!
module.exports = {
login: function(req, res) {
var isAuthenticated = function(){...} <-- Authenticated by waterlocks
if(isAuthenticated) {
res.view('home');
}
else {
res.view('login', {errorMessage: "Invalid username or password"});
}
}
};
Ok, so basically I went with the solution posted here (Sails.js Waterlock /auth/register causes error 500). ;0)
module.exports = require('waterlock').waterlocked({
// Endpoint for registering new users. Taken from: https://stackoverflow.com/questions/29944905/sails-js-waterlock-auth-register-causes-error-500/29949255#29949255
register: function (req, res) {
var params = req.params.all(),
def = waterlock.Auth.definition,
criteria = {},
scopeKey = def.email !== undefined ? 'email' : 'username'; // Determines if the credentials are using username or emailaddess.
var attr = { password: params.password }
attr[scopeKey] = params[scopeKey];
criteria[scopeKey] = attr[scopeKey];
waterlock.engine.findAuth(criteria, function (err, user) {
if (user)
return res.badRequest("User already exists");
else
waterlock.engine.findOrCreateAuth(criteria, attr, function (err, user) {
if (err)
return res.badRequest(err);
delete user.password;
return res.ok(user);
});
});
}
});

Facebook send message

I am new to node.js and want to send private message to my facebook friends. I used facebook-chat
but above framework is not supported.
Please give me sample code or example for the same.
I use facebook-chat-api module:
var login = require("facebook-chat-api");
login({
email: "your#mail.com",
password: "password"
}, function callback(err, api) {
if (err) return console.error(err);
var userId = "12345";
var msg = {
body: "Hey! That's Node.js!"
};
api.sendMessage(msg, userID);
});
Example above didn't work with (string) user nicknames - only with user ids.