Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // controller
- @controller("/public/auth")
- export class AuthController implements interfaces.Controller {
- constructor(
- @inject(TYPES.AuthService) private authService: AuthService,
- @inject(TYPES.Logger)
- private logger: ILogger
- ) {}
- @httpPost("/", TYPES.AuthMiddleWare)
- private async index(req, res) {
- const dto: IAuthDto = req.body;
- try {
- const token = await this.authService.getToken(dto);
- this.logger.log("success auth");
- return res.json(Requester.createBody({ token }));
- } catch (e) {
- return res.json(Requester.createError(e));
- }
- }
- }
- // middleware
- @injectable()
- export class AuthMiddleware extends BaseMiddleware {
- public handler(
- req: express.Request,
- res: express.Response,
- next: express.NextFunction
- ) {
- const dto: IAuthDto = req.body;
- if (!AuthValidator.isValid(dto)) {
- throw new InvalidDataError();
- }
- next();
- }
- }
- // validator
- export class AuthValidator {
- public static isValid(data: IAuthDto): boolean {
- const isEmailValid = EmailValidator.isValid(data.email);
- try {
- const isPasswordLength = validator.isLength(data.password, {
- min: MIN_PASSWORD_LENGTH,
- max: MAX_PASSWORD_LENGTH,
- });
- return isEmailValid && isPasswordLength;
- } catch (e) {
- return false;
- }
- }
- }
- // service
- @injectable()
- export class AuthService implements IAuthService {
- constructor(
- @inject(TYPES.UserRepository) private repository: IUserRepository,
- @inject(TYPES.Logger) private logger: ILogger
- ) {}
- public async getToken(dto: IAuthDto): Promise<string> {
- this.logger.log("Try auth", dto.email);
- const user: User = await this.getUser(dto.email);
- this.checkRole(user.role);
- await this.comparePassword(dto.password, user.passwordHash);
- const updatedUser = await this.updateLastEnter(user);
- return TokenGenerator.getToken(updatedUser);
- }
- private async getUser(email: string): Promise<User> {
- const user = await this.repository.getUserByEmail(email);
- if (user) {
- return user;
- }
- this.logger.log("User not exist", email);
- throw new InvalidUserOrPasswordError();
- }
- private checkRole(role: string) {
- if (role !== UserRole.USER) {
- this.logger.log("Wrong role!");
- throw new InvalidUserRoleError();
- }
- }
- private async comparePassword(password: string, hash: string) {
- const isSuccess = await bcrypt.compare(password, hash);
- if (!isSuccess) {
- this.logger.log("Wrong password");
- throw new InvalidUserOrPasswordError();
- }
- }
- private async updateLastEnter(user: User): Promise<User> {
- return await this.repository.updateUserIdentity(user.id);
- }
- }
- // controller test
- describe("AuthController", function () {
- it("/auth При верном логине/пароле возращается токен", async () => {
- await request(app)
- .post("/public/auth")
- .send(environment.test.auth)
- .expect((res) => {
- assert.strictEqual(validator.isJWT(res.body.data.token), true);
- });
- });
- it("/auth При не верном логине/пароле возращается ошибка", async () => {
- await request(app)
- .post("/public/auth")
- .send({
- email: "masquitos@mail.ru",
- password: "123456",
- })
- .expect((res) => {
- const e = new InvalidUserOrPasswordError();
- assert.strictEqual(res.body.error.code, e.code);
- });
- });
- it("/auth При не валидных данных код 22", async () => {
- await request(app)
- .post("/public/auth")
- .send({
- email: "mail",
- password: null,
- })
- .expect((res) => {
- const err = new InvalidDataError();
- assert.strictEqual(res.body.error.code, err.code);
- });
- });
- });
- // service test
- describe("AuthService", function () {
- it("При не верной роли ошибка", async () => {
- const getUser = () => Promise.resolve<User>(new User(
- null,
- null,
- null,
- null,
- null,
- UserRole.SERVICE_SUPPORT,
- null,
- null
- ));
- const stub = sinon.stub(AuthService.prototype, <any>"getUser");
- stub.callsFake(getUser);
- const service = diContainer.get<IAuthService>(TYPES.AuthService);
- await assert.rejects(
- () => service.getToken({ email: "asda", password: " 123" }),
- new InvalidUserRoleError()
- );
- });
- });
Add Comment
Please, Sign In to add comment