What my register endpoint does before it saves anyone: transactions, soft deletes, and a poka-yoke in NestJS
I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service), and this time it's about the auth service: what actually happens when someone registers or logs in.
The save is the last thing that happens.
Registering is a transaction, not a save call
My register method doesn't call save() on a new user right away. It opens a transaction first, because two weird cases live inside it:
async register(registerDto: RegisterDto) {
const { username, password, role } = registerDto;
return await this.dataSource.transaction(async (manager) => {
const transactionalRepo = manager.getRepository(UserAccount);
const existingUser = await transactionalRepo.findOne({
where: { username },
});
if (existingUser) {
if (!existingUser.isDeleted) {
throw new ConflictException(`Registration Failed: The username '${registerDto.username}' already exists.`);
}
// Restore soft-deleted user
const hashedPassword = await bcrypt.hash(password, 10);
Object.assign(existingUser, {
password: hashedPassword,
userType: role || Role.STUDENT,
isDeleted: false,
});
const savedUser = await transactionalRepo.save(existingUser);
const { password: _, ...result } = savedUser;
return result;
}
const hashedPassword = await bcrypt.hash(password, 10);
// Poka-Yoke: Public registration strictly creates STUDENT role
const newUser = transactionalRepo.create({
username,
password: hashedPassword,
userType: Role.STUDENT,
});
const savedUser = await transactionalRepo.save(newUser);
const { password: _, ...result } = savedUser;
return result;
});
}
Three things going on here.
First, the whole method runs inside dataSource.transaction. If anything throws, nothing is half-saved. For a school attendance system this matters: a user row that exists without its related setup is a bug waiting for a demo.
Second, the soft-delete case. My users are soft-deleted (isDeleted flag), so a username can be "taken" by an account that doesn't really exist anymore. If I just threw "username already exists" for those, a returning student could never get their old username back. So if the existing row is soft-deleted, I reactivate it: new hashed password, isDeleted: false. If it's a live account, then it's a real conflict.
Third, my favorite line in the file: // Poka-Yoke: Public registration strictly creates STUDENT role. Even if the request body says role: "admin", a new public registration becomes a STUDENT. The DTO accepts a role, and the service ignores it. I wrote about the guard side of this in my first post; this is the same idea at the write layer. You can't register yourself into power.
Also notice the return: const { password: _, ...result } = savedUser. The hashed password never leaves the method, even hashed.
Login has a migration fallback I didn't expect to need
The login method is mostly normal: find the user, bcrypt.compare, sign a token. But there's a branch in it that exists because of how the project grew:
let isMatch = await bcrypt.compare(password, user.password);
// [Migration Fallback] If Bcrypt fails, check if the password was
// stored as plain-text (old users).
if (!isMatch && password === user.password) {
isMatch = true;
// Automatically hash the plain-text password for future logins.
user.password = await bcrypt.hash(password, 10);
await this.userRepository.save(user);
}
Early seed users had plain-text passwords in the database. I didn't want to write a one-off migration script for a handful of rows, so the login path does the migration itself: if bcrypt fails but the stored value equals what you typed, it lets you in once and immediately rehashes your password with bcrypt. From that login on, the plain-text copy is gone.
Is this how I'd do it in a bigger system? No. It means a plain-text comparison runs on every failed bcrypt check, and the fallback stays in the code forever unless someone removes it. For a student project with a small user table it got the job done, and I learned the pattern exists. Being honest about it is part of why I'm writing these posts.
The rest of login is a role check (if the client says "I'm logging in as staff", the stored role has to match) and then the token.
The token is small on purpose
The whole payload is three fields:
export interface JwtPayload {
sub: number;
username: string;
role: Role;
}
And the strategy just turns that back into the request user:
async validate(payload: JwtPayload) {
return {
userAccountId: payload.sub,
userId: payload.sub,
username: payload.username,
userType: payload.role,
role: payload.role
};
}
The duplicate fields (userAccountId and userId, userType and role) are there because different parts of the codebase grew up reading different names. Not pretty, but it means the guards from my first post get role where they expect it and older code gets userType where it expects that.
What goes into the token matters because everything after login trusts it. Three fields is enough: who you are, and what you're allowed to be.
What I take from this
- The interesting part of an auth endpoint is usually everything around the hash: transactions, soft deletes, and forcing safe defaults.
- Migration fallbacks inside business logic work, but they're a debt note. Write them down, or they become permanent.
- Keep tokens tiny. Every claim you add is something you have to keep true.
Everything above is from the real repo. I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) in Alexandria, Egypt, open to junior roles and freelance work.
More posts from this project:
- Circuit breaker + WAL engine: https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp
- The NestJS-to-Python boundary: https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g
- GitHub: https://github.com/ZiadtahaM
- Email: zia**********@gmail.com
- dev.to: https://dev.to/ziadtaha
Comments
No comments yet. Start the discussion.