Create Password Protected Pages in Craft

I recently set up some password protected pages in Craft, working with Chris Chiles here at Mighty. The client wanted something they could keep secure, yet provide access to indicated people. Here’s how I did it.

Set Per Entry Password

Within Craft create a new Plain Text field for the entry you would like password protected. The password for the entry can be a phrase, random string of numbers and letters, whatever.

Create a Login Template

In Craft, set up a route to the login template including the slug of the page you are password protecting. For example, blog/{slug}/login.

Within your login template create a form that:

  1. Contains a field for your password
  2. Posts to itself

It should look something like this:

    <form id="check-code" action="/{{ craft.request. getPath() }}" method=“POST”>
        <input type="text" name="access-code" id="access-code" />
        <input type="submit" value="Submit" class="submit" />
    </form>

Check Form Submission against Entry’s Password

Within the login template wrap the form in a conditional that checks for the password field’s POST value when the page is reloaded following successful form submission (I use Parsley for pre-submission form validation).

    {% if craft.request.getPost('access-code') %}

    {% else %}

        <form action="/{{ craft.request. getPath() }}" method="POST">
            …
        </form>

    {% endif %}

Now, select the entry using craft.request.getSegment() and compare its password field against the post data from our form submission. If they don’t match then create a duplicate of our form from below with some kind of error message (I’m sure there’s a way to include the forms, without repeating markup using a macro or something). This allows the user to try again if they got it wrong.

    {% if craft.request.getPost('access-code') %}

        {% set entry = craft.entries.section({entrySection}).slug(craft.request.getSegment(2)).first() %}

        {% if entry.passwordField == craft.request.getPost('access-code') %}    

        {% else %}

            <form action="/{{ craft.request. getPath() }}" method="POST">
                <p>Your access code was incorrect</p>
                <input type="text" name="access-code" id="access-code" />
                <input type="submit" value="Submit" />
            </form>

        {% endif %}

    {% else %}

        <form action="/{{ craft.request. getPath() }}" method="POST">
            …
        </form>

    {% endif %}

Now, if the password and the post data do much we need to set a cookie and redirect the user to the entry’s template. In order to set the cookie, I’m using Andrew Welch’s Cookies plugin. In this case I’m setting the cookie to expire with the current browser session, but you can set it to be whatever you want following PHP’s set cookie parameters.

    {% if craft.request.getPost('access-code') %}

        {% set entry = craft.entries.section({entrySection}).slug(craft.request.getSegment(2)).first() %}

        {% if entry.passwordField == craft.request.getPost('access-code') %}

            {{ setCookie( craft.request.getSegment(2), entry.passwordField, 0, "/") }}
            {% redirect "blog/"~craft.request.getSegment(2) %}

        {% else %}

            <form action="/{{ craft.request. getPath() }}" method="POST">
                …
            </form>

        {% endif %}

    {% else %}

        <form action="/{{ craft.request. getPath() }}" method="POST">
            …
        </form>

    {% endif %}

Check for Cookie in Entry’s template

At the top of your entry template check if the entry has a password set and if the browser does not have a cookie set, whose name matches the entry’s slug and whose value matches the entry’s password. If those conditions are met then the user has not logged in and will be redirected to the login page. Otherwise, the template will continue loading and the user will see the entry template.

    {% if (entry.passwordField != "") and (getCookie( entry.slug ) != entry.passwordField) %}

        {% redirect "blog/"~entry.slug~"/login" %}

    {% endif %}

Bonus

Once you’ve tested out that this process is working you, or other credentialed site users, may not want to have to enter in the password each time. Simply add another conditional to the entry template’s password/cookie check.

    {% if (entry.passwordField != "") and (getCookie( entry.slug ) != entry.passwordField) and (currentUser == false) %}

        {% redirect "blog/"~entry.slug~"/login" %}

    {% endif %}

Now, if the user is logged in to the site the conditional will be bypassed and they will be able to see the content without getting redirected to the login page.

Conclusion

The process of password protecting certain pages could serve many purposes. Here’s a few ideas:

  1. Content that you want to be able to distribute privately. Proposals, design comps, etc.
  2. Could serve as an intranet without the intranet for small organizations.
  3. You want to provide access to content editors who are not registered users so you can get feedback.
  4. RickRolling your friends.

Give it a whirl.

As discussed in the previous post of this series, typography has history. Technological advance has changed the means of its production as well as its aesthetic form (fashion plays a part here as well). Hundreds of years of history have given typography an expansive lexicon, intricate classifications, and even anatomical terms. This complex world is perfect for people who like to dive deep into subjects. There’s always more to research and tease out.

Typography-Presentation-2015-03-21.014
Typography-Presentation-2015-03-21.015

The two counterweights of typographic production, efficiency and freedom, have create a centuries-long push and pull. The earliest printers had a world of possibilities at their disposal. In letterpress printing the type and layout were up to the printer and the creative palette was wide, but the process was tedious. If they could imagine an illustrated drop cap or exotic gold leaf, and their patrons had deep enough pockets, they could do the painstaking labor and make it happen. The beauty of the Gutenberg Bibles is an example of this craftsmanship. However, Gutenberg’s ruinous debt was also demonstrative of the expensive and difficult process.

Typography-Presentation-2015-03-21.016

Gutenberg Bible

Typography-Presentation-2015-03-21.017

Dropcap

Typography-Presentation-2015-03-21.018

Letterpress

Typography-Presentation-2015-03-21.019

Woodblock printed livestock sale posters.

It wasn’t until the 20th century that the basic mechanics of typographic production took a major leap in efficiency. Machines like the Linotype, named for the lines of hot type that it would produce from the operators input on the keyboard, drastically reduced the amount of pre-press time from printing. The nature of this advancement in convenience naturally reduced the freedom available to the designer. The typographic palette was greatly reduced as it became necessary to work with what would fit on a usable keyboard, in many cases, interjecting illustrations and other glyphs into layouts would be seen as impractical. The efficiency of the keyboard would carry over into typewriters and modern computers, along with its inherent limitations.

Typography-Presentation-2015-03-21.020

The Linotype machine.

Typography-Presentation-2015-03-21.021

The next major evolution in typographic production arrived with the advent of photo lithography and widespread offset printing. As unlimited as the possibilities had seemed with letterpress, things were really cooking now. Photography could be reproduced in vivid color, typography could be placed in a layered manner that truly integrated it in design. However, like all the previous shifts the increased freedom again reduced the efficiency of production. Huge production departments cut transparent sheets of type from the foundry into their layouts, meticulously arranging them along with photography and illustration in a very precise form of collage. Imagine a whole floor of underpaid production artists taking Don Draper’s quippy line and somebody’s sketch and turning it into something that could actually be printed.

Typography-Presentation-2015-03-21.022

Muhammad Ali on the April 1968 cover of Esquire.

It wasn’t until the advent of the desktop publishing on personal computers that efficiency and freedom found equal footing. We have now arrived at typographic modernity and the possibilities are immense.

Typography-Presentation-2015-03-21.024

Outrage

We are constantly assaulted by tragedy in our connected world. The news of massacres in distant lands, societal injustice, natural disasters, and disease outbreaks flow through every stream we have. When faced with this abundance of bad news it seems that if we feel any genuine sorrow at all it is quickly replaced by anger and outrage. Surely this should have been avoided! Somebody should have seen this coming! It’s not really surprising. After all, tragedy exposes our fear of helplessness and anger feels productive. I won’t argue that anger hasn’t, at times, motivated action and substantive change and improvement in our world. However, outrage seems to always carry a distorting effect on our expectations.

Outrage makes people feel that they can avoid the consequences of a world where we all bump up against each other, and everything around us. If only we come up with a system complex enough and clairvoyant enough we can all live without fear of danger, injustice, or offense. Time and experience seem to prove the opposite. Well intentioned systemic interventions in our society introduce unintended problems while trying to target specific ills. A measured approach to problem solving is comfortable with this reality, but outrage is not. Outrage is a beast that can never be satiated, it only grows more hungry as utopian dreams are unsatisfied.

This is not to say that we should not try to solve problems, even with big sweeping programs. But we need to understand that any solution or system we come up with must be provisional, subject to revision or rejection. This is especially hard in government, where political will is much more limited than outrage, and once programs are established they are nearly impossible to kill. Understanding that solutions are provisional cuts off outrage at the knees. We know these are not perfect solutions, but that’s part of life, and we can improve them as needed.

Becoming Steve Jobs

I was not a fan of Walter Isaacson’s biography of Steve Jobs. So, I was very pleased to learn of a new biography, Becoming Steve Jobs, by Brent Schlender and Rick Tetzeli. The book promised to show a fuller picture of the man and his work, with the cooperation of many of the people with whom Jobs worked closely. I finished the book last night and thought I’d write a few thoughts about it.

What I liked

The authors seem to have a much better understanding of Steve Job’s actual work. They didn’t rely on quasi-supernatural “reality distortion fields” to explain his persuasive gifts or motivational powers. They instead focus on his understanding of the motivations and needs of those with whom he negotiated, and the intense drive that focused his teammates, and cast off those who couldn’t keep up.

They did not give short shrift to Steve’s years after leaving Apple, when he served as CEO of NeXT and Pixar. In fact, these years serve as the central crux to their whole thesis. Namely, that Steve Jobs was a spoiled, yet gifted tyrant with little regard for anyone around him until he became closely associated with gifted creative leaders and managers in Ed Catmull and John Lasseter at Pixar. The authors are explicit in their point of view, sometimes to a fault, but I think they correctly understand that those “wilderness” years were key to the success of Steve’s second act at Apple.

The story is mainly told from Brent Schlender’s perspective, a journalist who had a lot of contact with Jobs, on and off the record. His grasp of the business side of Silicon Valley pays off and drives the narrative, and makes up for his slight hand waving at some technological aspects of Apple’s work.

What I didn’t like

The authors are business journalists and it shows. When NeXT and Apple were not doing well financially, especially in comparison to Microsoft, the authors clearly regard them as complete failures. There is too little appreciation given to what these companies did well and the reason there was a fairly rabid fan base upon Steve’s return to help propel Apple’s renewal by evangelizing the brand. Regardless of the confusion in Apple’s leadership, those of us who used Macs in the 90s regarded them as far superior to anything Microsoft produced. In addition to this loyal fan base, the technical excellence of NeXT’s software served as the foundation for everything Apple has been able to do over the last 16 years. The authors seemed to disregard what was going right in these companies because they didn’t overpower Microsoft immediately, although their modern incarnations arguably have.

The authors also fell into the same trap that Isaacson did regarding Jobs’ animosity toward Adobe. While Isaacson saw evidence of resentment playing out in Apple’s introduction of iPhoto, Schlender and Tetzeli see it in Steve’s policy on Flash on iOS. Steve may have harbored a grudge against Adobe, but here’s the thing in the case of Flash, he was absolutely right. Flash is pretty terrible in a few ways that would’ve been very important to Jobs and the success of Apple’s products. It had terrible performance and quickly drained battery on mobile devices, and often on desktops as well. The rightness of the course has been borne out by Android abandoning Flash as well, despite the fact that it was a differentiating selling point against iOS. Steve may have been gleeful to not cater to Adobe, but it was the right decision.

One minor issue I have is placing Apple’s run-in with anti-trust law with ebook sellers next to the Silicon Valley wage fixing scandal. The wage fixing scandal seems to have been a case of outright abuse of authority, with little regard for the effect on the livelihoods of people below the top levels of the companies involved. It is rightly seen as an abuse of power. The ebook scandal, on the other hand, can be best understood as the real monopoly player, Amazon, lobbying to have a threat to its dominance squashed by regulators. A recognition of the murkiness of this case, compared to the relative straight forward nature of the wage-fixing scandal, would have been appreciated.

Conclusion

One thing that occurred to me in the book is that it has a much more applicable message for those trying to learn from Steve Job’s life than the Isaacson book. The authors quote Jobs as saying, “I am who I am,” as an excuse for bad behavior. However, their narrative demonstrates that Steve Jobs became who he was be honing his individual gifts over his lifetime until he could put them to their best use. Jobs became a better and better version of himself. If readers take away the message that they can become the best version of themselves by identifying their gifts and sanding down their rough edges, then they will realize that they don’t have to try to be like this one renowned individual. That would be something worth remembering.

Typography I: Heritage

I recently gave a presentation on typography internally at Mighty in the Midwest and to the public at GRDevDay. I want to share it here as well, so I am breaking the material up into sections and repurposing it here. This is the first segment.

Typography I: Heritage

Martin Luther

Martin Luther

Martin Luther was a man who disappointed his father by becoming a monk and then a priest, rather than embracing a respectable worldly profession. He lived in Saxony (modern Germany) and gradually became disillusioned with his ministry because of attitudes and practices in the Church that he saw as a fall from grace. Principle among his concerns were the sale of indulgences. So, as was the custom for scholarly disputes, he nailed his concerns in the Ninety-Five Theses on the Power and Efficacy of Indulgences to the door of Castle Church of Wittenberg in 1517.

Ninety-Five Theses on the Power and Efficacy of Indulgences

Ninety-Five Theses on the Power and Efficacy of Indulgences

Luther could not have known at that moment what he would set in motion. The movement this written rant would start spark massive upheavals across Europe. Eventually the church would reform these practices and discontinue the sale of indulgences, however they would not be able to stop continued dissatisfaction and the over-through of Catholic dominance in many nations. Within Luther’s own country a peasant revolt would flare, claiming the lives of thousands and earning his condemnation.

Luther’s frustration would have immense consequences, but he could not have been the first person at odds with the societal and religious order of Europe. Christian monasticism had existed for over a thousand years, giving many people access to written history and sacred texts. Surely Luther could not have been the first to protest. What made the difference this time?

Printing

Typography-Presentation-2015-03-21.009

Within two months the 95 Theses had spread across Europe. It was reprinted, expanded upon, and remixed everywhere to appeal to people of all classes, including the illiterate. The printing press allowed Luther’s ideas to reach beyond his town and inspire action in others. Technological progression collapsed the distance between people.

95 Theses Reprint

A reprint of the 95 Theses

Christ & the money changers vs priests gathering offerings

A political cartoon contrasting the Biblical story of Christ casting the money changers from the temple with priests collecting payment from peasants.

Previously, knowledge of history, scripture, theology, and philosophy were strictly the domain of the educated. Which meant aristocrats, monarchs, and monks. But with the printing press literacy began to spread throughout society. Suddenly, people could realize that maybe the Bible didn’t say what they had been taught it said, but religion wasn’t the only thing brought into discussion by the advent of widespread printing. The historical writings of the ancient Romans and Greeks exposed alternate forms of government and unchurched philosophy to Enlightenment thinkers. These sea-changes would eventually lead to the establishment of a democratic republic in the United States.

Typography-Presentation-2015-03-21.010
The Boston Massacre

A broadsheet describing The Boston Massacre, a key historical event leading to the American Revolution. Although the version of events described in the piece were dubious, this is how people throughout the colonies would have learned about it.

The Declaration of Independence

A printing of the Declaration of Independence. Modern Americans are more familiar with the handwritten copy, but most colonists would have seen a printing like this.

Printing has been at the center of every society shift since Martin Luther and typography is at the center of printing. The transmission of ideas projected power in ways that only armies could do before. This is the heavy heritage of typography. In this craft of printers who labored over letters in musty workshops with pulp, hot lead, ink, and heavy machinery we find the seeds of our modern world.

Typography-Presentation-2015-03-21.012

Beethoven

When I was growing up my family would take frequent, long road trips to visit my Grandmother in Albuquerque, New Mexico. My parents had a handful of staple cassettes for us to listen to: Mr Bach Comes to Call, Vivaldi’s Ring of Mystery, and my favorite, Beethoven Lives Upstairs. My parents did occasionally listen to music from this century, my father would get a far off look in his eyes whenever Queen would come over the radio, but our household largely was filled with classical music. The children were obligated to take piano lessons, we would often come home to find my mother listening to Beethoven’s 9th while folding laundry, and Handel’s Messiah was a constant during the Holiday season.

When I became a teenager this music fell by the wayside as my tastes followed those of most teenagers trying to be cool while not popular. Some of what I liked then has stood the test of time, but much of it has proven itself culturally and emotionally bankrupt. In recent months I have found myself returning to the classical music of my childhood when I need to think, meditate, and focus. I have been drawn back to Beethoven particularly.

Beethoven always seemed like somebody I could relate to. I grew up in a family of manic depressives. Strong swings of emotion and drama were central to my world. Consequently, the moody, belligerent, obviously afflicted with brilliance, and emotionally present Beethoven spoke to me. The man became deaf, yet, despite the frustration of his disability, composed some of the most lasting music in western civilization.

Beethoven connects me with something primal, and reminds me of my childhood. He inspires me to do better and never use a character flaw or ingrained attribute as an excuse for lack of effort. He reminds me that hardship and frustration can be transitory if I don’t let them keep me from pushing forward.

I’ve included links to some of my favorite Beethoven music below. Maybe they’ll do something for you.

Your Own Typewriter

I absolutely love Matthew Butterick’s article regarding Medium. I previously wrote about my disappointment with the growth of Medium among established writers, so you can probably guess the tone of Butterick’s piece. Most of his critiques center around what is behind one of Medium’s proudest features, typography:

… I wouldn’t say that Medium’s ho­mo­ge­neous de­sign is bad ex ante. Among web-pub­lish­ing tools, I see Medium as the equiv­a­lent of a frozen pizza: not as whole­some as a meal you could make your­self, but for those with­out the time or mo­ti­va­tion to cook, a po­ten­tially bet­ter op­tion than just eat­ing peanut but­ter straight from the jar.

Then he comes around to the base criticism that applies to all of these social networks where you give up ownership, in fact or practice, of your content for convenience.

In truth, Medium’s main prod­uct is not a pub­lish­ing plat­form, but the pro­mo­tion of a pub­lish­ing plat­form. This pro­mo­tion brings read­ers and writ­ers onto the site. This, in turn, gen­er­ates the us­age data that’s valu­able to ad­ver­tis­ers. Boiled down, Medium is sim­ply mar­ket­ing in the ser­vice of more mar­ket­ing. It is not a “place for ideas.” It is a place for ad­ver­tis­ers. It is, there­fore, ut­terly superfluous…

… Tempt­ing per­haps. But where does it lead? I fear that writ­ers who limit them­selves to pro­vid­ing “con­tent” for some­one else’s “branded plat­form” are go­ing to end up with as much lever­age as cows on a dairy farm…

I previously wrote about the importance of having your own place online. Invest in your own home, it’s easier than ever, and much more rewarding than subletting from someone else.

Medium

Manton Reece responds to Realmac’s new Typed.com and Ben Thompson’s bullish attitude about blogging services and social networks. Manton addresses the changing landscape of blogging and its platforms:

…even if those changes aren’t “a bad thing”, they can have bad consequences. Medium is a beautifully designed site and there is some great writing published there. But if it discourages people from owning their own content and writing at their own domain name, then it is a step back for the web.

I totally agree. I’m always disappointed to follow a link to an article and land on Medium. It is especially depressing when the article is written by someone with a well established blog and a history of good writing.1 Despite Manton’s suggestion that Medium can serve as a good place for cross posting, most of these articles do not exist on the author’s own site.

Because all Medium posts are based on the same small kit of parts and fit in the platform’s overall brand and aesthetic, the identity of the author is greatly diminished. The writing may actually be individualistic, but the visual voice is homogeneous. In fact, if Medium were to add the customizability necessary to overcome this issue they would become no different than their competitors, like Squarespace or Wordpress.com. Their differentiation from other blogging platforms is what makes them boring and their content unpalatable to me.

I have actually published a post on Medium and, shamefully, that post has not existed on my own site until today.2 There were very positive aspects to the service; the editor is nice, I actually had helpful input and promotion from a Medium editor, and it was easy to see the reach of the article. But those early days are gone and Medium seems like a place for people who don’t blog regularly. There’s nothing wrong with that per se, but just like with Snippets, I like to own my content.

There is a place for services like Medium, but it would be depressing if it was the only place. Owning a domain name is powerful, it allows you to create an online home for yourself and make it what you want. A service can do many things, but it can’t do that.


  1. One of the benefits that Ben Thompson brings up is the individualistic nature of blogs, which Medium greatly diminishes, even for established voices. 

  2. You should read it. It’s a post I’m particularly proud of and as the Match approaches again it is timely. 

The News

I’ve made a short guide to the news media to anyone who feels their blood rising when watching, reading, or listening to the news. I am not talking about conservative news outlets or liberal news outlets, I’m talking about all news outlets.

  1. The news media is not interested in portraying groups representatively. They are only interested in outliers, exceptions, dissidents, and authority figures.
  2. The news media create quotes for you and then seek your approval, hopefully. It makes their stories flow better, but should be taken with a grain of salt.
  3. The news media, like all of us, is inherently biased. Just as historians cannot help but telegraph their view of the world in the facts they choose to present, journalists color their facts through editing, selection, and tone. The idea of an impartial media is a relatively recent invention. Newspapers were born out of partisanship, as party organs, and attempts to make them more objective have had a mixed record. Bias isn’t inherently bad, as long as it is understood by the audience. The way a story is portrayed says as much about the teller as it does about the story itself.
  4. The news media loves emotionally charged subjects. They make you watch, read, or listen longer, which means they can sell more ads. Your news about GM’s auto recalls are probably brought to you by GM’s advertising department.
  5. The news media love to talk about themselves. Expect stories about persecuted journalists to take precedence over any similar story involving anyone else. Many of us love what we do and many of us think it’s important to society, but few of us have a microphone.

There you have it, Noah’s guide to the news media.

Settings by Location

Dan Moren wrote a great post at Six Colors detailing a great idea for location-based security on Macs and iOS devices.

Location services have been a major function of iOS since its earliest days, and they’ve increasingly played a part in OS X in recent years as well. At the same time, given that we have devices that always seem to know where we are, why can’t we use that a little bit more to our advantage?

It is of a piece with an idea I’ve had for a while to have location-based settings of all kinds. For example, I love the fact that, as of Yosemite, I can make and answer phone calls on my iPhone through my Mac. Every chance I’ve had to use it has been great, and I find it very convenient. However, I work in an open office and do not like to answer phone calls sitting at my desk. I would love the ability to set this feature to inactive whenever I’m in my office, but active at home. Some more possibilities for location-based settings include:

All these possibilities, and more, could be opened to us if settings, in general, could be geofenced. It certainly fits with the Apple’s ideas of Continuity and would be very helpful to a wide variety of users.

Older Posts