Nest.js + Typeorm: Identity authentication, transaction management

Source: Internet
Author: User
Tags findone md5 encryption

Knowledge points
    • JWT Identity Verification
    • MD5 encryption
    • Use of Typeorm transactions (transaction)

This article continues the previous article, continue to implement the login function, and implement the API identity authentication, view all the source code.

JWT Identity Verification

For the majority of applications, identity authentication is an essential component, and the user's identity authentication authorization strategy and methods are very many, the choice of which method depends on the needs of the project.

Passport is a popular certification library in node. JS, and this project uses the PASSPORT-JWT policy to authenticate users.

JWT (Json Web Token) is a concise, URL-safe declarative specification for communicating security information between two parties. JWT, as an open standard (RFC 7519), defines a concise, self-contained method for communicating information between two communication parties in the form of a JSON object. Because of the presence of digital signatures, this information is trustworthy, and JWT can be signed using the HMAC algorithm or the public-private key pair of RSA.

Installation
NPM Install--save @nestjs/passport Passport passport-jwt  Jsonwebtoken

Add Jwt.stratagy.ts:

Import {EXTRACTJWT, strategy} from 'PASSPORT-JWT'; import {Authservice} from './auth.service'; import {passportstrategy} from '@nestjs/passport'; import {injectable, unauthorizedexception} from '@nestjs/common'; import {jwtpayload} from './jwt-payload.interface'@Injectable () exportclassJwtstrategy extends Passportstrategy (strategy) {constructor (Private ReadOnlyAuthservice:authservice) {Super ({JwtFromRequest:ExtractJwt.fromAuthHeaderAsBearerToken (), Passreqtocallback:true, Secretorkey:'Secretkey',    }); }  AsyncValidate (Payload:jwtpayload, done:function) {Console.log ('entered JWT')    Constuser =await  This. Authservice.validateuser (Payload.usernmae); if(!user) {      returnDoneNewUnauthorizedexception (),false); } Done (NULL, user); }}

The token is obtained through the Validate () method and passed to the Auth.service for validation.

Add Autn.service.ts:

Import {injectable} from '@nestjs/common'Import {Repository} from 'Typeorm'; import {jwtpayload} from './jwt-payload.interface'Import* asJwt from 'Jsonwebtoken'; import {Employee} from '.. /entities/employee.entity'Import {injectrepository} from '@nestjs/typeorm'; @Injectable () ExportclassAuthservice {User:employee Constructor (@InjectRepository (Employee)Private ReadOnlyEmployeerepository:repository<employee>) { }    AsyncCreatetoken (userName:string, Passwoerd:string): promise<any> {        ConstUser:jwtpayload ={usernmae:username, passwoerd:passwoerd}returnJwt.sign (User,'Secretkey', {expiresin:3600 }); }    AsyncValidateUser (Name:string): promise<any> {        return  This. Employeerepository.findone ({name:name}); }    AsyncFindemployeebyname (Name:string): promise<employee> {        return  This. Employeerepository.findone ({name:name}); } getUser (): Employee {return  This. User; }    AsyncLogin (Name:string, Password:string): promise<any> {         This. user =await  This. Employeerepository.findone ({name:name}); if( This. user! = undefined && This. User.password = =password) {            return  This. Createtoken ( This. User.Name, This. User.password); } Else {            return 'Login failed!'        }    }}

In Auth.service, Createtoken () is used to generate token information, ValidateUser () authentication information, login for the user to log in, in login to query the user name first to verify the password, and then generate token back to the front end. Here the token is generated specifying the expiry time and Secretkey.

Auth.controller.ts:

Import {Controller, Get, Param, Useguards, Httpstatus, Httpcode} from '@nestjs/common'; import {Authservice} from './auth.service'; import {Authguard} from '@nestjs/passport'; import {callback} from './jwt.strategy'@Controller ('Auth') ExportclassAuthcontroller {Constructor (Private ReadOnlyAuthservice:authservice) {} @Get ('Login') @HttpCode (Httpstatus.ok)AsyncLogin (@Param ()params): promise<any> {        return This.authService.login (Params.name, Params.password);} @Get ('Checklogin') @UseGuards (Authguard ('JWT', {session:false, callback})) //@UseGuards (New Roleguard ([' admin ']))     PublicChecklogin () {return "Valid User:"+ This. Authservice.getuser (). Name; }
}

Auth.controller in Checklogin, when accessed, uses the userguard of the passport to configure the JWT policy to verify identity information and to specify the call callback function after validation is complete.

MD5 encryption

This demo uses a relatively simple encryption strategy, MD5.

Installation package:

NPM Install--save @types/crypto-js crypto-js

The encryption process is also relatively simple

Import * as crypto from ' crypto-js ' Employee.password = crypto. MD5 (' 123 '). ToString ();
Use of Typeorm transactions (transaction)

Transactions are a common application scenario in Srvice, and there are several ways to manage transactions in the official documentation of Typeorm, and this article describes two basic ways to use it.

1.getManager (implicit commit, implicit rollback)
AsyncEdit (): promise<string> {if(employee) {returnGetManager (). Transaction (AsyncTransactionalentitymanager = {                awaitTransactionalentitymanager.update<employee> (Employee, {name:'Novak'}, {age: at }); awaitTransactionalentitymanager.delete<company> (company, {ID:Ten }); Let a='123bew'; Console.log (a[Ten].length);//Manufacturing Exceptions}). Then (res = {                return 'tranction Done'            }).Catch(Error = {                return 'Tranction failed,'+Error; })        } Else {            return 'Employee not found'; }    }

Use GetManager (). Transaction to create the transaction module, in order to verify the effect, this article intentionally wrote an exception statement. The result of the validation is that the transaction is automatically rolled back after an exception occurs, and if there is no exception, the transaction is automatically committed.

2.queryRunner (Explicit commit, explicit-rollback)
AsyncEditusequeryrunner (): promise<string>{Let employee=await  This. Employeerepository.findone ({name:"Novak" }); Console.log (employee)if(employee) {ConstConnection =getconnection (); ConstQueryrunner =Connection.createqueryrunner (); awaitQueryrunner.connect (); awaitqueryrunner.starttransaction (); Try {                awaitQueryrunner.manager.update<employee> (Employee, {name:'Novak'}, {age: - }); /*Let a = ' 123bew '; Console.log (a[10].length); */                awaitqueryrunner.committransaction (); return 'Transaction Done'            } Catch(err) {awaitqueryrunner.rollbacktransaction (); return 'Transaction Failed'            }        } Else {            return 'Employee not found'        }    }

You can see from the code that Queryrunner is explicitly committing and rolling back the transaction.

Nest.js + Typeorm: Identity authentication, transaction management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.