Ionic social login with WordPress backend JSON API User - angularjs

I want to build an Ionic application with WordPress back-end.
I Installed JSON API user,and I want to use Facebook login, but I can not figure it out how I will call the token and pass it to the JSON page. Please any recommend any good article about these technologies, it will help a lot.
Thank you.

Its very easy, once you have configured Facebook.
You must have FB plugin
installed. Once you call facebook cordova plugin you will get token in response after you try to call fb.login.
And then you can call fb connect function and pass access_token
getWPToken(facebooktoken){
this.http.get('yourdomaindotcom/json-api/user/fb_connect/?
access_token='+token).map(res => res.json()).subscribe(data => {
console.log(data);
this.cookie = data.cookie;
this.storage.get('wp_cookie').then((val)=>{
this.storage.set("wp_cookie", this.cookie);
this.event.publish("cookie",this.cookie);
});
},
err => {
console.log("Oops!");
});
}

Related

Google SignIn: Redirect Uri in GSI client flow

I’m trying to use the new Google Identity Services to sign in an user to get access to manage his calendars.
My current auth function looks like this in JS:
const auth = async () => {
return new Promise((resolve) => {
const GTokenClient = google.accounts.oauth2.initTokenClient({
client_id: GOOGLE_CLIENT_ID,
scope: GOOGLE_CALENDAR_SCOPE,
prompt: '',
callback: resolve
});
if (gapi.client.getToken() === null) {
GTokenClient.requestAccessToken({ prompt: 'consent' });
} else {
GTokenClient.requestAccessToken({
prompt: ''
});
}
});
};
In desktop web browsers it works fine and the promise resolves but in smartphones (currently trying with an iPhone12) the browser opens a new tab and it stays there loading after giving permissions.
I’m aware that you can set a redirect with the code flow, but it is possible to do the same with the client flow?
I don’t know what to do honestly because there are no examples to implement this behavior using the client flow in the Google documentation.
I only want to be able to redirect the user to the initial screen, if I close the tab that google creates for signing in the calendar is loaded and everything seems fine, it is just a matter of redirection.

AngularFire2 - using access token from Google Auth for Google APIs

Google Authentication through AngularFire2 returns the Firebase access token, but not the Google access token for use on Google APIs. What's the proper way to get the access token from the AngularFire2 auth?
Angular: 2.4.9
Firebase: 3.5.2
AngularFire: 2.0.0-beta.8
Here's a plunkr:
http://plnkr.co/edit/qIbtcp?p=preview
You'll notice in the constructor:
constructor(af: AngularFire, public auth$: AngularFireAuth, public http:Http) {
auth$.subscribe((state: FirebaseAuthState) => {
if(state){
this.signedIn = true
}
});
firebase.auth()
.getRedirectResult()
.then((result) => {
console.log('result', result);
if (result.credential) {
// This gives you a Google Access Token.
var token = result.credential.accessToken;
console.log('token',token)
this.getPeople(token)
.subscribe(
people => console.log('people',people),
error => console.log(error));
}
var user = result.user;
})
.catch(err => console.log(err));
}
Where I call firebase.auth() is where I try to get the Google Access Token. However on first login, I get this error:
{
error: {
code: 403,
message: "Request had insufficient authentication scopes.",
status: "PERMISSION_DENIED"
}
}
I know this shouldn't happen because I tried the same setup with strictly Firebase (no AngularFire2), in this example:
https://embed.plnkr.co/zxOfRZ1PDDb7ee5qzIKW/
So is there an issue with sharing auth tokens between AngularFire and just Firebase? Does anyone have an example of this working?
Found a similar issue on StackOverflow:
Using Firebase Auth to access the Google Calendar API
I ended up using the same approach, it seems that you need to manually use the Google API's Javascript client, and use that credential to sign in with Firebase.

Angular PouchDb and Auth Example

I tried great example angularjs todo app:
https://github.com/danielzen/todo-ng-pouchdb
and now I'm trying use it with some authentication plugin, but without success ( https://github.com/nolanlawson/pouchdb-authentication ). Todo app use some old angular-pouchdb lib.
Please do you have any tip to example where is used angular, pouchdb and auth plugin to login, signup to couchdb.
My problems with log into CouchDb were because of wrong auth params, I didn't wrap login values into array with key auth.
So just example of correct call to server:
$scope.sync = $scope.tasks.$db.replicate.sync('http://www.server.info:5984/' + dbName,
{live: true, "auth": {username:"john", password:"secret"}})
.on('error', function (err) {
});

Can't share Facebook image post with Cordova Facebook plugin

I've created a Cordova/Angular app that pulls a Facebook feed from the api. I'm now trying to add the ability to share one of the Facebook posts on your own timeline. I'm using the Cordova Facebook plugin found here https://github.com/jeduan/cordova-plugin-facebook4
The problem is that when I try to share an image post I just get a "An error occurred. Please try again later" in the Share dialog that appears. I'm not sure how to setup the options to share images properly.
Here's my current code for the share:
var options = {
method: 'share',
href: post.link,
caption: post.message
};
$cordovaFacebook.showDialog(options).then(
function (res) {
success(res);
},
function (error) {
console.log(error);
fail(error);
});
Any ideas what the options should be to share an image?

How should I make sure the user accessing a backend rendered frontend route is authenticated?

I'm using Laravel and Angular to write a web app.
In the front end Laravel is used to create the basic template, but otherwise controlled by Angular. In the back end laravel is used to create a restful API.
I have a few routes like this:
Route::group(['domain' => 'domain.com'], function() {
Route::get('/', ['as' => 'home', function () {
return view('homepage');
}]);
Route::get('/login', ['as' => 'login', function () {
return view('login');
}]);
//users should be authenticated before accessing this page
Route::get('/dashboard', ['as' => 'dashboard', function () {
return view('dashboard');
}]);
});
Route::group(['domain' => 'api.domain.com', 'middleware' => ['oauth']], function() {
Route::post('/post/create', ['uses' => 'PostController#store']);
Route::get('/post/{id}', ['uses' => 'PostController#show']);
//other API endpoints
// ...
});
I want to make sure my domain.com/dashboard URL is only accessed by authenticated users.
In my backend I have OAuth implemented for my API routes which makes sure the user accessing those routes are authentic. Laravel's Auth::once() is used by the OAuth library to make sure the user credentials are correct then generates an access_token. Since Auth::once() is a "stateless" function no session or cookies are utilized and I cannot use Auth::check() to make sure a user is authenticated before the dashboard page is rendered.
How should I go about checking to see if the user trying to access domain.com/dashboard is authenticated? Should I send the access_token in the header when I forward the user from /login to /dashboard? Or should I implement Laravel's a session/cookie based authentication?
EDIT: As per this: Adding http headers to window.location.href in Angular app I cannot forward the user to the dashboard page with an Authorization header.
In order to reuse my API for my mobile apps I STRONGLY prefer to use some sort of token based authentication.
I would advise to use JWT (JSON Web Tokens) to control for authentication.
I think there are several tutorials for their use with Lavarel and AngularJS. I'm more into Python and I use Flask, but the followings look interesting :
Simple AngularJS Authentication with JWT : the AngularJS configuration
Token-Based Authentication for AngularJS and Laravel Apps : the connection with Laravel
JSON Web Token Tutorial: An Example in Laravel and AngularJS
Pierre was right in suggesting JWT for your token based auth.
When the user successfully logs in, before you finish the request, you can create a JWT and pass that back to the client. You can store it on the client (localStorage, sessionStorage) if you want. Then on subsequent requests, put the JWT inside of your Authorization header. You can then check for this header in your middleware and prevent access to your API routes if the token is valid. You can also use that token on the client and prevent Angular from switching routes if the token doesn't exists or isn't valid.
Now if you are trying to prevent the user from accessing the page entirely on initial load (Opens browser, goes straight to domain.com/dashboard), then I believe that is impossible since there is no way to get information about the client without first loading some code on the page.
Not sure about Angular, as I have never used it, but have you tried targeting a controller with your dashboard route? For example
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
UserController.php (I'm assuming you have a blade called dashboard.blade.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function getDashboard()
{
if(Auth::user()) {
return view('dashboard');
} else {
redirect()->back();
}
}
}
Also, you could always group whichever routes you want to protect with this (taken from the Laravel 5.2 documentation):
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
EDIT: Regarding the session token, your login blade should have this in its code:
<input type="hidden" name="_token" value="{{ Session::token() }}">
When the /dashboard HTML loads, does it already include data specific to the user's account?
I would suggest to load the /dashboard HTML separately from the user's data, and hide the dashboard items with ng-cloak while Angular loads the data to populate it.
Redirect to /dashboard URL
Load (static?) dashboard HTML / Angular app, hiding all parts with ng-cloak.
Have Angular access the API using the access_token to load all dashboard data.
Revealing the parts of the dashboard when the data from the API comes in, or showing an error message if the access_token wan't valid.
That way, your /dashboard HTML could actually be just a static HTML file and directly served by the web server and cached by any proxy on the way.
If that isn't an option, you could put your access_token into a cookie with Javascript that runs on the /login view, then redirect to /dashboard, then have your server-side /dashboard view read the cookie to check if the access_token is valid. But that sounds messy and mixes up things that should be separated.
#Pierre Cordier #Mr_Antivius Thank you guys for your answer, it helped me get insight into the problem and allowed me to tinker with with JWT but ultimately did not product a solution for me.
To allow only authenticated users to access domain.com/dashboard I had to implement a hybrid session and OAuth authentication system. I decided to go with Sentinel (instead of Laravel's out of the box auth system) because it has a user permission system I need in other places in my app. I use this library for the OAuth Server.
Here is what I do in my controller:
POST domain.com/auth/authenticate:
public function processLogin(Request $request)
{
$credentials = [
'email' => $request->input('username'),
'password' => $request->input('password'),
];
try
{
$sentinel = Sentinel::authenticate($credentials);
}
catch (\Cartalyst\Sentinel\Checkpoints\ThrottlingException $e)
{
$response = ['error' => [$e->getMessage()]];
$httpStatus = 429;
return response()->json($response, $httpStatus);
}
catch (\Cartalyst\Sentinel\Checkpoints\NotActivatedException $e)
{
$response = ['error' => [$e->getMessage()]];
$httpStatus = 401;
return response()->json($response, $httpStatus);
}
if ($sentinel) //user credentials correct
{
//get oauth token
$oauthToken = Authorizer::issueAccessToken();
$response = ['success' => true, 'user' => ['id' => $sentinel->id, 'email' => $sentinel->email]] + $oauthToken;
$httpStatus = 200;
}
else
{
$response = ['success' => false, 'error' => ['Incorrect credentials']];
$httpStatus = 401;
}
return response()->json($response, $httpStatus);
}
Here is the method the OAuth library looks at to authenticate the user:
public function verifyAuth($email, $password)
{
$credentials = [
'email' => $email,
'password' => $password,
];
if ($user = Sentinel::stateless($credentials))
{
return $user->id;
}
else
{
return false;
}
}
This would create a response like so:
{
"success": true,
"user": {
"id": 1,
"email": "email#domain.tld"
},
"access_token": "6a204bd89f3c8348afd5c77c717a097a",
"token_type": "Bearer",
"expires_in": 28800,
"refresh_token": "092a8e1a7025f700af39e38a638e199b"
}
Hope this helps someone out there
Side Note: I'm sending a POST request to domain.com/auth/authenticate instead of api.domain.com/auth/authenticate because I could not get domain.com/dashboard to recognize sentinel's cookie if I posted to api.domain.com. I've tried changing domain in config/session.php to .domain.com but still nothing. Maybe I'm doing something wrong?

Resources