DEV Community

Cover image for From Broken Auth Template to Production-Grade Project Management API β€” Finished with GitHub Copilot
Ali Haroon
Ali Haroon

Posted on

From Broken Auth Template to Production-Grade Project Management API β€” Finished with GitHub Copilot

GitHub β€œFinish-Up-A-Thon” Challenge Submission

GitHub Copilot Finish-Up-A-Thon Challenge submission β€” May 21–June 7, 2026.

πŸ”— Project Source


Every developer has that one folder. The one with a half-built project that got shelved mid-way, full of potential but never shipped. Mine was a Node.js authentication boilerplate β€” 12 files, a working register endpoint, and 8 silent bugs that made the entire password-reset flow fail without a single error message.

This challenge gave me the perfect reason to open it back up. What I shipped after 4 days with GitHub Copilot is something I'm genuinely proud of.


The Before: An Honest Assessment

Before writing a single line of new code, I ran a full audit on what I actually had.

The project i did'nt even touch from last 3 moonths My initial codebase:

My initial codebase: 12 files, auth-only, 8 bugs, no task management, no error handling, ~55% complete.

Here is what I found:

What was working (sort of):

  • User registration and login β€” but login only accepted email, ignoring the username field it was receiving
  • JWT middleware β€” but with a dead { header } import from express-validator sitting at the top
  • Email verification flow β€” but the verification URL in every email was pointing to /api/v1/users/verify-email/ which didn't exist
  • Forgot password β€” completely broken because forgotPasswordMailgenContent was imported in auth.controllers.js but never actually imported from mail.js

What was silently broken:

The most dangerous bug was in resetForgotPassword. The token lookup was doing:

crypto.createHash("sha-256") // ← wrong
Enter fullscreen mode Exit fullscreen mode

The correct algorithm name in Node.js crypto is "sha256" β€” no hyphen. This meant every single password reset attempt would silently fail to find the user in the database and return "Token is invalid or expired" β€” even for a valid token that was seconds old. A user would never know why.

Eight bugs total. None of them throwing loud errors. All of them breaking real user flows.


Phase 1: The Git Branching Wall β€” My First Real Fear

I need to be honest about something before I talk about code.

When I saw the challenge requirement β€” "work must be done on a separate branch"
β€” my first reaction was anxiety, not excitement.

Branches. Merging. Checkout. These words had always looked intimidating to me.
I had been using Git for months but only ever on main. One branch.
Push and pray. The mental model of parallel branches, switching between them,
and then merging them back together genuinely confused me. I had avoided it
completely.

The challenge didn't give me that option.

So I sat down, read the docs properly for the first time, and actually understood
what a branch is β€” it's just a pointer to a commit. A safe copy of your work
where you can build freely without touching the original. That's it.
The terminology had made it sound far more complicated than it actually was.

git checkout -b copilot-challenge-submission
git push origin copilot-challenge-submission
Enter fullscreen mode Exit fullscreen mode

Two commands. Branch created, pushed to GitHub.
The thing I had been afraid of for months took about 90 seconds.

The branch on GitHub
The branch on GitHub

This is one of those lessons that only clicks when you have a real reason
to do it. The challenge forced my hand and I am genuinely grateful for that.
I now understand branching, I understand why teams use it, and I understand
how to merge back to main when the work is done. A wall I had been walking
around for months turned out to be a door I just hadn't tried to open.

I kept the original broken code on main intentionally β€” as honest
documentation of where I started. The entire transformation lives on
copilot-challenge-submission. Anyone can compare the two branches on GitHub
and see exactly what changed.


Phase 2: Setting Up the Right Way

The challenge required work on a dedicated branch, which aligned perfectly with good Git hygiene. I created copilot-challenge-submission from main to keep the original skeleton untouched and build the finished version on top.

new copilot-challenge-submission branch for Copilot challenge
Branch created, Copilot sidebar active in VS Code. Ready to go.

One important early step: adding ADMIN_SECRET to the .env file. The original codebase accepted a role field on registration with zero protection β€” anyone could register as "admin" by just passing "role": "admin" in the body. Copilot helped me add a secret-key guard:

// anyone can register, but claiming admin requires the secret key
let assignedRole = "member";
if (role === "admin" || role === "project_admin") {
    if (adminSecret !== process.env.ADMIN_SECRET) {
        throw new ApiError(403, "Invalid admin secret key");
    }
    assignedRole = role;
}
Enter fullscreen mode Exit fullscreen mode

Small change. Massive security difference.


Phase 3: Fixing the Bugs with Copilot

I opened each broken file and used Copilot Chat (sidebar) to describe what I was seeing. The workflow was:

  1. Open the file in VS Code
  2. Describe the symptom to Copilot: "This function always returns 'token invalid' even for fresh tokens β€” why?"
  3. Copilot would identify the issue and suggest the fix
  4. I reviewed, understood, and accepted

Copilot identifying the sha-256 hash algorithm bug
Copilot identifying the sha-256 hash algorithm bug. The fix is one character β€” removing the hyphen β€” but finding it without AI would have taken much longer.

Here is the full bug list, fixed in one focused session:

# Bug File Impact
1 sha-256 β†’ sha256 in crypto hash auth.controllers.js Password reset always failed
2 forgotPasswordMailgenContent not imported auth.controllers.js ReferenceError in production
3 action and outro outside body in email template mail.js Forgot-password email had no button
4 HTTP status 489 (not real) auth.controllers.js Invalid response code
5 Login only searched by email, ignored username auth.controllers.js Username login silently failed
6 Route typo /resend-emil-verification auth.routes.js Endpoint unreachable
7 Dead { header } import auth.middleware.js Lint noise, dead code
8 Verify email URL had /users/ not /auth/ auth.controllers.js Every verification email 404'd

After fixing all 8: npm run dev β†’ register β†’ check Mailtrap β†’ click verify link β†’ 200 OK. First time that flow had ever actually worked end to end.


A Note on Honesty: When Copilot Wasn't Enough

GitHub Copilot was my primary tool throughout this sprint β€”
but I want to be transparent about something.

Copilot has usage limits. There were moments, especially during
the longer building sessions on Day 3 and Day 4, where I hit
those limits mid-flow. A schema half-written. A controller
function halfway through. The suggestion stream would slow down
or stop responding the way it had been.

In those moments, I did what any developer would do β€”
I used what was available. I turned to other LLMs (Claude and
ChatGPT at different points) to keep the momentum going,
asked similar questions, got the code, reviewed it the same way
I reviewed Copilot's output, and kept building.

I am mentioning this because I think honesty matters more than
a clean narrative. The challenge is called a "Finish-Up-A-Thon"
β€” the goal is to finish the project. The AI tools I used were
assistants, not authors. Every line of generated code went
through my eyes, my understanding, and my decision to accept,
modify, or reject it.

What I can say with confidence: GitHub Copilot inside VS Code β€”
the inline suggestions, the Chat sidebar, the Ctrl+I inline
chat β€” handled the majority of the heavy lifting.
The workflow of describing what I wanted in plain English and
getting working code back in seconds is genuinely transformative
for a developer at my stage.

The bug-finding session on Day 1 was almost entirely Copilot.
The activity logger pattern β€” Copilot. The RBAC middleware β€”
Copilot. The Swagger JSDoc annotations across 40+ routes β€”
Copilot with some Claude assistance when the limit hit.

I learned from all of it. That is what matters.


Phase 4: Building What Was Always Missing

With a stable auth foundation, I shifted to building the actual project management system. This is where Copilot went from debugging tool to genuine pair programmer.

The Data Models

I navigated to src/models/ and used Copilot Inline Chat (Ctrl+I) to scaffold each new schema. My prompt style was always specific about relationships:

"Create a Mongoose schema for a Project model. It should have name, description, status (enum: active/on_hold/completed/cancelled), a createdBy ObjectId ref to User, and a members array where each member has a user ObjectId ref and a role string. Add compound indexes for createdBy and members.user."

Four new models created:

src/models/
β”œβ”€β”€ project.models.js    ← Project with embedded members[]
β”œβ”€β”€ task.models.js       ← Updated: added priority, dueDate, project ref
β”œβ”€β”€ comment.models.js    ← Comments on tasks
└── activity.models.js   ← Audit log for every action
Enter fullscreen mode Exit fullscreen mode

The Activity Logger β€” My Favourite Part

The most elegant piece of the system is the logActivity() utility. It gets called after every meaningful action across every controller β€” but it's designed to never crash the main request even if it fails:

export const logActivity = async (action, entity, entityId, userId, metadata = {}) => {
    try {
        await ActivityLog.create({ action, entity, entityId, performedBy: userId, metadata });
    } catch (err) {
        // Silently swallow β€” logging must never break a real request
        console.error("Activity log failed silently:", err.message);
    }
};
Enter fullscreen mode Exit fullscreen mode

Now every create, update, delete, login, and comment is recorded. Admins can query GET /api/v1/activity and see a full audit trail. Members see only their own activity.

I described this pattern to Copilot and it immediately suggested the try/catch wrapper with the silent swallow β€” a pattern I had read about but never implemented myself.

Task Management: More Than a Todo List

The original constants.js had TaskStatusEnum defined (todo, In_progress, done) but no task model, no routes, and no controllers. The constants were written but the feature was never built.

I added TaskPriorityEnum to match:

export const TaskPriorityEnum = {
    LOW: "low",
    MEDIUM: "medium",
    HIGH: "high",
    URGENT: "urgent",
};
Enter fullscreen mode Exit fullscreen mode

Then built the full task system on top β€” with one GET /tasks endpoint that does everything:

GET /api/v1/tasks?search=login&priority=urgent&overdue=true&sortBy=dueDate&order=asc&page=1&limit=10
Enter fullscreen mode Exit fullscreen mode

That single endpoint handles full-text search across title and description, filter by status/priority/assignee/project, overdue detection, sorting, and pagination β€” all composable together.


The Tool I Had Never Seen Before: Swagger

I want to be upfront about something β€” before this challenge,
I had never used Swagger in my life.

I had heard the word. I had seen screenshots of it in tutorials.
But I had never actually sat down, configured it, and had it
generate live documentation from my own code.

When I first ran npm run dev after wiring up swagger-ui-express
and opened http://localhost:8000/api/v1/docs β€” I genuinely did
not expect what I saw. Every single route, laid out visually.
Request bodies with example values. A padlock icon showing which
routes needed authentication. A "Try it out" button that let me
test my own API without opening Postman.

I spent probably 20 minutes just clicking through it before I
remembered I had more features to build.

Swagger UI on my own project
My first time seeing Swagger UI on my own project.
Every route documented, explorable directly in the browser.

The learning curve was real though. My first Swagger setup
showed "No parameters" on every POST route β€” because I had
forgotten that Swagger needs JSDoc @swagger comments above
each route to know what the request body looks like.
The routes existed and worked perfectly, but Swagger had no
idea what data they expected.

Here is what an empty POST route looks like in Swagger vs
a documented one:

// ❌ Before β€” Swagger shows "No parameters"
router.route("/projects").post(createProject);

// βœ… After β€” Swagger shows a full interactive form
/**
 * @swagger
 * /api/v1/projects:
 *   post:
 *     summary: Create a new project
 *     tags: [Projects]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - name
 *             properties:
 *               name:
 *                 type: string
 *                 example: My Awesome App
 *               status:
 *                 type: string
 *                 enum: [active, on_hold, completed, cancelled]
 *                 example: active
 */
router.route("/projects").post(createProject);
Enter fullscreen mode Exit fullscreen mode

Once I understood the pattern, documenting every route became
satisfying rather than tedious. You write the comment once,
and Swagger generates a fully interactive UI from it.
Any developer who clones the repo can open /api/v1/docs,
authorize with their JWT token, and test every single endpoint
without reading a single line of code.

That is what "production-grade API documentation" actually means.
I understood the concept before this project.
Now I understand why it matters.

get tasks
POST /tasks with all fields filled β€” title, priority urgent,
due date set. One click to Execute. This is what
"Try it out" looks like in practice.


Phase 5: The Features That Make It Shine

Projects with Member Access Control

POST   /api/v1/projects               ← create (creator auto-becomes project_admin)
GET    /api/v1/projects               ← list projects I created + am member of
GET    /api/v1/projects/:id           ← project detail + all its tasks
PATCH  /api/v1/projects/:id           ← update (project_admin or owner)
DELETE /api/v1/projects/:id           ← delete (owner only, unlinks tasks)
POST   /api/v1/projects/:id/members   ← add member with role
DELETE /api/v1/projects/:id/members/:userId  ← remove member
Enter fullscreen mode Exit fullscreen mode

Non-members get a clean 403 when trying to access a project they don't belong to. The PROJECT_ADMIN role that was defined in the original constants.js but never enforced now actually does something.

Task Comments

Three routes, one model, makes the whole system feel collaborative:

POST   /api/v1/tasks/:taskId/comments          ← add comment
GET    /api/v1/tasks/:taskId/comments          ← paginated list
DELETE /api/v1/tasks/:taskId/comments/:id      ← delete own comment (or admin)
Enter fullscreen mode Exit fullscreen mode

Deleting a task cascade-deletes all its comments. getTaskById now includes a commentsCount field.

Dashboard Stats

GET /api/v1/tasks/stats
Enter fullscreen mode Exit fullscreen mode

Returns:

{
  "stats": {
    "total": 24,
    "byStatus": { "todo": 10, "In_progress": 9, "done": 5 },
    "byPriority": { "urgent": 3, "high": 7, "medium": 11, "low": 3 },
    "myTasks": 6,
    "overdueTasks": 2,
    "recentTasks": [...]
  }
}
Enter fullscreen mode Exit fullscreen mode

One endpoint. Everything a frontend dashboard needs.


The Final API Surface

Auth β€” /api/v1/auth

Method Endpoint Auth
POST /register β€”
POST /login β€”
POST /logout JWT
GET /current-user JWT
GET /verify-email/:token β€”
POST /resend-email-verification JWT
POST /refresh-token β€”
POST /forgot-password β€”
POST /reset-password/:token β€”
POST /change-password JWT
PATCH /update-avatar JWT
PATCH /update-profile JWT

Tasks β€” /api/v1/tasks Β· Projects β€” /api/v1/projects Β· Activity β€” /api/v1/activity


Production Signals Added

Signal Implementation
Security headers helmet() β€” 11 headers set automatically
Rate limiting express-rate-limit β€” 10 req/15 min on auth endpoints
Request logging morgan β€” dev mode and combined production format
Global error handler 4-param Express middleware β€” no stack traces to clients
404 handler Custom JSON response for unknown routes
Input validation express-validator on all auth routes
File upload validation multer with type filter (JPEG/PNG/WebP) + 2MB limit
API documentation Swagger UI + swagger-jsdoc, OpenAPI 3.0
Audit logging Every meaningful action logged with metadata
RBAC verifyRole() middleware enforced at route level

Postman Proof

User registration
User registration returning 201 with the created user object (sensitive fields excluded).

User registration For Admin user
User registration For Admin user returning 201 with the created user object (sensitive fields excluded).

Login returning
Login returning access token, refresh token, and user object. Tokens auto-saved to Postman environment via test script.

aggregated counts by status
Dashboard stats endpoint β€” aggregated counts by status and priority.

Activity feed
Activity feed showing audit trail of all actions.

deleting Task
RBAC working correctly β€” member role correctly blocked from deleting tasks.


What GitHub Copilot Actually Did

I want to be specific because "I used Copilot" is easy to say.

Copilot found bugs I would have stared at for hours. The sha-256 vs sha256 issue β€” I had been running the reset flow and getting "token expired" responses. I described the symptom to Copilot Chat and it immediately asked "is the hash algorithm name correct in Node.js crypto?" β€” and that was it. Five seconds.

Copilot taught me patterns I knew existed but hadn't implemented. The silent-swallow try/catch in logActivity(). The $or MongoDB query for login by email or username. The validateBeforeSave: false pattern in Mongoose saves. I knew all of these things conceptually. Copilot showed me the exact idiomatic way to write them.

Copilot accelerated schema and boilerplate generation. Every new model, every new controller β€” I described what I wanted in plain English and got working code back in seconds. I reviewed every suggestion before accepting. I rejected probably 20% and adjusted another 30%. But starting from something working is dramatically faster than starting from blank.

Copilot didn't write the architecture. The decision to use an embedded members[] array in Project rather than a separate collection β€” that was mine. The fire-and-forget logger pattern β€” I described it to Copilot and it implemented it. The overdue filter composing with other query params β€” my design, Copilot's implementation. This felt like genuine pair programming.


What I Learned

Finishing is harder than starting. Starting a project is exciting β€” you make fast decisions and the wins come quickly. Finishing means auditing what you have, being honest about what's broken, and fixing unglamorous bugs before adding new features. The 8-bug fix session on Day 1 was the most important thing I did.

The "silent failure" is the worst kind of bug. Six of my eight bugs produced no error β€” they just returned wrong data or hit a route that didn't exist. Without end-to-end testing, you'd never find them. With Copilot, describing the symptom was enough to surface the cause.

AI pair programming works best when you lead. The best outputs came when I was specific: "This function needs to search by email OR username using MongoDB's \$or operator β€” modify the findOne call" produced better results than "fix my login function." Copilot responds to context and intent. The more precisely I described what I wanted, the less reviewing and editing I had to do.

Git branching went from intimidating to obvious. I had avoided branches
for months because the terminology looked complex. The challenge requirement
forced me to actually do it β€” and it took two commands. Sometimes the only
way to stop fearing a tool is to have no choice but to use it.


Links

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.