Meteor - initiate client login automatically - meteor

i have a meteor app where i'm using nginx with an internal SSO service to authenticate. I'm able to do this successfully and retrieve user details in the nginx set http headers on the server Meteor.onConnection method.
At this point, i'm not sure what the best approach is to get access to the user details on the client side. I feel like i should use the built in Meteor Accounts but i'm not sure how to initiate the login process from the client since the user will not actually be logging in through the Meteor client but through a redirect that happens through nginx. I feel like i need a way to automatically initiate the login process on the meteor side to set up the meteor.users collection appropriately, but i can't figure out a way to do that.

Checkout the answers here. You can pass the userId (or in whatever you want to pass the user) through nginx to the server then onto the client to login. You can generate and insert the token in a Webapp.connectHandler.
import { Inject } from 'meteor/meteorhacks:inject-initial';
// server/main.js
Meteor.startup(() => {
WebApp.connectHandlers.use("/login",function(req, res, next) {
Fiber(function() {
var userId = req.headers["user-id"]
if (userId){
var stampedLoginToken = Accounts._generateStampedLoginToken();
//check if user exists
Accounts._insertLoginToken(userId, stampedLoginToken);
Inject.obj('auth', {
'loginToken':stampedLoginToken
},res);
return next()
}
}).run()
})
}
Now you can login on the client side with the help of the meteor-inject-initial package
import { Inject } from 'meteor/meteorhacks:inject-initial';
// iron router
Router.route('/login', {
action: function() {
if (!Meteor.userId()){
Meteor.loginWithToken(Inject.getObj('auth').loginToken.token,
function(err,res){
if (err){
console.log(err)
}
}
)
} else {
Router.go('/home')
}
},
});

Related

Creating deeply nested object in Prisma securely

I am using Prisma and Nextjs with the following data structure, with authentication using Next-Auth.
user
|-->profile
|-->log
|-->sublog
Right now the CRUD is sent to the database via API routes on Nextjs. And I want to write to sublog securely via the API.
So when I write this, it is open-ended:
const sublog = await prisma.sublog.create({
data: {
name: req.body.name,
content: req.body.content,
log: {
connect: {
id: req.body.logId,
}
}
}
})
I have access to the user session from the frontend and backend in order to get the userID. But I am not sure how to make the form submission secure that only if the user who owns the log can they be allowed to submit a sublog.
Any ideas on how to securely submit something securely while it is deeply nested?
P.S. Note that I can turn on and off any component that edit/delete data at the frontend - but that's only on the frontend, I want to secure it on the API so that even if the client somehow is able to access a form within the log that doesn't belong to them, it would still push an error from the API since the client don't belong there.
You'd need to make a prisma query that checks who owns the log before allowing the prisma.sublog.create to be executed. Prisma is agnostic to the concept of ownership - You need to add and check that logic yourself.
const fullLog = await prisma.log.findUnique({
select: { // don't know what your model looks like, just guessing
id: true,
profile: {
select: {
userId: true
}
}
},
where: {
id: req.body.logId
}
});
// currentUserId = however you get the current user's id
if (fullLog && fullLog.profile.userId !== currentUserId) {
// throw an error
}

Next.js does not render authentication state properly after keycloak login

I have a basic next.js application that does two things:
provide an authentication mechanism using keycloak
talk to a backend server that authorizes each request using the keycloak-access-token
I use the #react-keycloak/ssr library to achieve this. The problem now is that after I login and get redirected back to my application the cookie that contains the kcToken is empty. After I refresh my page it works like expected.
I understand that maybe my entire process flow is wrong. If so, what is the "usual" way to achieve what is mentioned above?
export async function getServerSideProps(context) {
const base64KcToken = context.req.cookies.kcToken // the cookie that keycloak places after login
const kcToken = base64KcToken ? Buffer.from(base64KcToken, "base64") : ""
// the backend server passes the token along to keycloak for role-based authorization
const res = await fetch(`${BACKEND_URL}/info`, {
headers: {
"Authorization": "Bearer " + kcToken
}
})
const data = await res.json()
// ... exception handling is left out for readability ...
return {
props: {
data
}
}
}
export default function Home({data}) {
const router = useRouter() // the next.js client side router to redirect to keycloak
const { keycloak, initialized } = useKeycloak() // keycloak instance configured in _app.js
if (keycloak && !initialized && keycloak.createLoginUrl) router.push(keycloak.createLoginUrl())
return (
<div> ... some jsx that displays data ... </div>
)
}
This process basically works but it feels really bad because a user that gets redirected after login is not able to see the fetched data unless he refreshes the entire page. This is because when getServerSideProps() is called right after redirect the base64KcToken is not there yet.
Also everything related to the login-status (eg. logout button) only gets displayed after ~1sec, when the cookie is loaded by the react-keycloak library.

User redirect and authentication with middleware of Nuxt

I'm trying to redirect a user to a login page if the user is not logged in when he tries to access certain pages with the following code.
// middlware/authenticated.js
import firebase from 'firebase'
export default function ({ store, redirect }) {
let user = firebase.auth().currentUser
store.state.user = user //this doesn't work
if (!user) {
console.log('redirect')
return redirect('/login')
}
}
However, the problem is with this code when I refresh a page I'm redirected to login page although without using the middleware, I can stay in the same page with logged in. For some reasons, which I don't know why, firebase can't work in middleware.
How should I modify this middleware or implement this function?
Thanks.
//middleware/authenticated.js
export default function ({
store,
redirect
}) {
if (!store.getters['index/isAuthenticated']) {
return redirect('/login')
}
}
//post.vue
async mounted () {
if (process.browser) {
let user;
if (!this.user) user = await auth(); // this auth is a plugin
await Promise.all([
this.user ? Promise.resolve() : this.$store.dispatch("setUser", { user: user || null })
]);
this.isLoaded = true;
}
},
//plugins/auth.js
import firebase from '~/plugins/firebase'
function auth () {
return new Promise((resolve, reject) => {
firebase.auth().onAuthStateChanged((user) => {
resolve(user || false)
})
})
}
export default auth
By default Firebase persists the users logged in status on successful authentication. This example uses the session, to store the user uid and cookies to store the users token and used in situations where the sessions has ended (example when browser is closed) and then a new session started but where the user is still authenticated according to Firebase. In cases like these the user will not need to sign in to view protected resources.
Your basic Middleware to protect it should look like this (if you have a Store Module called User)
export default function ({ store, redirect }) {
if (!store.getters['modules/user/isAuthenticated']) {
return redirect('/auth/signin')
}
}
In your main Store you use the ServerInit Function to get the User if there is one saved in the Cookies and load it into your User Store Module which will be used for verification in the Middleware.
Your User Store Module should look like this, and keep in mind that you remove the Cookie when you Log the User out so that he is fully logged out.
I used the things i mentioned above as the beginning of my Authentication and modified it a bit, which you can also do. Most of the credit goes to davidroyer who has set up this nice Github Repo which includes all needed files as a good example on how to accomplish your goal.

Meteor server-side redirection when new user is created

I want to redirect when a new user account has been created.
Accounts.onCreateUser(function(options, user) {
// what to do?
})
I am using iron:router but Router.go() doesn't work because it's only for the client. Iron Router is said to support server-side redirection but in this case, I am not sure how to apply it.
You can use your own method in client code that calls a server method which will call Accounts.createUser. If the method succeeds you can then perform a redirect. e.g
//client method
Meteor.call('createUser', userObj, function(err,data) {
if (err) {
//account creation failed
} else {
//success, redirect
Router.go('routeName');
}
});
//server code
Meteor.methods({
createUser: function(user) {
//account creation
Accounts.createUser(user);
}
});

How to get Meteor.user() to return on the server side?

in a file called /server/main.js (in order to ensure it is loaded last).
console.dir(Meteor.user());
Throws:
Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
So I try to use, in the same file:
console.dir(this.userId);
returns:
undefined
so, not giving up, I'm thinking "that's fine I'll just read from the cookies in the header":
var connect = Npm.require('connect');
__meteor_bootstrap__.app.use(connect.query()).use(function(req, res, next) {
console.dir(req.headers);
next();
});
.... returns nothing in terms of cookies except for 'cookie: 'uvf=1''
I'm not sure what to conclude - this is senseless as I can otherwise use the Meteor.Account framework just fine, read/set user properties, etc. The server is clearly aware of the user, and the current user clearly logged in.
I'm at a complete loss, any explanation / hint / pointer would be greatly appreciated.
You have to use Meteor.user() in a place where a request is made from the client (such as a Meteor.methods or a Meteor.publish).
It can't be placed anywhere else because meteor wouldn't know at that point in the code the user is supposed to bound to. If there is a place a request of some form is made from the client it can do this:
In a Meteor.publish:
Meteor.publish("collection", function() {
//returns undefined if not logged in so check if logged in first
if(this.userId) {
var user = Meteor.users.findOne(this.userId);
//var user is the same info as would be given in Meteor.user();
}
});
In a Meteor.methods:
Meteor.methods({
"test":function() {
//should print the user details if logged in, undefined otherwise.
console.log(Meteor.user());
}
}
To use Meteor.user() on a server side route:
You need Meteor router installed as a package via meteorite to allow you to have a server rendered page. (installed via mrt install router)
A server side route could then handle the web request:
Meteor.Router.add('/awebpage', function(id) {
var userId = this.params.userid;
var logintoken = this.params.logintoken;
var isdirect = this.param.direct;
var user = Meteor.users.findOne({_id:userId,"services.resume.loginTokens.token":logintoken});
if(user) {
//the user is successfully logged in
return "You, "+user.profile.name+", are logged in!";
}
else
{
if(isdirect) {
return "<h3>Loading</h3><script>window.location.href="/awebpage?direct=true&userid="+localStorage.getItem("Meteor.userId") +"&logintoken="+localStorage.getItem("Meteor.loginToken")</script>";
}
else
{
return "Not logged in"
}
}
});
So now when you visit /awebpage it would check whether the user is logged in and do the thing you want when they are logged in. Initially there is a redirect to relay the data from localstorage back to the URI.
You can expose the userId with Meteor.publish() to global scope. Then you can use it with Meteor.Router's server side routes.
--
/server/publications.js
CurrentUserId = null;
Meteor.publish(null, function() {
CurrentUserId = this.userId;
});
-
/server/routes.js
Meteor.Router.add('/upload', 'POST', function() {
if (!CurrentUserId)
return [403, 'Forbidden'];
// proceed with upload...
});
You can use the logged in callback
Accounts.onLogin((obj)->
user = ob.user
)
Accounts.onLogin(function(obj){
var user = ob.user
})
I recently wrote a blog post describing solution to this: https://blog.hagmajer.com/server-side-routing-with-authentication-in-meteor-6625ed832a94.
You basically need to set up a server route using a https://atmospherejs.com/mhagmajer/server-router package and you can get current user with this.userId just like with Meteor methods.

Resources