Chettinad Academy Students: Adding a Simple Login System Safely in an Internship Project

Chettinad Academy Students: Adding a Simple Login System Safely in an Internship Project

Facebook
Twitter
LinkedIn
WhatsApp
Email

A safe beginner login system needs three things: passwords stored only as slow salted hashes (bcrypt or argon2), a short-lived signed JWT returned after a successful login, and middleware that rejects any request to a private route without a valid token. Get those three right, keep secrets out of your code, and test each failure case on purpose, and your internship project will be safer than most student apps.

This guide teaches that one skill and nothing else. It covers the logic, a compact illustrative implementation in Node.js and Express, a 14-day schedule that fits a short internship, and a security checklist in which every common mistake comes with a test you can run yourself.

What “safe” means for a login system in a beginner project

Authentication answers “who are you?” Authorization answers “what are you allowed to do?” Beginners often mix the two. Your first goal is authentication: prove a returning user is the same person who registered. The second goal is a simple authorization rule: a user can only read and change their own data.

You are not building a bank. You are building a small app where a stolen database or a curious classmate cannot easily expose real passwords or someone else’s records. Realistic goals for a two-week project are:

  • If your database leaks, attackers cannot read the passwords.
  • If someone guesses a URL, they cannot see private data without logging in.
  • If a token is stolen or expires, the damage is limited by its short life.
  • If someone tries a wrong password, the error message reveals nothing useful.

Password hashing: store a verifier, never the password

Hashing turns a password into a fixed-length string that cannot be reversed. At login you hash the attempt and compare it with the stored hash. Three details matter.

Use a password hashing function, not a fast hash

MD5, SHA-1 and plain SHA-256 are built to be fast, which helps attackers who test billions of guesses per second. bcrypt, scrypt and argon2 are deliberately slow and include a random salt, so two users with the same password get different hashes. For a Node.js beginner app, the bcrypt or bcryptjs package is a sensible choice.

Choose a cost factor you can justify

bcrypt has a “cost” (salt rounds). A value around 10 to 12 is a common starting point for small apps. Higher is slower for everyone, including your own server, so measure hashing time on your machine and avoid values so high that logins take seconds.

Never log or return the password or its hash

Strip passwordHash from every API response and never print request bodies containing passwords in your logs. This is one of the most common accidental leaks in student projects.

Free 2-Week CareerSwami Internship

Online, 14 days, with a free offer letter and a free completion certificate once you finish the work. Check with your college that it fits your requirement before you enrol.

Apply for the free internship

JWT sessions: what the token is and what it is not

A JSON Web Token has three Base64URL parts: header, payload and signature. The server signs the first two parts with a secret. Anyone can read the payload; only the server can produce a valid signature. That leads to the rules below.

  • Put only an identifier in the payload, such as the user ID in the sub claim. Never put passwords, phone numbers or other private data inside.
  • Set an expiry. A 15-minute access token is easy to implement. A longer-lived refresh flow is optional and usually out of scope for 14 days.
  • Keep the signing secret in an environment variable, long and random, and never commit it to GitHub.
  • Pin the algorithm when verifying (for example HS256) so a forged token cannot choose a weaker one.

Where should the browser keep the token?

There is no perfect answer, and the trade-off is worth understanding. A token in localStorage is simple but readable by any injected script (an XSS bug). A token in an HttpOnly cookie cannot be read by JavaScript, but you then need to think about CSRF, using SameSite cookies and, for state-changing requests, a CSRF defence. For a beginner project either is acceptable if you can explain the risk. If you use cookies, set HttpOnly, Secure (on HTTPS) and SameSite=Lax or Strict.

Protected routes: the middleware that does the real work

A protected route runs a small function before your handler. It reads the token, verifies the signature and expiry, attaches the user ID to the request, and stops with a 401 if anything fails. Hiding a link in the front end protects nothing, because anyone can call your API directly. Every private endpoint must be guarded on the server.

Illustrative Express example: register, log in, and guard a route

The snippet below is an illustrative sketch of the pattern, not a tested or production-ready codebase. Adapt it to your own structure and run your own tests. It assumes express, bcrypt and jsonwebtoken are installed, and that db is a placeholder for your database layer.

// auth.js (illustrative)
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const COST = 12;
const JWT_SECRET = process.env.JWT_SECRET; // long random value, never committed

async function register(req, res) {
  const { email, password } = req.body;
  if (!email || !password || password.length < 10) {
    return res.status(400).json({ error: 'Invalid email or password too short' });
  }
  const passwordHash = await bcrypt.hash(password, COST);
  await db.users.insert({ email: email.toLowerCase(), passwordHash });
  return res.status(201).json({ message: 'Registered' });
}

async function login(req, res) {
  const { email, password } = req.body;
  const user = await db.users.findByEmail((email || '').toLowerCase());
  const ok = user && await bcrypt.compare(password || '', user.passwordHash);
  if (!ok) {
    return res.status(401).json({ error: 'Invalid email or password' });
  }
  const token = jwt.sign({ sub: user.id }, JWT_SECRET, {
    algorithm: 'HS256',
    expiresIn: '15m'
  });
  return res.json({ token });
}

function requireAuth(req, res, next) {
  const header = req.headers.authorization || '';
  const [scheme, token] = header.split(' ');
  if (scheme !== 'Bearer' || !token) {
    return res.status(401).json({ error: 'Missing token' });
  }
  try {
    const payload = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] });
    req.userId = payload.sub;
    return next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid or expired token' });
  }
}

// app.get('/api/notes', requireAuth, async (req, res) => {
//   const notes = await db.notes.findByOwner(req.userId); // filter by owner
//   res.json(notes);
// });

Notice four choices in this sketch. The same error message is returned whether the email or the password was wrong. The notes query filters by req.userId, so one user cannot list another’s notes. The secret comes from the environment. And the token carries only an ID and an expiry.

Security checklist: common authentication mistakes and how to test each one

Use this table as a pass/fail list before you submit your project. Each test can be done with a browser, Postman, Thunder Client or curl.

# Common mistake Why it hurts How to test it
1 Storing plain-text or fast-hashed (MD5/SHA) passwords A leaked database exposes real passwords Register a user, open the database directly and confirm the stored value starts with a bcrypt prefix such as $2b$, not your password
2 Returning the hash in API responses Gives attackers offline material to crack Call login, register and any “get profile” endpoint and search the JSON for passwordHash
3 Different errors for “no such user” and “wrong password” Lets attackers discover which emails are registered Try a fake email and a real email with a wrong password; the message and status code should be identical
4 JWT secret hard-coded or pushed to GitHub Anyone with the secret can forge tokens for any user Search your repository and its history for the secret; confirm .env is in .gitignore and an .env.example has placeholder values only
5 No token expiry A stolen token works forever Decode a token at a JWT debugger and confirm an exp claim exists; temporarily set a 5-second expiry and confirm a later request returns 401
6 Private routes not guarded on the server Anyone can call the API directly Call every private endpoint with no token, a garbage token and an expired token; all must return 401
7 Not pinning the verification algorithm Forged tokens using unexpected algorithms may be accepted Confirm your verify call lists allowed algorithms; modify one character of a valid token’s signature and confirm rejection
8 Broken object-level access: any logged-in user can read any record User A reads User B’s data by changing an ID in the URL Log in as two users, create data as A, then request A’s record ID with B’s token; expect 403 or 404
9 Sensitive data inside the JWT payload Payloads are readable by anyone holding the token Paste your token into a JWT decoder and confirm only ID, issue time and expiry appear
10 No limit on login attempts Allows unlimited password guessing Send 20 wrong logins quickly; with a rate limiter such as express-rate-limit you should see 429 responses
11 Weak or missing password rules Users pick “123456” Try registering with a 3-character password and a common one; the first must be refused, and a minimum length (10+) is a good rule
12 Token in a cookie without flags Easier theft through scripts or insecure transport In browser dev tools, Application tab, confirm HttpOnly, Secure (on HTTPS) and SameSite are set
13 Using HTTP in the deployed demo Credentials travel in readable form Open the deployed URL and confirm HTTPS is enforced before sharing it
14 Secrets or passwords printed in logs Logs are often shared when debugging Log in once, then read your terminal and log files for the password string

Worked illustrative test run: catching an ownership bug

This scenario is illustrative, to show the thinking behind check #8. Imagine a notes app where GET /api/notes/:id is wrapped in requireAuth but the handler runs db.notes.findById(req.params.id) with no owner check.

  1. Register two users, Asha and Ravi.
  2. Log in as Asha, save her token, and create a note. Say it gets ID 7.
  3. Log in as Ravi and send GET /api/notes/7 with Ravi’s token.
  4. If the response shows Asha’s note, the route is authenticated but not authorized. That is a real bug even though your “no token” test passed.
  5. Fix it by querying with both values: findOne({ id: req.params.id, ownerId: req.userId }). Return 404 when nothing matches.
  6. Repeat step 3. Ravi should now get 404, and Asha should still get her note.

Write this test down in your README. A reviewer reading “tested cross-user access with two accounts” learns more about your care than any feature list.

Chettinad Academy students: placing a login-system project in your own academic context

CARE’s admissions page describes it as a Deemed-to-be University at Chettinad Health City, Kelambakkam, established under the UGC Act. That is an admissions-page description, so treat the wording as a starting point and check the current page. The official home page lists the university’s faculties and schools, including Medicine, Allied Healthcare Sciences, Nursing, Architecture, Pharmaceutical Sciences, Physiotherapy, Occupational Therapy and Law.

Why does that matter for a login-system project? Your department may be in any of those areas, or you may be building a web project as an elective skill. A login system is useful well beyond computer science: a clinic appointment tracker, a pharmacy stock sheet or a design portfolio with private client pages all need protected routes. If you handle anything resembling patient or client information, even as fake sample data, build the safe habits from this guide from day one.

The home page also links to a central Examination Section, an Academic Bank of Credits page and a Project / Dissertation Template page for PG programmes, plus a “Form of Internship” PDF and an “Intern Care” section that appear to relate to the medical internship rather than a web project. A CDCT page is also linked, and its function is unconfirmed. Treat all of these as pointers to ask about, not as rules that cover your internship. The academic calendar page lists yearly PDFs, so use the official academic calendar to plan your 14 days around exams and breaks.

Verification steps before you rely on this internship for anything official

  1. Ask your department office or class coordinator, in writing, whether a self-chosen online internship is recognised for your programme and what document they accept as proof.
  2. Ask whether any credit, internship-hours or project requirement exists for your scheme, and request the regulation or circular that states it by name and year.
  3. Open the CDCT page and ask that office whether it handles internship letters, verification or training support for your school.
  4. Download the 2026-27 calendar from the official calendar page and mark the exam and holiday dates, then fix your 14 days in a clear window.
  5. If you handle any real personal data, even from a class exercise, ask your faculty mentor what data-handling rules apply before you collect it.

A 14-day plan for building and testing the login system

The free two-week online internship from CareerSwami runs for 14 days and includes a free offer letter and a free completion certificate after successful completion. It has 26 tracks, and this plan fits a Full Stack Web Development project in that window. Adjust the pace to your own schedule.

Days Focus Output to show
1-2 Project setup, user model, environment variables, .gitignore Repository with .env.example and no secrets
3-4 Registration with validation and bcrypt hashing Database screenshot showing hashes only
5-6 Login endpoint, generic error messages, JWT with expiry Decoded token showing ID and exp only
7-8 requireAuth middleware and one private resource Requests returning 401 with no, bad and expired tokens
9-10 Ownership checks and a basic front end (login form, token handling) Two-user cross-access test passing
11 Rate limiting and password rules 429 response after repeated failures
12 Run the full checklist table above Completed pass/fail list in the README
13 Deploy over HTTPS, re-test on the live URL Working demo link
14 README, short demo video, final cleanup Submission-ready project

What to put in your README so reviewers see the security thinking

  • A short “Security decisions” section: hashing algorithm and cost, token lifetime, where the token is stored and why.
  • The checklist with a pass or fail note for each row, and an honest “not implemented” for anything you skipped, such as refresh tokens.
  • Setup steps using .env.example, so a reviewer can run the app without your real secret.
  • Known limitations, for example “no password reset flow” or “no email verification”.

Frequently Asked Questions

Is bcrypt enough, or should I use argon2?

For a beginner project, bcrypt with a sensible cost is a well-understood choice and is enough. Argon2 is a newer option and is also fine if your library supports it. What matters most is avoiding plain text and fast hashes, and being able to explain your choice.

Can I store the JWT in localStorage?

You can, and many tutorials do. The risk is that any script injected through an XSS bug can read it. An HttpOnly cookie reduces that risk but brings CSRF considerations. Pick one, write down the trade-off in your README and keep your front end free of unsafe HTML rendering either way.

How long should a token last?

Short for access tokens. Fifteen minutes to an hour is common in small projects. If that makes users log in too often, a refresh-token design is the next step, but it adds complexity that may not fit in 14 days.

Do I need to log users out on the server?

With plain stateless JWTs, logout usually means deleting the token on the client and letting it expire. True server-side revocation needs a denylist or session table. For a first project, short expiry plus client-side deletion is acceptable, provided you say so.

Why return the same error for a wrong email and a wrong password?

Different messages let an attacker check which emails have accounts. A single message such as “Invalid email or password” gives away nothing. Also compare hashes even when the user is not found if you want to reduce timing differences, though that refinement is optional at this level.

Should I build login myself or use a service like Firebase Auth or Auth0?

Hosted services are often the safer choice for real products. For learning, building the flow once yourself shows what those services do for you. You could say in your README that a production version would likely move to a managed provider.

Will this project count for credit at my college as a Chettinad Academy of Research and Education student?

CareerSwami’s internship offers a free offer letter and completion certificate, not academic credit. Whether your department recognises it for any requirement is a decision for your college, so ask in writing using the verification steps above.

Is it safe to test with real passwords?

No. Use throwaway test accounts and made-up passwords, never one you use anywhere else, and delete test data before sharing a database dump or demo.

Related Full Stack Web Development guides

Ready to put this into practice?

Join the free two-week CareerSwami online internship in Full Stack Web Development. The internship, the offer letter and the completion certificate are free.

Start your free 2-week internship

Web Stories

Scroll to Top