Using Zend_Auth in Pimcore - zend-auth

Im new to Pimcore and I'm trying to use Zend Auth with pimcore objects. I assume this is a wise approach and it seems more or less logical to me. I've done the initial setup of the object within pimcore itself. Now I'm trying to work out how to connect it to zend auth, that is, for example when I extend zend auth and have my own login function, how do i check if the login is valid in my object?
Does someone have a guide that I could use on this perhaps? otherwise if someone could point me in the right direction that would be great
Jason

You can follow this guide: http://www.pimcore.org/forum/discussion/419/zend_auth_adapter-for-pimcore-objects , it worked well for me.
UPDATE: The link above has been taken away, so laying out the full answer here:
First, you need to put ObjectAdapter.php in website/lib/Website/Auth/ObjectAdapter.php .
Then, this is how you login your user (use as you prefer, for example in your controller init function):
$authAdapter = new Website_Auth_ObjectAdapter('Object_Users', 'o_key', 'password', '/users/');
// The parameters are 1. object you keep your users in, 2. the field that contains their username (I use o_key which is the name of the object itself, to keep unique usernames without fuzz), and 3. the password field in the user object.
// Setup auth adapter
$authAdapter->setIdentity($username)->setCredential($password);
$auth = Zend_Auth::getInstance();
// Authenticate
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// Login successful
} else {
// Login failed
}
To check for a login-session, use:
$this->auth = Zend_Auth::getInstance();
if ($this->auth->hasIdentity()) {
// We have a login session (user is logged in)
$userObject = $this->auth->getIdentity();
}
To kill a session:
Zend_Auth::getInstance()->clearIdentity();

Related

How do I check if a user has entered the URL from another website in Django?

I want an effect to be applied when a user is entering my website. So therefore I want to check for when a user is coming from outside my website so the effect isnt getting applied when the user is surfing through different urls inside the website, but only when the user is coming from outside my website
You can't really check for where a user has come from specifically. You can check if the user has just arrived on your site by setting a session variable when they load one of your pages. You can check for it before you set it, and if they don't have it, then they have just arrived and you can apply your effect. There's some good examples of how sessions work here: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Sessions
There's a couple of ways to handle this. If you are using function based views, you can just create a separate util function and include it at the top of every page, eg,
utils.py
def first_visit(request):
"""returns the answer to the question 'first visit for session?'
make sure SESSION_EXPIRE_AT_BROWSER_CLOSE set to False in settings for persistance"""
if request.session['first_visit']:
#this is not the first session because the session variable is used.
return False
else:
#This is the first visit
...#do something
#set the session variable so you only do the above once
request.session[first_visit'] = True
return True
views.py
from utils.py import first_visit
def show_page(request):
first_visit = first_visit(request)
This approach gives you some control. For example, you may not want to run it on pages that require login, because you will already have run it on the login page.
Otherwise, the best approach depends on what will happen on the first visit. If you want just to update a template (eg, perhaps to show a message or run a script on th epage) you can use a context processor which gives you extra context for your templates. If you want to interrupt the request, perhaps to redirect it to a separate page, you can create a simple piece of middleware.
docs for middleware
docs for context processors
You may also be able to handle this entirely by javascript. This uses localStorage to store whether or not this is the user's first visit to the site and displays the loading area for 5 seconds if there is nothing in localStorage. You can include this in your base template so it runs on every page.
function showMain() {
document.getElementByID("loading").style.display = "none";
document.getElementByID("main").style.display = "block";
}
const secondVisit = localStorage.getItem("secondVisit");
if (!secondVisit) {
//show loading screen
document.getElementByID("loading").style.display = "block";
document.getElementByID("main").style.display = "none";
setTimeout(5000, showMain)
localStorage.setItem("secondVisit", "true" );
} else {
showMain()
}

Is Viewflow for superusers only?

I'm learning django viewflow (non-Pro) and the all processes that I've been creating works for superuser users only
Is that normal?
Thanks, José.-
Edit 2: My specific problem is that my user can start the process, but he can't continue it (can't see the "otro_paso" task. See the code below), only if he's not superuser. When I cnange him to superuser, works.. why??
Edit 1: I'm using django-material auto-generated forms
A way to make it work is implementing custom views, making the permission validation programmatically
Edit 3:
Here's the flows.py part:
#frontend.register
class Flujo_Proceso_Recursos_fisicos(Flow):
process_class = Proceso_Recursos_fisicos
process_title = 'Recursos físicos'
process_description = 'Registro de recursos físicos'
inicio = flow.Start(
CreateProcessView,
fields=['anio'],
task_title='Iniciar'
).Available(
username='jose'
).Permission(
'helloworld.puede_participar_biblioteca'
).Next(this.otro_paso)
otro_paso = flow.View(
UpdateProcessView,
fields=['campus'],
task_title='Campus',
task_description= "Completar campus",
).Permission(
'helloworld.puede_participar_biblioteca'
).Assign(
username='jose'
).Next(this.fin)
fin = flow.End(
task_title='Finalizado',
)
To make a task available for a user, you need to auto-assign it with flow.View(..).Assign(...) or provide permission that would make this task available for a user - flow.View(..).Permission(..)
For the reference, you can check the demos
https://github.com/viewflow/viewflow/blob/master/demo/helloworld/flows.py#L42
https://github.com/viewflow/viewflow/blob/master/demo/shipment/flows.py#L28

Storing in Django Sessions

I have a ReactJS component inside a Django template, where a user clicks on a checkout button, posts the item_code and gets redirected to checkout:
onCheckout = () => {
fetch("/onCheckout/", {
method: "POST",
body: JSON.stringify({'item': this.props.item_info.code})
}).then(window.location.replace("/checkout"))
}
A Django view receives the request and stores it in a session.
def onCheckout(request):
if request.method == "POST":
items = request.session.get('items', [])
new_item = json.loads(request.body.decode('utf-8'))['item']
items.append(new_item)
request.session['items'] = items
I am having a issue with storing data in the session. After the first item gets stored correctly in the array, and I then checkout on a second item, the items array starts acting up:
(Pdb) items
['15130BC.ZZ.8042BC.01']
(Pdb) new_item
'5213G-001'
(Pdb) items
['15130BC.ZZ.8042BC.01']
(Pdb) items
['5213G-001']
If I try to access request.session['item'] from any other view function, I get a KeyError.
I am fairly new to Django, any help would be appreciated. Also, I would like to know if there are better alternatives to accomplish the above.
Sessions Config
settings.SESSION_ENGINE = 'django.contrib.sessions.backends.db'
settings.SESSION_CACHE_ALIAS = 'default'
settings.CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
Some reading on change detection for Django sessions: https://docs.djangoproject.com/en/2.0/topics/http/sessions/#when-sessions-are-saved
Based on your code, it appears to me that the change detection should happen. However, let's try to brute force this, can you add the following line as the last line of your code: request.session.modified = True - see if this fixes your issue?
Update: some basic checks
Can you verify the following
Check if your db backend is configured priestly
If you want to use a database-backed session, you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.
Check if your session Middleware is enabled
Sessions are implemented via a piece of middleware. The default settings.py created by django-admin startproject has SessionMiddleware activated. To enable session functionality, edit the MIDDLEWARE_CLASSES setting and make sure it contains 'django.contrib.sessions.middleware.SessionMiddleware'.
Update 2: Test the session
Maybe modify a style existing endpoint as follows and see if you are able to store values and persist them in session :
test_keys = request.session.get('test_keys', [])
test_keys.append(random.randint())
request.session['test_keys'] = test_keys
return Response(request.session.get('test_keys', []))
You should see that each time you hit the api, you get a list with one new integer in it in addition to all past values. Lmk how this goes.

Admin Logged In Validation - Front End Opencart

Is there any way to check if the admin is logged in at front-end in Opencart? I would like to show a notice bar with content "Admin Logged In" when I open my store.
To be precise, in the controller of my module, i would like to add:
$data['admin_logged'] = some_function;
and when I echo it in my .tpl to get 1 if admin is logged in or 0 if not.
Actually i got it done by:
// Check if admin is logged in - frontend
$this->user = new User($this->registry);
$data['admin_logged']=($this->user->isLogged())
Now you can use if($admin_logged) /* do stuff here */
Thank you anyway
Yes, you can check it, using the User class:
$data['admin_logged'] = $this->user->isLogged() ? 1 : 0;

Creating a userlogin with token and tokensecret

I'm using Dropnet library to communicate with Dropbox.
After I accept the first time that my account allows my APP I save the token and secret forn next time I can process whatever I want without asking the user again.
But after I do this code:
Try
client.UserLogin = New UserLogin()
client.UserLogin.Token = dropboxAtoken
client.UserLogin.Secret = dropboxAsecret
Dim accountInfo As AccountInfo = client.AccountInfo()
' More of my code
Catch ex As DropNet.Exceptions.DropboxException
messagebox.show(ex.Message.ToString)
End Try
I receive this error:
{"error": "Parameter not found: oauth_token"}
Can anyone help please.
You should use the overload on the DropNetClient constructor that takes both API keys and User tokens that way it will get correctly wired up.
Or create the instance of the UserLogin first then set it on the client.
See the code for the setter of that parameter wires it up when setting it:
https://github.com/DropNet/DropNet/blob/master/DropNet/Client/Client.cs#L32