윤영준 윤영준 2024-10-04
updates for new database and encrpytions, application updates, refactors
@176675e2882d590d6eff42ba293ee15d874a1e88
action.py
--- action.py
+++ action.py
@@ -34,7 +34,9 @@
 
 
 @Action.route('/gps_update')
+
 class GPS_update(Resource):
+    @Action.doc(responses={200: 'Success'})
     @Action.doc(responses={401: 'Unauthorized'})
     @Action.doc(responses={500: 'Internal Error'})
     def post(self):
@@ -68,12 +70,10 @@
                     500: f"ERROR! Mismatching length of data in trip_log! \n timestamp : {time_stamp_len} \n latitude : {latitude_len} \n longitude : {longitude_len}"
                    }
 
-         
         df = pd.DataFrame(data["trip_log"])
         df["user_id"] = data["user_id"]
         df["trip_id"] = data["trip_id"]
-        
-       	
+
         columns = df.columns
         data_csv_block = df.to_csv(header=False, index=False)
         print(f"recieved : {data}")
@@ -110,8 +110,8 @@
             return {"result" : "ERROR! INVALID TRIP_ID!"}, 500
 
         trip_id = data["trip_id"]
-        trip_distance_m = data["trip_distance_m"]
-        trip_time_s = data["trip_time_s"]
+        trip_distance_m = data["total_distance_m"]
+        trip_time_s = data["total_time_s"]
         abrupt_start_count = data["abrupt_start_count"]
         abrupt_stop_count = data["abrupt_stop_count"]
         abrupt_acceleration_count = data["abrupt_acceleration_count"]
@@ -146,7 +146,7 @@
         # Check if token is provided
         if not token:
             return {'result': 'fail', 'msg': '토큰이 없습니다.'}, 401
-
+       
         try:
             # Decode the token to verify it
             decoded_token = jwt.decode(token, "secret", algorithms=['HS256'])
@@ -157,9 +157,13 @@
             return {'result': 'fail', 'msg': '유효하지 않은 토큰입니다.'}, 401
 
         # Interact with the DB to get user history
+
+        data = request.get_json()
+        user_id = data["user_id"]
         try:
             db = DB()
             result, status_code = db.get_history(user_name=user_id)
             return {'result': 'success', 'data': result}, status_code
         except Exception as e:
-            return {'result': 'fail', 'msg': str(e)}, 500
(파일 끝에 줄바꿈 문자 없음)
+            print(str(e))
+            return {'result': 'fail', 'msg': str(e)}, 500
app.py
--- app.py
+++ app.py
@@ -27,5 +27,5 @@
 api.add_namespace(Action, '/action')
 
 if __name__ == "__main__":
-    app.run(debug=True, host='0.0.0.0', port=15857)
+    app.run(debug=True, host='0.0.0.0', port=27461)
     print("Flask Start")
auth.py
--- auth.py
+++ auth.py
@@ -1,5 +1,5 @@
-from flask import request,jsonify,render_template,redirect,url_for
-from flask_restx import Resource, Api, Namespace, fields
+from flask import request,jsonify
+from flask_restx import Resource, Namespace, fields
 from database.database import DB
 import datetime
 import jwt
@@ -34,7 +34,7 @@
 })
 
 user_fields_register = Auth.inherit('User reigster', user_fields, {
-    'password': fields.String(description='Password', required=True),'email': fields.String(description='email', required=True),'user_sex': fields.String(description='sex', required=True),'phone': fields.String(description='phone', required=True)
+    'password': fields.String(description='Password', required=True),'email': fields.String(description='email', required=True),'phone': fields.String(description='phone', required=True)
 
 })
 
@@ -58,9 +58,6 @@
             }, 200
 
 
-
-
-
 @Auth.route('/register')
 class AuthRegister(Resource):
     @Auth.expect(user_fields_register)
@@ -73,7 +70,7 @@
         id_ = data['id']
         password = data['password']
         user_email = data['email']
-        sex = data['user_sex']
+        # sex = data['user_sex']
         phone = data['phone']
 
         # Prepare data for registration
@@ -81,7 +78,7 @@
             'username': id_,
             'password': password,
             'email': user_email,
-            'sex': sex,
+            # 'sex': sex,
             'phone': phone
         }
 
@@ -159,23 +156,23 @@
 
         if result['status'] == 'success':
             payload = {
-                'id': id,
+                'id': id_,
                 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=14)
             }
             token = jwt.encode(payload, "secret", algorithm='HS256')
-            return jsonify({'result': 'success', 'token': token})
+            return {'result': 'success', 'token': token}, 200
         else :
-            return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})
+            return {'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'}, 401
 
 
-@Auth.route('/secession')
-class AuthSecession(Resource):
+@Auth.route('/withdraw')
+class AuthWithdraw(Resource):
     def post(self):
          db=DB()
          id = request.json['token']
          payload = jwt.decode(id, "secret", algorithms=['HS256'])
          db.db_delete_id(payload['id'])
-         return {'secession':'success'}
+         return {'secession':'success'}, 200
 
 
 
database/database.py
--- database/database.py
+++ database/database.py
@@ -73,13 +73,14 @@
         password = data.get('password', '').strip()
         email = data.get('email', '').strip()
         phone = data.get('phone', '').strip()
+        phone = phone.replace("-","")
         sex = data.get('sex', '').strip()
 
         # Validate username
         if not username:
             return None, "Username is required."
-        if len(username) > 255:
-            return None, "Username must not exceed 255 characters."
+        if len(username) > 26:
+            return None, "Username must not exceed 26 characters."
 
         # Validate password
         if not password:
@@ -96,11 +97,11 @@
             return None, "Phone number must be in the format 010XXXXXXXX where X are digits."
 
         # Validate sex input
-        if not sex:
-            return None, "Sex is required."
-        if sex not in ['Male', 'Female', 'Non-binary', 'Other']:
-            return None, "Invalid value for sex."
-
+        # if not sex:
+        #    return None, "Sex is required."
+        # if sex not in ['Male', 'Female', 'Non-binary', 'Other']:
+        #    return None, "Invalid value for sex."
+        sex = "WHATEVER"
         return {
             'username': username,
             'password': password,
@@ -239,7 +240,7 @@
     ):
 
         self.cur.execute(f"""
-            INSERT INTO trip_log (username, trip_id, timestamp, total_distance_m, total_time_s, abrupt_start_count, abrupt_stop_count,
+            INSERT INTO trip_log (user_id, trip_id, timestamp, total_distance_m, total_time_s, abrupt_start_count, abrupt_stop_count,
              abrupt_acceleration_count, abrupt_deceleration_count, helmet_on, final_score)
             VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
         """, (
@@ -256,6 +257,15 @@
             final_score
             )
         )
+
+    def db_delete_id(self,user_id) :
+        cur = self.conn.cursor()
+        cur.execute(f'''
+        delete
+        from "{self.schema}".user_id ui
+        where user_id  = '{user_id}'
+        ''')
+        cur.close()
 
     def get_history(self, user_name):
         """
@@ -294,7 +304,7 @@
                        abrupt_stop_count, abrupt_acceleration_count, abrupt_deceleration_count, 
                        helmet_on, final_score
                 FROM trip_log
-                WHERE username = %s
+                WHERE user_id = %s
                 AND timestamp >= NOW() - INTERVAL '1 month'
             """, (user_name,))
 
Add a comment
List