I'm trying to authenticate using github.
I configured properly the callback, successRedirect and failureRedirect.
The successRedirect page is called. In this page I try to call the authenticate function.
client.authenticate({
strategy: 'github'
})
The promise resolve with a token but when I try to access a secured service, it returns an error. Then If I try to retry to access a second time to the service, it works.
Can someone explain me or provide me a working example.
My code:
const hello = client.service('hello');
function getVal(iter) {
console.log("Iter " + iter)
hello.get(1, {}).then((data) => {
console.log('User is logged');
console.dir(data)
}, (error) => {
console.dir(error)
getVal(iter + 1)
})
}
client.authenticate({
strategy: 'github'
}).then((token) => {
console.dir(token)
getVal(0)
}, (error) => console.dir(error));
In the logs I see that the first call to the service fails with an authentication error but not the second while I'm supposed to be logged (because it's in the configured success redirection)
My logs:
Object { accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2…" }
Iter 0
{
className: "not-authenticated"
code: 401
……
}
Iter 1
User is logged
{…}
The oAuth2 client usage API shows that instead of calling authenticate you just have to link the user to /auth/github to kick of the oAuth flow:
Login With GitHub
Related
So recently I decided that I need to access a protected api endpoint in google app script. The only thing I can find is app-script-oauth2, the reason this does not work is because my middleware for the tRPC endpoint (code below) says if there is not a session (which is stored in a prisma db) you cannot access the api.
.middleware(async ({ ctx: { session }, next }) => {
if (!session) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next();
})
I have also tried to login and try to make the request but it seems as if the request is completely unrelated to the local session. I know this isn't a ton to work from but any help at all would be greatly appreciated.
When using node v16.16.0, redis-cli 7.0.0 & "redis": "^4.2.0"
getting such exeption below:
Caught exception: TypeError: listener is not a function Exception
origin: uncaughtException[2022-07-18T07:39:30.386Z] process.on
uncaughtException ERRORCODE 105199 TypeError: listener is not a
function
at Function._RedisCommandsQueue_emitPubSubMessage (/mnt/c/Projects/konnectcore/app/sse/sse/node_modules/#redis/client/dist/lib/client/commands-queue.js:241:9)
at RedisCommandsQueue._RedisCommandsQueue_handlePubSubReply (/mnt/c/Projects/konnectcore/app/sse/sse/node_modules/#redis/client/dist/lib/client/commands-queue.js:283:100)
It's working fine while using node redis "redis": "^2.8.0".
I had a similar issue where I was using probably some old way of subscribing and receiving the messages. Something like this:
sub.on('message', (channel, message) => {
redisClient.hSet('values', message, someFunction);
});
sub.subscribe('channel');
I hope you are using the right way of publishing and subscribing to a channel in redis client. Here is one example from their documentation:
// This is how you create the client
import { createClient } from 'redis';
const client = createClient();
// This is the subscriber part
const subscriber = client.duplicate();
await subscriber.connect();
await subscriber.subscribe('channel', (message) => {
console.log(message); // 'message'
});
// This is an example of how to publish a message to the same channel
await publisher.publish('channel', 'message');
Here is the link if you would like to see some more details about publishing and subscribing of the messages using node-redis client: https://github.com/redis/node-redis#pubsub
I want to integrate Quasar with FeathersJS using Feathers-Vuex
Feathers-Vuex uses a pattern to:
promise to authenticate from localStorage/cookies
.then( /*start the new Vue() app */ )
I created my app with Quasar CLI 1.0.beta16-ish and looked through /src and couldn't find the main entry point for Quasar. I feel like I'm missing something.
What includes src/store/index.js?
quasar.conf.js includes this comment - where is the main.js
// app boot file (/src/boot)
// --> boot files are part of "main.js"
boot: ["axios"],
Feathers-Vuex includes a Nuxt integration guide that may solve the same problem. These packages are all new to me, and I'm excited to learn them!
Thank you!
The part of main.js is included in quasar app.js that you can find in .quasar folder. The src/store/index.js contains the Vuex Store definition. A "store" is basically a container that holds your application state.
For more detail visit - https://quasar-framework.org/guide/app-vuex-store.html https://quasar-framework.org/guide/app-plugins.html
I ended up with two things:
Adding Feathers-Vuex to my backend.
Adding this "boot file" in my Quasar project
The comments are a bread-crumb trail if I ever have to figure it out again :-)
/*
Context:
For 3rd-party API's, we us /src/boot/axios.js
For our own API's, we use FeathersClient (socket.io & REST)
https://docs.feathersjs.com/guides/basics/clients.html
https://docs.feathersjs.com/api/authentication/client.html#appconfigureauthoptions
Our FeathersClient is in `/src/lib/feathersClient.js`
and imported into `/src/store/index.js`
which is imported by Quasar's build system. /src/quasar.conf.js setting(?)
Feathers-vuex integrates Vuex with FeathersClient:
https://feathers-vuex.feathers-plus.com/auth-module.html
Feathers-Vuex proxies it's authentication/logout actions to FeathersClient
https://github.com/feathers-plus/feathers-vuex/blob/master/src/auth-module/actions.js
The parameters for these actions are here:
https://docs.feathersjs.com/api/authentication/client.html#appauthenticateoptions
In addition to this module, you can use FeathersVuex state in UI from here:
https://feathers-vuex.feathers-plus.com/auth-module.html
This module:
Create a Feathers Auth integration for Vue as a Quasar Boot Module.
// Use case: test if user is authenticated
if (Vue.$auth.currentUser()) { ... }
// Use case: get current user's email
name = Vue.$auth.currentUser("email") || "anonymous"
// Use case: Login
Vue.$auth.login({
strategy: 'local',
email: 'my#email.com',
password: 'my-password'
});
// Use case: Logout
// logs out and sends message
let p = Vue.$auth.logout();
// After logout, go home
p.then(() => {
// User data still in browser
router.push({ name: "home"});
// To clear user data, do a hard refresh/redirect - https://feathers-vuex.feathers-plus.com/common-patterns.html#clearing-data-upon-user-logout
location && location.reload(true)
});
*/
export default ({ app, router, store, Vue }) => {
// Create the API demonstrated above
const auth = {
currentUser(prop) {
let u = store.state.auth.user || false;
if (u && prop) return u[prop];
return u;
},
login(authData, quiet) {
return store
.dispatch("auth/authenticate", authData)
.then(() => {
Vue.prototype.$q.notify({
message: "Welcome back!",
type: "info"
});
})
.catch(err => {
if (!quiet) {
console.log(err);
Vue.prototype.$q.notify({
message: "There was a problem logging you in.",
type: "error"
});
}
});
},
logout(quiet) {
return store.dispatch("auth/logout").then(() => {
if (!quiet)
Vue.prototype.$q.notify({
message: "You've been logged out.",
type: "info"
});
});
},
register(authData) {}
};
// Auth from JWT stored in browser before loading the app. true => suppress token not found error
auth.login("jwt", true);
// Add API to Vue
Vue.prototype.$auth = auth;
// If you would like to play with it in the console, uncomment this line:
// console.log(auth);
// Then, in the console:
/*
temp1.login({
strategy: "local",
email: "feathers#example.com",
password: "secret"
})
*/
// If you haven't created this user, see here:
// https://docs.feathersjs.com/guides/chat/authentication.html
// For this REST api endpoint
/*
curl 'http://localhost:3001/users/' -H 'Content-Type: application/json' --data-binary '{ "email": "feathers#example.com", "password": "secret" }'
*/
};
I have two problems, I need to be able to redirect users from facebook permissions acceptance from passportjs-facebook and from paypal payments redirect but I don't know how to do this in angular. I need to access posted JSON data coming from my own express server with an angular route which receives and uses that data.
If I do an a href="/auth" login button it sends my user to facebook's page to grant app permissions, after they do it redirects them to /auth/facebook/callback which is a blank white page with this json: {"ok":true,"status":"Login successful","success":true,"token":"...", user: {..}, }. How do I make it so they are redirected back to a page on my angular2 app and that this token is read into a json object within my apps so I can put it in local storage? This is my backend code:
userRouter.get('/auth', passport.authenticate('facebook', {scope: ['public_profile', 'user_friends', 'email']}), (req, res) => {});
userRouter.get('/auth/facebook/callback', function(req,res,next){
passport.authenticate('facebook', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Login failed'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful',
success: true,
token: token
});
});
})(req,res,next);
});
I'd use a res.redirect to the URL of one of your Angular pages, and include the token as a query string.
res.redirect('/#!/myprofile?token=MYTOKEN'); instead of the res.status(200).json... code
Alternatively you can parse the query string sent with the redirect right away in Angular as in this example, but I think that way can be a bit messy. That example will also help you through accessing query strings in Angular2.
I am trying to implement simple authentication with react-router. I think there is an issue with replace and callback. Consider following code:
1) Routing configuration
function getRoutes() {
return {
path: "/",
indexRoute: require("./Home"),
component: require("./Shared/Layout"),
onEnter: handleEnter,
childRoutes: [
require("./Login"),
require("./Secured"),
require("./Any")
]
}
}
function handleEnter(nextState, replace, callback) {
let state = store.getState()
if (!state.hasIn(["shared", "user"])) {
store.dispatch(fetchUser())
.then(callback)
}
}
2) ./Secured route configuration
export = {
path: "/secured",
component: require("./Secured"),
onEnter(nextState, replace) {
let state = store.getState()
if (!state.getIn(["shared", "user"])) {
replace("/login")
}
}
}
It should work like this:
Fetch user when entering root route (async operation, we need callback)
Go to /secured and check whether user is authenticated when entering the route
If user is not authenticated go to /login
The problem is that the /login page will not be rendered. The URL is changed to /login, but nothing is displayed and there are no error messages in console. When I remove callback parameter from the root route configuration, it starts working as expected.
Am I doing something wrong?
Well, it was really stupid :) I've forgot to call callback when user is already authenticated.