Categories
Web Development

Symfony 5+ how to import or link to javascript and css files with webpack encore

Symfony has a handy way of importing your css and javascript files into your templates/pages to use them. You can find the full info in the docs link here.

This was a little confusing to me at first.  Mostly due to my lack of knowledge of some of the Webpack and  modern JS features like importing.
Basically when you update the webpack configuration to add another entry point for a separate Javascript file, it also creates a matching CSS file if your javascript file imports any CSS.  Many 3rd party packages will have imports, as I found out with SunEditor(totally awesome wysiwyg html editor). So when you try to create a script that relies on a CSS file of it’s own like suneditor you need to import like this inside the file.

//edit-about-user.js
import 'suneditor/dist/css/suneditor.min.css'
import suneditor from 'suneditor'
import plugins from 'suneditor/src/plugins'
let aboutInput = 'about-input';
suneditor.create(aboutInput, {
    plugins: plugins,
    buttonList: [
        ['undo', 'redo'],
        ['font', 'fontSize', 'formatBlock'],
        ['paragraphStyle', 'blockquote'],
        ['bold', 'underline', 'italic', 'strike', 'subscript', 'superscript'],
        ['fontColor', 'hiliteColor', 'textStyle'],
        ['removeFormat'],
        '/', // Line break
        ['outdent', 'indent'],
        ['align', 'horizontalRule', 'list', 'lineHeight'],
        ['table', 'link', 'image', 'video', 'audio' /** ,'math' */], // You must add the 'katex' library at options to use the 'math' plugin.
        /** ['imageGallery'] */ // You must add the "imageGalleryUrl".
        ['fullScreen', 'showBlocks', 'codeView'],
        ['preview', 'print'],
        ['save', 'template']
    ]
})

This is what confused me I thought the Javascript code would automatically include the CSS file when I included the Javascript in the page with a tag like this

//inside edit-about-user.html.twig
{% block javascript_extra %}
{{ encore_entry_script_tags('editAboutUser') }}
{% endblock %}

block javascipt is my custom twig section, encore_entry_script_tags includes the javascript. This is where I falsely assumed that the import statement above would include the CSS in the page along with the Javascript. The above encore_entry_script_tags function only includes the Javascript. To include the CSS which is the same from the import statement above you must use another tag.

//inside edit-about-user.html.twig
{% block stylesheets %}
{# 'app' must match the first argument to addEntry() in webpack.config.js #}
{{ parent() }}
{{ encore_entry_link_tags('editAboutUser') }}
{% endblock %}

Again block stylesheets is just my custom twig block section. encore_entry_link_tags is the magic needed to include the CSS on the page that the import statement included above. This is what confused me I thought Webpack was bundling the CSS somehow with the JS. What it does is create two files one CSS and one Javascript. You must use the encore_entry functions to include both to get what ever project you are using functioning.

So as I found out you must include both the CSS and JS with encore_entry_ tag functions.

Categories
Resources Web Development

Fonts and icons resource list

Everything you need to know about web fonts – awesome article that explains what fonts are, how they work on the web and the history of how things have changed.

Google Fonts getting started page – Use some fonts for free from google fonts. Google now has icons too.

Categories
Resources Web Development

CSS links and resources

Setting Height And Width On Images Is Important Again – great article explaining how browsers operate on images with CSS and HTML sizing.

Cumulative layout shifts – this is when the content on your page shifts due to images, video or other content loading in the page.

Categories
Web Development

How to get the user id in a service in Symfony 5

I’m no Symfony expert, I write what I find as I find it. Nothing in the documentation really covers this subject, so I am not sure what the correct way is of if there even is one.

There are a few ways I have found to get a user id. None of the classes you can inject such as UserInterface, SessionInterface, TokenInterface, Security etc. contain an actual getUserId() method.

You can  get a user object from the Security class, as seen in the documentation here. To do so you type hint aka Dependency Inject your service constructor with Security but not just any Security will do there is also one by Sensio labs and another. You want this Security

use Symfony\Component\Security\Core\Security;

Then your ide wont show it or will warn something about a polymorphic call blah blah, but apparently there is a getId() method of the user returned from Security and you can get a user id like this.


/** @var User $user */
$user = $this->security->getUser()->getId();
if(!empty($user){
$userId = $user->getId();
}

This method may return null if the user is not logged in so you need to check for that. The @var syntax tells the IDE what is going on so it knows there is a getId() method, you will also need to import that class. The User object it refers to is your App/Entity/User class.

Forgive me if anything is wrong.
Link to a Symfony cast with a little more info but not much.

Categories
Resources Web Development

How does login and authentication work in Symfony 5.*

This is mostly for myself as a reminder. The most frustrating part of Symfony is Authentication because the information is scattered all over between articles, symfonycasts etc. just all over, like a unicorn farting out rainbow sprinkles.

There are two versions of authentication an old one and a new one. The old one uses Authentication providers the new one users just Authetincators. No one but the authors of Symfony know WTF the difference is though.

Note : to add confusion Symfony refers to what you usually call Sessions as Tokens FFS.

First off a list of files involved in the login process :

  1. The login form obviously app/templates/security/login.html.twig
  2. A security controller app/src/Controller/SecurityController.php
  3. A user Provider aka the User entity class app/src/Entity/User.php
  4. An Authenticator app/src/Security/LoginFormAuthenticator.php

When a user requests /login Symfony first calls LoginFormAuthenticator.php to check to see if the user is logged in/authenticated so the work is not done in the controller like most other actions. To change, add, remove anything from the authentication process you make changes in the LoginFormAuthenticator.php methods.

There is a new experimental Authentication system it still uses authenticators but a slightly different process.

This authenticator is listed in the app/config/packages/security.yaml file under firewalls:main:guard:athenticators as

- App\Security\LoginFormAuthenticator

symfony firewall authenticator section

Every time a request is made the firewall will use the authenticator listed to try to authenticate the user. If authentication fails Symfony secretly behind the scenes tries other ways to authenticate the user as you can see in the image below.

symfony guards
Secret guards attack

As you can see in the image above Symfony will try your guard you listed in the configuration file, but it also tries it’s own secret list of default authenticators.

For information about the login form see this article in the scatterdocs. A little more info about the login form and process from the Symfony Spaghetti docs.

Categories
Resources Web Development

Symfony Session resources list

Plain session docs – This is the symfony documentation page about Sessions alone. This link shows the basic configuration and use of Sessions in Symfony. This also mentions not starting a session for Anonymous users and has links to other info about sessions.

Configuring Sessions and Save handlers – Symfony documentation link. This covers more about how to configure sessions and their Save Handlers. This is some of the better information about Sessions and how they work in Symfony. It covers the save handlers and more of the configuration information.

Session proxy examples – Symfony Documentation link. This covers how to create your own session handler. It also discusses how to encrypt session data with an example.

Framework configuration – Symfony documentation link. This covers many of the options for the security component of Symfony.

Store sessions in a database – Symfony documentation link that describes how to store session data in a database or Redis.

Session Management – Symfony documentation link. Explains how sessions are managed in symfony. Gives a good overview and important information about how symfony functions. It covers the functions symfony uses to replace PHP session functions and how to use them. This also covers the ways to work with sessions in Symfony. Oddly this covers Flash messages too.

 

Categories
Uncategorized

Symfony events resources, links and videos

To see a list of all events use this command

 php bin/console debug:event-dispatcher

Built-in Symfony Events – this covers some of how events work in Symfony and the basic default events that fire with every request.

The HTTP kernel component – This gets to the core of Symfony and it’s event system. The kernel is driven by events. This also covers the basic flow of events that symfony follows when a request enters the system.

Events and event listeners – More information about symfony events.

The EventDispacher component – This is more about the symfony system events.

An example of how to use the EventDispacher component

Videos

This video covers how to create a custom event subscriber

Categories
Software Development Web Development Web Security

Authentication vs Authorization what is the difference?

Authentication/Authorization these terms are often confused. Here I will clarify them.

Authentication — Login, proving who a user is one way or another. After a user is logged into a system a session cookie is usually created to re-authenticate the user so they don’t have to login every single page view.

Authorization — Can a user view or access something once Authenticated? Authorization includes things like administration panel access, viewing a users profile or post or media etc.

Categories
Resources Web Development

Symfony errors and exception handling resources

How to customize error pages – Documentation page about how to create custom error pages.
How to Customize Access Denied Responses – specifically about how to customize access denied responses. This is useful for when you use voters to authorize a users access to content.

Categories
Resources Software Development

Ethereum Solidity programming links and resources.

Links and resources about Ethereum Solidity programming language.

Videos