Skip to content

Commit

Permalink
Merge pull request #14 from Mundreanuc223/main
Browse files Browse the repository at this point in the history
Merging Aarons changes
  • Loading branch information
Mundreanuc223 authored Oct 15, 2024
2 parents 5d0efc7 + fe44c2d commit e44a150
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea/workspace.xml
.idea
6 changes: 6 additions & 0 deletions vault/src/Components/LoginForm/LoginForm.css
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,10 @@

.register-link p a:hover{
text-decoration: underline;
}

.wrapper .error-message{
font-size: 15px;
text-align: center;
margin-top: 20px;
}
43 changes: 38 additions & 5 deletions vault/src/Components/LoginForm/LoginForm.jsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,50 @@
import React from 'react';
import React, { useState } from 'react';
import './LoginForm.css';
import { FaUser } from "react-icons/fa";
import { FaLock } from "react-icons/fa";
const LoginForm = () =>{

const LoginForm = () => {
// State to store the username and password
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [errorMessage, setErrorMessage] = useState('');

// Function to handle form submission
const handleSubmit = async (e) => {
e.preventDefault(); // Prevents page reload or default form submission
try {
// Send a POST request to backend
const response = await fetch('http://127.0.0.1:5000/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }), // Send username and password
});

const data = await response.json();

if (response.ok) {
console.log('Login successful:', data.message);
} else {
setErrorMessage(data.message); // Show error message to the user
}
} catch (error) {
console.error('Error during login:', error);
setErrorMessage('Something went wrong. Please try again.');
}
};

return (
<div className='wrapper'>
<form action="">
<form onSubmit={handleSubmit}>
<h1>Login</h1>
<div className="input-box">
<input type="text" placeholder='Username' required />
<input type="text" placeholder='Username' required value={username} onChange={(e) => setUsername(e.target.value)} />
<FaUser className= 'icons' />
</div>
<div className="input-box">
<input type="text" placeholder='Password' required />
<input type="text" placeholder='Password' required value={password} onChange={(e) => setPassword(e.target.value)} />
<FaLock className= 'icons'/>
</div>
<div className="remember-forgot">
Expand All @@ -23,6 +55,7 @@ const LoginForm = () =>{
<div className="register-link">
<p>Need an account?<a href="#">Register</a></p>
</div>
{errorMessage && <p className="error-message">{errorMessage}</p>}
</form>
</div>
);
Expand Down
2 changes: 1 addition & 1 deletion vault/src/backend/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Backend Guide

## 1. Ensure you have SQLite and Flask downloaded
## 1. Ensure you have SQLite, Flask, and Flask-cors downloaded


### Table Format Example:
Expand Down
62 changes: 60 additions & 2 deletions vault/src/backend/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from flask import Flask, jsonify, request
import sqlite3
from datetime import datetime
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# Creates the database with multiple tables
def init_db():
Expand All @@ -14,7 +16,7 @@ def init_db():
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
email TEXT UNIQUE,
password TEXT NOT NULL,
profile_pic TEXT,
bio TEXT,
Expand Down Expand Up @@ -52,9 +54,21 @@ def init_db():
connection.close()

def get_db_connection():
connection = sqlite3.connect('vault_database.db')
connection = sqlite3.connect('vault_database.db', timeout=10.0)
return connection

def insert_new_user(username, password):
conn = get_db_connection()
cursor = conn.cursor()

cursor.execute('''
INSERT INTO users (username, password) VALUES (?, ?)
''', (username, password))

conn.commit()
conn.close()


# Initializes the database (will only need to be run when first creating the DB and anytime we add new fields/schemas to the tables
@app.route('/init', methods=['GET'])
def initialize_database():
Expand All @@ -71,6 +85,50 @@ def get_users():
conn.close()
return jsonify(users)

# Login handling
@app.route('/login', methods=['POST'])
def login():
data = request.json
username = data['username']
password = data['password']

conn = get_db_connection()
cursor = conn.cursor()

# Checking if username is in database and if password is correct
cursor.execute("SELECT username, password FROM users WHERE username = ? AND password = ?", (username, password))
user = cursor.fetchone()
conn.close()

if user:
return jsonify({"status": "success", "message": "Login successful!"}), 200
else:
return jsonify({"status": "failure", "message": "Username or password incorrect."}), 400

# Registration handling
@app.route('/register', methods=['POST'])
def register():
data = request.json
username = data['username']
password = data['password']

conn = get_db_connection()
cursor = conn.cursor()

cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
existing_user = cursor.fetchone()

if existing_user:
# Username is already in database/is taken
conn.close()
return jsonify({"error": "Username already taken"}), 409

# Adding username and password into the database
cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
conn.commit()
conn.close()
return jsonify({"status": "success", "message": "Account created!"}), 201

if __name__ == '__main__':
init_db()
app.run(debug=True)
Expand Down
Binary file modified vault/src/backend/vault_database.db
Binary file not shown.

0 comments on commit e44a150

Please sign in to comment.