Saturday, November 9, 2019

Sự khác nhau giữa cookie, session, localStorage và sessionStorage

 

I. Tóm tắt:

  1. Cookie:

    1.  Cookie chỉ được lưu trữ dưới dạng string
    2. Nó được lưu ở client side
    3. Kích thước của mỗi cookie là 40, và bị giới hạn số cookie sử dụng là 20
    4. Cookies có thể dissable.
    5. Nó không an toàn bảo mật.
    6. Có 2 loại cookie: liên tục và không liên tục.

        2.   Session

    1. Session có thể lưu bất kỳ dữ liệu nào bởi vì values của chúng là object
    2. Nó được lưu ở server side
    3. Nó được xem bảo mật an toàn vì nó được lưu với file dưới mã hóa nhị phân và có thể giải mã ở sever
    4. Không giới hạn quy mô và số session trong một ứng dụng
    5. Chúng ta không thể disable session và cũng có thể sử dụng session mà không có cookie
    6. Nhược điểm của chúng là nếu ta sử dụng quá nhiều session hay dung lượng lớn nó sẽ gây cho server "nặng"
    7. Session có thể không liên tục và có giới hạn thời gian  

       3.Cache:

    1. Cache thường dùng để lưu video,hình ảnh, web thành các bit vào ổ cứng máy tính.


II. Tìm hiểu chi tiết:

   1. Session:

    - Đúng như tên gọi của nó, session là dùng để lưu trữ thông tin phiên làm việc. Nói cách khác, cách giao tiếp giữa client to server.
   Session bắt đầu khi nào ?
  - Nó bắt đầu khi client send request tới server, nó tồn tại xuyên suốt từ trang này đến trang khi.
  - Nó chỉ mất đi khi hết thời gian timeout, hoặc close application.
  -  Mỗi session đều có định danh là SES-SIONID. Vậy để hiểu nhau thì nó sẽ tạo ra cookie lưu ở browser và session id tương ứng sẽ được lưu ở server.
  - Giá trị của session thì được lưu trong một tệp tin trong máy chủ server.
  - Giá trị thường lưu vào session là: thông tin đăng nhập, giỏ hàng,...

 2. Cookie:

 - Cũng giống như session, nó dùng để lưu thông tin tạm thời.
 - Tệp tin cookie được tạo ra ở server và sent xuống browser và được lưu trữ ở browser.
 - Khi access vào application thì nó sẽ send cookie tới server để cập nhật hoạt động trước đó.
 - Chú ý là không được bao giờ lưu thông tin quan trọng vào cookie, vì nó dễ dang chỉ sửa và có nguy hiểm hơn là dựa vào đó attack application của mình.
- Giá trị thường lưu là: thao tác người dùng, tần suất ghé thăm, thời gian truy cập, token để authentication... Tất cả thông tin được lưu mang tính tạm thời và được lưu trong 1 khoảng thời gian ngắn.
- Nó sẽ được giữ và không bị mất khi đóng browser, ngoài trừ khi set "expiress: N/A". Mặt khác, chúng ta có thể sex expiress đế nó từ xóa khi hết timeout.
- Note:
+ Limited size: 4Kb.
+ Thường cho phép lưu authenticate expiress: 3-4 months, cho phép lưu trữ thông tin để khi cần dăng nhập cho các lần sau.
+ Nếu cookie dùng để set authenticate thì nên set httpOnly: true. Nghĩa là không cho phép đọc cookie từ js nên tránh được script.
+ Tuyệt đối cấm lưu password chưa được mã hóa mà nên dùng token-based authentication.

3. Cache:

 -  Đây là bộ nhớ đệm, được lưu trữ tạm thời trong máy tính.
 - Giá trị thường lưu là: tài liệu web, hình ảnh, video, html,... để giảm tải băng thông, tăng tốc độ load, truy cập vào web.
 - Bộ nhớ cache nó sẽ tải các bản sao các bit của web và lưu vào ổ cứng nên khi truy cập vào nó chỉ việc tải các bit có sẵn ở máy.

4.localStorage:

 - Nó như một table excell trong browser, chỉ có 2 trường: key và values.
 - Nó lưu ở browser cho đến khi nào chính tay chúng ta xóa đi.
 - Giá trị thường lưu là: ngôn ngữ, theme, danh mục sản phẩm, giao diện dashboard, layout, ...

5. SessionStorage:

 -  Gần giống với session storage
 - Nó sẽ mất đi khi chúng ta close tab, close browser,..
 - Nó dễ dàng được đọc bởi js, nên dễ dàng bị đánh cắp bằng cross-site scriting (XSS).
 - Tuyệt đối nghiêm cấm lưu thông tin nhạy cảm: username, password, tokenID, email người dùng cho cả localStorage và sessionStorage.
- Note: sessionStorage và localStorage nếu  sử dụng nhiều nó không ảnh hưởng đến hiệu suất của web nhưng 1 phần làm trình duyệt nặng thêm.
+ Khi 1 browser mà mở 2 tab trở lên thì sessionStorage không truy xuất thông tin được cho nhau, còn localStorage thì ngược lại.
+ Chỉ được lưu ở trình duyệt chứ không gởi được lên server, nó ngược với cookie.
+ Bù lại dung lượng lưu trữ sẽ cao hơn rất nhiều so với cookie








Wednesday, September 18, 2019

How to build a REST API in laravel 5.7

  1. Prerequisites:

    1. A basic knowledge of Laravel
    2. A basic knowledge of Rest APIs
    3. Have the laravel installer installed on your computer
     
  2.  What we'll be building:
    • The purpose of this demonstration, we'll be building a camera reviews API.
    • Users will be able to add create camera, update camera and delete camera.
    • Users will also be able to view a list all cameras and relationship in camera.
    • Finally, we'll add authentication with JSON Web Tokens( JWT) to make the API secured.
  3. Create a new Laravel app
  •  Via laravel installer 
                 Download the laravel installer using composer
             composer global require laravel/installer
  • Via Composer create project
          composer create-project --prefer-dist laravel/laravel api.camera
  • Local development server
      php artisan serve 
    
4.Create models and migrations
     A camera reviewers API will have 3 three models:
users,camera setting types, camera command types, camera settings. (camera category has many camera modems.)
We'll start by creating the camera category both controller and model:
> php artisan make:controller CameraCategoriesController --resource --model=CameraCategory
We'll do the same for the camera modem:
 > php artisan make:controller CameraModemsController --resource --model=CameraModem
  • Next, let's open the migration file generated for the camera category migrate and camera modem migrate. Update the up() method as below:
    public function up()
    {
        Schema::create('camera_categories', function (Blueprint $table){
          $table->increments('id');      $table->string('type_name');      $table->string('description');      $table->boolean('is_deleted')->default(0);      $table->boolean('is_published')->default(1);
        });}

public function up()
{
    Schema::create('camera_modems', function (Blueprint $table){
      $table->increments('id');      $table->string('modem_name');      $table->text('description')->nullable();      $table->text('MJPEG_stream_source')->nullable();      $table->text('H264_stream_source')->nullable();      $table->text('snapshot_source')->nullable();      $table->unsignedInteger('setting_type_id')->nullable();      $table->unsignedInteger('camera_category_id');      $table->foreign('camera_category_id')->references('id')
            ->on('camera_categories')->onDelete('cascade');    });}
public function down()
{
    Schema::dropIfExists('camera_modems',function (Blueprint $table) {
        $table->dropForeign('camera_category_id');    });}

we definne the fields for the camera modems table which are an auto increment ID.
Run the command below to run the migrations
> php artisan migrate

Remember to enter your database details in the .env file before running the command ablove.

Define relationships between models:
  • A user can management many camera categories, but a camera categories can only belong to one user. So, the relationship between the User model and camera categories modem is one-to-many relationship.
//app/Http/Models/Users.php
public function camera_categories(){
    return $this->hasMany(CameraCategory::class);
}  
    •       Next, let's define the inverse relation on the camera category model:

public function user(){
    return $this->belongTo(User::class);} 
 Likewise, a category can be have many camera modems. This is also a one-to-many relationship.Add the code below in the category model:

public function cameraModems(){
    return $this->hasMany(CameraModem::class);}
Then we define the inverse relationship inside the camera modem model:
 //app/Http/Models/CameraModem.php
public function cameraCategory()
{
    return $this->belongsTo(CameraCategory::class, 'camera_category_id');} 

4.Allowing mass assignment on some fields

 


               
 
 

Sunday, January 13, 2019

Clear cache in laravel

  1. There are some command line clear cache in laravel as:
  •  Clear application cache: php artisan cache:clear

  • Clear route cache: php artisan route:clear

  • Clear config cache: php artisan config:cache

  • Clear complied view files: php artisan view:cache
 - If you don't know how to use specific artisan command, you just need add "help".
Ex: php artisan help view:clear
  • In addition, we have some other command line : 
              - If you want to clearling all session data in laravel, you tried this:
php artisan cache:clear
 or   
type: php artisan tinker > Session::flush().
Some times, you use guide to flushing all sessions:  php artisan key:generate

(If you know some other commands,please let me know by commenting below.Thank you for reading.)