hussein2000 commited on
Commit
c8e724a
1 Parent(s): 03e7882

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -51
app.py CHANGED
@@ -1,69 +1,133 @@
1
  from flask import Flask, request, jsonify
2
  import requests
3
- from bs4 import BeautifulSoup
 
4
 
5
  app = Flask(__name__)
6
 
7
- # Example URL, modify based on the search page you're targeting
8
- url = "https://html.duckduckgo.com/html/"
 
 
 
9
 
10
- # Function to fetch results from a specific page (1st page: page_num=1, 2nd page: page_num=2, etc.)
11
- def fetch_duckduckgo_results(search_query, page_num=1):
12
- headers = {
13
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
14
- }
15
 
16
- # DuckDuckGo uses 's' parameter for result offset, calculate offset for pages (e.g., 0 for first, 50 for second)
17
- offset = (page_num - 1) * 50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- # Search query parameters (assuming DuckDuckGo), 's' is for pagination
20
- params = {'q': search_query, 's': offset}
21
 
22
- # Send request to DuckDuckGo or relevant HTML page
23
- response = requests.get(url, headers=headers, params=params)
 
 
 
24
 
25
- # Check if request was successful
26
- if response.status_code != 200:
27
- return {"error": f"Failed to retrieve data: {response.status_code}"}
28
 
29
- # Parse HTML content
30
- soup = BeautifulSoup(response.text, 'html.parser')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- # Find all result blocks
33
- results = []
34
- for result in soup.find_all('div', class_='result__body'):
35
- title_tag = result.find('h2', class_='result__title')
36
- snippet_tag = result.find('a', class_='result__snippet')
37
- icon_tag = result.find('img', class_='result__icon__img')
38
- url_tag = result.find('a', class_='result__a')
39
-
40
- if title_tag and snippet_tag and icon_tag and url_tag:
41
- result_data = {
42
- 'title': title_tag.text.strip(),
43
- 'description': snippet_tag.text.strip(),
44
- 'icon_url': "https:" + icon_tag['src'] if icon_tag else None,
45
- 'url': url_tag['href']
46
  }
47
- results.append(result_data)
48
-
49
- return results
50
-
51
- # API endpoint for fetching search results
52
- @app.route('/search', methods=['GET'])
53
- def search():
54
- # Get query parameters
55
- search_query = request.args.get('query', default='', type=str)
56
- page_num = request.args.get('page', default=1, type=int)
57
-
58
- if not search_query:
59
- return jsonify({"error": "Search query is required"}), 400
 
60
 
61
- # Fetch results from DuckDuckGo
62
- results = fetch_duckduckgo_results(search_query, page_num)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Return results as JSON
65
- return jsonify(results)
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- # Run the Flask application
68
  if __name__ == '__main__':
69
  app.run(host="0.0.0.0", port=7860)
 
1
  from flask import Flask, request, jsonify
2
  import requests
3
+ import json
4
+ import base64
5
 
6
  app = Flask(__name__)
7
 
8
+ # GitHub credentials from environment variables
9
+ GITHUB_TOKEN = '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' # Set your token in environment variables
10
+ REPO_OWNER = 'hussein2000-oo'
11
+ REPO_NAME = 'dbailloolloloolollhrthlnewrgnk'
12
+ USER_FILE_NAME = 'user.json'
13
 
14
+ # Function to fetch user data from GitHub
15
+ def fetch_user_data():
16
+ url = f'https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{USER_FILE_NAME}'
17
+ headers = {'Authorization': f'token {GITHUB_TOKEN}'}
18
+ response = requests.get(url, headers=headers)
19
 
20
+ if response.status_code == 200:
21
+ content = response.json()
22
+ user_data = json.loads(base64.b64decode(content['content']).decode('utf-8'))
23
+
24
+ # Ensure user_data is a dictionary
25
+ if not isinstance(user_data, dict):
26
+ print("User data is not in the expected format. Initializing empty user data.")
27
+ user_data = {}
28
+
29
+ return user_data, content['sha'] # Return the SHA for updating the file
30
+ else:
31
+ print("Failed to fetch user data:", response.status_code, response.json())
32
+ return {}, None # Return an empty dict if fetching fails
33
+
34
+
35
+ # Function to update user data on GitHub
36
+ def update_user_data(user_data, sha):
37
+ url = f'https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{USER_FILE_NAME}'
38
+ headers = {'Authorization': f'token {GITHUB_TOKEN}'}
39
 
40
+ updated_content = base64.b64encode(json.dumps(user_data).encode('utf-8')).decode('utf-8')
 
41
 
42
+ payload = {
43
+ "message": "Update user.json with new user",
44
+ "content": updated_content,
45
+ "sha": sha
46
+ }
47
 
48
+ response = requests.put(url, headers=headers, json=payload)
 
 
49
 
50
+ if response.status_code == 200:
51
+ print("User data updated successfully.")
52
+ else:
53
+ print("Failed to update user data:", response.status_code, response.json())
54
+
55
+
56
+ # API endpoint to create a user account
57
+ @app.route('/api/create_user', methods=['POST'])
58
+ def create_user():
59
+ data = request.json
60
+ username = data.get('username')
61
+ password = data.get('password')
62
+ first_name = data.get('first_name')
63
+ last_name = data.get('last_name')
64
+ birthday = data.get('birthday')
65
+ security_questions = data.get('security_questions')
66
+
67
+ user_data, sha = fetch_user_data()
68
 
69
+ if user_data is not None:
70
+ if username in user_data:
71
+ return jsonify({"message": "User already exists."}), 400
72
+ else:
73
+ user_data[username] = {
74
+ "password": password,
75
+ "first_name": first_name,
76
+ "last_name": last_name,
77
+ "birthday": birthday,
78
+ "security_questions": security_questions # Store security questions
 
 
 
 
79
  }
80
+ update_user_data(user_data, sha)
81
+ return jsonify({"message": f"User {username} created successfully."}), 201
82
+ else:
83
+ return jsonify({"message": "Could not create user. User data fetch failed."}), 500
84
+
85
+
86
+ # API endpoint to sign in
87
+ @app.route('/api/sign_in', methods=['POST'])
88
+ def sign_in():
89
+ data = request.json
90
+ username = data.get('username')
91
+ password = data.get('password')
92
+
93
+ user_data, _ = fetch_user_data()
94
 
95
+ if user_data is not None and isinstance(user_data, dict):
96
+ if username in user_data:
97
+ if user_data[username]['password'] == password: # Corrected password check
98
+ return jsonify({"message": "Signed in successfully!"}), 200
99
+ else:
100
+ return jsonify({"message": "Sign in failed."}), 401
101
+ else:
102
+ return jsonify({"message": "User not found."}), 404
103
+ else:
104
+ return jsonify({"message": "Unexpected data format in user.json."}), 500
105
+
106
+
107
+ # API endpoint to reset password using security questions
108
+ @app.route('/api/reset_password', methods=['POST'])
109
+ def reset_password():
110
+ data = request.json
111
+ username = data.get('username')
112
+ answers = data.get('answers')
113
+
114
+ user_data, _ = fetch_user_data()
115
 
116
+ if username in user_data:
117
+ questions = user_data[username]['security_questions ']
118
+
119
+ # Check if answers match
120
+ if all(user_data[username]['security_questions'][q] == answers[q] for q in questions):
121
+ new_password = data.get('new_password')
122
+ user_data[username]['password'] = new_password
123
+ update_user_data(user_data, _)
124
+ return jsonify({"message": "Password reset successfully."}), 200
125
+ else:
126
+ return jsonify({"message": "Security answers do not match."}), 401
127
+ else:
128
+ return jsonify({"message": "User not found."}), 404
129
+
130
+
131
 
 
132
  if __name__ == '__main__':
133
  app.run(host="0.0.0.0", port=7860)