0%

Web Security

  • Assume the worst case *
  • Exposed to threats
    • Data theft/ destruction
    • System attacks
  • vulnerabilities
  • defencsive using automated alerts

Attack Types

  • Malicious code execution
  • Cryptography attacks: hide secrets
  • Data interception
  • Denial of Service

owasp.org/www-project-top-ten/
OWASP Top Ten Web Application Security Risks | OWASP
The OWASP Top 10 is the reference standard for the most critical web application security risks. Adopting the OWASP Top 10 is perhaps the most effective first step towards changing your software development culture focused on producing secure code.
owasp.org

XSS

  • Cross-Site Scripting: request from one domain to another domain
    -> html entities
  • A type of injection
  • Malicious scripts are injected into web sites
  • scripts could be entered on any inputs

XSS Solutions

Escape/ Sanitiza all user inputs
Escape all the input before actually putting it on sensible places
XSS Protection Cheatsheet

SQL Injection

  • just USE Sequelize
  • parameterized statements
  • escaping user inputs
  • privileges control
  • SQL Injection Prevention Cheatsheet

CSRF

  • Cross-Site Request Forgery
  • forces a user to input st unauthorized

CSRF Solutions

  • Identifying source origin
  • access-control-allow-origin
  • Synchronizer Tokens

HTTPS

  • http is not safe, HTTPS is same with http over TLS
  • only expose the host to a DNS server and the target IP
    < Secured things >
    • path
    • query
    • payload
    • every method
The Handshake
  • negociation the certificate

Heroku / Let’s Encrypt
gives HTTP certificate for free

Hack Bounties
to test the security

Server -> Client

  • test server with Postman
  • fix react server err with adding err_msg keyword (SKIP_PREFLIGHT_CHECK) in .env file in client

*
Date.now : function reference
Date.now() : create Date object

*
require(folder) => exports ‘index.js’ file in the folder

*
req.params(id) -> findById(id) works
Because id is the primary key of the Schma, which works as Index

*
findByIdAndUpdate()
mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

Mongoose v5.11.17: API docs

mongoosejs.com

*
always put cors at the top, otherwise router will work without applying cors

*
import .vs. require
masteringjs.io/tutorials/node/import-vs-require

Import vs Require in Node.js
Now that Node.js has native support for ESM imports, should you use require() or import? Here’s what you need to know.
masteringjs.io
*
personalise Date type fomat
momentjs.com/

Moment.js | Home
Format Dates moment().format(‘MMMM Do YYYY, h:mm:ss a’); moment().format(‘dddd’); moment().format(“MMM Do YY”); moment().format(‘YYYY [escaped] YYYY’); moment().format(); Relative Time moment(“20111031”, “YYYYMMDD”).fromNow(); moment(“20120620”, “YYYYMMDD”
momentjs.com
[ Index ]

[ Router ]

[ Controller ]

[ Model ]

[ App ]

[ ApiService ]

[ TopicForm ]

[ TopicList ]

[ TopicItem ]

React Context

: pass through App -> Sidebar + ( Dashboard -> AddComment)

  1. Provider: Owner
  2. Consumer(s)
    • share the parent
    • a subtree of the provider
  • argument = null => inaccessible to the provider

  • value = {42} => give the value to the CurrentUserContext.Provider, give access

  • { value => } => give CurrentUserContext.Provider a Function

–> Modify

Hooks

  1. Classes
  2. Reuse stateful logic is hard
  3. Logic spread into lifecycle methods

Only call hooks at/from…

  • the top level
  • function components or custom hooks

Function Components

  • function name with ‘use’
  • useState()

setCounter(counter+1) => (update): counter = counter+1

  • useEffect()
  • useEffect without [] (initializing) => call setInterval exponentially (setInterval itself calls the function exponentially, it’s like ex*ex)
  • useContext()

React Component Lifecycle

  • Mounting
  • Updating
  • Unmounting: remove the component => without any re-rendering or updating

render -> mount -> (setState()) -> render -> update

The form tag

Controlled Components

export the parent element -> pass to the child data -> repeat … to the grandchild
LIKE A TREE

React

  • not framework (collection of libraries) => same as express(Angular)/ koa (React)
    • libary for creating interactive UIs
    • rendering engine -> need 3rd party lib
  • component-based
  • unopinionated
  • JSX template
  • every component receives props(transfer from parent to the child) and/or handle its own state(own obj handled by the component itself)

React Component (Class)

  • render()

return JSX template –> html element

inherit in the parent component

JSX

Props

name=”Sara” -> this.props.name (this ctx: MyComponent)
this.props => 해당 class를 부르는 child component attribute 전달 및 실행

App- Parent- Child

State

React Application

  • ReactDOM.render()

-> replace the normal DOM with virtual DOM (ReactDOM)

Conditional Rendering

Loop Rendering

{} : act as JavaScript

Events

flows data from parent to children
handleChange (e) {} === handleChange = (e) => {}
*** arrow function => solves a lot of problems because it gets rid of the ctx of passing argument but passes the function scope which called it to this context

Observable

angular.io/guide/observables
Angular
angular.io

RxJS

  • PULLING system
    producer
    consumer
  • PUSHING system
    producer: pushes the data to a consumer

www.youtube.com/watch?v=ei7FsoXKPl0

Singluar Plural
Synchronous Value Iterable
Asynchronous Promise Observable

  • linear vector time
  • seperated randomly (spreaded)
    e.g. User Interaction: key stroke like click button, create event
  • receives promises for multiple times
  • compatibility: consistancy, handled by observables

※ Everything is a Stream

Subscribe

  • observable$ => always with ‘$’

Operators

observable$.pipe(
operator(),

).subscribe(data => …)

  • pipe(): throwing every single element a time
  • operators are listed in order
  • filter(): Array.filter과 비슷
    filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
  • receiving bunch of events spreaded in time
  • not returning an array
  • true: pass / false: filtered out
  • map()
  • take the element and returns the conditioned element
  • scan()

As you can see from above code, similar to reduce function the scan function passes output of first function, as the input to the next function execution but the only difference being that, the result of each function execution is stored in an array and that array is returned as a result.

You can notice that, the last element of the resulting array is 15which was the output of reduce function.

  • subscribe(): final function that receives the information
  • make sure it returns anything, not error
  • next(): call the next function in the stream
  • expressJS
    Middleware functions are functions that have access to the request object(req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Starting with Express 5, middleware functions that return a Promise will call next(value) when they reject or throw an error. next will be called with either the rejected value or the thrown Error.

  • Angular (angular.io/guide/observables)
    Note that a next() function could receive, for instance, message strings, or event objects, numeric values, or structures, depending on context. As a general term, we refer to data published by an observable as a stream. Any type of value can be represented with an observable, and the values are published as a stream.
  • complete(): close the stream
  1. Cold Observable
    : only one subscription at one
    : receive last value in the stream
    : stream one direction, prepare data and spread them all at one together
    same info to all the users
  2. Hot Observable
    : can connect to the same stream the other one
    : multiple streamers
    can use former value after next function
  • debounceTime(k): wait for k(ms) after stopped typing and put arg in the stream

👀 Why do we need both ngOnInit() and constructor()?
The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like new MyClass(someArg);

ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component.

  • constructor: rendoring first
  • initialise mainly properties
  • have nothing which could stop executing
  • ngOnInit: happen after first rendor, fulfill others
  • triggering the function, asking for datas, populate them in the final

BEM (Block Element Modifier)

getbem.com/naming

Module

Container

take the logic

Data Binding

  • [(ngModel)] = “property” : binding input property with handling model

Typescript and Angular Decorators

Typescript Decorators

www.typescriptlang.org/docs/handbook/decorators.html
Documentation - Decorators
TypeScript Decorators overview
www.typescriptlang.org

  • meta programming changing target without modifying metadata (classes)
  • annotate or modify the target

labelling the target

@function: function decorator, decorator creater(factory)

  • return function (target) => put class into the target
  • return what you decorate (classDecorator -> return class info …)

…toppings: string[] –> toppings = [‘tomato’, ‘mozzarella’, ‘basil’]

memoize() : // _.memoize(func)

Memoizes a given function by caching the computed result.
Useful for speeding up slow-running computations.
You may assume that the memoized function takes only one argument and that it is a primitive.
Memoize should return a function that when called, will check if it has already computed the result for the given argument and return that value instead of recomputing it.

Object Properties

How to define a property?

ob.foo = ‘bar’; // direct
// Object.defineProperty(obj, ‘foo’, {value: ‘bar’}); //(ppt, ppt_name, object// describe the behaviour of the ppt //ppt_value)

Attribute name

  • Value (Any type) // actual value
    // default values of 3 boolean functions of defineProperty(): false // if we define obj with assigning it, then default == true !!!
  • Writable (Boolean) // whether the property value can be changed or not
  • Enumerable (Boolean) // makes it appear to be in loops (listed in ‘for-in’ enumeration)
    // 💥 Is Array enumerable?
  • Configurable (Boolean) // +Writable +Enumerable // whether we can delete the property or change any attribute apart from attr // configurable lets us change the writable property, writable lets us change the value property

Angular Decorators

Component

target: class MyComponent

Injectable

Input

@Input: input decorator => able to pass the value from parent template using the tag to the child component class

Output

@Output: output decorator => sen the info to the parent element
💥 Child’s view
input is meant to receive information from the parent element
output is meant to send info to the parent

Angular

TypeScript

www.typescriptlang.org/docs/handbook/intro.html

Handbook - The TypeScript Handbook
Your first step to learn TypeScript
www.typescriptlang.org

let [varName] : [varType] = [value];

  • enum : dictionary
  • function => need to specify the types of parameters
  • getting rid of any error of classes…
  • testing if we generate any error
  • typing faster

imraccoon-developer.tistory.com/11

TypeScript, 왜 써야되나?? (feat. 장단점)
JavaScript가 es6로 바뀌면서 큰 인기를 끌기 시작했습니다. 또한, Node.js로 할 수 있는 것들이 점점 많아졌으며, 지금도 많아지고 있습니다. 처음에는 웹에서 사용하기 위한 스크립트 언어로 활용되
imraccoon-developer.tistory.com

Angular Architecture

  • Modules
  • Components
  • Services

Modules

  • connected through Metadata
  • Component === View
  • Service: share functionality through entire app
  • dependency injector

@NgModule: function

  • bootstrap: starting point, start compiling
  • decorators: annotate data to give extra info to(of) the target

–> decorating: NgModule targeting AppModule

Components

  • A class meant to be as reusable (when applies) as possible

  • Defines application data and logic

  • Bound to a template, an HTML file

  • give users all the functionality of the app

  • create DOM and add components thus drawing a tree: [tree] template -> components (+ template) -> …

  • communicate with each other and give access of information to users

  • component = instance of a class, independent element but communicate with others as a class

  • render the DOM as a new node

  • shadow DOM to encapsulate the component, not affected by exeternal interventions
    Shadow DOM
    different DOM, OWN capsulated environment

polymer-library.polymer-project.org/2.0/docs/devguide/shadow-dom
Shadow DOM is a new DOM feature that helps you build components. You can think of shadow DOM as a scoped subtreeinside your element.

  • Root Component
  • contain everything
  • Root Template
  • Navigation Component: works itself, alone
  • Container Component: including other components
  • Filtering Component
  • receive the input data
  • render into different components (list, map)

e.g. Scenario
if like one of the list component item -> passed up to the container -> reflect that to the map component
filtering info in the filter component -> passed up to the container -> reflect that to the map component

Data Binding

when user gives the input, then DOM will communicate using property in [(ng-model)] = “property”

  • handler: function declared component

object => {}

  • 2 way binding: class component <-> template
  • selector: ‘movie-details’ –> director obj go in trhough selector

Services

  • private: TS property, can’t access it from other classes