Ver Fonte

fixed add and remove account logic

Karl Hudgell há 1 mês atrás
pai
commit
660e81603d
4 ficheiros alterados com 177 adições e 59 exclusões
  1. 29 1
      app.py
  2. 31 3
      lib/reqs.py
  3. 95 0
      templates/add_account.html
  4. 22 55
      templates/user_accounts.html

+ 29 - 1
app.py

@@ -3,7 +3,7 @@ from flask import Flask, render_template, request, redirect, url_for, session, f
 from flask_caching import Cache
 import requests.auth
 from lib.datetime import filter_accounts_current_month
-from lib.reqs import (get_urls, get_user_accounts)
+from lib.reqs import (get_urls, get_user_accounts, add_user_account, delete_user_account)
 import requests
 import base64
 from flask import Flask
@@ -78,5 +78,33 @@ def user_accounts():
     base_url = app.config['BASE_URL']  # Access base_url from the config    
     return render_template('user_accounts.html', username=session['username'], user_accounts=get_user_accounts(base_url, session['auth_credentials']), auth=session['auth_credentials'])
 
+
+@app.route('/accounts/add', methods=['GET', 'POST'])
+def add_account():
+    base_url = app.config['BASE_URL']  # Access base_url from the config
+    if request.method == 'POST':
+        username = request.form['username']
+        password = request.form['password']
+        stream = request.form['stream']
+        
+        if add_user_account(base_url, session['auth_credentials'], username, password, stream):
+            cache.clear()  # Clears all cache entries
+            return redirect(url_for('user_accounts'))
+        return render_template('add_account.html')
+    
+    return render_template('add_account.html')
+
+@app.route('/accounts/delete', methods=['POST'])
+def delete_account():
+    stream = request.form.get('stream')
+    username = request.form.get('username')
+    base_url = app.config['BASE_URL']
+    
+    if delete_user_account(base_url,session['auth_credentials'], stream, username):
+        cache.clear()  # Clears all cache entries
+        return redirect(url_for('user_accounts'))
+    return redirect(url_for('user_accounts'))
+
+
 if __name__ == '__main__':
     app.run(debug=app.config['DEBUG'], host=app.config['HOST'], port=app.config['PORT'])

+ 31 - 3
lib/reqs.py

@@ -40,12 +40,40 @@ def delete_user_account(base_url: str, auth: str, stream:str, username:str) -> b
     Returns:
         bool: _description_
     """    
-    url = f"{base_url}/getUserAccounts"
+    url = f"{base_url}/deleteAccount"
 
     payload = {"stream": stream, "user": username}
 
     headers = {"Authorization": f"Basic {auth}"}
 
     response = requests.request("POST", url, headers=headers, data=payload)
-    res_json = json.loads(response.text)
-    return res_json
+    if "Deleted" in response.text:
+        return True
+    else:
+        return False
+
+
+
+def add_user_account(base_url: str, auth: str, username:str, password:str, stream:str,) -> bool:
+    """_summary_
+
+    Args:
+        base_url (str): _description_
+        auth (str): _description_
+        stream (str): _description_
+        username (str): _description_
+
+    Returns:
+        bool: _description_
+    """    
+    url = f"{base_url}/addAccount"
+
+    payload = {"username": username, "password": password, "stream": stream}
+
+    headers = {"Authorization": f"Basic {auth}"}
+
+    response = requests.request("POST", url, headers=headers, data=payload)
+    if "Added successfully" in response.text:
+        return True
+    else:
+        return False

+ 95 - 0
templates/add_account.html

@@ -0,0 +1,95 @@
+<!-- templates/add_account.html -->
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Add Account - KTVManager</title>
+    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
+    <style>
+        /* Hide the spinner by default */
+        #loadingSpinner {
+            display: none;
+        }
+    </style>
+</head>
+<body>
+
+    <!-- Navbar -->
+    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
+        <a class="navbar-brand" href="/">KTVManager</a>
+        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
+            <span class="navbar-toggler-icon"></span>
+        </button>
+        <div class="collapse navbar-collapse" id="navbarNav">
+            <ul class="navbar-nav ml-auto">
+                <li class="nav-item">
+                    <a class="nav-link" href="/">Home</a>
+                </li>
+                <li class="nav-item">
+                    <a class="nav-link" href="/accounts">Accounts</a>
+                </li>
+                <li class="nav-item">
+                    <a class="nav-link" href="/urls">URLs</a>
+                </li>
+            </ul>
+        </div>
+    </nav>
+
+    <!-- Sub-navigation for Accounts -->
+    <div class="bg-light py-2">
+        <div class="container">
+            <ul class="nav nav-pills">
+                <li class="nav-item">
+                    <a class="nav-link" href="/accounts">List Accounts</a>
+                </li>
+                <li class="nav-item">
+                    <a class="nav-link active" href="/accounts/add">Add Account</a>
+                </li>
+            </ul>
+        </div>
+    </div>
+
+    <!-- Main Content -->
+    <div class="container mt-5">
+        <h1>Add Account</h1>
+        <br>
+        
+        <form action="/accounts/add" method="POST" onsubmit="showLoading()">
+            <div class="form-group">
+                <label for="username">Username</label>
+                <input type="text" class="form-control" id="username" name="username" required>
+            </div>
+            <div class="form-group">
+                <label for="password">Password</label>
+                <input type="text" class="form-control" id="password" name="password" required>
+            </div>
+            <div class="form-group">
+                <label for="stream">Stream Name</label>
+                <input type="text" class="form-control" id="stream" name="stream" required>
+            </div>
+            <button type="submit" class="btn btn-primary" id="submitButton">
+                <span class="spinner-border spinner-border-sm" id="loadingSpinner" role="status" aria-hidden="true"></span>
+                <span id="buttonText">Add Account</span>
+            </button>
+        </form>
+    </div>
+
+    <footer class="bg-dark text-white text-center py-3 mt-5">
+        <p>&copy; 2024 KTV Manager | All rights reserved</p>
+    </footer>
+
+    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
+    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.0.7/dist/umd/popper.min.js"></script>
+    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
+    <script>
+        function showLoading() {
+            // Disable the button to prevent multiple submissions
+            document.getElementById("submitButton").disabled = true;
+            // Show spinner and change button text
+            document.getElementById("loadingSpinner").style.display = "inline-block";
+            document.getElementById("buttonText").textContent = "Working...";
+        }
+    </script>
+</body>
+</html>

+ 22 - 55
templates/user_accounts.html

@@ -7,13 +7,6 @@
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
     <link rel="stylesheet" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
     <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css">
-    <style>
-        .password-blur {
-            filter: blur(4px);
-            transition: filter 0.3s ease;
-            cursor: pointer;
-        }
-    </style>
 </head>
 <body>
     <!-- Navbar -->
@@ -31,6 +24,20 @@
         </div>
     </nav>
 
+    <!-- Sub-navigation for Accounts -->
+    <div class="bg-light py-2">
+        <div class="container">
+            <ul class="nav nav-pills">
+                <li class="nav-item">
+                    <a class="nav-link active" href="/accounts">List Accounts</a>
+                </li>
+                <li class="nav-item">
+                    <a class="nav-link" href="/accounts/add">Add Account</a>
+                </li>
+            </ul>
+        </div>
+    </div>
+
     <!-- Main Content -->
     <div class="container mt-5">
         <h2>{{ username }}'s Accounts</h2>
@@ -55,11 +62,15 @@
                         <td>{{ account.stream }}</td>
                         <td><a href="{{ account.streamURL }}" target="_blank">{{ account.streamURL }}</a></td>
                         <td>{{ account.expiaryDate_rendered }}</td>
-                        <td class="password-cell password-blur" data-password="{{ account.password }}">********</td>
+                        <td>{{ account.password }}</td>
                         <td>
-                            <button class="btn btn-danger delete-account-btn" data-stream="{{ account.stream }}" data-username="{{ account.username }}">
-                                Delete
-                            </button>
+                            <form action="/accounts/delete" method="POST" style="display:inline;">
+                                <input type="hidden" name="stream" value="{{ account.stream }}">
+                                <input type="hidden" name="username" value="{{ account.username }}">
+                                <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this account?');">
+                                    Delete
+                                </button>
+                            </form>
                         </td>
                     </tr>
                     {% endfor %}
@@ -78,7 +89,6 @@
     <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
     <script src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
     <script>
-        const authValue = "{{ auth | safe }}";  // Passing `auth` safely
         $(document).ready(function() {
             $.fn.dataTable.ext.type.order['date-eu'] = function(data) {
                 const parts = data.split('/');
@@ -93,49 +103,6 @@
                     { "type": "date-eu", "targets": 4 }
                 ]
             });
-
-            $('#accountsTable tbody').on('click', '.password-cell', function() {
-                const $cell = $(this);
-                $cell.text($cell.data('password'));
-                $cell.removeClass('password-blur');
-                
-                $(document).on('click.password', function(event) {
-                    if (!$(event.target).closest('.password-cell').length) {
-                        $cell.text('********').addClass('password-blur');
-                        $(document).off('click.password');
-                    }
-                });
-            });
-
-            // Delete functionality
-            $('.delete-account-btn').click(async function() {
-                const stream = $(this).data('stream');
-                const username = $(this).data('username');
-                
-                if (confirm(`Are you sure you want to delete account for stream: ${stream}, username: ${username}?`)) {
-                    try {
-                        const response = await fetch('http://vps.k-world.me.uk:3001/deleteAccount', {
-                            method: 'POST',
-                            headers: {
-                                'Content-Type': 'application/json',
-                                'Authorization': 'Basic ' +  authValue  // Adjust auth here as needed
-                            },
-                            body: JSON.stringify({ stream, username })
-                        });
-
-                        const result = await response.json();
-                        if (response.ok) {
-                            alert(result.message);
-                            $(this).closest('tr').remove();
-                        } else {
-                            alert(result.error || 'Failed to delete account');
-                        }
-                    } catch (error) {
-                        console.error('Error deleting account:', error);
-                        alert('Error occurred while deleting account');
-                    }
-                }
-            });
         });
     </script>
 </body>