class-transformer#classToPlain TypeScript Examples

The following examples show how to use class-transformer#classToPlain. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
private static listOAuthApplications(req: Request, res: Response, next: NextFunction) {
        const user = req.currentUser!;
        oauthRepo
            .listForUser(user)
            .then((result) => {
                if (result.isError && result.error) {
                    res.render('oauth_applications', {
                        _error: result.error.errorCode,
                    });
                    return;
                }

                res.render('oauth_applications', {
                    // @ts-ignore
                    _csrfToken: req.csrfToken(),
                    // some parameters come from the create routes successful redirect
                    application_id: req.query.application_id,
                    application_secret: req.query.application_secret,
                    applications: classToPlain(result.value),
                    _error: req.query.error,
                    _success: req.query.success,
                });
            })
            .catch((err) => res.render('oauth_applications', {_error: err}));
    }
Example #2
Source File: UserController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// User List API
    /**
     * @api {get} /api/auth/userlist User List API
     * @apiGroup Authentication
     * @apiParam (Request body) {Number} limit limit
     * @apiParam (Request body) {Number} offset offset
     * @apiParam (Request body) {String} keyword keyword
     * @apiParam (Request body) {Number} count count in number or boolean
     * @apiHeader {String} Authorization
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "message": "Successfully get user list",
     *      "data":"{}"
     *      "status": "1"
     * }
     * @apiSampleRequest /api/auth/userlist
     * @apiErrorExample {json} User Profile error
     * HTTP/1.1 500 Internal Server Error
     */
    @Get('/userlist')
    @Authorized()
    public async findAll(@QueryParam('limit') limit: number, @QueryParam('offset') offset: number, @QueryParam('keyword') keyword: string, @QueryParam('count') count: number | boolean, @Res() response: any): Promise<any> {
       console.log(keyword);
        const relation = ['usergroup'];
        const WhereConditions = [ {
            name: 'deleteFlag',
            value: 0,
        }];
        const user = await this.userService.list(limit, offset, ['userId', 'username', 'firstName', 'lastName', 'email', 'address', 'phoneNumber', 'avatar', 'avatarPath', 'password', 'createdDate'], relation,  WhereConditions, keyword, count);
        const successResponse: any = {
            status: 1,
            data: classToPlain(user),
            message: 'Successfully get All user List',
        };
        return response.status(200).send(successResponse);
    }
Example #3
Source File: transactions.service.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
private async upsert(
    prisma: BasePrismaClient,
    { hash, fee, size, notes, spends }: UpsertTransactionOptions,
  ): Promise<Transaction> {
    const networkVersion = this.config.get<number>('NETWORK_VERSION');
    hash = standardizeHash(hash);

    return prisma.transaction.upsert({
      create: {
        hash,
        network_version: networkVersion,
        fee,
        size,
        notes: classToPlain(notes),
        spends: classToPlain(spends),
      },
      update: {
        fee,
        size,
        notes: classToPlain(notes),
        spends: classToPlain(spends),
      },
      where: {
        uq_transactions_on_hash_and_network_version: {
          hash,
          network_version: networkVersion,
        },
      },
    });
  }
Example #4
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
// this route will take an API KeyPair and return a JWT token encapsulating the user to which the supplied
    // KeyPair belongs
    private static getToken(req: Request, res: Response, next: NextFunction) {
        const key = req.header('x-api-key');
        const secret = req.header('x-api-secret');
        // provide a sane default of a 24 hour token expiry
        const expiry = req.header('x-api-expiry') || '24h';

        if (key && secret) {
            keyRepo.validateKeyPair(key, secret).then((valid) => {
                if (!valid) {
                    res.status(401).send('unauthorized');
                    return;
                }

                KeyPairMapper.Instance.UserForKeyPair(key).then((user) => {
                    if (user.isError) {
                        // even though its an error with the user, we don't want
                        // to give that away, keep them thinking its an error
                        // with credentials
                        res.status(401);
                        return;
                    }


                    const token = jwt.sign(classToPlain(user.value), Config.encryption_key_secret, {expiresIn: expiry});
                    res.status(200).json(token);
                    return;
                });
            });
        } else {
            res.status(401).send('unauthorized');
            return;
        }
    }
Example #5
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
private static login(req: Request, res: Response, next: NextFunction) {
        const request = oauthRepo.authorizationFromRequest(req);

        // if they've logged in following an auth request redirect to the authorize page vs. the profile page
        if (request) {
            res.redirect(
                buildUrl('/oauth/authorize', {
                    queryParams: classToPlain(request),
                }),
            );
            return;
        }

        return res.redirect('/oauth/profile');
    }
Example #6
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
private static loginSaml(req: Request, res: Response) {
        const oauthRequest = oauthRepo.authorizationFromRequest(req);

        // if this login is part of an OAuth request flow, we must save it in cache
        // so that we can restore it as part of the redirect
        if (oauthRequest) {
            const token = Buffer.from(uuidv4()).toString('base64');
            Cache.set(token, classToPlain(oauthRequest), 60 * 10).then((set) => {
                if (!set) {
                    res.redirect(buildUrl('/oauth', {queryParams: {error: `unable to set RelayState in cache`}}));
                    return;
                }

                req.query.RelayState = token;

                passport.authenticate('saml', {
                    failureRedirect: '/unauthorized',
                    failureFlash: true,
                })(req, res);
            });
        } else {
            passport.authenticate('saml', {
                failureRedirect: '/unauthorized',
                failureFlash: true,
            })(req, res);
        }
    }
Example #7
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
private static loginPage(req: Request, res: Response, next: NextFunction) {
        req.logout(); // in case a previous user logged into a session
        const oauthRequest = oauthRepo.authorizationFromRequest(req);

        return res.render('login', {
            // @ts-ignore
            _csrfToken: req.csrfToken(),
            oauthRequest: classToPlain(oauthRequest),
            registerLink: buildUrl('/oauth/register', {
                queryParams: req.query,
            }),
            loginWithWindowsLink: buildUrl('/login-saml', {
                queryParams: req.query,
            }),
            _success: req.query.success ? DOMPurify.sanitize(req.query.success as string) : undefined,
            _error: req.query.error ? DOMPurify.sanitize(req.query.errory as string) : undefined,
            saml_enabled: Config.saml_enabled,
        });
    }
Example #8
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
private static oauthApplicationPage(req: Request, res: Response) {
        if (req.oauthApp) {
            res.render('oauth_application_single', {
                // @ts-ignore
                _csrfToken: req.csrfToken(),
                application: classToPlain(req.oauthApp),
            });
        } else {
            res.redirect(
                buildUrl('/oauth/applications', {
                    queryParams: {error: `uanble to find oauth application`},
                }),
            );
            return;
        }
    }
Example #9
Source File: local.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
/*
 This middleware will attempt to authenticate a user using the local authentication method
 if the user has already been authenticated it will pass them to the next handler
 in the chain - http://www.passportjs.org/packages/passport-local/
*/
export function LocalAuthMiddleware(req: express.Request, resp: express.Response, next: express.NextFunction): any {
    const oauthRepo = new OAuthRepository();
    const oauthRequest = oauthRepo.authorizationFromRequest(req);

    if (req.isAuthenticated()) {
        next();
        return;
    }

    passport.authenticate('local', (err, user, info) => {
        if (err) {
            return resp.redirect(buildUrl('/oauth', {queryParams: {error: `${err}`}}));
        }
        if (!user) {
            return resp.redirect(buildUrl('/oauth', {queryParams: req.query}));
        }
        req.logIn(user, (err) => {
            if (err) {
                return resp.redirect(buildUrl('/oauth', {queryParams: {error: err.toString()}}));
            }

            if (oauthRequest) {
                return resp.redirect(
                    buildUrl('/oauth/authorize', {
                        queryParams: classToPlain(oauthRequest),
                    }),
                );
            }

            return resp.redirect('/oauth/profile');
        });
    })(req, resp, next);
}
Example #10
Source File: users.service.ts    From knests with MIT License 6 votes vote down vote up
/**
     * The first user signing up will also have the ADMIN role. The rest of them, only the NORMAL role.
     *
     * @param user :UserSignupDTO
     */
    async signup(user: UserSignupDTO): Promise<UserDTO | undefined> {

        try {
            const [total] = await this.knex('users').count();
            const signupRoles = [UserRoles.NORMAL];

            if (parseInt(total.count as string, 10) === 0) {
                signupRoles.push(UserRoles.ADMIN);
            }
            const newUser = await this.create(new UserDTO(classToPlain(user)));


            // adding Roles
            const adminUser = await this.addRolesToUser(newUser, signupRoles);

            const res = new UserDTO(classToPlain(adminUser));

            return res;
        } catch (e) {
            this.logger.debug(e);
            throw e;
        }

    }
Example #11
Source File: user-repository.ts    From malagu with MIT License 6 votes vote down vote up
@Transactional()
    async update(user: User): Promise<User> {
        const repo = OrmContext.getRepository(User);
        const oldUser = await repo.findOne(user.id);
        if (oldUser) {
            const newUser = plainToClassFromExist(oldUser, classToPlain(user));
            return repo.save(newUser);
        }
        throw new UserNotFoundError(user.id);
    }
Example #12
Source File: interface.ts    From cloudformation-cli-typescript-plugin with Apache License 2.0 6 votes vote down vote up
@Exclude()
    public serialize(removeNull = true): Dict {
        const data: Dict = JSON.parse(JSON.stringify(classToPlain(this)));
        // To match Java serialization, which drops 'null' values, and the
        // contract tests currently expect this also.
        if (removeNull) {
            for (const key in data) {
                const value = data[key];
                if (value == null) {
                    delete data[key];
                }
            }
        }
        return data;
    }
Example #13
Source File: interface.ts    From cloudformation-cli-typescript-plugin with Apache License 2.0 5 votes vote down vote up
@Exclude()
    static serializer = {
        classToPlain,
        plainToClass,
    };
Example #14
Source File: CustomerOrderController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Customer Order List API
    /**
     * @api {get} /api/orders/order-list My Order List
     * @apiGroup Store order
     * @apiHeader {String} Authorization
     * @apiParam (Request body) {Number} limit limit
     * @apiParam (Request body) {Number} offset offset
     * @apiParam (Request body) {Number} count count in number or boolean
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "message": "Successfully show the Order List..!!",
     *      "status": "1",
     *      "data": {},
     * }
     * @apiSampleRequest /api/orders/order-list
     * @apiErrorExample {json} Order List error
     * HTTP/1.1 500 Internal Server Error
     */
    // Order List Function
    @Get('/order-list')
    @Authorized('customer')
    public async orderList(@QueryParam('limit') limit: number, @QueryParam('offset') offset: number, @QueryParam('count') count: number | boolean, @Req() request: any, @Res() response: any): Promise<any> {
        const search = [
            {
                name: 'customerId',
                op: 'where',
                value: request.user.id,
            },
        ];
        const whereConditions = 0;
        const select = ['orderId', 'customerId', 'orderStatus', 'total', 'createdDate', 'orderPrefixId'];
        const relation = ['orderStatus'];
        const OrderData = await this.orderService.list(limit, offset, select, search, whereConditions, relation, count);
        if (count) {
            const Response: any = {
                status: 1,
                message: 'Successfully get Count. ',
                data: OrderData,
            };
            return response.status(200).send(Response);
        }
        const promises = OrderData.map(async (results: any) => {
            const Id = results.orderId;
            const countValue = await this.orderProductService.findAndCount({where: {orderId: Id}});
            results.items = countValue[1];
            return results;
        });
        const result = await Promise.all(promises);
        const successResponse: any = {
            status: 1,
            message: 'Successfully shown the order list. ',
            data: classToPlain(result),
        };
        return response.status(200).send(successResponse);
    }
Example #15
Source File: CustomerController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Login API
    /**
     * @api {post} /api/customer/login login API
     * @apiGroup Store
     * @apiParam (Request body) {String} emailId User Email Id
     * @apiParam (Request body) {String} password User Password
     * @apiParamExample {json} Input
     * {
     *      "emailId" : "",
     *      "password" : "",
     * }
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "data": "{
     *         "token":''
     *      }",
     *      "message": "Successfully login",
     *      "status": "1"
     * }
     * @apiSampleRequest /api/customer/login
     * @apiErrorExample {json} Login error
     * HTTP/1.1 500 Internal Server Error
     */
    // Login Function
    @Post('/login')
    public async login(@Body({validate: true}) loginParam: CustomerLogin, @Req() request: any, @Res() response: any): Promise<any> {
       const resultData = await this.customerService.findOne({
                select: ['id', 'firstName', 'email', 'mobileNumber', 'password', 'avatar', 'avatarPath', 'isActive'],
                where: {email: loginParam.emailId, deleteFlag: 0},
            });
            if (!resultData) {
                const errorUserNameResponse: any = {
                    status: 0,
                    message: 'Invalid EmailId',
                };
                return response.status(400).send(errorUserNameResponse);
            }
            if (resultData.isActive === 0) {
                const errorUserInActiveResponse: any = {
                    status: 0,
                    message: 'InActive Customer.',
                };
                return response.status(400).send(errorUserInActiveResponse);
            }
            if (await Customer.comparePassword(resultData, loginParam.password)) {
                // create a token
                const token = jwt.sign({id: resultData.id}, '123##$$)(***&');

                const loginLog = new LoginLog();
                loginLog.customerId = resultData.id;
                loginLog.emailId = resultData.email;
                loginLog.firstName = resultData.firstName;
                loginLog.ipAddress = (request.headers['x-forwarded-for'] ||
                    request.connection.remoteAddress ||
                    request.socket.remoteAddress ||
                    request.connection.socket.remoteAddress).split(',')[0];
                const savedloginLog = await this.loginLogService.create(loginLog);
                const customer = await this.customerService.findOne({where: {email: loginParam.emailId, deleteFlag: 0}});
                customer.lastLogin = savedloginLog.createdDate;
                await this.customerService.create(customer);
                   const successResponse: any = {
                        status: 1,
                        message: 'Loggedin successfully',
                        data: {
                            token,
                            user: classToPlain(resultData),
                        },
                    };
                    return response.status(200).send(successResponse);
            }
            const errorResponse: any = {
                status: 0,
                message: 'Invalid password',
            };
            return response.status(400).send(errorResponse);
    }
Example #16
Source File: CustomerController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Customer Register API
    /**
     * @api {post} /api/customer/register register API
     * @apiGroup Store
     * @apiParam (Request body) {String} name Name
     * @apiParam (Request body) {String} password User Password
     * @apiParam (Request body) {String} confirmPassword Confirm Password
     * @apiParam (Request body) {String} emailId User Email Id
     * @apiParam (Request body) {Number} phoneNumber User Phone Number (Optional)
     * @apiParamExample {json} Input
     * {
     *      "name" : "",
     *      "password" : "",
     *      "confirmPassword" : "",
     *      "emailId" : "",
     *      "phoneNumber" : "",
     * }
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "message": "Thank you for registering with us and please check your email",
     *      "status": "1"
     * }
     * @apiSampleRequest /api/customer/register
     * @apiErrorExample {json} Register error
     * HTTP/1.1 500 Internal Server Error
     */
    // Customer Register Function
    @Post('/register')
    public async register(@Body({validate: true})registerParam: CustomerRegisterRequest, @Req() request: any, @Res() response: any): Promise<any> {
        const newUser = new Customer();
        newUser.firstName = registerParam.name;
        newUser.password = await Customer.hashPassword(registerParam.password);
        newUser.email = registerParam.emailId;
        newUser.username = registerParam.emailId;
        newUser.mobileNumber = registerParam.phoneNumber;
        newUser.isActive = 1;
        newUser.ip = (request.headers['x-forwarded-for'] ||
            request.connection.remoteAddress ||
            request.socket.remoteAddress ||
            request.connection.socket.remoteAddress).split(',')[0];
        const resultUser = await this.customerService.findOne({where: {email: registerParam.emailId, deleteFlag: 0}});
        if (resultUser) {
            const successResponse: any = {
                status: 1,
                message: 'You already registered please login.',
            };
            return response.status(400).send(successResponse);
        }
        if (registerParam.password === registerParam.confirmPassword) {
            const resultData = await this.customerService.create(newUser);
            const emailContent = await this.emailTemplateService.findOne(1);
            const message = emailContent.content.replace('{name}', resultData.firstName);
            const sendMailRes = MAILService.registerMail(message, resultData.email, emailContent.subject);
            if (sendMailRes) {
                const successResponse: any = {
                    status: 1,
                    message: 'Thank you for registering with us. Kindly check your email inbox for further details. ',
                    data: classToPlain(resultData),
                };
                return response.status(200).send(successResponse);
            } else {
                const errorResponse: any = {
                    status: 0,
                    message: 'Registration successful, but unable to send email. ',
                };
                return response.status(400).send(errorResponse);
            }
        }
        const errorPasswordResponse: any = {
            status: 0,
            message: 'A mismatch between password and confirm password. ',
        };
        return response.status(400).send(errorPasswordResponse);
    }
Example #17
Source File: CommonListController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Zone List API
    /**
     * @api {get} /api/list/zone-list Zone List API
     * @apiGroup Store List
     * @apiParam (Request body) {Number} limit limit
     * @apiParam (Request body) {Number} offset offset
     * @apiParam (Request body) {String} keyword keyword
     * @apiParam (Request body) {Number} count count should be number or boolean
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "message": "Successfully get zone list",
     *      "data":{
     *      "countryId"
     *      "code"
     *      "name"
     *      }
     *      "status": "1"
     * }
     * @apiSampleRequest /api/list/zone-list
     * @apiErrorExample {json} Zone error
     * HTTP/1.1 500 Internal Server Error
     */
    @Get('/zone-list')
    public async zonelist(@QueryParam('limit') limit: number, @QueryParam('offset') offset: number, @QueryParam('keyword') keyword: string, @QueryParam('count')count: number | boolean, @Res() response: any): Promise<any> {
        const select = ['zoneId', 'countryId', 'code', 'name', 'isActive'];
        const search = [
            {
                name: 'name',
                op: 'like',
                value: keyword,
            },
            {
                name: 'isActive',
                op: 'where',
                value: 1,
            },
        ];

        const WhereConditions = [];
        const relation = ['country'];

        const zoneList = await this.zoneService.list(limit, offset, select, search, WhereConditions, relation, count);
        if (zoneList) {
            const successResponse: any = {
                status: 1,
                message: 'Successfully get all zone List',
                data: classToPlain(zoneList),
            };
            return response.status(200).send(successResponse);
        } else {
            const errorResponse: any = {
                status: 1,
                message: 'unable to get zone List',
            };
            return response.status(400).send(errorResponse);
        }
    }
Example #18
Source File: ZoneController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Zone List API
    /**
     * @api {get} /api/zone/zone-list Zone List API
     * @apiGroup Zone
     * @apiHeader {String} Authorization
     * @apiParam (Request body) {Number} limit limit
     * @apiParam (Request body) {Number} offset offset
     * @apiParam (Request body) {String} keyword keyword
     * @apiParam (Request body) {Number} count count should be number or boolean
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "message": "Successfully get zone list",
     *      "data":{
     *      "countryId"
     *      "code"
     *      "name"
     *      }
     *      "status": "1"
     * }
     * @apiSampleRequest /api/zone/zone-list
     * @apiErrorExample {json} Zone error
     * HTTP/1.1 500 Internal Server Error
     */
    @Get('/zone-list')
    @Authorized()
    public async zonelist(@QueryParam('limit') limit: number, @QueryParam('offset') offset: number, @QueryParam('keyword') keyword: string, @QueryParam('count')count: number | boolean, @Res() response: any): Promise<any> {
        const select = ['zoneId', 'countryId', 'code', 'name', 'isActive'];
        const search = [
            {
                name: 'name',
                op: 'like',
                value: keyword,
            },
        ];

        const WhereConditions = [];
        const relation = ['country'];

        const zoneList = await this.zoneService.list(limit, offset, select, search, WhereConditions, relation, count);
        if (zoneList) {
            const successResponse: any = {
                status: 1,
                message: 'Successfully get all zone List',
                data: classToPlain(zoneList),
            };
            return response.status(200).send(successResponse);
        } else {
            const errorResponse: any = {
                status: 1,
                message: 'unable to get zone List',
            };
            return response.status(400).send(errorResponse);
        }
    }
Example #19
Source File: UserController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Login API
    /**
     * @api {post} /api/auth/login Login
     * @apiGroup Authentication
     * @apiParam (Request body) {String} username User Username
     * @apiParam (Request body) {String} password User Password
     * @apiParamExample {json} Input
     * {
     *      "username" : "",
     *      "password" : "",
     * }
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "data": "{
     *         "token":''
     *      }",
     *      "message": "Successfully login",
     *      "status": "1"
     * }
     * @apiSampleRequest /api/auth/login
     * @apiErrorExample {json} Login error
     * HTTP/1.1 500 Internal Server Error
     */
    @Post('/login')
    public async login(@Body({ validate: true }) loginParam: LoginRequest, @Res() response: any): Promise<any> {
        console.log(loginParam.username);
        console.log(loginParam.password);
        const user = await this.userService.findOne({
            where: {
                username: loginParam.username,
                deleteFlag: 0,
                }, relations: ['usergroup'],
        });
    if (user) {
      if (await User.comparePassword(user, loginParam.password)) {
          // create a token
          const token = jwt.sign({id: user.userId}, '123##$$)(***&');
          if (user.usergroup.isActive === 0) {
              const errorResponse: any = {
                  status: 0,
                  message: 'InActive Role',
              };
              return response.status(400).send(errorResponse);
          }
          if (token) {
              const newToken = new AccessToken();
              newToken.userId = user.userId;
              newToken.token = token;
              const tokenSave = await this.accessTokenService.create(newToken);
              console.log(tokenSave);
          }
        const successResponse: any = {
            status: 1,
            message: 'Loggedin successful',
            data: {
                token,
                user: classToPlain(user),
            },
        };
        return response.status(200).send(successResponse);
      } else {
          const errorResponse: any = {
          status: 0,
          message: 'Invalid password',
          };
          return response.status(400).send(errorResponse);
      }
    } else {

          const errorResponse: any = {
                status: 0,
                message: 'Invalid username',
          };
          return response.status(400).send(errorResponse);
    }
    }
Example #20
Source File: ProductController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Product Detail API
    /**
     * @api {get} /api/product/product-detail/:id Product Detail API
     * @apiGroup Product
     * @apiHeader {String} Authorization
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "status": "1"
     *      "message": "Successfully get product Detail",
     *      "data":"{}"
     * }
     * @apiSampleRequest /api/product/product-detail/:id
     * @apiErrorExample {json} productDetail error
     * HTTP/1.1 500 Internal Server Error
     */
    @Get('/product-detail/:id')
    @Authorized()
    public async productDetail(@Param('id') id: number, @Res() response: any): Promise<any> {
        const productDetail: any = await this.productService.findOne({
            productId: id,
        });
        const productDetails: any = classToPlain(productDetail);
        productDetails.productImage = await this.productImageService.findAll({
            select: ['productId', 'image', 'containerName', 'defaultImage'],
            where: {
                productId: id,
                },
        });
        productDetails.Category = await this.productToCategoryService.findAll({
            select: ['categoryId', 'productId'],
            where: {productId: id},
        }).then((val) => {
            const category = val.map(async (value: any) => {
                const categoryNames = await this.categoryService.findOne({categoryId: value.categoryId});
                const temp: any = value;
                if (categoryNames !== undefined ) {
                    temp.categoryName = categoryNames.name;
                } else {
                    temp.categoryName = '';
                }
                return temp;
            });
            const results = Promise.all(category);
            return results;
        });
        const successResponse: any = {
            status: 1,
            message: 'Successfully get productDetail',
            data: productDetails,
        };
        return response.status(200).send(successResponse);
    }
Example #21
Source File: ProductController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Product List API
    /**
     * @api {get} /api/product/productlist Product List API
     * @apiGroup Product
     * @apiHeader {String} Authorization
     * @apiParam (Request body) {Number} limit limit
     * @apiParam (Request body) {Number} offset offset
     * @apiParam (Request body) {String} keyword keyword
     * @apiParam (Request body) {String} sku sku
     * @apiParam (Request body) {String} status status
     * @apiParam (Request body) {Number} price=1/2 if 1->asc 2->desc
     * @apiParam (Request body) {Number} count count in number or boolean
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "status": "1"
     *      "message": "Successfully get product list",
     *      "data":"{}"
     * }
     * @apiSampleRequest /api/product/productlist
     * @apiErrorExample {json} productList error
     * HTTP/1.1 500 Internal Server Error
     */
    @Get('/productlist')
    @Authorized()
    public async productList(@QueryParam('limit') limit: number, @QueryParam('offset') offset: number, @QueryParam('keyword') keyword: string, @QueryParam('sku') sku: string, @QueryParam('status') status: string, @QueryParam('price') price: number, @QueryParam('count') count: number | boolean, @Res() response: any): Promise<Product> {
        const select = ['productId', 'sku', 'name', 'quantity', 'price', 'image', 'imagePath', 'todayDeals', 'isActive'];

        const relation = [];

        const WhereConditions = [
            {
                name: 'name',
                op: 'like',
                value: keyword,
            }, {
                name: 'sku',
                op: 'like',
                value: sku,
            }, {
                name: 'isActive',
                op: 'like',
                value: status,
            },
        ];
        const productLists: any = await this.productService.list(limit, offset, select, relation, WhereConditions, 0, price, count);
        if (count) {
            const successRes: any = {
                status: 1,
                message: 'Successfully got count ',
                data: productLists,
            };
            return response.status(200).send(successRes);
        }
        const productList = productLists.map(async (value: any) => {
            const defaultValue = await this.productImageService.findOne({
                where: {
                    productId: value.productId,
                    defaultImage: 1,
                },
            });
            const temp: any = value;
            temp.productImage = defaultValue;
            return temp;
        });
        const results = await Promise.all(productList);

        const successResponse: any = {
            status: 1,
            message: 'Successfully got the complete product list. ',
            data: classToPlain(results),
        };
        return response.status(200).send(successResponse);
    }
Example #22
Source File: CustomerController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// Recently Added Customer List API
    /**
     * @api {get} /api/customer/recent-customerlist Recent Customer List API
     * @apiGroup Customer
     * @apiHeader {String} Authorization
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "status": "1"
     *      "message": "Successfully get customer list",
     *      "data":{
     *      "location" : "",
     *      "name" : "",
     *      "created date" : "",
     *      "isActive" : "",
     *      }
     * }
     * @apiSampleRequest /api/customer/recent-customerlist
     * @apiErrorExample {json} customer error
     * HTTP/1.1 500 Internal Server Error
     */
    @Get('/recent-customerlist')
    @Authorized()
    public async recentCustomerList(@Res() response: any): Promise<any> {
        const order = 1;
        const WhereConditions = [
            {
                name: 'deleteFlag',
                value: 0,
            },
        ];
        const customerList = await this.customerService.list(0, 0, 0, WhereConditions, order, 0);
        const successResponse: any = {
            status: 1,
            message: 'Successfully got Customer list.',
            data: classToPlain(customerList),
        };

        return response.status(200).send(successResponse);
    }
Example #23
Source File: metatype_relationship_pair.spec.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
describe('A Metatype Relationship Pair should', async () => {
    let containerID: string = process.env.TEST_CONTAINER_ID || '';

    before(async function () {
        if (process.env.CORE_DB_CONNECTION_STRING === '') {
            Logger.debug('skipping metatype tests, no mapper layer');
            this.skip();
        }
        await PostgresAdapter.Instance.init();
        const mapper = ContainerMapper.Instance;

        const container = await mapper.Create(
            'test suite',
            new Container({
                name: faker.name.findName(),
                description: faker.random.alphaNumeric(),
            }),
        );

        expect(container.isError).false;
        expect(container.value.id).not.null;
        containerID = container.value.id!;

        return Promise.resolve();
    });

    after(async () => {
        await ContainerMapper.Instance.Delete(containerID);
        return PostgresAdapter.Instance.close();
    });

    it('be able to assign metatype ids on plainToClass transformation', async () => {
        const check = plainToClass(MetatypeRelationshipPair, {
            destination_metatype_id: '1',
            origin_metatype_id: '1',
            relationship_id: '1',
        });
        expect(check.originMetatype).not.undefined;
        expect(check.destinationMetatype).not.undefined;
        expect(check.relationship).not.undefined;

        // verify that the resulting object has simple strings for id's
        const plain = classToPlain(check);
        expect(plain.origin_metatype_id).to.be.a('string');
        expect(plain.origin_metatype).to.be.a('object');
        expect(plain.destination_metatype_id).to.be.a('string');
        expect(plain.destination_metatype).to.be.a('object');
        expect(plain.relationship).to.be.a('object');
        expect(plain.relationship_id).to.be.a('string');

        return Promise.resolve();
    });
});
Example #24
Source File: oauth_repository.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
// exchanges a token for a JWT to act on behalf of the user
    async authorizationCodeExchange(exchangeReq: OAuthTokenExchangeRequest): Promise<Result<string>> {
        const userRepo = new UserRepository();
        const cached = await Cache.get<object>(exchangeReq.code!);
        if (!cached) return new Promise((resolve) => resolve(Result.Failure('unable to retrieve original request from cache')));

        const originalReq = plainToClass(OAuthRequest, cached);

        const user = await userRepo.findByID(originalReq.user_id!);
        if (user.isError) return new Promise((resolve) => resolve(Result.Pass(user)));

        // quick verification between requests
        if (originalReq.redirect_uri !== exchangeReq.redirect_uri) return new Promise((resolve) => resolve(Result.Failure('non-matching redirect uri')));
        if (originalReq.client_id !== exchangeReq.client_id) return new Promise((resolve) => resolve(Result.Failure('non-matching client ids')));

        // if PKCE flow, verify the code
        if (exchangeReq.code_verifier) {
            if (originalReq.code_challenge_method === 'S256') {
                const hash = base64url(crypto.createHash('sha256').update(exchangeReq.code_verifier).digest());

                if (hash !== decodeURIComponent(originalReq.code_challenge!))
                    return new Promise((resolve) => resolve(Result.Failure('PKCE code challenge does not match')));
            } else {
                // for whatever reason we have to run the decode URI component twice on the original req, don't ask
                // why - just don't remove it or you'll break it
                if (exchangeReq.code_verifier !== decodeURIComponent(decodeURIComponent(originalReq.code_challenge!)))
                    return new Promise((resolve) => resolve(Result.Failure('PKCE code challenge does not match')));
            }
        } else {
            // if we're not doing PKCE there must be a client secret present
            const application = await OAuthMapper.Instance.Retrieve(exchangeReq.client_id!);
            if (application.isError) return new Promise((resolve) => resolve(Result.Pass(application)));

            const valid = await bcrypt.compare(exchangeReq.client_secret!, application.value.client_secret!);

            if (!valid) return new Promise((resolve) => resolve(Result.Failure('invalid client')));
        }

        const token = jwt.sign(classToPlain(UserToReturnUser(user.value)), Config.encryption_key_secret, {expiresIn: '720m'});

        return new Promise((resolve) => resolve(Result.Success(token)));
    }
Example #25
Source File: CategoryController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
// Update Category API
    /**
     * @api {put} /api/update-category/:id Update Category API
     * @apiGroup Category
     * @apiHeader {String} Authorization
     * @apiParam (Request body) {number} categoryId Category categoryId
     * @apiParam (Request body) {String} name Category name
     * @apiParam (Request body) {number} parentInt Category  parentInt
     * @apiParam (Request body) {number} sortOrder Category sortOrder
     * @apiParam (Request body) {String} metaTagTitle Category metaTagTitle
     * @apiParam (Request body) {String} metaTagDescription Category metaTagDescription
     * @apiParam (Request body) {String} metaTagKeyword Category metaTagKeyword
     * @apiParam (Request body) {Number} status Category status 1-> Active 0-> inactive
     * @apiParamExample {json} Input
     * {
     *      "categoryId" : "",
     *      "name" : "",
     *      "parentInt" : "",
     *      "sortOrder" : "",
     *      "metaTagTitle" : "",
     *      "metaTagDescription" : "",
     *      "metaTagKeyword" : "",
     *      "status" : "",
     * }
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "message": "Successfully updated Category.",
     *      "status": "1"
     * }
     * @apiSampleRequest /api/update-category/:id
     * @apiErrorExample {json} Category error
     * HTTP/1.1 500 Internal Server Error
     */
    @Put('/update-category/:id')
    @Authorized()
    public async updateCategory(@Body({validate: true}) category: UpdateCategoryRequest, @Res() response: any, @Req() request: any): Promise<Category> {
        const categoryId = await this.categoryService.findOne({
            where: {
                categoryId: category.categoryId,
            },
        });
        if (!categoryId) {
            const errorResponse: any = {
                status: 0,
                message: 'Invalid categoryId',
            };
            return response.status(400).send(errorResponse);
        }
        categoryId.name = category.name;
        categoryId.parentInt = category.parentInt;
        categoryId.sortOrder = category.sortOrder;
        categoryId.metaTagTitle = category.metaTagTitle;
        categoryId.metaTagDescription = category.metaTagDescription;
        categoryId.metaTagKeyword = category.metaTagKeyword;
        categoryId.isActive = category.status;
        const categorySave = await this.categoryService.create(categoryId);

        const deleteCategory = await this.categoryPathService.find({where: {categoryId: category.categoryId}});
        for (const val of deleteCategory) {
            await this.categoryPathService.delete(val.categoryPathId);
        }

        const getAllPath: any = await this.categoryPathService.find({
            where: {categoryId: category.parentInt},
            order: {level: 'ASC'},
        });
        console.log(getAllPath);
        let level = 0;
        for (const path of getAllPath) {
            const CategoryPathLoop: any = new CategoryPath();
            CategoryPathLoop.categoryId = categorySave.categoryId;
            CategoryPathLoop.pathId = path.pathId;
            CategoryPathLoop.level = level;
            this.categoryPathService.create(CategoryPathLoop);
            level++;
        }

        const newCategoryPath = new CategoryPath();
        newCategoryPath.categoryId = categorySave.categoryId;
        newCategoryPath.pathId = categorySave.categoryId;
        newCategoryPath.level = level;
        await this.categoryPathService.create(newCategoryPath);

        if (categorySave !== undefined) {
            const successResponse: any = {
                status: 1,
                message: 'Successfully updated category.',
                data: classToPlain(categorySave),
            };
            return response.status(200).send(successResponse);
        } else {
            const errorResponse: any = {
                status: 0,
                message: 'Unable to update the category. ',
            };
            return response.status(400).send(errorResponse);
        }
    }
Example #26
Source File: CustomerController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
// Customer Edit Profile API
    /**
     * @api {post} /api/customer/edit-profile Edit Profile API
     * @apiGroup Store
     * @apiHeader {String} Authorization
     * @apiParam (Request body) {String} firstName First Name
     * @apiParam (Request body) {String} lastName Last Name
     * @apiParam (Request body) {String} password password
     * @apiParam (Request body) {String} emailId User Email Id
     * @apiParam (Request body) {Number} phoneNumber User Phone Number (Optional)
     * @apiParam (Request body) {String} image Customer Image
     * @apiParamExample {json} Input
     * {
     *      "firstName" : "",
     *      "lastName" : "",
     *      "password" "",
     *      "emailId" : "",
     *      "phoneNumber" : "",
     *      "image": "",
     * }
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "message": "Successfully updated your profile.",
     *      "status": "1"
     * }
     * @apiSampleRequest /api/customer/edit-profile
     * @apiErrorExample {json} Register error
     * HTTP/1.1 500 Internal Server Error
     */
    // Customer Profile Edit Function
    @Post('/edit-profile')
    @Authorized('customer')
    public async editProfile(@Body({validate: true}) customerEditProfileRequest: CustomerEditProfileRequest, @Req() request: any, @Res() response: any): Promise<any> {
        const image = customerEditProfileRequest.image;
        let name;

        const resultData = await this.customerService.findOne({
            select: ['id', 'firstName', 'lastName', 'email', 'mobileNumber', 'address', 'zoneId', 'countryId', 'pincode', 'avatar', 'avatarPath', 'password'],
            where: {id: request.user.id},
        });
        if (image) {
            const base64Data = new Buffer(image.replace(/^data:image\/\w+;base64,/, ''), 'base64');
            const type = image.split(';')[0].split('/')[1];
            name = 'Img_' + Date.now() + '.' + type; // path.extname(file.originalname);
            const path = 'customer/';
            let val: any;
            if (env.imageserver === 's3') {
                val = await this.s3Service.imageUpload((path + name), base64Data, type);
            } else {
                val = await this.imageService.imageUpload((path + name), base64Data);
            }
            console.log(val);
            resultData.avatar = name;
            resultData.avatarPath = path;
        }
        resultData.firstName = customerEditProfileRequest.firstName;
        resultData.lastName = customerEditProfileRequest.lastName;
        resultData.email = customerEditProfileRequest.emailId;
        resultData.mobileNumber = customerEditProfileRequest.phoneNumber;
        resultData.username = customerEditProfileRequest.emailId;
        if (customerEditProfileRequest.password) {
            // if (await Customer.comparePassword(resultData, customerEditProfileRequest.oldPassword)) {
            resultData.password = await Customer.hashPassword(customerEditProfileRequest.password);
            const updateUserData = await this.customerService.update(resultData.id, resultData);
            if (updateUserData) {
                const successResponseResult: any = {
                    status: 1,
                    message: 'Your profile Update Successfully.',
                    data: classToPlain(updateUserData),
                };
                return response.status(200).send(successResponseResult);
            }

        }
        const updateuserData = await this.customerService.update(resultData.id, resultData);
        const successResponse: any = {
            status: 1,
            message: 'Your profile Update Successfully.',
            data: classToPlain(updateuserData),
        };
        return response.status(200).send(successResponse);
    }
Example #27
Source File: ProductController.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
// Product Details API
    /**
     * @api {get} /api/product-store/productdetail/:id Product Detail API
     * @apiGroup Store
     * @apiHeader {String} Authorization
     * @apiSuccessExample {json} Success
     * HTTP/1.1 200 OK
     * {
     *      "status": "1"
     *      "message": "Successfully get product Detail",
     *      "data":"{}"
     * }
     * @apiSampleRequest /api/product-store/productdetail/:id
     * @apiErrorExample {json} productDetail error
     * HTTP/1.1 500 Internal Server Error
     */
    @Get('/productdetail/:id')
    public async productDetail(@Param('id') id: number, @Req() request: any, @Res() response: any): Promise<any> {
        const productDetail: any = await this.productService.findOne({
            productId: id,
        });
        const productDetails: any = classToPlain(productDetail);
        productDetails.productImage = await this.productImageService.findAll({
            select: ['productId', 'image', 'containerName', 'defaultImage'],
            where: {
                productId: id,
                },
        });
        productDetails.Category = await this.productToCategoryService.findAll({
            select: ['categoryId', 'productId'],
            where: {productId: id},
        }).then((val) => {
            const category = val.map(async (value: any) => {
                const categoryNames = await this.categoryService.findOne({categoryId: value.categoryId});
                const temp: any = value;
                if (categoryNames !== undefined ) {
                    temp.categoryName = categoryNames.name;
                } else {
                    temp.categoryName = '';
                }
                return temp;
            });
            const results = Promise.all(category);
            return results;
        });
            if (request.header('authorization')) {
            let customerId;
            jwt.verify(request.header('authorization').split(' ')[1], '123##$$)(***&', (err, decoded) => {
                if (err) {
                    console.log(err);
                }
                console.log('lll', decoded.id);
                customerId = decoded.id;
            });
            const wishStatus = await this.customerWishlistService.findOne({
                where: {
                    productId: id,
                    customerId,
                },
            });
            if (wishStatus) {
                productDetails.wishListStatus = 1;
            } else {
                productDetails.wishListStatus = 0;
            }

            const customerDetail = await this.customerService.findOne({where: {id: customerId}});
            const viewLog: any = new ProductViewLog();
            viewLog.productId = id;
            viewLog.customerId = customerDetail.id;
            viewLog.firstName = customerDetail.firstName;
            viewLog.lastName = customerDetail.lastName;
            viewLog.username = customerDetail.username;
            viewLog.email = customerDetail.email;
            viewLog.mobileNumber = customerDetail.mobileNumber;
            viewLog.address = customerDetail.address;
            await this.productViewLogService.create(viewLog);
        } else {
            productDetails.wishListStatus = 0;
        }

        const successResponse: any = {
            status: 1,
            message: 'Successfully get productDetail',
            data: productDetails,
        };
        return response.status(200).send(successResponse);
    }