Home / MAD2 / Week 8 / Real questions
60 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
. Which of the following best explains the relationship between the header and the signature in JWT authentication?``` header.payload.signature ```

```javascript const numbers = [10, 20, 30, 40, 50]; const [num1, , num2, ...rest] = numbers; const [a = 100, b = 200] = [undefined, 0]; console.log(num1, num2, rest); console.log(a, b); ```
A client first accesses
and then tries to access
. Which of the following statements are correct?```python
from flask import Flask, jsonify
from flask_jwt_extended import JWTManager, create_access_token, \
jwt_required
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "secret"
jwt = JWTManager(app)
@app.route("/token")
def token():
access_token = create_access_token(identity="Ravi")
return jsonify(access_token=access_token)
@app.route("/dashboard")
@jwt_required()
def dashboard():
return jsonify(message="Dashboard Access Granted")
```
/token
/dashboard
can only be accessed if a valid JWT token is sent with the request./dashboard
header while accessing protected routes.Authorization
is automatically stored by Flask and reused for future requests./token
Which of the following statements are correct? (Select all that apply)```python
app.config["JWT_SECRET_KEY"] = "my-secret"
jwt = JWTManager(app)
@jwt.user_identity_loader
def load(user):
return user.username
@jwt.user_lookup_loader
def user_lookup(_jwt_header, jwt_data):
identity = jwt_data["sub"]
return User.query.filter_by(username=identity).one_or_none()
@app.route('/login', methods=["POST"])
def login():
user = User.query.filter_by(username="u1").one_or_none()
token = create_access_token(identity=user)
return {"access_token": token}
@app.route('/dashboard')
@jwt_required()
def dashboard():
return {
"username": current_user.username
}
```
decorator ensures that only requests with a valid JWT can access
.``` @jwt_required() ``` /dashboard
determines what value is stored in the "sub" field of the JWT.``` user_identity_loader ```
is removed,
will not be automatically populated.``` user_lookup_loader ``` current_user
directly stores the entire user object inside the JWT.```python create_access_token(identity=user) ```
will still execute but
will be None./dashboard current_user
object is reconstructed using the identity extracted from the JWT.current_user
Which of the following statements correctly describes what happens in Tab 2?```javascript
// Executed in Tab 1
localStorage.setItem("theme", "dark");
sessionStorage.setItem("cart", "3-items");
```
and
return their respective values.```javascript
localStorage.getItem("theme")
```
```javascript
sessionStorage.getItem("cart")
```
returns "dark", but
returns null.```javascript
localStorage.getItem("theme")
```
```javascript
sessionStorage.getItem("cart")
```
returns "3-items", but
returns null.```javascript
sessionStorage.getItem("cart")
```
```javascript
localStorage.getItem("theme")
```
header.``` Authorization: Bearer <token> ```
can read the identity stored in the token.``` get_jwt_identity() ```
.In authentication using Flask-JWT-Extended, what does the payload part of the JWT stores?``` "header.payload.signature" ```
What will be the output of the above program?```javascript
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
const { firstName, city, ...rest } = person;
const newPerson = { firstName, location: city, ...rest };
console.log(firstName);
console.log(rest);
console.log(newPerson);
```
```
John
{ city: 'New York', lastName: 'Doe', age: 30 }
{ firstName: 'John', location: 'New York', city: 'New York', lastName:
'Doe', age: 30 }
```
```
John
{ 'lastName': 'Doe', 'age': 30 }
{ 'firstName': 'John', 'location': 'New York', 'lastName': 'Doe', 'age': 30 }
```
```
John
{ 'lastName': 'Doe', 'age': 30 }
{ 'firstName': 'John', 'location': 'New York', 'city': 'New York', 'lastName':
'Doe', 'age': 30 }
```
```
undefined
{ firstName: 'John', city: 'New York', lastName: 'Doe', age: 30 }
{ firstName: 'John', location: 'New York' }
```
Three requests are made to this application: GET /api/open (no authentication headers)1. GET /api/secure (no authentication headers)2. GET /api/superuser with valid authentication token but user has role 'basic' (not 'superuser')3. What will be the response status codes for these requests, respectively?```python
@app.route('/api/open')
def open_endpoint():
return jsonify({'message': 'Open access', 'status': 'success'})
@app.route('/api/secure')
@auth_required('token')
def secure_endpoint():
return jsonify({'message': 'Secure access', 'status': 'authenticated'})
@app.route('/api/superuser')
@auth_required('token')
@roles_required('superuser')
def superuser_endpoint():
return jsonify({'message': 'Superuser access', 'status': 'authorized'})
```
You are developing an analytics platform using Flask and Flask-JWT-Extended. A user sends a POST request to
with:
. Then tries to access
. Which of the following statements are correct?```python
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, \
jwt_required, get_jwt_identity
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "secret"
jwt = JWTManager(app)
@app.route("/login", methods=["POST"])
def login():
username = request.json.get("username")
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
@app.route("/stats")
@jwt_required()
def stats():
current_user = get_jwt_identity()
return jsonify(message=f"Welcome {current_user}")
```
/login
```json
{ "username": "Jassi" }
```
/stats
route will return "Welcome Jassi" only if a valid JWT token is sent in the Authorization header/stats
will result in an unauthorized error/stats

/stats
Backend: app.py

```javascript
methods: {
async login() {
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: this.email, password: this.password })
});
const data = await response.json();
console.log(data.message);
}
}
```
```python
@app.route('/login', methods=['POST'])
def login():
email = request.json['email']
password = request.json['password']
query = f"SELECT * FROM users WHERE email = '{email}'" \
f" AND password = '{password}'"
result = db.execute(query)
if result:
return jsonify({"message": "Login successful"})
return jsonify({"message": "Invalid credentials"})
```
Which of the following options correctly matches Concept / Issue and Description?| Concept / Issue | Description | |---|---| | A. "Chatty" nature of REST APIs | 1. Static HTML is enhanced with event handlers after initial page load | | B. Limitation of REST as a query mechanism | 2. May require multiple API calls to fetch data for a single view | | C. JavaScript Hydration | 3. Focuses on decoupling storage, logic, and presentation using APIs | | D. JAMStack approach | 4. Does not allow clients to specify exactly what data is required in one request |
Which of the following statements is/are CORRECT about this implementation?```javascript
mounted() {
const storedToken = localStorage.getItem('userToken');
if (storedToken) {
this.validateToken(storedToken)
.then(user => {
this.user = user;
this.isAuthenticated = true;
})
.catch(err => {
localStorage.removeItem('userToken');
this.isAuthenticated = false;
});
}
}
```
Which of the following is the correct matching?| Storage Type | Characteristic | | :---------------- | :-------------------------------------------------------------------------------- | | 1. Session Storage | A. Data automatically encrypts itself without developer intervention. | | 2. Token Storage | B. Data persists only until the browser/tab is closed. | | 3. Cookie Storage | C. Often used to store authentication tokens securely on the client side. | | | D. Data persists across sessions, typically stored on the client and sent with every HTTP request. |

```python
response.set_cookie('session_id', 'abc123', secure=option1,
samesite=option2)
```
Promise rejects automatically

Promise resolves and `response.ok = true`

Promise resolves and `response.ok = false`

Promise stays as pending

Code:
```javascript
const setTheme = (theme) => {
localStorage.setItem('theme', theme);
console.log('Theme set to:', theme);
};
const getTheme = () => {
return localStorage.getItem('theme') || 'light';
};
setTheme('dark');
console.log(getTheme());
```
```javascript
const saveToken = (token) => {
sessionStorage.setItem('authToken', token);
};
const getToken = () => {
return sessionStorage.getItem('authToken') || null;
};
```
Consider the following JavaScript code running in a browser:
```javascript
localStorage.setItem('score', '10');
sessionStorage.setItem('multiplier', '3');
for (let i = 0; i < 2; i++) {
let score = localStorage.getItem('score');
let multiplier = sessionStorage.getItem('multiplier');
score = score + 5;
multiplier = multiplier * 2;
localStorage.setItem('score', score);
sessionStorage.setItem('multiplier', multiplier);
}
console.log(localStorage.getItem('score'));
console.log(sessionStorage.getItem('multiplier'));
```
What will be the output in the browser console?
20 12

20 NaN

NaN 12

None of these

Given the Flask app:
```python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})
@app.route('/api/data')
def data():
return {"msg": "Success"}
```
frontend code:
```javascript
fetch("http://localhost:5000/api/data")
.then(res => res.json())
.then(data => console.log(data));
```
What will happen when run from a Vue app hosted at http://localhost:5173?
The `localStorage` object stores data with no expiration date, even after the browser is closed.

The `sessionStorage` object keeps data only for the duration of the page session.

Both `localStorage` and `sessionStorage` can store data in key-value pair format.

Data stored in `sessionStorage` is available across different browser tabs.

Consider the below CORS enabled flask app.
```python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:5000"}})
@app.route("/api/data")
def data():
return {"message": "Hello from Flask"}
```
If a Vue.js frontend (simulation given below) at "http://localhost:3000" tries to fetch data, what will happen?
```javascript
fetch("http://localhost:5000/api/data")
.then(response => response.json())
.then(data => console.log(data));
```
Consider the below flask implementation with JWT based authentication.
```python
from flask import Flask, request, jsonify
import jwt
import datetime
app = Flask(__name__)
SECRET_KEY = "supersecret"
def generate_token(user):
return jwt.encode(
{"user": user, "exp": datetime.datetime.utcnow() +
datetime.timedelta(seconds=10)},
SECRET_KEY,
algorithm="HS256"
)
@app.route("/login", methods=["POST"])
def login():
user = request.json.get("user")
token = generate_token(user)
return jsonify({"token": token})
@app.route("/protected", methods=["GET"])
def protected():
token = request.headers.get("Authorization").split(" ")[1]
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
return jsonify({"message": f"Hello {payload['user']}!"})
except jwt.ExpiredSignatureError:
return jsonify({"error": "Token expired"}), 401
except jwt.InvalidTokenError:
return jsonify({"error": "Invalid token"}), 403
```
If a Vue.js client sends this request 15 seconds after login, what response will it receive
(assume the token sent is the one, which was received from login)?
```javascript
fetch("http://localhost:5000/protected", {
method: "GET",
headers: { "Authorization": "Bearer <JWT_TOKEN>" }
})
.then(res => res.json())
.then(console.log);
```
```json
{ "message": "Hello user!" }
```
```json
{ "error": "Token expired" }
```
```json
{
"error": "Invalid token"
}
```
```json
{
"message": "Access granted"
}
```

What will be the response
by the following fetch
request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET"
})
.then(response => {
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.


What will be the result of the following fetch request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET",
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.."
}
})
.then(response => {
if (response.status === 403) {
throw new Error("403 Forbidden: Insufficient permissions");
}
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
What will be rendered on the browser for the given value of localStorage?
```
{
token: 112,
userRole: "manager"
}
```
Consider the following JavaScript code.
```javascript
export default {
data() {
return {
loginToken: '',
};
},
mounted() {
this.loginToken = sessionStorage.getItem('authToken') || '';
},
methods: {
updateToken(newToken) {
this.loginToken = newToken;
sessionStorage.setItem('authToken', newToken);
}
}
};
```
What will happen when a user calls the updateToken method with a new value and then refreshes the page?
The new token will be lost, and the "loginToken" data property will be reset to an empty string.

The new token will be preserved in session storage, and the "LoginToken" data property will be populated with the stored value on page refresh.

The method will throw an error because sessionStorage cannot be modified directly.

The "loginToken" data property will be updated, but the session storage will remain unchanged.

Consider the below flask SSE implementation.
```python
from flask import Flask, Response
import time
app = Flask(__name__)
def event_stream():
for i in range(5):
yield f"data: Message {i}"
time.sleep(1)
@app.route('/events')
def sse():
return Response(event_stream(), mimetype="text/event-stream")
```
And the Vue.js frontend:
```html
<template>
<div>
<p v-for="msg in messages" :key="msg">{{ msg }}</p>
</div>
</template>
<script>
export default {
data() {
return { messages: [] };
},
mounted() {
const eventSource = new EventSource("http://localhost:5000/events");
eventSource.onmessage = (event) => {
this.messages.push(event.data);
};
},
};
</script>
```
What will happen when a user opens this page?

Which of the following statements
is correct for the following fetch
request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET"
})
.then(response => {
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
What will be rendered on the browser for the given value of localStorage?
```json
{
"token": 112,
"userRole": "admin"
}
```
Consider the below javascript program.
```javascript
const obj = { a: 1, b: 2 };
const { a, ...rest } = obj;
console.log(a, rest);
```
What will be the output of the above program?
Consider the below Vue.js application.
```html
<template>
<div>
<button @click="goToPage('Home')">Go to Home</button>
<button @click="goToPage('About')">Go to About</button>
<button @click="goToPage('Contact')">Go to Contact</button>
<div v-if="visitedPages.length">
<h3>Visited Pages:</h3>
<ul>
<li v-for="(page, index) in visitedPages" :key="index">{{ page }}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
visitedPages: []
};
},
mounted() {
const storedPages = JSON.parse(sessionStorage.getItem('visitedPages')) || [];
this.visitedPages = storedPages;
},
methods: {
goToPage(page) {
this.visitedPages.push(page);
sessionStorage.setItem('visitedPages',
JSON.stringify(this.visitedPages));
this.$router.push(`/${page.toLowerCase()}`);
}
}
};
</script>
```
In the following code, which attributes ensure that the cookie will only be sent over HTTPS and restrict it from cross-site requests?
```
response.set_cookie('session_id', 'abc123', secure=option1, samesite=option2)
```
Suppose you want the user data to only be accessible by an authenticated user.
What security issue exists in this code?
// Javascript
```javascript
methods: {
async fetchUserData() {
const response = await fetch(`/api/user/${this.userId}`)
const data = await response.json()
this.userData = data
}
}
```
# Flask route
```python
@app.route('/api/user/<user_id>')
def get_user(user_id):
query = f"SELECT * FROM users WHERE id = {user_id}"
result = db.execute(query)
return jsonify(result)
```
Consider the following HTML, which includes Vue 2 and Vuex CDN links.
```html
<div id="app">
<p v-if="userData">User: {{ userData.name }}</p>
<p v-else>No user data available</p>
</div>
<script>
const store = new Vuex.Store({
state: {
userData: null
},
mutations: {
setUserData(state, data) {
state.userData = data;
}
},
actions: {
fetchUserData({ commit }) {
return fetch('https://httpstat.us/500')
.then(response => {
if (!response.ok) throw new Error('Network error');
return response.json();
})
.then(data => {
commit('setUserData', data);
},
error => {
commit('setUserData', { name: 'Luke' })
})
.catch(() => {
commit('setUserData', null);
});
}
}
});
new Vue({
el: '#app',
store,
created() {
this.$store.dispatch('fetchUserData');
},
computed: {
userData() {
return this.$store.state.userData;
}
}
});
</script>
```
What will be rendered on the browser, if the fetch request gets back 500 status code?
Consider the below Vue component.
```javascript
export default {
data() {
return {
userName: '',
};
},
mounted() {
this.userName = sessionStorage.getItem('userName') || '';
},
watch: {
userName(newVal) {
sessionStorage.setItem('userName', newVal);
}
}
};
```
What will happen when the user enters a new value for "userName" and refreshes the page?
Consider the below Vuex implementation.
```javascript
const store = new Vuex.Store({
state: {
token: sessionStorage.getItem('authToken') || null
},
mutations: {
setToken(state, token) {
state.token = token;
sessionStorage.setItem('authToken', token);
},
clearToken(state) {
state.token = null;
sessionStorage.removeItem('authToken');
}
},
actions: {
login({ commit }, token) {
commit('setToken', token);
},
logout({ commit }) {
commit('clearToken');
}
}
});
```
After the user logs in with a token and refreshes the page, what will happen to the Vuex state and the session storage?
Consider the following JavaScript code snippet.
```javascript
// Code Snippet 1
sessionStorage.setItem('username', 'course_user');
let storedUsername = sessionStorage.getItem('username');
// Code Snippet 2
sessionStorage.removeItem('username');
let removedUsername = sessionStorage.getItem('username');
// Code Snippet 3
sessionStorage.clear();
let clearedStorage = sessionStorage.username;
```
What will be the values of 'storedUsername', 'removedUsername', and 'clearedStorage' after the execution of the above code snippets?