This is my strategy, which is defined on a server.register(). I'm basing my work off a tutorial and it is literally copied from it but it doesn't work.
server.auth.strategy('standard', 'cookie', {
password: 'somecrazycookiesecretthatcantbeguesseswouldgohere', // cookie secret
cookie: 'app-cookie', // Cookie name
isSecure: false, // required for non-https applications
redirectTo: '/login',
ttl: 24 * 60 * 60 * 1000 // Set session to 1 day
});
server.auth.default({
strategy: 'standard',
mode: 'required',
scope: ['admin']
});
This is my login route where the error occurs:
server.route({
method: 'POST',
path: '/login',
config: {
auth: false,
validate: {
payload: {
email: Joi.string().email().required(),
password: Joi.string().min(2).max(200).required()
}
},
handler: function (request, reply) {
getValidatedUser(request.payload.email, request.payload.password)
.then(function (user) {
if (user) {
//ERROR OCCURS HERE: IT SAYS SESSION IS UNDEFINED
request.auth.session.set(user);
return reply('Login Successful!');
} else {
return reply(Boom.unauthorized('Bad email or password'));
}
});
// .catch(function (err) {
// return reply(Boom.badImplementation());
// });
}
}
});
I've tried so many things but this part is crucial for this work and I can't find anyone with the same problem. Help please!
hapi-auth-cookie has changed the way cookies are set and cleared. As of version 5.0.0, use request.cookieAuth.set() and request.cookieAuth.clear(). You are probably using a more recent version of the plugin than is used in the package.json of the tutorial.
source:
https://github.com/hapijs/hapi-auth-cookie/commit/d233b2a3e4d0f03ef53b91b7929b8dbadbff624c
Related
I have a Nuxt app setup with #nuxt/auth. The user always get redirected to login page whenever the page is refreshed. I guess the server side of the Nuxt app is not logged in while the client side is logged in. The JWT access token is gotten from an Express API. Please can someone help me to solve this?. Here is my nuxt.config.js
auth: {
redirect: {
login: '/',
logout: '/',
home: '/dashboard',
},
resetOnError: true,
rewriteRedirects: true,
strategies: {
local: {
token: {
property: 'data.accessToken',
},
user: {
property: 'data[0]',
autoFetch: false,
},
endpoints: {
login: {
url: '/api/v1/users/login',
method: 'post',
},
logout: false,
user: {
url: '/api/v1/users',
method: 'get',
propertyName: false,
},
},
},
},
},
And my dashboard.vue
export default {
middleware: ['auth'],
};
Here is my working nuxt.config.js
export default {
router: {
middleware: ['auth'],
},
modules: [
'#nuxtjs/auth-next'
],
auth: {
redirect: {
login: '/login',
home: '/',
logout: '/login',
callback: false, // not used here in our case
},
localStorage: false, // REALLY not secure, so nah
resetOnError: true, // kick the user if any error happens w/ the auth
strategies: {
local: {
scheme: 'refresh', // used for the refreshToken flow
token: {
property: 'access_token',
maxAge: 3600, // only useful if not detected on the login
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30, // 1 month
},
clientId: process.env.IAM_CLIENT_ID, // our application's ID aka browser
user: {
property: 'employee',
autoFetch: false, // no need to fetch the user, will be done in gql
},
endpoints: {
login: { url: '/login', method: 'post' },
refresh: { url: '/oauth/refresh', method: 'post' },
user: false, // as told above, this one is not needed
logout: { url: '/logout', method: 'get' },
},
tokenRequired: true,
tokenType: 'JWT',
},
},
plugins: [
'~/plugins/nuxt-axios.js',
{ src: '~/plugins/nuxt-auth.js', mode: 'client' },
],
}
nuxt-auth.js is a basic logger in case of an error
import $toast from '~/mixins/buefy-toast'
export default function ({ $auth }) {
$auth.onError((_name, error) => {
$toast.open({ message: error })
})
}
Another important part is my login flow (triggered on a form submit)
export default {
methods: {
async authMe() {
const succesfulLogin = await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password,
},
})
if (succesfulLogin) {
await this.$auth.setUser({
email: this.email,
password: this.password,
})
}
}
// ...
}
}
We do basically not get the user on the API while authenticating, but rather submit the credentials and validate them, then setting the flag manually with the function $auth.setUser. This is the only part that I handle to pass the loggedIn flag to true, the remaining configuration is just project configuration.
We do also have some refreshToken on our JWT but you can totally omit this one.
Axios config file is basically setting our app's needed headers.
The auth middleware is the one coming w/ the #nuxt/auth module itself, I did not wrote it myself. This is totally working (cookies + vuex state) when generated with target: 'static'.
I'm a bit stuck on this problem.
I have read all the mongoose documentation about middleware and some stackoverflow issue and was unable to find-out how to solve my problem without duplicating queries (find then remove).
Normally, pre middleware on remove will not fire when call from Model and not from document. But according with the doc, if I add {query: true}, my function will be called from model query.
I use the latest monngoose version (5.4.16)
Here is my code.
let mySchema= new mongoose.Schema({
name: String,
comment: String
}, { usePushEach: true });
mySchema.pre('remove', { document: true }, function() {
console.log('remove document');
});
mySchema.pre('remove', { query: true }, function() {
console.log('remove');
});
const MyModel = mongoose.model('MyModel', mySchema);
And the call here
MyModel.deleteOne({ _id: modelId }, (errorRm) => {
if (errorRm) {
return res.json({ success: false, message: `${errorRm.message}` });
}
return res.json({ success: true, message: 'Model successfully removed' });
});
The model is successfully removed but nothing is logged from the "pre" functions...
Any help would be welcomed.
It's because you're using MyModel.deleteOne(). Use MyModel.remove() and it will work.
Acoording to the documentation:
You can pass options to Schema.pre() and Schema.post() to switch whether Mongoose calls your remove() hook for Document.remove() or Model.remove():
I’m using mean.js to let registered users access content. It’s sort of working. I can change isAllowed to !isAllowed to let people see the content. The problem is that content is not authorized when the user logs in. The articles example works fine. But when I create my own section, logged in users can’t access pages!
So basically if I log in, I get message: 'User is not authorized' if I try going to localhost:3000/requestoffwork
If I log in and change isAllowed to !isAllowed, I can access it
'use strict';
/**
* Module dependencies.
*/
var acl = require('acl');
// Using the memory backend
acl = new acl(new acl.memoryBackend());
/**
* Invoke Articles Permissions
*/
exports.invokeRolesPolicies = function () {
acl.allow([{
roles: ['admin'],
allows: [{
resources: '/api/articles',
permissions: '*'
}, {
resources: '/api/articles/:articleId',
permissions: '*'
}]
}, {
roles: ['user'],
allows: [{
resources: '/requestoffwork',
permissions: '*'
}, {
resources: '/api/articles/:articleId',
permissions: ['get']
}]
}, {
roles: ['guest'],
allows: [{
resources: '/api/articles',
permissions: ['get']
}, {
resources: '/api/articles/:articleId',
permissions: ['get']
}]
}]);
};
/**
* Check If Articles Policy Allows
*/
exports.isAllowed = function (req, res, next) {
var roles = (req.user) ? req.user.roles : ['guest'];
// If an article is being processed and the current user created it then allow any manipulation
if (req.article && req.user && req.article.user.id === req.user.id) {
return next();
}
// Check for user roles
acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
if (err) {
// An authorization error occurred.
return res.status(500).send('Unexpected authorization error');
} else {
if (isAllowed) {
// Access granted! Invoke next middleware
return next();
} else {
return res.status(403).json({
message: 'User is not authorized'
});
}
}
});
};
This is the route
app.route('/requestoffwork').all(managementPolicy.isAllowed)
.get(management.list)
.post(management.submit);
And here's the data for the user
{"_id":"5788fe46587a1c0b07a04078","displayName":"","provider":"local","__v":0,"created":"2016-07-15T15:16:22.625Z","roles":["user"],"profileImageURL":"modules/users/client/img/profile/default.png","email":"email#gmail.com","lastName":"","firstName":”"}
Did you add the permissions to the client side routes ass well ?
In modules/youModule/client/config/youModule.client.routes.js add this:
function routeConfig($stateProvider) {
$stateProvider
.state('yourState', {
abstract: true,
url: '/requestoffwork',
template: '<ui-view/>',
data: {
roles: ['user'], //here you must specify the roles as well
pageTitle: 'requestoffwork'
}
})
}
Hope this helps.
I can't figure out what's causing this error with https://github.com/sahat/satellizer
satellize.js configurations
withCredentials: !1,
tokenRoot: null,
cordova: !1,
baseUrl: "/#",
loginUrl: "/auth/login",
signupUrl: "/auth/signup",
unlinkUrl: "/auth/unlink/",
tokenName: 'token',
tokenPrefix: "satellizer",
authHeader: "Authorization",
authToken: "Bearer",
storageType: "localStorage",
app.js
.config(function($authProvider) {
$authProvider.facebook({
clientId: '******'
});
$authProvider.google({
clientId: '****'
});
})
controller
$scope.socialLogin = function(provider) {
$auth.authenticate(provider)
.then(function(data) {
toastr.success('You have successfully signed in with ' + provider + '!');
$rootScope.$broadcast('session',2)
})
.catch(function(error) {
if (error.error) {
// Popup error - invalid redirect_uri, pressed cancel button, etc.
toastr.error(error.error);
} else if (error.data) {
// HTTP response error from server
toastr.error(error.data.message, error.status);
} else {
toastr.error(error);
}
});
};
expecting a token named token error here
service is called on broadcast
api/me 404 error here
var app = angular.module('app');
app.factory('Account', function($http) {
return {
getProfile: function() {
return $http.get('api/me');
},
updateProfile: function(profileData) {
return $http.put('api/me', profileData);
}
};
});
I've tried all the variations on the github page there doesn't seem to be a solid solution for this.
Thought it might be because of the # in the url
changed the base url to /# and got error.
I added
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
that doesn't work either, what am I doing wrong?
I think the error is when you are returning a JSON response from your server.
the format of the JSON response should be in the format.
{ "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0.yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw"}
so check what JSON response you are getting. and if you need more info on it check the issues tab of the GitHub link you have provided.
I'm using ivpusic/angular-cookie package at the moment for my local app. I can set a simple cookie like this one:
ipCookie('force-premium', true, { expires: 1, path: '/' });
But, whenever I put in a domain name different than null, this won't work. For example, this wouldn't create a cookie for me
ipCookie('force-premium', true, { expires: 1, path: '/', domain: 'localhost' });
But somehow this works
ipCookie('force-premium', true, { expires: 1, path: '/', domain: '' });
What is the problem with this code? I need to set the domain name because I want to create a domain-wide cookies as I have several subdomains for this app.
Hope this helps:
https://gitlab.isb-sib.ch/calipho/nextprot-search/commit/8d9e022f3648c5df3390389a0b2c50d53501239c?view=parallel
if ($window.location.hostname === "localhost") {
ipCookie('nxprofile', profile);
ipCookie('nxtoken', token);
} else {
ipCookie('nxprofile', profile, { domain: '.nextprot.org' });
ipCookie('nxtoken', token, { domain: '.nextprot.org' });
}