Update permission in vue-acl - laravel

I implemented vue-acl it works but when i update the permission then my menus are not hide & showing instantly as per permission on frontend.
There are only single role but i have add, edit, delete, view permission for all menu. when i update these permission then vue reactive property is not working.
Its working after manual refresh of the page.
& once i manually refresh the page then acl.js file is calling , i add this path in main.js as well.
This may be because after updating the permission, vue acl instance is not updating, also global rules are not updating.
I try a lot from past 2 days but not found any help.
my acl.js file like
import Vue from 'vue'
import { AclInstaller, AclCreate, AclRule } from 'vue-acl'
import router from '#/router'
Vue.use(AclInstaller)
let initialRole = 'admin'
let permissionarray = null;
const userInfo = JSON.parse(localStorage.getItem('userInfo'))
if (userInfo && userInfo.userRole) initialRole = userInfo.userRole
if (userInfo && userInfo.permissions) permissionarray = userInfo.permissions
const rolePermissions = {}
// Default Permission
rolePermissions[initialRole] = new AclRule(initialRole).generate()
rolePermissions['default'] = new AclRule('default').or(initialRole).generate()
// Roles Permission
for (var key in permissionarray) {
for(var key2 in permissionarray[key])
{
if(permissionarray[key][key2] == true){
rolePermissions[key+'_'+key2] = new AclRule(key+'_'+key2).or(initialRole).generate()
}else{
rolePermissions[key+'_'+key2] = new AclRule(key+'_'+key2).generate()
}
}
}
//console.log(rolePermissions);
export default new AclCreate({
initial : initialRole,
notfound : '/error-403',
router,
acceptLocalRules : true,
globalRules: rolePermissions,
})
my main.js file like
File Name: main.js
Description: main vue(js) file
import Vue from 'vue'
import App from './App.vue'
// Vuesax Component Framework
import Vuesax from 'vuesax'
Vue.use(Vuesax)
// axios
import axios from './axios.js'
Vue.prototype.$http = axios
// Theme Configurations
import '../themeConfig.js'
// Globally Registered Components
import './globalComponents.js'
// Vue Router
import router from './router'
// Vuex Store
import store from './store/store'
// Vuexy Admin Filters
import './filters/filters'
import interceptorsSetup from './helpers/interceptors'
interceptorsSetup()
// VeeValidate
import VeeValidate from 'vee-validate'
Vue.use(VeeValidate)
import * as VueGoogleMaps from 'vue2-google-maps'
Vue.use(VueGoogleMaps, {
load: {
// Add your API key here
key: 'xyz',
libraries: 'places' // This is required if you use the Auto complete plug-in
}
})
// Vuejs - Vue wrapper for hammerjs
import { VueHammer } from 'vue2-hammer'
Vue.use(VueHammer)
// PrismJS
import 'prismjs'
import 'prismjs/themes/prism-tomorrow.css'
// ACL
import acl from './acl/acl'
Vue.config.productionTip = false
new Vue({
router,
store,
acl,
render: h => h(App)
}).$mount('#app')
Thanks in advance

can you show how did you implement your rules update?
I was facing the same problem.
So I decide to manage the rules by Store ( vuex )
I'm using VUEXY template, so in my store, I did insert this code this._vm.$acl.change(user_permissions_array).
Then you will can check and validate the permissions inside all components with
$acl.check('your_rule_string') or $acl.get.indexOf('your_rule_string') > -1
I hope it can help you.

Related

'fileSystemModule' was not found in '#nativescript/core'

Trying to write to a local file in Android.
Tried import {fileSystemModule} from "#nativescript/core"; but get error 'fileSystemModule' was not found in '#nativescript/core'.
Have also tried import {fileSystemModule} from "#nativescript/core/file-system" but it doesn't exist. I'm using plain Javascript.
Nativescript 8.0.2
The import paths are updated in the recent versions of NativeScript. You can access these directly now without having to go through fileSystemModule. See code below:
import { knownFolders, File, Folder } from '#nativescript/core';
To write to a local file using the latest NativeScript would look like this:
writeToFile(): void {
const folder = knownFolders.documents().getFolder(FOLDER_NAME);
const file = folder.getFile(FILE_NAME.txt);
file.writeText(SOME_STRING_TO_WRITE_TO_FILE);
}
To write to an accessible location in Android, you can use the following:
writeToFile(): void {
const folderPath = path.join(android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString())
const folder = Folder.fromPath(folderPath);
const file = folder.getFile(FILE_NAME.txt);
file.writeText(SOME_STRING_TO_WRITE_TO_FILE);
}

prisma-select issue for custom output path

I am getting the below error when I try to use
const select = new PrismaSelect(info).value;
[Nest] 65877 - 17/05/2021, 16:45:13 [ExceptionsHandler] Cannot find module '.prisma/client'
My PrismaClient is in a custom path rather than the default, as I am using a monorepo for multiple microservices.
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "darwin"]
output = "../src/.generated/prisma/client"
}
Is there a way to point PrismaSelect to the correct Client?
The solution was shared by the author of the package
Import custom instance of Prisma Client
import { Prisma } from '../../.generated/prisma/client';
Pass dmmf object to PrismaSelect constructor
const select = new PrismaSelect(info, { dmmf: [Prisma.dmmf] }).value;

How to create a NativeView in Nativescript-Angular?

I'm developing a mobile App with Nativescript and Angular, but I've a problem to create an headerView to add inside the CFAlertDialog (I'm using the plugin nativescript-cfalert-dialog).
I created a service to inject to several components in my app, which is something like this
import * as application from 'tns-core-modules/application'
#Injectable()
export class PlayerDialogService {
...
constructor() {
const context = application.android.context as android.content.Context;
this.generateAndroidNativeView(context)
}
private generateAndroidNativeView(context: android.content.Context) {
this.usernameLabel = new android.widget.TextView(context)
this.usernameLabel.setTextSize(20)
this.fullNameLabel = new android.widget.TextView(context)
this.fullNameLabel.setTextSize(16)
this.playerImage = new android.widget.ImageView(context)
this.playerImage.setMaxWidth(48)
this.playerImage.setMaxHeight(48)
this.textStackLayout = new android.widget.LinearLayout(context)
this.textStackLayout.addView(this.usernameLabel)
this.textStackLayout.addView(this.fullNameLabel)
this.stackLayout = new android.widget.LinearLayout(context)
this.stackLayout.addView(this.playerImage)
this.stackLayout.addView(this.textStackLayout)
}
}
Fact is that everytime the dialog is loaded (I open a component/view that has the PlayerDialogService injected), I get this error:
JS: ERROR TypeError: Cannot read property 'usernameLabel' of undefined
I'm afraid I'm not passing the correct Context (despite it's not an empty object, nor an undefined one), but has a constructor included. So... what am I missing?

Unable to start a Session in Flask within a function

I'm running Flask Session and using Eve as an API. For the Session code I'm following the example here https://pythonhosted.org/Flask-Session/
from flask import Flask, session
from flask.ext.session import Session
app = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)
#app.route('/set/')
def set():
session['key'] = 'value'
return 'ok'
#app.route('/get/')
def get():
return session.get('key', 'not set')
I have an Eve API located under /api, and I want to avoid starting a new Session for those requests at least.
I want to start my flask Session only if the request.environ['PATH_INFO'] doesn't start with '/api/' but whenever I put Session() anywhere else it fails.
Following the example:
sess = Session()
sess.init_app(app)
When I try to do that in before_request or similar, then I get:
A setup function was called after the first request was handled.
and if I try to start a session in a normal content generator I get:
AttributeError: 'SecureCookieSession' object has no attribute 'sid'
How can I start a session conditionally, depending on the path/environment/etc?
My current code looks like this:
import flask
import xml.etree.ElementTree as ElementTree
from bson.objectid import ObjectId
from random import shuffle, choice as pick
from cgi import escape as escapehtml
from time import mktime
from urllib import quote as escapeurl, unquote_plus as unescapeurl
from flask import Flask, request, session, render_template, send_from_directory, jsonify, redirect, abort
from flask.ext.session import Session
from flask.ext.login import LoginManager, login_user, logout_user, current_user, UserMixin, user_logged_in, login_required, fresh_login_required
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired, URLSafeTimedSerializer
from flask_mail import Mail, Message
from wtforms import Form, BooleanField, PasswordField
from flask.ext.mongoengine import MongoEngine
from flask.ext.security import Security, MongoEngineUserDatastore, RoleMixin, UserMixin
from flask.ext.principal import Principal, Permission, RoleNeed
from flask_security.forms import RegisterForm, Required, StringField
from flask_images import Images
from eve import Eve
from eve.auth import TokenAuth
from flask.ext.moment import Moment
from eve.io.mongo import Validator
from flask.ext.cors import CORS, cross_origin
from app.admin.one1 import one1
from app.emails.emails import emails
from app.alligator.alligator import alligator
from app.data.ndm_feed.ndm_feed import ndm_feed
from flask.ext import excel
...
login_serializer = URLSafeTimedSerializer(app.secret_key)
login_manager = LoginManager()
app.config.from_object(__name__)
login_manager.init_app(app)
Session(app)
and to avoid starting sessions for API calls I am trying to do things like this:
#app.before_request
def before_request():
if not request.environ['PATH_INFO'].startswith('/api/'):
Session(app)
or the equivalent:
#app.before_request
def before_request():
if not request.environ['PATH_INFO'].startswith('/api/'):
sess = Session()
sess.init_app(app)
But I can't seem to find a way to do it without the errors above.
How can I start a Flask session conditionally, depending on the path/environment/etc?
Actually your app already created before you use this: #app.before_request so it means you are late to add new configuration or extension initialize. Bu you can do with Blueprint:
# api.py
from flask import Blueprint
from flask_session import Session
sess = Session()
api = Blueprint('api', __name__)
# yourapp.py
...
def create_app():
...
try:
from api import api, sess
sess.init_app(app)
app.register_blueprint(api)
# views.py
#api.route('/set/')
def set():
session['key'] = 'value'
return 'ok

Sending partials from keystone.js for use with ui.view

Been trying to get my head around this, but can't for the life of me figure out what I'm missing.
So I want to set up keystone, but want to use angular on the front end, and I want to avoid reloading the page every time.
Got angular running quite fine and pretty quickly. But now I am trying to set up the routes on the backend for the partials, and while I can manage to get them set up to answer, I can not get them to just send the partial, whatever I do it sends the whole page back to me. with html, body, head.
So far I have managed to figure out that I need a route, so imported my uiview directory and added the following route:
var keystone = require('keystone');
var middleware = require('./middleware');
var importRoutes = keystone.importer(__dirname);
// Common Middleware
keystone.pre('routes', middleware.initLocals);
keystone.pre('render', middleware.flashMessages);
// Import Route Controllers
var routes = {
views: importRoutes('./views'),
uiviews: importRoutes('/uiviews'),
};
// Setup Route Bindings
exports = module.exports = function (app) {
// Views
app.get('/', routes.views.index);
app.get('/uiviews/index',routes.uiviews.index);
app.get('/blog/:category?', routes.views.blog);
app.get('/blog/post/:post', routes.views.post);
app.get('/gallery', routes.views.gallery);
app.all('/contact', routes.views.contact);
// NOTE: To protect a route so that only admins can see it, use the requireUser middleware:
// app.get('/protected', middleware.requireUser, routes.views.protected);
};
I think what is happening is that the pre compiler ( keystone.pre('routes', middleware.initLocals);) gets hold of it and wraps it all the way it thinks it is suppose to, but I'm not certain.
I even tried to create a uiviews.js in ./routes with just my uiroute, but that gives me 404 errors
var keystone = require('keystone');
var middleware = require('./middleware');
var importRoutes = keystone.importer(__dirname);
// Import Route Controllers
var routes = {
uiviews: importRoutes('/uiviews'),
};
// Setup Route Bindings
exports = module.exports = function (app) {
// Views
console.log('uiroutes added');
app.get('/uiview/index',routes.uiviews.index);
// NOTE: To protect a route so that only admins can see it, use the requireUser middleware:
// app.get('/protected', middleware.requireUser, routes.views.protected);
};
Any ideas?
This is more of a Express question and not of keystone.Js.
You have not said which router you want partially. and neither shared rendering code of that handler.
Any way Make sure that the template you are using does not include any other template. particularly default.jade
I finally managed to figure out what I was missing.
Technically it is not keystone.js that controls what is sent, it is handlebars. This might be obvious to everyone but me.
However, the trick is to tell handlebars not to include the layout, which is done using {layout: false}. So my uiview route looks like this (last little line does the magic):
var keystone = require('keystone');
exports = module.exports = function(req, res) {
console.log("request for index received");
var view = new keystone.View(req, res),
locals = res.locals;
console.log(locals);
// Render the view
console.log(view)
view.render('uiviews/index', {layout: false});
};
with the index.js router looking like this:
var keystone = require('keystone');
var middleware = require('./middleware');
var importRoutes = keystone.importer(__dirname);
// Common Middleware
keystone.pre('routes', middleware.initLocals);
keystone.pre('render', middleware.flashMessages);
// Import Route Controllers
var routes = {
views: importRoutes('./views'),
uiviews: importRoutes('/uiviews'),
};
// Setup Route Bindings
exports = module.exports = function (app) {
// Views
console.log('index added');
app.get('/', routes.views.index);
app.get('/partners', routes.views.partners);
app.get('/blog/:category?', routes.views.blog);
app.get('/blog/post/:post', routes.views.post);
app.get('/gallery', routes.views.gallery);
app.get('/philosophy', routes.views.philosophy)
app.get('/socialmedia', routes.views.socialmedia)
app.all('/contact', routes.views.contact);
app.get('/uiviews/index', routes.uiviews.index)
// NOTE: To protect a route so that only admins can see it, use the requireUser middleware:
// app.get('/protected', middleware.requireUser, routes.views.protected);
};
And now you can call [host]/uiviews/index and only receive a partial route.

Resources