Authentication: Process of verifying the identity of a user Authorisation: Process of verifying an identity's access privileges

1. Authentication

1.1 hash

import hashlib

print("mypassword")
print("mypassword".encode())
print(hashlib.sha256("mypassword".encode()))
print(hashlib.sha256("mypassword".encode()).hexdigest())

That's why we need to hashing passwords and checking them against stored hashes, it's much more safe.

Example: auth.py

from json import dumps
from flask import Flask, request
import hashlib

APP = Flask(__name__)

data = {
    'users': [],
}

def getData():
    global data
    return data

def generateToken(username):
    return username

def getUserFromToken(token):
    data = getData()
    userInput = token
    for user in data['users']:
        if user['username'] == userInput:
            return userInput
    return None

@APP.route('/secrets', methods=['GET'])
def get():
    user = getUserFromToken(request.args.get('token'))
    if user is not None:
        password = None
        for dataUser in data['users']:
            if dataUser['username'] == user:
                password = dataUser['password']
        return dumps({
            'secrets' : password,
        })
    else:
        raise ValueError("Invalid permissions or token")

@APP.route('/register', methods=['POST'])
def create():
    info = request.get_json()
    data = getData()
    data['users'].append({
        'username': info['username'],
        'password': hashlib.sha256(info['password'].encode()).hexdigest(),
    })
    return dumps({
        'token': generateToken(info['username']),
    })

@APP.route('/login', methods=['POST'])
def connect():
    info = request.get_json()
    data = getData()
    print(data)
    for user in data['users']:
        if user['username'] == info['username']:
            if user['password'] == hashlib.sha256(info['password'].encode()).hexdigest():
                return dumps({
                    'token': generateToken(info['username']),
                })
    raise ValueError("Invalid username or password")

if __name__ == '__main__':
    APP.run(port=15333)

2. Authorisation

After authentication, how do you keep system knowing who you are?

2.1 Token

What is a "token"?

A packet of data used to authorise the user.

What kind of tokens exist?

User ID: The ID number of the particular user . JWT'd User ID: The ID number of a particular user stored in a JWT. Session: Some kind of ID representing that unique login event, whereby the session is tied to a user ID. JWT's Session: Some kind of ID representing a session that is stored in a JWT.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1dd5287d-a957-4680-9172-466de33af29a/Screen_Shot_2021-04-26_at_4.04.11_PM.png