Sunday, December 1, 2024

MAD2-Viva -preparations

 MAD2 Viva - Preparations: Tips, Resources, and Strategies

"A complete guide to acing your Modern Applications Development 2 Viva for IITM BS Degree."

"Preparing for the MAD2 Viva can feel overwhelming, but with the right strategies and resources, you can approach it with confidence. This post covers essential tips, key topics, and effective preparation techniques."

a. Preparation Checklist

  • Content Example:
    • ✅ Revise all assignments and projects
    • ✅ Understand Flask basics
    • ✅ Practice REST API concepts
    • ✅ Be ready to explain your project in detail
    • ✅ Prepare for common Viva questions

Key Topics to Focus On

  • Example:
    • Flask Basics: Understand routing, request handling, and templates.
    • SQLAlchemy: Be clear on models and relationships.
    • API Development: Know how REST APIs work and how you implemented them in your project.
    • Frontend Basics: Be ready to explain any Vue.js/HTML/CSS integration
What is a primary key?
A primary key is a fundamental concept in database design. It is a unique identifier for each record (row) in a database table.

Definition

A primary key is:

  1. Unique: No two rows in a table can have the same value for the primary key.
  2. Non-Nullable: The primary key field(s) must always have a value (i.e., it cannot contain NULL).
  3. Immutable: Ideally, the value of a primary key should not change once it is assigned to a record.

Purpose

  • To ensure uniqueness in the table.
  • To provide a way to reference records in relationships (e.g., foreign keys in other tables).
  • To allow for efficient indexing and searching.

Characteristics

  1. Single-Column or Composite:
    • A primary key can be a single column (e.g., id) or a combination of columns (composite key).
  2. Automatically Indexed:
    • Most database systems automatically create an index on the primary key for faster lookups.

Example in SQL

Single-Column Primary Key:

sql code

CREATE TABLE Users ( id INT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50) );
  • Here, id is the primary key, uniquely identifying each user.

Composite Primary Key:

sql code

CREATE TABLE Orders ( order_id INT, product_id INT, quantity INT, PRIMARY KEY (order_id, product_id) );
  • Here, the combination of order_id and product_id uniquely identifies each row.

Why Use a Primary Key?

  • Ensures data integrity by preventing duplicate rows.
  • Makes relationships between tables possible via foreign keys.
  • Improves query performance with indexing.

Primary Key vs Unique Key

  • Both enforce uniqueness, but a table can only have one primary key, while it can have multiple unique keys.
  • A primary key does not allow NULL values, but a unique key can allow null values.
Can we replace primary key with Not-Null and auto Increment?

No, you cannot fully replace a primary key with just NOT NULL and AUTO_INCREMENT  though they might achieve some overlapping functionality. Here’s why:

What NOT NULL and AUTO_INCREMENT Do

  1. NOT NULL:

    • Ensures that a column cannot have NULL values.
    • Does not guarantee uniqueness across rows.
  2. AUTO_INCREMENT :

    • Automatically generates sequential values for a column when new rows are inserted.
    • Often combined with NOT NULL to ensure no gaps or duplicates.
    • Does not enforce uniqueness by itself.

When NOT NULL + AUTO_INCREMENT Is Used Without Primary Key

You can use NOT NULL and AUTO_INCREMENT alone if:

  • You don’t need to enforce uniqueness across rows.
  • You’re not creating relationships between tables.
  • Example: You want to track insert order but don’t require the column to be the unique identifier.

Example:

sqlcode

CREATE TABLE ExampleTable ( order_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(50) );
  • Here, order_id will increment automatically but is not a primary key. Duplicates are possible if no PRIMARY KEY or UNIQUE constraint is applied.

Best Practice

  • Always use a primary key to ensure uniqueness and proper indexing if the column is meant to uniquely identify rows.
  • If the column should auto-generate values, you can combine AUTO_INCREMENT or SERIAL with the PRIMARY KEY constraint.

Example:

sqlcode

CREATE TABLE Users ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL );
  • Here:
    • id is NOT NULL and AUTO_INCREMENT to generate sequential values.
    • PRIMARY KEY ensures uniqueness and allows relationships with other tables.

Key Takeaway

  • NOT NULL + AUTO_INCREMENT ≠ PRIMARY KEY.
  • To fully replicate a primary key’s functionality (uniqueness, indexing, referential integrity), you must explicitly define it or use a UNIQUE constraint along with NOT NULL and AUTO_INCREMENT.
2.Where did you use the Flask Security?
In your  Application , Flask Security is typically used to manage authentication, authorization, and role-based access control, user management.

In your Application , Flask Security likely facilitates:

  1. Authentication for login/logout functionality.
  2. Role Management for admins, professionals, and customers.
  3. Password Hashing for secure user registration and management.
  4. Route Protection using @roles_required, @login_required, and @auth_required.

How to Identify Where It’s Used

To pinpoint exactly where Flask Security is used in your app:

  1. Look for imports like
    from flask_security import Security, roles_required, auth_required, login_required
  2. Check your user model:
    • Ensure it includes Role and UserRoles tables if Flask Security's role-based features are used.
  3. Inspect routes with decorators like @roles_required or @login_required.
  4. Configuration Settings 
SECURITY_JOIN_USER_ROLES = True
    SECURITY_PASSWORD_SALT = "thisissaltt"#salt for hashing passwords
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    WTF_CSRF_ENABLED = False
    CORS_HEADERS ='Content-Type',
    SECURITY_TOKEN_AUTHENTICATION_HEADER = 'Authentication-Token'

Flask Security Implemented by following ways

user authentication,role management,password hashing,session security

1. User Authentication-verification of the user is allowed to access the resources,

where all the routes required user login

Flask Security provides an easy way to handle user login/logout and password management.
You likely used it to:

  • Allow users and admins to log in securely.
  • Provide session management . 

2. Role Management

Since your application includes multiple roles (Admin,users), Flask Security is likely used to manage access control for these roles:  
  • @roles_required to enforce role-based access on certain routes.
  • Role definitions within your SQLAlchemy models
  • 3. Password Hashing and Security

    Flask Security includes built-in password hashing using libraries like werkzeug to secure user passwords in the database

    Use Case in Your App:

    • User registration (/register routes) would hash passwords before saving them to the database.
    • Password reset functionality (if implemented) to securely manage forgotten passwords.

    4. Route Protection

    Flask Security provides decorators like:

    • @login_required: Ensures only logged-in users can access specific routes.
    • @roles_required: Restricts access to users with specific roles.
    • @auth_required: Checks for authentication tokens in APIs.

    You may have used these to restrict access to routes:

    • Protect the admin dashboard with @roles_required('admin').

    5. Token-Based Authentication (Optional for API)

    If your application includes an API, Flask Security could have been used to:

    • Issue authentication tokens for API requests.
    • Use @auth_required to validate tokens.
    An authentication token is a digital credential used to verify the identity of a user or application when accessing a resource, such as a web application or API.
     Authorisation?
  • Authentication: Verifying that a user is logged in or not(verification of user)
  • authentication confirms "who you are,"
  • Authorization: Determining whether verified user  can  do
  • authorization decides "what you are allowed to do."

  • Is Admin authorised or authenticated?
    In Context of an Admin

    Both Authenticated and Authorized:

    • This is the case for an admin. They are first authenticated (logged in) and then authorized (granted access to admin-only actions)
    Authorized but Not Authenticated------invalid
    Template inheritance?

     Flask that allows you to create a base  template with common elements (header, footer)
     and then extend it in other templates. This approach promotes code reuse and consistent design
    what is virtualDOM?
    The Virtual DOM (VDOM) is a lightweight, in-memory representation of the real DOM (Document Object Model). It is used by modern JavaScript frameworks like React and Vue.js to improve performance by minimizing direct manipulation of the real DOM.

    What is the DOM?

    The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a webpage as a tree of objects that can be manipulated with programming languages like JavaScript.

    When a web page is loaded in a browser:

    1. The browser parses the HTML and CSS.
    2. It creates a DOM that represents the page’s structure and content.

    How to implement search functionality by username?
  • Backend: Add a search endpoint using SQLAlchemy to query by username.
  • Frontend: Build a Vue form with search input and a button to fetch results.
  • Database: Query the database for  username field 

    @app.route('/api/search',methods=['GET'])
    def search():
        query = args.get.query('username',' ')
        if not query:
            return josinify({"message":"query is username required"}),400
       users = User.query.filter(User.username.ilike(f'%{query}%')).all
       results = [{'id': user.id, 'username': user.username, 'email': user.email} for user in users]
       return   jsonify(results)
     
    Key Points:
    • request.args.get('username'): Retrieves the username parameter from the query string.

    • ilike: Case-insensitive matching using SQL's LIKE keyword.
    • %{query}%: Enables partial matching (finds usernames containing the search query).

      2. Frontend: Vue.js Implementation

      Create a search input and display results dynamically.

      Search Component:

    • <template>
    •   <div>
    •     <!-- Search Input -->
    •     <form class="d-flex" role="search">
    •       <input
    •         type="text"
    •         class="form-control me-2"
    •         v-model="searchQuery"
    •         placeholder="Search by username"
    •         aria-label="Search"
    •         style="width: 400px;"
    •       />
    •       <button
    •         type="button"
    •         class="btn btn-outline-primary"
    •         @click="searchUsers"
    •       >
    •         Search
    •       </button>
    •     </form>

    •     <!-- Results -->
    •     <ul v-if="results.length > 0">
    •       <li v-for="user in results" :key="user.id">
    •         {{ user.username }} - {{ user.email }}
    •       </li>
    •     </ul>
    •     <p v-else-if="searched">No users found.</p>
    •   </div>
    • </template>

    • <script>
    • export default {
    •   data() {
    •     return {
    •       searchQuery: '', // Input value
    •       results: [], // Search results
    •       searched: false // Flag to show "No users found" message
    •     };
    •   },
    •   methods: {
    •     async searchUsers() {
    •       try {
    •         const response = await fetch(
    •           `/search?username=${encodeURIComponent(this.searchQuery)}`
    •         );
    •         if (!response.ok) throw new Error('Failed to fetch');
    •         const data = await response.json();
    •         this.results = data;
    •         this.searched = true; // Mark as searched to show no-results message if applicable
    •       } catch (error) {
    •         console.error('Error searching users:', error);
    •       }
    •     }
    •   }
    • };
    • </script>


  • No comments:

    Post a Comment

    Mangerial Economics Quiz1 solutions Guide

    Mangerial Economics Quiz1 solutions Guide  solutions watch on you tube channel