dewmyth-auth-nestjs-mongo v0.0.3
How to use
- Install the package
npm install dewmyth-auth-nestjs-mongo
- Go to the NestJS module where you want to use the package and import the module and import the
AuthModule
from the library
import { AuthModule } from 'dewmyth-auth-nestjs-mongo';
- Add the
AuthModule
to the imports array of the module with themongoUri
property set to the uri of the mongo database you want to connect to
imports: [
AuthModule.forRoot({
mongoUri:
'your-mongo-uri', // The uri to connect to the mongo database
}),
],
Now you can use the
AuthService
in your moduleImport the
AuthService
from the library to whatever the sevice or controller you want to use it in
import { AuthService } from 'dewmyth-auth-nestjs-mongo';
- Then inject the
AuthService
into the constructor of the service or controller
constructor(
private readonly authService: AuthService,
) {}
- Now you can use the
AuthService
to create a user and login a user
Create a User
A basic function that will accept the user's email, password, and username and return the created user. The created user will be saved on the mongodb database under the users
collection. The password will be hashed using bcrypt
before saving it to the database.
async createUser() {
const newUser = await this.authService.createUser({
email: 'sampleEmail@email.com'
password: 'samplePassword',
username: 'sampleUsername',
});
}
Login a User
A basic function that will accept the user's email and password and return the logged user. The function will check if the user exists in the database and if the password matches the hashed password in the database. If the user exists and the password matches, the user will be logged in and a token will be returned.
async loginUser() {
const loggedUser = await this.authService.loginUser({
email: 'sampleEmail@email.com'
password: 'samplePassword',
});
}
Optionally you can pass the JWT secret and the JWT expiration time in the options object. The default JWT secret
async loginUser() {
const loggedUser = await this.authService.loginUser({
email: 'sampleEmail@email.com'
password: 'samplePassword',
},
'sampleSecret', // The JWT secret
'1h', // The JWT expiration time, Please refere JWT documentation for more information
);
}