4

We're considering using Craft for a new project. One of the features requested is to have a password protected area. Each user would have access to their own files only. So we'd need to be able to setup users and assign files to them. It also needs to be simple enough that the client could do this without our intervention.

I'm pretty familiar with how I would do this with EE but wondered if/how it could be done with Craft.

11

It is very easy within your templates to define requirements for whether the page itself, or portions of the content are displayed, and/or route the user to another page if they do not meet the page requirements. For example, you can check whether the user is logged in, belongs to a particular group, is the author of the entry, has a specific permission (and even create your own permissions), and any combination of the above. Here are a few examples, but in general there is a lot flexibility here.

{% if currentUser %}
    ...
{% endif %}

{% if craft.session.isLoggedIn %}
    ...
{% endif %}

{% if currentUser.isInGroup( group ) %}
    ...
{% endif %}

{% if currentUser.id == entry.author.id %}
    ...
{% endif %}

{# custom permission #}
{% if currentUser.can('viewContent') %} 
    ...
{% endif %}

When retrieving entries using ElementCriteriaModel you can also find by author, group, relatedTo, etc. so that you can only show the user links to entries that they have access to. To find entries where the author is the currentUser, for example, you could use something like this:

{% set entries = craft.entries.section('blog').authorId(currentUser.id).find() %}
{% for entry in entries %}
    <a href="{{ entry.url }}">{{ entry.title }}</a>
{% endfor %}

If you wanted to let the site admins assign user(s) to articles on an article-by-article basis independent of author, you could also use an entries fieldtype to create a relationship to user(s), and then find entries using the relatedTo method.

{% set entries = craft.entries.section('blog').relatedTo(currentUser).find() %}
{% for entry in entries %}
    <a href="{{ entry.url }}">{{ entry.title }}</a>
{% endfor %}

The same technique can be applied to assets (i.e. pdf files) just as easily.

For more information have a look at the documentation on UserModel, craft.session, craft.users, and ElementCriteriaModel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.