User Management & Authentication
Relevant source files
The following files were used as context for generating this wiki page:
- packages/core/src/services/users/UsersAuthService.ts
- packages/core/src/auth/jwt.strategy.ts
- packages/common/src/entities/User.ts
- packages/admin-web-angular/src/app/@core/auth/admin-auth.guard.ts
- packages/core/src/services/users/UsersService.ts
- packages/admin-web-angular/src/app/app.module.ts
- packages/shop-mobile-expo/src/screens/authentication/SignUp.screen.tsx
- packages/core/src/services/services.app.ts
The User Management and Authentication system is a core component of the Ever Demand platform, providing a secure and robust mechanism for handling user identity across various client applications. Built on the NestJS framework, it leverages Passport.js for authentication strategies, primarily using JSON Web Tokens (JWT) for session management. The system is designed to be headless, serving multiple frontends including an Angular admin panel and mobile apps.
This system is responsible for user registration (local, social), login, password management, and securing API endpoints. It defines a comprehensive User data model and exposes its functionality through a GraphQL API, enabling seamless integration with different client-side technologies.
User Data Model
The central entity for user management is the User entity, which is defined using TypeORM decorators. It stores essential user information, profile details, and relationships to other parts of the system.
Sources: packages/common/src/entities/User.ts
Entity Relationship Diagram
The diagram below illustrates the structure of the User entity and its relationship with the embedded GeoLocation entity.
User Entity Fields
The User entity contains the following fields:
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier for the user (ObjectID). |
firstName | string | The user's first name. |
lastName | string | The user's last name. |
email | string | The user's email address. Must be unique. |
phone | string | The user's phone number. |
image | string | URL to the user's profile picture. |
password | string | The hashed password for the user. |
apartment | string | The user's apartment number. |
geoLocation | GeoLocation | Embedded object containing the user's address information. |
isBanned | boolean | Flag to indicate if the user is banned. Defaults to false. |
isDeleted | boolean | Flag for soft-deleting the user. Defaults to false. |
stripeCustomerId | string | The customer ID from the Stripe payment gateway. |
socialIds | string[] | An array of IDs from social login providers. |
_createdAt | Date | Timestamp of when the user was created. |
_updatedAt | Date | Timestamp of the last update. |
Sources: packages/common/src/entities/User.ts:18-100
Backend Authentication
The backend authentication is handled by the @ever-platform/core package, using NestJS modules and services. It relies on Passport.js and JWTs.
Core Components
UsersAuthService: The primary service for handling authentication logic. It orchestrates user validation, registration, and token generation.UsersService: Manages CRUD operations for theUserentity, including creating new users during registration and retrieving user data.JwtStrategy: A Passport.js strategy that validates incoming JWTs from theAuthorizationheader to protect endpoints.
Sources: packages/core/src/services/users/UsersAuthService.ts, packages/core/src/auth/jwt.strategy.ts, packages/core/src/services/users/UsersService.ts
Local Authentication Flow (Login)
The login process validates a user's credentials and, if successful, returns a JWT.
- A client sends a
loginrequest with an email and password. UsersAuthService.login()is called.- It calls
validateUser()to check the email and compare the provided password with the stored hash. - If validation is successful,
JwtService.sign()is used to generate anaccess_token. - The token is returned to the client.
The following sequence diagram illustrates this flow:
Registration Flow
The registration process creates a new user in the database.
- A client sends a
registerrequest with user details (email, password, name, etc.). UsersAuthService.register()is called.- It first checks if a user with the given email already exists using
UsersService.isUserEmailExists(). - If the email is unique, it hashes the password using
bcrypt. - It then calls
UsersService.create()to save the new user to the database. - Finally, it logs the new user in by calling
login()to generate and return a JWT.
This flow is visible in client applications like the Expo mobile app, which uses the REGISTER_USER_MUTATION to interact with the backend.
Sources: packages/core/src/services/users/UsersAuthService.ts:74-106, packages/shop-mobile-expo/src/screens/authentication/SignUp.screen.tsx:274-358
Social Authentication
The platform supports social authentication via Google and Facebook. This is configured in ServicesApp using Passport.js strategies.
- The
_passportSetupmethod initializespassport. - The
SocialStrategiesServiceprovides the Google and Facebook strategies. - Express routes like
/auth/facebookand/auth/googleare set up in_setupAuthRoutesto handle the OAuth flow.
Sources: packages/core/src/services/services.app.ts:351-372, 608-659
JWT Strategy and Validation
Protected routes are secured using the JwtStrategy. This strategy extracts the JWT from the Authorization header of incoming requests.
The JwtStrategy class:
- Extends
PassportStrategy(Strategy). - Is configured to extract the token as a Bearer token.
- Uses a secret key from the environment configuration (
env.JWT_SECRET).
The validate method receives the decoded JWT payload and returns a user object, which NestJS then attaches to the Request object.
// packages/core/src/auth/jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: env.JWT_SECRET,
});
}
async validate(payload: IJwtPayload): Promise<IUser> {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
Sources: packages/core/src/auth/jwt.strategy.ts:13-31
Frontend Integration
The frontend applications integrate with the authentication system to protect routes and manage user sessions.
Route Protection (Angular Admin)
In the Angular admin application, route access is controlled by AdminAuthGuard. This guard implements the CanActivate interface.
The canActivate method checks if the user is authenticated using NbAuthService. If the user is not authenticated, it redirects them to the login page (/auth/login).
Attaching JWT to API Requests
The Angular admin app uses Apollo Client for GraphQL communication. An ApolloLink is configured to automatically attach the JWT to the header of every outgoing request.
The setContext function retrieves the token from the application's Store and sets the Authorization header. This link is then combined with the HTTP and WebSocket links.
// packages/admin-web-angular/src/app/app.module.ts:111-122
const authLink: ApolloLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = store.token;
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
Sources: packages/admin-web-angular/src/app/app.module.ts:111-122
Client-Side Registration
The mobile and web clients provide UI for user registration. For example, the SignUp.screen.tsx in the Expo mobile app contains a form that collects user data. Upon submission, it calls the REGISTER_USER_MUTATION via Apollo Client, which triggers the backend registration flow. After a successful registration, it often proceeds to automatically log the user in using the USER_LOGIN mutation.
Sources: packages/shop-mobile-expo/src/screens/authentication/SignUp.screen.tsx:61-64, 274-358
Summary
The User Management and Authentication system in Ever Demand is a well-structured, feature-rich component. It uses industry-standard practices like JWTs and Passport.js within a modern NestJS backend. The clear separation between the authentication service (UsersAuthService), data management service (UsersService), and the data model (User entity) makes the system maintainable and scalable. Its headless design is effectively demonstrated by its integration with multiple clients, including an Angular admin panel and a React Native mobile app, which handle token storage, route guarding, and authenticated API requests.