-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
279 lines (248 loc) · 9.76 KB
/
api_server.py
File metadata and controls
279 lines (248 loc) · 9.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python3
"""
SQLite-powered Mock API Server for DOE Hardware Integration
Serves Intune and DeviceHub APIs from SQLite database
"""
from flask import Flask, request, jsonify
import sqlite3
import json
import uuid
from datetime import datetime
app = Flask(__name__)
# Database configuration
DB_FILE = "doe_devices.db"
def get_db_connection():
"""Get SQLite database connection"""
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row # Return rows as dictionaries
return conn
def format_intune_device(row):
"""Convert database row to Intune API format"""
return {
"id": row['id'],
"userId": str(uuid.uuid4()),
"deviceName": row['device_name'],
"ownerType": "company",
"managedDeviceOwnerType": "company",
"managementState": row['management_state'],
"enrolledDateTime": row['enrolled_date_time'],
"lastSyncDateTime": row['last_sync_date_time'],
"complianceState": row['compliance_state'],
"jailBroken": "Unknown",
"managementAgent": "mdm",
"osVersion": row['os_version'],
"easActivated": True,
"easDeviceId": str(uuid.uuid4()),
"easActivationDateTime": row['enrolled_date_time'],
"aadRegistered": True,
"azureADRegistered": True,
"deviceEnrollmentType": "windowsAzureADJoin",
"lostModeState": "disabled",
"activationLockBypassCode": None,
"emailAddress": row['user_principal_name'],
"azureActiveDirectoryDeviceId": str(uuid.uuid4()),
"azureADDeviceId": str(uuid.uuid4()),
"deviceRegistrationState": "registered",
"deviceCategoryDisplayName": row['device_category'],
"isSupervised": False,
"exchangeLastSuccessfulSyncDateTime": row['last_sync_date_time'],
"exchangeAccessState": "allowed",
"exchangeAccessStateReason": "none",
"remoteAssistanceSessionUrl": None,
"remoteAssistanceSessionErrorDetails": None,
"isEncrypted": True,
"userPrincipalName": row['user_principal_name'],
"model": row['model'],
"manufacturer": row['manufacturer'],
"imei": None,
"complianceGracePeriodExpirationDateTime": "2025-10-09T18:44:38.127Z",
"serialNumber": row['serial_number'],
"phoneNumber": None,
"androidSecurityPatchLevel": None,
"userDisplayName": "NYC DOE User",
"configurationManagerClientEnabledFeatures": None,
"wiFiMacAddress": row['wifi_mac_address'],
"deviceHealthAttestationState": None,
"subscriberCarrier": None,
"meid": None,
"totalStorageSpaceInBytes": row['total_storage_bytes'],
"freeStorageSpaceInBytes": int(row['total_storage_bytes'] * 0.6), # Mock free space
"managedDeviceName": row['device_name'],
"partnerReportedThreatState": "activated",
"retireAfterDateTime": "2028-09-08T18:44:38.127Z",
"usersLoggedOn": [],
"preferMdmOverGroupPolicyAppliedDateTime": row['enrolled_date_time'],
"autopilotEnrolled": True,
"requireUserEnrollmentApproval": False,
"managementCertificateExpirationDate": "2026-09-09T18:44:38.127Z",
"iccid": None,
"udid": None,
"roleScopeTagIds": ["0"],
"windowsActiveMalwareCount": 0,
"windowsRemediatedMalwareCount": 0,
"notes": row['notes'],
"configurationManagerClientHealthState": None,
"configurationManagerClientInformation": None,
"ethernetMacAddress": row['wifi_mac_address'].replace(':', '').upper(),
"physicalMemoryInBytes": row['physical_memory_bytes'],
"processorArchitecture": "x64",
"specificationVersion": None,
"joinType": "azureADJoined",
"skuFamily": None,
"skuNumber": None,
"managementFeatures": "none",
"chromeOSDeviceInfo": [{
"annotatedAssetId": row['serial_number'].replace('NYC-SN', 'NYC-AT'),
"annotatedLocation": "NYC Department of Education",
"annotatedUser": row['user_principal_name'],
"lastSyncDateTime": row['last_sync_date_time'],
"supportEndDateTime": "2029-09-03T00:00:00.000Z"
}],
"operatingSystem": row['operating_system'],
"deviceType": "chromeOS"
}
def format_devicehub_asset(row):
"""Convert database row to DeviceHub API format"""
return {
"assetId": row['asset_id'],
"assetTag": row['asset_tag'],
"manufacturer": row['manufacturer'],
"model": row['model'],
"category": row['category'],
"status": row['status'],
"location": {
"building": row['location_building']
} if row['location_building'] else None,
"assignedTo": {
"name": row['assigned_to_name'],
"department": row['assigned_to_department']
} if row['assigned_to_name'] else None,
"purchaseInfo": {
"purchasePrice": row['purchase_price'],
"purchaseDate": row['purchase_date'] if row['purchase_date'] else "",
"warrantyExpiration": row['warranty_expiration']
}
}
@app.route('/api/intune/deviceManagement/managedDevices', methods=['GET'])
def get_intune_devices():
"""Get Intune devices with optional filtering"""
conn = get_db_connection()
cursor = conn.cursor()
# Parse filter parameter
filter_param = request.args.get('$filter', '')
if filter_param:
# Look for serial number in filter (simple parsing)
serial_number = filter_param.strip()
cursor.execute('''
SELECT * FROM intune_devices
WHERE serial_number = ?
''', (serial_number,))
else:
# Return all devices (with pagination support)
limit = int(request.args.get('$top', 100)) # Default 100 items
offset = int(request.args.get('$skip', 0))
cursor.execute('''
SELECT * FROM intune_devices
ORDER BY serial_number
LIMIT ? OFFSET ?
''', (limit, offset))
devices = cursor.fetchall()
conn.close()
# Format response
response = {
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#deviceManagement/managedDevices",
"value": [format_intune_device(device) for device in devices]
}
return jsonify(response)
@app.route('/api/devicehub/assets/serial/<serial_number>', methods=['GET'])
def get_devicehub_asset_by_serial(serial_number):
"""Get DeviceHub asset by serial number"""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM devicehub_assets
WHERE serial_number = ?
''', (serial_number,))
asset = cursor.fetchone()
conn.close()
if asset:
return jsonify(format_devicehub_asset(asset))
else:
return jsonify({"error": "Asset not found"}), 404
@app.route('/api/devicehub/assets', methods=['GET'])
def get_devicehub_assets():
"""Get all DeviceHub assets with pagination"""
conn = get_db_connection()
cursor = conn.cursor()
limit = int(request.args.get('limit', 100))
offset = int(request.args.get('offset', 0))
cursor.execute('''
SELECT * FROM devicehub_assets
ORDER BY serial_number
LIMIT ? OFFSET ?
''', (limit, offset))
assets = cursor.fetchall()
conn.close()
response = {
"assets": [format_devicehub_asset(asset) for asset in assets],
"pagination": {
"limit": limit,
"offset": offset,
"count": len(assets)
}
}
return jsonify(response)
@app.route('/health', methods=['GET'])
def health_check():
"""Health check endpoint"""
conn = get_db_connection()
cursor = conn.cursor()
# Check database connectivity and count records
cursor.execute("SELECT COUNT(*) as device_count FROM devices")
device_count = cursor.fetchone()['device_count']
cursor.execute("SELECT COUNT(*) as intune_count FROM intune_devices")
intune_count = cursor.fetchone()['intune_count']
cursor.execute("SELECT COUNT(*) as devicehub_count FROM devicehub_assets")
devicehub_count = cursor.fetchone()['devicehub_count']
conn.close()
return jsonify({
"status": "healthy",
"database": DB_FILE,
"records": {
"devices": device_count,
"intune": intune_count,
"devicehub": devicehub_count
},
"endpoints": {
"intune": "/api/intune/deviceManagement/managedDevices",
"devicehub": "/api/devicehub/assets"
}
})
@app.route('/', methods=['GET'])
def index():
"""API documentation"""
return jsonify({
"name": "DOE Mock APIs - SQLite Edition",
"description": "Mock Intune and DeviceHub APIs powered by SQLite database",
"endpoints": {
"/health": "Health check and database statistics",
"/api/intune/deviceManagement/managedDevices": "Intune devices API",
"/api/intune/deviceManagement/managedDevices?$filter=SERIAL": "Filter Intune by serial",
"/api/devicehub/assets": "DeviceHub assets API",
"/api/devicehub/assets/serial/{serial}": "DeviceHub asset by serial"
},
"database": {
"file": DB_FILE,
"total_devices": "~350K from NYC CSV"
}
})
if __name__ == '__main__':
print("🚀 Starting DOE Mock API Server (SQLite Edition)")
print(f"📊 Database: {DB_FILE}")
print("🌐 Endpoints:")
print(" - http://localhost:5000/ (documentation)")
print(" - http://localhost:5000/health (health check)")
print(" - http://localhost:5000/api/intune/deviceManagement/managedDevices")
print(" - http://localhost:5000/api/devicehub/assets")
print()
app.run(debug=True, host='0.0.0.0', port=5000)