Wednesday, April 06, 2022

Install Angular Material on Ubuntu

Here is how to install Angular Material on Ubuntu:

 

1. Install NODEJS/NPM

inside of a terminal type: sudo apt install nodejs

as an alternative you can use nvm:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash 

then just type: nvm install --lts

this will download install and use latest long-term supported version of node.

 

2. Install the angular CLI

with npm i -g @angular/cli

 

3. Create new project: ng new myproject

 

4. Add Material Design: ng add @angular/material

 

5. Restart ng serve if running and enjoy your Material enabled project!

Tuesday, March 29, 2022

Ubuntu: how to restore packages after interrupted apt upgrade

Often you might stop running apt update && apt dist-upgrade.

Here is the one-line command that will resume reinstalling the unfinished, or half-configured packages for you. It creates list of packages which can be passed to apt install:  

grep  "08:18:.* half-configured"  /var/log/dpkg.log.1 /var/log/dpkg.log |  awk '{printf "%s ", $5}'

first part of the command will grab only half-configured packages, while the second part will grab just the package name.

Here is the command in full:

sudo apt install --reinstall $(grep  "08:18:.* half-configured"  /var/log/dpkg.log.1 /var/log/dpkg.log |  awk '{printf "%s ", $5}')

You can configure 08:18 with the time you know the packages were interrupted form installing.

Best luck!

Monday, March 28, 2022

Wordpress customizations inside functions.php

Here are few tips on how to customize your Wordpress, without having to resort to plugins, just insert the following php code inside your functions.php file. I will be adding more.

Redirect inner page to outer domain:
add_action('template_redirect','redirect_from_to');
function redirect_from_to(){
  if (is_page('mypage')){
    wp_redirect('http://www.google.com',301);
    exit()
  }
}
Note: mypage must be created in order for the redirect to work.


Allow svg files to be uploaded:

function cc_mime_types($mimes){

$mimes['svg']='image/svg';

return $mimes;

}

add_filter('upload_mimes','cc_mime_types');


Cheers!

Monday, February 22, 2021

Debug Laravel / PHP applications with XDebug in VSCODE

We will setup debugging using xdebug with PHP inside of visual studio code. 

Quick setup:

1) install php-xdebug:

sudo apt install php-xdebug

2) inside of php.ini at the end of the file set: 

[xdebug] 

xdebug.start_with_request = yes 

xdebug.mode = debug 

xdebug.discover_client_host = false 

3) install php debug extension in VSCODE and set the port of the vscode php debug extension to 9003.

Now you can press F5 and start debugging.

 

 

 

Alternatively you can install xdebug using pecl. 

The setup is valid for Ubuntu both on bare-metal as well as under Windows 10 with WSL.

Enjoy !

Sunday, September 27, 2020

JWT - JSON WEB TOKENS security

Refresh tokens are helpful stateless technology, because they have longer time of expiry than the secure tokens, and can be used to send requests back to the server for reissuing of normal secure tokens. 

The primary aim of a refresh token is to regenerate the authentication for the user in such way, that the user doesn't need to manually re-login into the system.

The flow of using refresh together with secure tokens is the following: Initially we're making a request containing valid combination of user/password payload to a server. After performing checks the server is generating and returning to us a pair of secure and refresh tokens. It is sending the refresh token as an http only cookie, which cannot be read or modified by the browser. Later in the process of work, when the secure token is about to expire we use the cookie containing the refresh token information to make request to the server. The server checks its validity in its database and sends back to the client a new pair of refresh secure tokens. 

In summary we use refresh tokens when our access token is expired, and we would like to renew it as well as to renew the refresh token. That is why it has longer expiration time than the access token. Keep in mind that, when the refresh token is expired we need to manually re-login the user. For the technical implementation of refresh tokens is very good if you manage to place the refresh token inside of http-only cookie, because on the client side JavaScript and other techniques cannot exploited to modify this type of cookie. In rare cases, if attackers send a refresh request to the server they cannot get the newly issued secure token. If you would like to increase the security of the generated tokens you can also include browser and os fingerprinting inside of the token payload. 

For the authentication server it is good it can perform the following specific actions: to be able to generate access and refresh tokens to revoke tokens(to delete the refresh token). When a refresh token is generated it usually goes through the following process: check whether there is an user id in the internal database with a token, check the validity of the token, check the number of tokens for this user: how many they are, because one user can generate and overflow our database and this is also a type of an attack. When everything is ready we can save the newly generated token into our database.


 

Access token is used when performing service requests

secret key is stored both in the server and in the JWT payload:
const Token = jwt.sign(
{ user: myUser }, // payload
jwtSecretKey,
{ expiresIn: '30d' }
);
on client side resides in local storage

 

1) Client side authentication - POST request to get the token:
payload: {
‘username:req.body.user’,
’password:req.body.password’
}

Response
Bearer: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwMSIsIm5hbWUiOiJKb2huIERvZSIsImlhdC

2) Client side: request + Authorization header
fetch(url, {
        method: 'GET',
        withCredentials: true,
        credentials: 'include',
        headers: {
            'Authorization': bearer,
        }
    })

request service with the token:
3) Server side authorization -
// const token = req.get('Authorization');
// token = token.slice(7, token.length);

app.route(‘/secret_url’).post(
jwtVerifier,
(req,res)=>res.send(‘info’)); // secret information

 


Refresh token is used when access token is expired in order to produce new access and refresh tokens.

  • has longer expire time than the access token, if expires the user is logged out.
  • on client side resides in httponly cookie, so client cannot modify it (attacker cannot get the new JWT refresh token)
  • includes browser fingerprint for extra security


The auth server can perform specific actions:

  • generate new access and refresh tokens
  • refresh tokens:
    •  check the user_id from the http transmitted refresh token cookie against internal refresh tokens list in order to regenerate new access & refresh tokens:
      • check refresh token validity (by comparing user_id inside the issued token list for the requested user)
      • prune the number of generated refresh tokens (because the user can be logged in from different devices)
      • save in a db the generated refresh tokens
  • revoke token (delete refresh token)

The practical implementation of both JWT secure and refresh tokens can be seen in these 2 courses:

Angular with PHP and JSON web tokens (JWT)

JavaScript User Authentication Login Script (JWT)

 

Congratulations !

 

Sunday, September 20, 2020

Starting with React


Here is how to create a simple application with the React front-end framework:


 

Setup the project:

sudo npm i -g create-react-app // install the dependencies
npx create-react-app my-react-app // create the initial application
npm start //start the live development server


App.js
import React from 'react';
import './App.css';
import Login from './loginComponent'; //default import
import {UsersList} from './usersList'; // specific import

const users = [ // using nested/presentational components
{ name: 'John', occupation: 'student', age: 23 },
{ name: 'Pete', occupation: 'teacher', age: 30 },
{ name: 'Anna', occupation: 'programmer', age: 35 }
];

const App = () => {
// double curly braces because of passing object and because of passing property
return (
<div className="App">
<Login user={{ name: "John", uid: 1000 }} />
<header className="App-header">
<UsersList users = {users} />
</header>
</div>
);
}

export default App;


usersList.js
import React from 'react';
import {UsersListItem} from './usersListItem'; // specific import

export const UsersList = ({ users }) => // getting especially users array from the passed array with props
( // with () we return automatically instead of writing {}
<>
{ users.map(user => <UsersListItem user={user} key={user.name} /> ) }
</>
);
// React will be used when we return react fragment


usersListItem.js
import React from 'react';
const sayMyName = (name) => {
alert(name);
}

export const UsersListItem = ({ user }) =>
(<div>
{user.name} -
{user.occupation} -
{user.age}
<button onClick={ ()=>sayMyName(user.name) }>Display name</button>
</div>
)


loginComponent.js
import React from 'react';
// show the import, conditionals and DOM element, also the export
// how to display props, destructurise in the passing parameters(props)

const Login = ({ user }) => {
let isAdmin = (user.uid) === 1000;
let logged_in = true;
// double conditional
return logged_in ? (
<>
hello mr.{user.name}
{ isAdmin ? `you are admin (conditional)` : null}
</>
)
: (<>please login</>)
}

export default Login;

Tuesday, September 15, 2020

Deploy Angular app to Vercel and Firebase for free

Here is how to do it very quickly:


 

For Firebase you'll need to install the following schematics:
ng add @angular/fire

then just do:
ng deploy

you'll be probably asked to authenticate with password in browser, and then your project will be on Internet.

If you would like to youse serverless functions for NodeJS interpretation here is the way:
sudo npm install -g firebase-tools 

firebase init functions

This will install and initialize the functions. Then go to the newly created /functions directory and install your packages such as: npm install nodemailer cors etc.

And now is time to edit the auto-generated index.js file.

When you are happy with the generated function you can deploy it, just run from the same directory: 

firebase deploy

For Vercel, after the registration just link your github repository to Vercel. You can see/edit your current local git configuration with:

git config --local -e

To link the remote origin of your repository to the local git repo use: 

git remote add origin  https://github.com/your_username/project.git

if there is something on the remote site, you can overwrite it with the local version using:
git push --set-upstream origin master -f

 
or just pull and merge the remote version: git pull origin master

Then just do your commits and when pushing you'll have a new version synchronized in Internet.

Congratulations and enjoy the: Angular for beginners - modern TypeScript and RxJS course!

Subscribe To My Channel for updates