Compare commits
1 Commits
prajakta-d
...
Laxmi-Devs
| Author | SHA1 | Date | |
|---|---|---|---|
| 87346b99f4 |
24
.env
24
.env
@@ -4,7 +4,7 @@
|
||||
FLASK_ENV=development
|
||||
FLASK_DEBUG=True
|
||||
FLASK_HOST=0.0.0.0
|
||||
FLASK_PORT=5011
|
||||
FLASK_PORT=5015
|
||||
|
||||
# -----------------------------
|
||||
# Security
|
||||
@@ -23,17 +23,15 @@ DB_USER=root
|
||||
DB_PASSWORD=root
|
||||
|
||||
# DATABASE_URL=mysql+pymysql://root:root@localhost/comparisondb
|
||||
# -----------------------------
|
||||
# LDAP Configuration
|
||||
# -----------------------------
|
||||
USE_LDAP_AUTH=true
|
||||
|
||||
LDAP_URL=ldap://192.168.0.25:389
|
||||
LDAP_BIND_DN=cn=admin,dc=lcepl,dc=org
|
||||
LDAP_BIND_PASSWORD=Lcepl1950@2026
|
||||
LDAP_BASE_DN=dc=lcepl,dc=org
|
||||
|
||||
# -----------------------------
|
||||
# LDAP Configuration new
|
||||
# -----------------------------
|
||||
LDAP_SERVER=ldap://host.docker.internal
|
||||
LDAP_PORT=389
|
||||
LDAP_USE_SSL=False
|
||||
|
||||
LDAP_DOMAIN=lcepl.org
|
||||
|
||||
# OpenLDAP standard username attribute
|
||||
LDAP_SEARCH_FILTER=(uid={username})
|
||||
|
||||
LDAP_BASE_DN=DC=lcepl,DC=org
|
||||
LDAP_SEARCH_BASE=OU=Users,DC=lcepl,DC=org
|
||||
|
||||
@@ -5,23 +5,20 @@ WORKDIR /app
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
default-libmysqlclient-dev \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy requirements and install Python dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt gunicorn
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Create necessary directories
|
||||
RUN mkdir -p app/logs app/static/uploads app/static/downloads
|
||||
ENV FLASK_APP=run.py
|
||||
|
||||
# Expose port
|
||||
EXPOSE 5001
|
||||
|
||||
# Run the application with Gunicorn (production WSGI server)
|
||||
CMD ["gunicorn", "--bind", "0.0.0.0:5001", "run:app"]
|
||||
# Run the application
|
||||
CMD ["python", "run.py"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from flask import Flask, redirect, url_for
|
||||
from app.config import Config
|
||||
from app.services.db_service import db, migrate
|
||||
from app.services.db_service import db
|
||||
from app.services.logger_service import LoggerService
|
||||
|
||||
def create_app():
|
||||
@@ -9,9 +9,6 @@ def create_app():
|
||||
|
||||
# Initialize extensions
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
|
||||
# Initialize Logger
|
||||
LoggerService.init_app(app)
|
||||
@@ -38,7 +35,10 @@ def register_blueprints(app):
|
||||
from app.routes.file_report import file_report_bp
|
||||
from app.routes.generate_comparison_report import generate_report_bp
|
||||
from app.routes.file_format import file_format_bp
|
||||
|
||||
# new
|
||||
from app.routes.activity_routes import activity_bp
|
||||
from app.routes.engineering_master_routes import engi_bp
|
||||
|
||||
app.register_blueprint(auth_bp)
|
||||
app.register_blueprint(user_bp)
|
||||
@@ -48,7 +48,10 @@ def register_blueprints(app):
|
||||
app.register_blueprint(file_report_bp)
|
||||
app.register_blueprint(generate_report_bp)
|
||||
app.register_blueprint(file_format_bp)
|
||||
|
||||
# new
|
||||
app.register_blueprint(activity_bp)
|
||||
app.register_blueprint(engi_bp)
|
||||
|
||||
|
||||
def register_error_handlers(app):
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import os
|
||||
# project base url
|
||||
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
class Config:
|
||||
# secret key
|
||||
@@ -23,23 +21,14 @@ class Config:
|
||||
)
|
||||
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
# uploads folder path
|
||||
UPLOAD_FOLDER = os.path.join(BASE_DIR, "static", "uploads")
|
||||
# file extension
|
||||
ALLOWED_EXTENSIONS = {"xlsx", "xls", "csv"}
|
||||
|
||||
# ---------------- LDAP settings ----------------
|
||||
USE_LDAP_AUTH = os.getenv("USE_LDAP_AUTH", "false").lower() == "true"
|
||||
# e.g. "ldap://192.168.0.25:389" or "ldaps://192.168.0.25:636" (preferred, encrypted)
|
||||
LDAP_SERVER = os.getenv("LDAP_URL", "ldap://192.168.0.25:389")
|
||||
# Service/admin account used only to SEARCH for a user's real DN.
|
||||
# The user's own password is never used for this bind.
|
||||
LDAP_BIND_DN = os.getenv("LDAP_BIND_DN", "cn=admin,dc=lcepl,dc=org")
|
||||
LDAP_BIND_PASSWORD = os.getenv("LDAP_BIND_PASSWORD", "")
|
||||
# Base DN to search for user entries under
|
||||
LDAP_BASE_DN = os.getenv("LDAP_BASE_DN", "dc=lcepl,dc=org")
|
||||
# Used only as a fallback to build an email if the directory entry has none
|
||||
LDAP_DOMAIN = os.getenv("LDAP_DOMAIN", "lcepl.org")
|
||||
# Filter used to find the user's entry by their login username.
|
||||
# Standard OpenLDAP attribute is "uid". Active Directory would use sAMAccountName.
|
||||
LDAP_SEARCH_FILTER = os.getenv("LDAP_SEARCH_FILTER", "(uid={username})")
|
||||
|
||||
# LDAP Configuration New
|
||||
LDAP_SERVER = os.getenv("LDAP_SERVER")
|
||||
LDAP_PORT = int(os.getenv("LDAP_PORT", 389))
|
||||
LDAP_USE_SSL = os.getenv("LDAP_USE_SSL", "False").lower() == "true"
|
||||
|
||||
LDAP_BASE_DN = os.getenv("LDAP_BASE_DN")
|
||||
LDAP_DOMAIN = os.getenv("LDAP_DOMAIN")
|
||||
|
||||
LDAP_SEARCH_BASE = os.getenv("LDAP_SEARCH_BASE")
|
||||
@@ -7,13 +7,10 @@ class User(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.String(200), nullable=False)
|
||||
email = db.Column(db.String(120), unique=True, nullable=False)
|
||||
password_hash = db.Column(db.String(255), nullable=True)
|
||||
auth_source = db.Column(db.String(20), nullable=False, default="local")
|
||||
password_hash = db.Column(db.String(255), nullable=False)
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
def check_password(self, password):
|
||||
if not self.password_hash:
|
||||
return False
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
@@ -1,49 +1,98 @@
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, flash, session
|
||||
from flask import (Blueprint, render_template, request, redirect, url_for, flash, session, current_app)
|
||||
|
||||
from app.services.user_service import UserService
|
||||
from app.constants.messages import SuccessMessage, ErrorMessage
|
||||
from app.constants.http_status import HTTPStatus
|
||||
|
||||
auth_bp = Blueprint("auth", __name__)
|
||||
|
||||
|
||||
# ==========================
|
||||
# LOGIN
|
||||
# ==========================
|
||||
@auth_bp.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
|
||||
if session.get("user_id"):
|
||||
current_app.logger.info("User already logged in.")
|
||||
return redirect(url_for("dashboard.dashboard"))
|
||||
|
||||
if request.method == "POST":
|
||||
email = request.form.get("email")
|
||||
password = request.form.get("password")
|
||||
|
||||
try:
|
||||
email = request.form.get("email", "").strip()
|
||||
password = request.form.get("password", "")
|
||||
|
||||
if not email or not password:
|
||||
flash(ErrorMessage.INVALID_REQUEST, "danger")
|
||||
current_app.logger.warning("Login failed. Email or password missing.")
|
||||
return render_template("login.html", title="Login")
|
||||
|
||||
user = UserService.validate_login(email, password)
|
||||
|
||||
if user:
|
||||
session.clear()
|
||||
session["user_id"] = user.id
|
||||
session["user_name"] = user.name
|
||||
session["user_email"] = user.email
|
||||
flash("Login successful", "success")
|
||||
session["email"] = user.email
|
||||
session.permanent = True
|
||||
|
||||
current_app.logger.info(f"Login successful. User={user.name}")
|
||||
flash(SuccessMessage.LOGIN, "success")
|
||||
return redirect(url_for("dashboard.dashboard"))
|
||||
|
||||
flash("Invalid email or password", "danger")
|
||||
current_app.logger.warning(f"Invalid login attempt. Email={email}")
|
||||
flash(ErrorMessage.LOGIN_FAILED,"danger")
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.exception("Login Error" )
|
||||
flash(ErrorMessage.INTERNAL_SERVER_ERROR,"danger")
|
||||
|
||||
return render_template("login.html", title="Login")
|
||||
|
||||
|
||||
# ==========================
|
||||
# LOGOUT
|
||||
# ==========================
|
||||
@auth_bp.route("/logout")
|
||||
def logout():
|
||||
username = session.get("user_name", "Unknown")
|
||||
session.clear()
|
||||
flash("Logged out successfully", "info")
|
||||
current_app.logger.info(f"Logout successful. User={username}")
|
||||
flash(SuccessMessage.LOGOUT,"info")
|
||||
|
||||
return redirect(url_for("auth.login"))
|
||||
|
||||
|
||||
# ==========================
|
||||
# REGISTER
|
||||
# ==========================
|
||||
@auth_bp.route("/register", methods=["GET", "POST"])
|
||||
def register():
|
||||
if request.method == "POST":
|
||||
name = request.form.get("name")
|
||||
email = request.form.get("email")
|
||||
password = request.form.get("password")
|
||||
|
||||
user = UserService.register_user(name, email, password)
|
||||
if not user:
|
||||
flash("Email already exists", "danger")
|
||||
if request.method == "POST":
|
||||
try:
|
||||
name = request.form.get("name", "").strip()
|
||||
email = request.form.get("email", "").strip()
|
||||
password = request.form.get("password", "")
|
||||
|
||||
if not name or not email or not password:
|
||||
flash(ErrorMessage.INVALID_REQUEST,"danger")
|
||||
return redirect(url_for("auth.register"))
|
||||
|
||||
flash("User registered successfully", "success")
|
||||
user = UserService.register_user(name, email, password)
|
||||
|
||||
if not user:
|
||||
current_app.logger.warning(f"Duplicate Registration: {email}")
|
||||
flash(ErrorMessage.DUPLICATE_ENTRY,"danger")
|
||||
return redirect(url_for("auth.register"))
|
||||
|
||||
current_app.logger.info(f"New user registered: {email}")
|
||||
flash(SuccessMessage.CREATED,"success")
|
||||
return redirect(url_for("auth.login"))
|
||||
|
||||
except Exception:
|
||||
current_app.logger.exception("User Registration Failed" )
|
||||
flash(ErrorMessage.INTERNAL_SERVER_ERROR,"danger")
|
||||
|
||||
return render_template("register.html",title="Register")
|
||||
@@ -29,17 +29,24 @@ def add_action_columns(df, model_key):
|
||||
if df.empty:
|
||||
return df
|
||||
|
||||
df.insert(0, "Select", df["Id"].apply(
|
||||
# Edit + Delete side by side in one "Action" column, both as icon buttons.
|
||||
df.insert(0, "Action", df["Id"].apply(
|
||||
lambda x: (
|
||||
f'<div class="d-flex gap-1">'
|
||||
f'<a href="/file/edit/{model_key}/{x}" class="btn btn-sm btn-warning edit-btn" title="Edit">'
|
||||
f'<i class="bi bi-pencil-square"></i></a>'
|
||||
f'<button class="btn btn-sm btn-danger delete-btn" data-id="{x}" data-model="{model_key}" title="Delete">'
|
||||
f'<i class="bi bi-trash"></i></button>'
|
||||
f'</div>'
|
||||
)
|
||||
))
|
||||
|
||||
df.insert(1, "Select", df["Id"].apply(
|
||||
lambda x: f'<input type="checkbox" class="row-check" data-id="{x}">'
|
||||
))
|
||||
|
||||
df["Update"] = df["Id"].apply(
|
||||
lambda x: f'<a href="/file/edit/{model_key}/{x}" class="btn btn-sm btn-warning edit-btn"><i class="bi bi-pencil-square"></i> Edit</a>'
|
||||
)
|
||||
|
||||
df["Delete"] = df["Id"].apply(
|
||||
lambda x: f'<button class="btn btn-sm btn-danger delete-btn" data-id="{x}" data-model="{model_key}">Delete</button>'
|
||||
)
|
||||
df["Id"] = range(1, len(df) + 1)
|
||||
df = df.rename(columns={"Id": "Sr No"})
|
||||
|
||||
return df
|
||||
|
||||
@@ -236,6 +243,30 @@ def report_file():
|
||||
else:
|
||||
bill.Fetch(ra_bill_no,subcontractor_id,location)
|
||||
|
||||
|
||||
# ---------------------------------------------------------
|
||||
if (
|
||||
bill.df_tr.empty and
|
||||
bill.df_mh.empty and
|
||||
bill.df_dc.empty and
|
||||
bill.df_laying.empty
|
||||
):
|
||||
flash(
|
||||
f"No records found for RA Bill No '{ra_bill_no}'. "
|
||||
"Please check the RA Bill No and try again."
|
||||
if ra_bill_no else
|
||||
"No records found for the selected filters.",
|
||||
"warning"
|
||||
)
|
||||
return render_template(
|
||||
"subcontractor_report.html",
|
||||
subcontractors=subcontractors,
|
||||
selected_sc_id=selected_sc_id,
|
||||
selected_ra_bill=ra_bill_no,
|
||||
selected_location=location,
|
||||
selected_category=category
|
||||
)
|
||||
|
||||
# -----------------------------------------
|
||||
# Generate Abstract Report for Web
|
||||
# -----------------------------------------
|
||||
@@ -256,6 +287,32 @@ def report_file():
|
||||
bill.df_tr = bill.df_mh = bill.df_dc = pd.DataFrame()
|
||||
|
||||
|
||||
if (
|
||||
category in ("tr", "mh", "dc", "laying")
|
||||
and bill.df_tr.empty and bill.df_mh.empty
|
||||
and bill.df_dc.empty and bill.df_laying.empty
|
||||
):
|
||||
category_labels = {
|
||||
"tr": "Trench Excavation",
|
||||
"mh": "Manhole Excavation",
|
||||
"dc": "Domestic Chamber",
|
||||
"laying": "Pipe Laying",
|
||||
}
|
||||
flash(
|
||||
f"No {category_labels[category]} records found for the "
|
||||
"selected filters.",
|
||||
"warning"
|
||||
)
|
||||
return render_template(
|
||||
"subcontractor_report.html",
|
||||
subcontractors=subcontractors,
|
||||
selected_sc_id=selected_sc_id,
|
||||
selected_ra_bill=ra_bill_no,
|
||||
selected_location=location,
|
||||
selected_category=category
|
||||
)
|
||||
|
||||
|
||||
# ===================================================
|
||||
# DOWNLOAD EXCEL
|
||||
# ===================================================
|
||||
@@ -267,16 +324,46 @@ def report_file():
|
||||
abstract = AbstractReportService(subcontractor_id=subcontractor_id,ra_bill_no=ra_bill_no)
|
||||
abstract.generate(workbook)
|
||||
|
||||
bill.df_tr.to_excel(writer,sheet_name="Tr.Ex",index=False)
|
||||
bill.df_mh.to_excel(writer,sheet_name="Mh.Ex",index=False)
|
||||
bill.df_dc.to_excel(writer,sheet_name="MH & DC",index=False)
|
||||
bill.df_laying.to_excel(writer,sheet_name="Pipe Laying",index=False)
|
||||
|
||||
sheet_map = [
|
||||
(bill.df_tr, "Tr.Ex"),
|
||||
(bill.df_mh, "Mh.Ex"),
|
||||
(bill.df_dc, "MH & DC"),
|
||||
(bill.df_laying, "Pipe Laying"),
|
||||
]
|
||||
for df, sheet_name in sheet_map:
|
||||
if not df.empty:
|
||||
df.to_excel(writer, sheet_name=sheet_name, index=False)
|
||||
writer.close()
|
||||
output.seek(0)
|
||||
|
||||
|
||||
sc_obj = next(
|
||||
(s for s in subcontractors if str(s.id) == str(subcontractor_id)),
|
||||
None
|
||||
)
|
||||
sc_name = sc_obj.subcontractor_name if sc_obj else "Subcontractor"
|
||||
sc_name = re.sub(r'[^A-Za-z0-9_-]+', '_', sc_name).strip('_')
|
||||
|
||||
name_parts = [sc_name]
|
||||
|
||||
if ra_bill_no:
|
||||
name_parts.append(f"RA{re.sub(r'[^A-Za-z0-9_-]+', '_', ra_bill_no)}")
|
||||
|
||||
if location:
|
||||
name_parts.append(re.sub(r'[^A-Za-z0-9_-]+', '_', location).strip('_'))
|
||||
|
||||
if category and category != "all":
|
||||
name_parts.append(category.upper())
|
||||
|
||||
if action == "excel_all":
|
||||
name_parts.append("All")
|
||||
|
||||
filename = "_".join(name_parts) + "_Report.xlsx"
|
||||
|
||||
return send_file(
|
||||
output,
|
||||
download_name= "subcontractor_Report.xlsx",
|
||||
download_name=filename,
|
||||
as_attachment=True
|
||||
)
|
||||
|
||||
|
||||
@@ -1,72 +1,130 @@
|
||||
from ldap3 import (
|
||||
Server,
|
||||
Connection,
|
||||
ALL,
|
||||
NTLM,
|
||||
SIMPLE,
|
||||
SUBTREE
|
||||
)
|
||||
|
||||
from flask import current_app
|
||||
from ldap3 import Server, Connection, ALL, SUBTREE
|
||||
from ldap3.core.exceptions import LDAPException
|
||||
from app.config import Config
|
||||
|
||||
|
||||
class LDAPService:
|
||||
"""
|
||||
Handles authentication against an LDAP / OpenLDAP server using the
|
||||
standard "search + bind" pattern:
|
||||
1. Bind with a service/admin account just to SEARCH for the user's DN.
|
||||
2. Re-bind using that DN + the password the user typed, to verify it.
|
||||
The user's typed password is only ever used in step 2, never sent
|
||||
anywhere else.
|
||||
LDAP / Active Directory Authentication Service
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def authenticate(username, password):
|
||||
"""
|
||||
Authenticate LDAP User
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": True,
|
||||
"user": {
|
||||
"username": "...",
|
||||
"name": "...",
|
||||
"email": "..."
|
||||
}
|
||||
}
|
||||
|
||||
OR
|
||||
|
||||
{
|
||||
"success": False,
|
||||
"message": "Invalid username or password"
|
||||
}
|
||||
"""
|
||||
|
||||
if not username or not password:
|
||||
return None
|
||||
return {
|
||||
"success": False,
|
||||
"message": "Username and Password are required."
|
||||
}
|
||||
|
||||
server = Server(current_app.config["LDAP_SERVER"], get_info=ALL)
|
||||
|
||||
# --- Step 1: bind as the admin/service account to search the directory ---
|
||||
try:
|
||||
admin_conn = Connection(
|
||||
server,
|
||||
user=current_app.config["LDAP_BIND_DN"],
|
||||
password=current_app.config["LDAP_BIND_PASSWORD"],
|
||||
auto_bind=True,
|
||||
|
||||
# -----------------------------------
|
||||
# LDAP SERVER
|
||||
# -----------------------------------
|
||||
server = Server(
|
||||
Config.LDAP_SERVER,
|
||||
port=Config.LDAP_PORT,
|
||||
use_ssl=Config.LDAP_USE_SSL,
|
||||
get_info=ALL
|
||||
)
|
||||
except LDAPException as e:
|
||||
current_app.logger.error(f"LDAP service account bind failed: {e}")
|
||||
return None
|
||||
|
||||
# --- Step 2: find the user's real DN + profile attributes ---
|
||||
try:
|
||||
search_filter = current_app.config["LDAP_SEARCH_FILTER"].format(username=username)
|
||||
admin_conn.search(
|
||||
search_base=current_app.config["LDAP_BASE_DN"],
|
||||
# -----------------------------------
|
||||
# Login Format
|
||||
#
|
||||
# username@domain.com
|
||||
# -----------------------------------
|
||||
user_dn = f"{username}@{Config.LDAP_DOMAIN}"
|
||||
|
||||
conn = Connection(
|
||||
server,
|
||||
user=user_dn,
|
||||
password=password,
|
||||
authentication=SIMPLE,
|
||||
auto_bind=True
|
||||
)
|
||||
|
||||
# -----------------------------------
|
||||
# Search User
|
||||
# -----------------------------------
|
||||
search_filter = f"(sAMAccountName={username})"
|
||||
|
||||
conn.search(
|
||||
search_base=Config.LDAP_SEARCH_BASE,
|
||||
search_filter=search_filter,
|
||||
search_scope=SUBTREE,
|
||||
attributes=["cn", "mail", "uid"],
|
||||
attributes=[
|
||||
"displayName",
|
||||
"mail",
|
||||
"givenName",
|
||||
"sn",
|
||||
"cn"
|
||||
]
|
||||
)
|
||||
except LDAPException as e:
|
||||
current_app.logger.error(f"LDAP search failed for '{username}': {e}")
|
||||
admin_conn.unbind()
|
||||
return None
|
||||
|
||||
if not admin_conn.entries:
|
||||
current_app.logger.warning(f"LDAP user not found: {username}")
|
||||
admin_conn.unbind()
|
||||
return None
|
||||
display_name = username
|
||||
email = ""
|
||||
|
||||
entry = admin_conn.entries[0]
|
||||
user_dn = entry.entry_dn
|
||||
name = str(entry.cn) if "cn" in entry and entry.cn.value else username
|
||||
email = (
|
||||
str(entry.mail)
|
||||
if "mail" in entry and entry.mail.value
|
||||
else f"{username}@{current_app.config['LDAP_DOMAIN']}"
|
||||
if conn.entries:
|
||||
|
||||
entry = conn.entries[0]
|
||||
|
||||
if "displayName" in entry:
|
||||
display_name = str(entry.displayName)
|
||||
|
||||
if "mail" in entry:
|
||||
email = str(entry.mail)
|
||||
|
||||
conn.unbind()
|
||||
|
||||
current_app.logger.info(
|
||||
f"LDAP Login Success : {username}"
|
||||
)
|
||||
admin_conn.unbind()
|
||||
|
||||
# --- Step 3: the actual auth check - bind AS the user with their password ---
|
||||
try:
|
||||
user_conn = Connection(server, user=user_dn, password=password, auto_bind=True)
|
||||
user_conn.unbind()
|
||||
except LDAPException as e:
|
||||
current_app.logger.warning(f"LDAP authentication failed for '{username}': {e}")
|
||||
return None
|
||||
return {
|
||||
"success": True,
|
||||
"user": {
|
||||
"username": username,
|
||||
"name": display_name,
|
||||
"email": email
|
||||
}
|
||||
}
|
||||
|
||||
return {"username": username, "name": name, "email": email}
|
||||
except Exception as ex:
|
||||
|
||||
current_app.logger.warning(
|
||||
f"LDAP Login Failed : {username} : {str(ex)}"
|
||||
)
|
||||
|
||||
return {
|
||||
"success": False,
|
||||
"message": "Invalid Username or Password."
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
from flask import current_app
|
||||
from app.models.user_model import User
|
||||
from app.services.db_service import db
|
||||
from app.services.ldap_service import LDAPService
|
||||
from flask import current_app
|
||||
|
||||
class UserService:
|
||||
|
||||
@@ -10,57 +9,21 @@ class UserService:
|
||||
if User.query.filter_by(email=email).first():
|
||||
return None
|
||||
|
||||
user = User(name=name, email=email, auth_source="local")
|
||||
user = User(name=name, email=email)
|
||||
user.set_password(password)
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
current_app.logger.info("User list viewed")
|
||||
return user
|
||||
|
||||
@staticmethod
|
||||
def validate_login(identifier, password):
|
||||
"""
|
||||
identifier = whatever was typed in the login form. Can be an email
|
||||
(local users) or an LDAP username, depending on USE_LDAP_AUTH.
|
||||
"""
|
||||
if current_app.config.get("USE_LDAP_AUTH"):
|
||||
ldap_user = UserService._validate_ldap_login(identifier, password)
|
||||
if ldap_user:
|
||||
return ldap_user
|
||||
return None
|
||||
user = User.query.filter_by(email=identifier).first()
|
||||
def validate_login(email, password):
|
||||
user = User.query.filter_by(email=email).first()
|
||||
if user and user.check_password(password):
|
||||
return user
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _validate_ldap_login(username, password):
|
||||
ldap_info = LDAPService.authenticate(username, password)
|
||||
if not ldap_info:
|
||||
return None
|
||||
return UserService._get_or_create_ldap_user(ldap_info)
|
||||
|
||||
@staticmethod
|
||||
def _get_or_create_ldap_user(ldap_info):
|
||||
"""
|
||||
LDAP is the source of truth for the password. We still keep a row in
|
||||
our local `users` table (no password) so the rest of the app - which
|
||||
expects a User with an id - keeps working unchanged.
|
||||
"""
|
||||
user = User.query.filter_by(email=ldap_info["email"]).first()
|
||||
if user is None:
|
||||
user = User(
|
||||
name=ldap_info["name"],
|
||||
email=ldap_info["email"],
|
||||
auth_source="ldap",
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
elif user.name != ldap_info["name"]:
|
||||
user.name = ldap_info["name"]
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
@staticmethod
|
||||
def get_all_users():
|
||||
return User.query.all()
|
||||
|
||||
@@ -124,29 +124,14 @@
|
||||
<i class="bi bi-arrow-left-right me-2"></i> Client vs Subcontractor
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<!-- <li>
|
||||
<a class="dropdown-item" href="/file/client_vs_subcont">
|
||||
<i class="bi bi-arrow-left-right me-2"></i> Comparison Report
|
||||
</a>
|
||||
</li> -->
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<!-- Masters -->
|
||||
<li class="nav-item dropdown">
|
||||
<a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="/engi">
|
||||
<i class="bi bi-gear me-2"></i> Masters
|
||||
</a>
|
||||
<ul class="dropdown-menu dropdown-menu-dark">
|
||||
<!-- Client Standard Rates -->
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/engi/subcontractor-rate">
|
||||
<i class="bi bi-file-earmark-text me-1"></i> Rate Master
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<!-- Client Standard Rates -->
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/engi/client-rate">
|
||||
<i class="bi bi-file-earmark-text me-1"></i> Client Standard Rates
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<!-- Formats -->
|
||||
<li class="nav-item">
|
||||
@@ -155,78 +140,50 @@
|
||||
</a>
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
|
||||
<!-- USER DROPDOWN -->
|
||||
<li class="nav-item dropdown">
|
||||
{% if session.get("user_id") %}
|
||||
<li class="nav-item dropdown ms-lg-3">
|
||||
|
||||
<a class="nav-link dropdown-toggle d-flex align-items-center text-white"
|
||||
href="#" id="profileDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
|
||||
<i class="bi bi-person-circle fs-4"></i>
|
||||
<span class="ms-2 fw-semibold">
|
||||
<a class="nav-link dropdown-toggle d-flex align-items-center gap-2" href="#"
|
||||
data-bs-toggle="dropdown">
|
||||
<i class="bi bi-person-circle fs-5"></i>
|
||||
<span class="d-none d-lg-inline">
|
||||
{{ session.get("user_name") }}
|
||||
</span>
|
||||
</a>
|
||||
|
||||
<ul class="dropdown-menu dropdown-menu-end dropdown-menu-dark border-0 shadow-lg bg-dark p-0"
|
||||
style="width:320px;">
|
||||
<ul class="dropdown-menu dropdown-menu-end dropdown-menu-dark shadow">
|
||||
|
||||
<!-- Profile Header -->
|
||||
<li class="text-center py-4 border-bottom border-secondary">
|
||||
<i class="bi bi-person-circle text-light" style="font-size:60px;"></i>
|
||||
<h5 class="mt-2 mb-0 fw-bold">
|
||||
<!-- User card -->
|
||||
<li class="px-3 py-3 text-center border-bottom">
|
||||
<i class="bi bi-person-circle fs-1"></i>
|
||||
<div class="fw-semibold mt-1">
|
||||
{{ session.get("user_name") }}
|
||||
</h5>
|
||||
<small class="text-secondary">
|
||||
{{ session.get("email") }}
|
||||
</small>
|
||||
</div>
|
||||
<small class="text-muted">Logged in user</small>
|
||||
</li>
|
||||
|
||||
<!-- Dashboard -->
|
||||
<li>
|
||||
<a class="dropdown-item text-light py-2" href="{{ url_for('dashboard.dashboard') }}">
|
||||
<a class="dropdown-item" href="/dashboard">
|
||||
<i class="bi bi-speedometer2 me-2"></i> Dashboard
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<!-- Activity Log page -->
|
||||
<li>
|
||||
<a class="dropdown-item text-light py-2" href="{{ url_for('activity.activity') }}">
|
||||
<i class="bi bi-clock-history me-2"></i> Activity Log
|
||||
<a class="dropdown-item" href="{{ url_for('activity.activity') }}">
|
||||
<i class="bi bi-clock-history me-2"></i>
|
||||
Activity Log
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<!-- Manage Account -->
|
||||
<li>
|
||||
<a class="dropdown-item py-2" href="#">
|
||||
<i class="bi bi-gear me-2"></i> Manage Account
|
||||
<a class="dropdown-item text-warning" href="/logout">
|
||||
<i class="bi bi-box-arrow-right me-2"></i> Logout
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<li><hr class="dropdown-divider border-secondary m-0"></li>
|
||||
|
||||
<!-- Logout Account -->
|
||||
<li>
|
||||
<a class="dropdown-item text-warning py-2" href="{{ url_for('auth.logout') }}">
|
||||
<i class="bi bi-box-arrow-right me-2"></i>
|
||||
Logout
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<!-- Footer -->
|
||||
<li class="text-center py-3 bg-secondary bg-opacity-10 border-top border-secondary">
|
||||
<small class="text-light">
|
||||
<i class="bi bi-shield-check text-success"></i>
|
||||
Secured by <strong>LCEPL</strong>
|
||||
</small>
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
{% endif %}
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
@@ -379,6 +336,7 @@
|
||||
|
||||
showLoader();
|
||||
const btn = this.querySelector("button[type='submit']");
|
||||
const originalBtnHtml = btn ? btn.innerHTML : null;
|
||||
|
||||
if(btn){
|
||||
btn.disabled = true;
|
||||
@@ -388,10 +346,24 @@
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
setTimeout(function () {
|
||||
hideLoader();
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalBtnHtml;
|
||||
}
|
||||
}, 3000);
|
||||
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
window.addEventListener("pageshow", function () {
|
||||
hideLoader();
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@
|
||||
|
||||
<option value="dc"
|
||||
{% if request.form.get('category')=='dc' %}selected{% endif %}>
|
||||
Manhole Domestic Chamber
|
||||
Domestic Chamber
|
||||
</option>
|
||||
|
||||
<option value="laying"
|
||||
@@ -155,51 +155,61 @@
|
||||
</div>
|
||||
|
||||
{% if tables %}
|
||||
{% set show_all = (not selected_category) or selected_category == 'all' %}
|
||||
<!-- Tabs -->
|
||||
<div class="card shadow-sm border-0 mt-4">
|
||||
<div class="card-header bg-light">
|
||||
<ul class="nav nav-pills">
|
||||
<li class="nav-item">
|
||||
<button class="nav-link active" data-bs-toggle="tab" data-bs-target="#abstract">
|
||||
<button class="nav-link {% if show_all %}active{% endif %}" data-bs-toggle="tab" data-bs-target="#abstract">
|
||||
<i class="bi bi-file-earmark-text"></i> Abstract
|
||||
</button>
|
||||
</li>
|
||||
|
||||
{% if show_all or selected_category == 'tr' %}
|
||||
<li class="nav-item">
|
||||
<button class="nav-link " data-bs-toggle="tab" data-bs-target="#tr">
|
||||
<button class="nav-link {% if selected_category == 'tr' %}active{% endif %}" data-bs-toggle="tab" data-bs-target="#tr">
|
||||
<i class="bi bi-cone-striped"></i> Trench Excavation
|
||||
</button>
|
||||
</li>
|
||||
{% endif %}
|
||||
|
||||
{% if show_all or selected_category == 'mh' %}
|
||||
<li class="nav-item">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#mh">
|
||||
<button class="nav-link {% if selected_category == 'mh' %}active{% endif %}" data-bs-toggle="tab" data-bs-target="#mh">
|
||||
<i class="bi bi-nut"></i> Manhole Excavation
|
||||
</button>
|
||||
</li>
|
||||
{% endif %}
|
||||
|
||||
{% if show_all or selected_category == 'dc' %}
|
||||
<li class="nav-item">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#dc">
|
||||
<button class="nav-link {% if selected_category == 'dc' %}active{% endif %}" data-bs-toggle="tab" data-bs-target="#dc">
|
||||
<i class="bi bi-grid-3x3"></i> Manhole & Domestic Chambers Construction
|
||||
</button>
|
||||
</li>
|
||||
{% endif %}
|
||||
|
||||
{% if show_all or selected_category == 'laying' %}
|
||||
<li class="nav-item">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#laying">
|
||||
<button class="nav-link {% if selected_category == 'laying' %}active{% endif %}" data-bs-toggle="tab" data-bs-target="#laying">
|
||||
<i class="bi bi-bezier2"></i> Pipe Laying
|
||||
</button>
|
||||
</li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="card-body">
|
||||
<div class="tab-content">
|
||||
|
||||
<div class="tab-pane fade show active" id="abstract">
|
||||
<div class="tab-pane fade {% if show_all %}show active{% endif %}" id="abstract">
|
||||
{{ abstract_html|safe }}
|
||||
</div>
|
||||
|
||||
{% if show_all or selected_category == 'tr' %}
|
||||
<!-- Trench -->
|
||||
<div class="tab-pane fade "id="tr">
|
||||
<div class="tab-pane fade {% if selected_category == 'tr' %}show active{% endif %}" id="tr">
|
||||
<div class="mb-3">
|
||||
<button onclick="deleteSelected('tr')" class="btn btn-danger">
|
||||
<i class="bi bi-trash"></i> Delete Selected
|
||||
@@ -209,9 +219,11 @@
|
||||
{{ tables.tr|safe }}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if show_all or selected_category == 'mh' %}
|
||||
<!-- MH -->
|
||||
<div class="tab-pane fade" id="mh">
|
||||
<div class="tab-pane fade {% if selected_category == 'mh' %}show active{% endif %}" id="mh">
|
||||
<div class="mb-3">
|
||||
<button onclick="deleteSelected('mh')" class="btn btn-danger">
|
||||
<i class="bi bi-trash"></i>Delete Selected
|
||||
@@ -221,9 +233,11 @@
|
||||
{{ tables.mh|safe }}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if show_all or selected_category == 'dc' %}
|
||||
<!-- DC -->
|
||||
<div class="tab-pane fade" id="dc">
|
||||
<div class="tab-pane fade {% if selected_category == 'dc' %}show active{% endif %}" id="dc">
|
||||
<div class="mb-3">
|
||||
<button onclick="deleteSelected('dc')"class="btn btn-danger">
|
||||
<i class="bi bi-trash"></i>
|
||||
@@ -234,9 +248,11 @@
|
||||
{{ tables.dc|safe }}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if show_all or selected_category == 'laying' %}
|
||||
<!-- Laying -->
|
||||
<div class="tab-pane fade" id="laying">
|
||||
<div class="tab-pane fade {% if selected_category == 'laying' %}show active{% endif %}" id="laying">
|
||||
<div class="mb-3">
|
||||
<button onclick="deleteSelected('laying')"
|
||||
class="btn btn-danger">
|
||||
@@ -248,6 +264,7 @@
|
||||
{{ tables.laying|safe }}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -256,31 +273,45 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Reset
|
||||
document.getElementById("resetBtn").addEventListener("click", function () {location.reload();});
|
||||
|
||||
document.getElementById("resetBtn").addEventListener("click", function () {
|
||||
window.location.href = window.location.pathname;
|
||||
});
|
||||
|
||||
// DATATABLE
|
||||
$(document).ready(function () {
|
||||
$('.datatable').DataTable({
|
||||
|
||||
$('.datatable').each(function () {
|
||||
$(this).DataTable({
|
||||
pageLength: 10,
|
||||
dom: 'Bfrtip',
|
||||
buttons: ['copy', 'csv', 'excel', 'print']
|
||||
buttons: ['copy', 'csv', 'excel', 'print'],
|
||||
initComplete: function () {
|
||||
|
||||
$(this).closest('.dataTables_wrapper')
|
||||
.find('thead tr th:first-child')
|
||||
.html('<input type="checkbox" class="select-all" title="Select All">');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
$("table thead tr th:first-child").html('<input type="checkbox" id="select-all">');
|
||||
}, 500);
|
||||
// SELECT ALL — scoped to the checkbox's own table only
|
||||
$(document).on("change", ".select-all", function () {
|
||||
$(this).closest("table").find(".row-check").prop("checked", this.checked);
|
||||
});
|
||||
|
||||
// SELECT ALL
|
||||
$(document).on("change", "#select-all", function () {
|
||||
$(".row-check").prop("checked", this.checked);
|
||||
// If a row checkbox is unchecked manually, uncheck that table's select-all
|
||||
$(document).on("change", ".row-check", function () {
|
||||
if (!this.checked) {
|
||||
$(this).closest("table").find(".select-all").prop("checked", false);
|
||||
}
|
||||
});
|
||||
|
||||
// GET IDS
|
||||
function getSelectedIds() {
|
||||
|
||||
function getSelectedIds(model) {
|
||||
let ids = [];
|
||||
$(".row-check:checked").each(function () {
|
||||
$("#" + model + " .row-check:checked").each(function () {
|
||||
ids.push($(this).data("id"));
|
||||
});
|
||||
return ids;
|
||||
@@ -288,7 +319,7 @@
|
||||
|
||||
// BULK DELETE
|
||||
function deleteSelected(model) {
|
||||
let ids = getSelectedIds();
|
||||
let ids = getSelectedIds(model);
|
||||
if (ids.length === 0) return alert("Select records");
|
||||
|
||||
if (!confirm(`Delete ${ids.length} record(s)?`)) return;
|
||||
|
||||
@@ -17,11 +17,9 @@ services:
|
||||
build: .
|
||||
container_name: comparison_app
|
||||
restart: always
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
FLASK_ENV: production
|
||||
FLASK_DEBUG: "False"
|
||||
FLASK_ENV: development
|
||||
FLASK_DEBUG: "True"
|
||||
FLASK_HOST: "0.0.0.0"
|
||||
FLASK_PORT: "5001"
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
Flask
|
||||
ldap3
|
||||
pandas
|
||||
openpyxl
|
||||
xlrd
|
||||
@@ -10,3 +9,4 @@ xlsxwriter
|
||||
matplotlib
|
||||
flask_sqlalchemy
|
||||
flask_migrate
|
||||
weasyprint
|
||||
4
run.py
4
run.py
@@ -1,11 +1,15 @@
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
from app import create_app
|
||||
from app.services.db_service import db
|
||||
import os
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
|
||||
app.run(
|
||||
host=os.getenv("FLASK_HOST"),
|
||||
port=int(os.getenv("FLASK_PORT")),
|
||||
|
||||
Reference in New Issue
Block a user