@zlspace/z-auth 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # ZAuth
2
+
3
+ ZAuth is a authentication service for ZLS.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @zlspace/z-auth
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### User Service
14
+
15
+ ```javascript
16
+ import { createConnection, UserService, RoleService, PermissionService } from "@zlspace/z-auth";
17
+ import type { I_Users } from "@zlspace/z-auth";
18
+
19
+ const zAuth = createConnection({
20
+ baseURL: "https://z-auth-stage.zerologicspace.com/api",
21
+ apiKey: "tenant-api-key",
22
+ apiSecretKey: "tenant-api-secret-key",
23
+ });
24
+
25
+ const userService = new UserService(zAuth);
26
+
27
+ async function example1() {
28
+ const users = await userService.getUserById("paradise-1704caa");
29
+ console.log(users);
30
+ }
31
+
32
+ example1();
33
+
34
+ Output:
35
+
36
+ {
37
+ id: 'paradise-86f98b7c5030',
38
+ email: 'stickdemon2043@gmail.com',
39
+ isBlocked: false,
40
+ isEmailVerified: true,
41
+ emailVerificationToken: null,
42
+ emailVerificationTokenExpiresAt: null,
43
+ passwordResetToken: null,
44
+ passwordResetTokenExpiresAt: null,
45
+ tenantId: 5,
46
+ refreshToken: null
47
+ }
48
+ ```
49
+
50
+ ```javascript
51
+ import { createConnection, UserService } from "@zlspace/z-auth";
52
+
53
+ const zAuth = createConnection({
54
+ baseURL: "https://z-auth-stage.zerologicspace.com/api",
55
+ apiKey: "tenant-api-key",
56
+ apiSecretKey: "tenant-api-secret-key",
57
+ });
58
+
59
+ const userService = new UserService(zAuth);
60
+
61
+ async function example2() {
62
+ const data: I_Users = {
63
+ email: "user@example.com",
64
+ password: "Asdf1234!",
65
+ roleId: [2,5]
66
+ }
67
+ const users = await userService.createUser(data);
68
+ console.log(users);
69
+ }
70
+
71
+ example2();
72
+
73
+ Output:
74
+ { error: 'Must be valid email address.', status: 400 }
75
+ { error: 'User already exists', status: 400 }
76
+
77
+ ```
78
+ ## Usage Function
79
+
80
+ ### User Service
81
+
82
+ ```javascript
83
+ createUser(data: I_Users)
84
+ login(data: I_LoginRequest)
85
+ forgotPassword(data: I_ForgotPasswordRequest)
86
+ getUserById(id: string)
87
+ resetPassword(token: string, data: I_ResetPassword)
88
+ changePassword(id: string, data: I_ChangePassword)
89
+ deleteUserById(id: string)
90
+ logout(id: string)
91
+ verifyEmail(token: string)
92
+ updateUserRole(userId: string, data: I_UpdateUserByIdRequest)
93
+
94
+ ```
95
+ ### Role Service
96
+
97
+ ```javascript
98
+ createRole(name:string, description?:string)
99
+ getAllRoles()
100
+ getRoleById (id: number)
101
+ updateRoleById (id:number, name:string, description?:string)
102
+ deleteRoleById (id : number)
103
+ getPermissionsByRoleId(id: number)
104
+ getAccessToken()
105
+ getRefreshToken()
106
+ ```
107
+
108
+ ### Permissions Service
109
+
110
+ ```javascript
111
+ createPermission(module:string,access:string,description?:string)
112
+ getAllPermissions()
113
+ getPermissionById (id: number)
114
+ updatePermissionById (id:number, module:string,access:string,description?:string)
115
+ deletePermissionById (id : number)
116
+ setPermissionByRoleId (roleId: number, permissionId: number[])
117
+ setAllPermissions(roleId:number)
118
+ ```
119
+
@@ -0,0 +1,128 @@
1
+ import * as axios from 'axios';
2
+
3
+ declare class ZAuthClient {
4
+ private client;
5
+ private baseURL;
6
+ private apiKey;
7
+ private apiSecretKey;
8
+ constructor(config: {
9
+ baseURL: string;
10
+ apiKey: string;
11
+ apiSecretKey: string;
12
+ });
13
+ private getHeaders;
14
+ get(url: string): Promise<axios.AxiosResponse<any, any, {}>>;
15
+ post(url: string, data?: any): Promise<axios.AxiosResponse<any, any, {}>>;
16
+ patch(url: string, data?: any): Promise<axios.AxiosResponse<any, any, {}>>;
17
+ delete(url: string): Promise<axios.AxiosResponse<any, any, {}>>;
18
+ }
19
+ declare function createConnection(config: {
20
+ baseURL: string;
21
+ apiKey: string;
22
+ apiSecretKey: string;
23
+ }): ZAuthClient;
24
+
25
+ interface I_Users {
26
+ email?: string;
27
+ contactNumber?: string;
28
+ password: string;
29
+ roleId: number[];
30
+ }
31
+ interface I_VerficationToken {
32
+ verificationToken: string;
33
+ verificationTokenExpiresAt: Date;
34
+ }
35
+ interface I_ResetPasswordToken {
36
+ resetToken: string;
37
+ resetTokenExpiresAt: Date;
38
+ }
39
+ interface I_LoginRequest {
40
+ email?: string;
41
+ contactNumber?: string;
42
+ password: string;
43
+ }
44
+ interface I_LoginResponse {
45
+ access_token: string;
46
+ refresh_token: string;
47
+ user: {
48
+ id: string;
49
+ roles: string[];
50
+ permissions: string[];
51
+ };
52
+ }
53
+ interface I_Payload {
54
+ id: string;
55
+ roles: string[];
56
+ permissions: string[];
57
+ }
58
+ interface I_ChangePassword {
59
+ currentPassword: string;
60
+ newPassword: string;
61
+ confirmPassword: string;
62
+ }
63
+ interface I_CreatedUser {
64
+ id: string;
65
+ message?: string;
66
+ }
67
+ interface I_ForgotPasswordRequest {
68
+ email?: string;
69
+ contactNumber?: string;
70
+ }
71
+ interface I_ForgotPasswordResponse {
72
+ resetToken: string;
73
+ }
74
+ interface I_UpdateUserByIdRequest {
75
+ email?: string;
76
+ contactNumber?: string;
77
+ roleId: number[];
78
+ }
79
+ interface I_ResetPassword {
80
+ password: string;
81
+ confirmPassword: string;
82
+ }
83
+ interface I_ResetPassword {
84
+ password: string;
85
+ confirmPassword: string;
86
+ }
87
+
88
+ declare class UserService {
89
+ private client;
90
+ constructor(client: ZAuthClient);
91
+ createUser(data: I_Users): Promise<any>;
92
+ login(data: I_LoginRequest): Promise<any>;
93
+ forgotPassword(data: I_ForgotPasswordRequest): Promise<any>;
94
+ resetPassword(token: string, data: I_ResetPassword): Promise<any>;
95
+ changePassword(id: string, data: I_ChangePassword): Promise<any>;
96
+ getUserById(id: string): Promise<any>;
97
+ deleteUserById(id: string): Promise<any>;
98
+ logout(id: string): Promise<any>;
99
+ verifyEmail(token: string): Promise<any>;
100
+ updateUserRole(userId: string, data: I_UpdateUserByIdRequest): Promise<any>;
101
+ getAccessToken(): Promise<any>;
102
+ getRefreshToken(): Promise<any>;
103
+ }
104
+
105
+ declare class RoleService {
106
+ private client;
107
+ constructor(client: ZAuthClient);
108
+ createRole(name: string, description: string): Promise<any>;
109
+ getAllRole(): Promise<any>;
110
+ getRoleById(id: number): Promise<any>;
111
+ updateRoleById(id: number, name: string, description: string): Promise<any>;
112
+ deleteRoleById(id: number): Promise<any>;
113
+ getPermissionsByRoleId(id: number): Promise<any>;
114
+ }
115
+
116
+ declare class PermissionsService {
117
+ private client;
118
+ constructor(client: ZAuthClient);
119
+ createPermission(module: string, access: string, description?: string): Promise<any>;
120
+ getAllPermissions(): Promise<any>;
121
+ getPermissionById(id: number): Promise<any>;
122
+ updatePermissionById(id: number, module: string, access: string, description?: string): Promise<any>;
123
+ deletePermissionById(id: number): Promise<any>;
124
+ setPermissionByRoleId(roleId: number, permissionId: number[]): Promise<any>;
125
+ setAllPermissions(roleId: number): Promise<any>;
126
+ }
127
+
128
+ export { type I_ChangePassword, type I_CreatedUser, type I_ForgotPasswordRequest, type I_ForgotPasswordResponse, type I_LoginRequest, type I_LoginResponse, type I_Payload, type I_ResetPassword, type I_ResetPasswordToken, type I_UpdateUserByIdRequest, type I_Users, type I_VerficationToken, PermissionsService, RoleService, UserService, createConnection };
@@ -0,0 +1,128 @@
1
+ import * as axios from 'axios';
2
+
3
+ declare class ZAuthClient {
4
+ private client;
5
+ private baseURL;
6
+ private apiKey;
7
+ private apiSecretKey;
8
+ constructor(config: {
9
+ baseURL: string;
10
+ apiKey: string;
11
+ apiSecretKey: string;
12
+ });
13
+ private getHeaders;
14
+ get(url: string): Promise<axios.AxiosResponse<any, any, {}>>;
15
+ post(url: string, data?: any): Promise<axios.AxiosResponse<any, any, {}>>;
16
+ patch(url: string, data?: any): Promise<axios.AxiosResponse<any, any, {}>>;
17
+ delete(url: string): Promise<axios.AxiosResponse<any, any, {}>>;
18
+ }
19
+ declare function createConnection(config: {
20
+ baseURL: string;
21
+ apiKey: string;
22
+ apiSecretKey: string;
23
+ }): ZAuthClient;
24
+
25
+ interface I_Users {
26
+ email?: string;
27
+ contactNumber?: string;
28
+ password: string;
29
+ roleId: number[];
30
+ }
31
+ interface I_VerficationToken {
32
+ verificationToken: string;
33
+ verificationTokenExpiresAt: Date;
34
+ }
35
+ interface I_ResetPasswordToken {
36
+ resetToken: string;
37
+ resetTokenExpiresAt: Date;
38
+ }
39
+ interface I_LoginRequest {
40
+ email?: string;
41
+ contactNumber?: string;
42
+ password: string;
43
+ }
44
+ interface I_LoginResponse {
45
+ access_token: string;
46
+ refresh_token: string;
47
+ user: {
48
+ id: string;
49
+ roles: string[];
50
+ permissions: string[];
51
+ };
52
+ }
53
+ interface I_Payload {
54
+ id: string;
55
+ roles: string[];
56
+ permissions: string[];
57
+ }
58
+ interface I_ChangePassword {
59
+ currentPassword: string;
60
+ newPassword: string;
61
+ confirmPassword: string;
62
+ }
63
+ interface I_CreatedUser {
64
+ id: string;
65
+ message?: string;
66
+ }
67
+ interface I_ForgotPasswordRequest {
68
+ email?: string;
69
+ contactNumber?: string;
70
+ }
71
+ interface I_ForgotPasswordResponse {
72
+ resetToken: string;
73
+ }
74
+ interface I_UpdateUserByIdRequest {
75
+ email?: string;
76
+ contactNumber?: string;
77
+ roleId: number[];
78
+ }
79
+ interface I_ResetPassword {
80
+ password: string;
81
+ confirmPassword: string;
82
+ }
83
+ interface I_ResetPassword {
84
+ password: string;
85
+ confirmPassword: string;
86
+ }
87
+
88
+ declare class UserService {
89
+ private client;
90
+ constructor(client: ZAuthClient);
91
+ createUser(data: I_Users): Promise<any>;
92
+ login(data: I_LoginRequest): Promise<any>;
93
+ forgotPassword(data: I_ForgotPasswordRequest): Promise<any>;
94
+ resetPassword(token: string, data: I_ResetPassword): Promise<any>;
95
+ changePassword(id: string, data: I_ChangePassword): Promise<any>;
96
+ getUserById(id: string): Promise<any>;
97
+ deleteUserById(id: string): Promise<any>;
98
+ logout(id: string): Promise<any>;
99
+ verifyEmail(token: string): Promise<any>;
100
+ updateUserRole(userId: string, data: I_UpdateUserByIdRequest): Promise<any>;
101
+ getAccessToken(): Promise<any>;
102
+ getRefreshToken(): Promise<any>;
103
+ }
104
+
105
+ declare class RoleService {
106
+ private client;
107
+ constructor(client: ZAuthClient);
108
+ createRole(name: string, description: string): Promise<any>;
109
+ getAllRole(): Promise<any>;
110
+ getRoleById(id: number): Promise<any>;
111
+ updateRoleById(id: number, name: string, description: string): Promise<any>;
112
+ deleteRoleById(id: number): Promise<any>;
113
+ getPermissionsByRoleId(id: number): Promise<any>;
114
+ }
115
+
116
+ declare class PermissionsService {
117
+ private client;
118
+ constructor(client: ZAuthClient);
119
+ createPermission(module: string, access: string, description?: string): Promise<any>;
120
+ getAllPermissions(): Promise<any>;
121
+ getPermissionById(id: number): Promise<any>;
122
+ updatePermissionById(id: number, module: string, access: string, description?: string): Promise<any>;
123
+ deletePermissionById(id: number): Promise<any>;
124
+ setPermissionByRoleId(roleId: number, permissionId: number[]): Promise<any>;
125
+ setAllPermissions(roleId: number): Promise<any>;
126
+ }
127
+
128
+ export { type I_ChangePassword, type I_CreatedUser, type I_ForgotPasswordRequest, type I_ForgotPasswordResponse, type I_LoginRequest, type I_LoginResponse, type I_Payload, type I_ResetPassword, type I_ResetPasswordToken, type I_UpdateUserByIdRequest, type I_Users, type I_VerficationToken, PermissionsService, RoleService, UserService, createConnection };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ 'use strict';var _=require('axios'),expressValidator=require('express-validator');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ___default=/*#__PURE__*/_interopDefault(_);var w=t=>___default.default.create({baseURL:t});var d=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey,this.apiSecretKey=e.apiSecretKey,this.client=w(this.baseURL);}getHeaders(){return {apikey:this.apiKey,apisecretkey:this.apiSecretKey}}async get(e){return this.client.get(e,{headers:this.getHeaders()})}async post(e,s){return this.client.post(e,s,{headers:this.getHeaders()})}async patch(e,s){return this.client.patch(e,s,{headers:this.getHeaders()})}async delete(e){return this.client.delete(e,{headers:this.getHeaders()})}};function U(t){return new d(t)}function i(t,e){return new Promise((s,r)=>{let o={body:e};(async()=>{for(let p of t.flat())await p(o,{},()=>{});let h=expressValidator.validationResult(o);if(h.isEmpty())s(true);else {let p=h.array().map(C=>C.msg);r(p);}})();})}var y=[expressValidator.body("email").optional().isEmail().withMessage("Must be valid email address."),expressValidator.body("contactNumber").optional().isLength({min:6}).withMessage("Contact number must be at least 6 characters long"),expressValidator.body("password").notEmpty().isString().withMessage("Password is required"),expressValidator.body("password").isLength({min:8}).withMessage("Password must be at least 8 characters long"),expressValidator.body("password").matches(/[A-Z]/).withMessage("Password must contain at least one uppercase letter"),expressValidator.body("password").matches(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/).withMessage("Password must contain at least one symbol"),expressValidator.body("roleId").notEmpty().withMessage("Role ID is required"),expressValidator.body("roleId").isArray({min:1}).withMessage("Atleast one role ID is required"),expressValidator.body("roleId").custom(t=>Array.isArray(t)?t.every(e=>typeof e=="number"&&!isNaN(e)):false).withMessage("Each role ID must be a number"),expressValidator.body().custom(t=>{if(!t.email&&!t.contactNumber)throw new Error("Either email or contact number is required");return true})],b=[expressValidator.body("password").notEmpty().withMessage("Password is required"),expressValidator.body("password").isLength({min:8}).withMessage("Password must be at least 8 characters long"),expressValidator.body("password").matches(/[A-Z]/).withMessage("Password must contain at least one uppercase letter"),expressValidator.body("password").matches(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/).withMessage("Password must contain at least one symbol"),expressValidator.body("confirmPassword").notEmpty().withMessage("Confirm Password is required"),expressValidator.body("confirmPassword").custom((t,{req:e})=>t===e.body.password).withMessage("Confirm Password must match Password")],P=[expressValidator.body("currentPassword").notEmpty().withMessage("Current Password is required"),expressValidator.body("currentPassword").isString().withMessage("Current Password must be a string"),expressValidator.body("newPassword").notEmpty().withMessage("New Password is required"),expressValidator.body("newPassword").isLength({min:8}).withMessage("New Password must be at least 8 characters long"),expressValidator.body("newPassword").matches(/[A-Z]/).withMessage("New Password must contain at least one uppercase letter"),expressValidator.body("newPassword").matches(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/).withMessage("New Password must contain at least one symbol"),expressValidator.body("confirmPassword").notEmpty().withMessage("Confirm Password is required"),expressValidator.body("confirmPassword").custom((t,{req:e})=>t===e.body.newPassword).withMessage("Confirm Password must match New Password")],f=[expressValidator.body("email").optional().isEmail().withMessage("Must be a valid email address"),expressValidator.body("contactNumber").optional().isLength({min:6}).withMessage("Contact number must be at least 6 characters long"),expressValidator.body().custom(t=>{if(!t.email&&!t.contactNumber)throw new Error("Either email or contact number is required");return true})],I=[expressValidator.body("email").optional().isEmail().withMessage("Must be a valid email address"),expressValidator.body("contactNumber").optional().isLength({min:6}).withMessage("Contact number must be at least 6 characters long"),expressValidator.body("roleId").notEmpty().withMessage("Role ID is required"),expressValidator.body("roleId").isArray({min:1}).withMessage("Atleast one role ID is required"),expressValidator.body("roleId").custom(t=>Array.isArray(t)?t.every(e=>typeof e=="number"&&!isNaN(e)):false).withMessage("Each role ID must be a number")];var m=class{constructor(e){this.client=e;}async createUser(e){try{return await i(y,e),(await this.client.post("/users",e)).data}catch(s){return Array.isArray(s)?{error:s.join(", "),status:400}:{error:s.response?.data||s.message,status:s.response?.status||500}}}async login(e){try{return (await this.client.post("/users/login",e)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async forgotPassword(e){try{return await i(f,e),(await this.client.post("/users/forgot-password",e)).data}catch(s){return Array.isArray(s)?{error:s.join(", "),status:400}:{error:s.response?.data||s.message,status:s.response?.status||500}}}async resetPassword(e,s){try{return await i(b,s),(await this.client.patch(`/users/reset-password/${e}`,s)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async changePassword(e,s){try{return await i(P,s),(await this.client.patch(`/users/change-password/${e}`,s)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async getUserById(e){try{return (await this.client.get(`/users/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async deleteUserById(e){try{return (await this.client.delete(`/users/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async logout(e){try{return (await this.client.get(`/users/logout/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async verifyEmail(e){try{return (await this.client.get(`/users/verify-email/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async updateUserRole(e,s){try{return await i(I,s),(await this.client.patch(`/users/update-role/${e}`,s)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async getAccessToken(){try{return (await this.client.get("/users/jwt-secert")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}async getRefreshToken(){try{return (await this.client.get("/users/refresh-secert")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}};var M=[expressValidator.body("name").notEmpty().withMessage("Name is required"),expressValidator.body("name").isString().withMessage("Name must be a string"),expressValidator.body("name").trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),expressValidator.body("name").isLength({min:3,max:16}).withMessage("Name must be between 3 and 16 characters"),expressValidator.body("description").optional().isString().withMessage("Description must be a string")],A=[expressValidator.body("name").optional().isString().trim().isLength({min:3,max:16}).withMessage("Name must be between 3 and 16 characters").customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),expressValidator.body("description").optional().isString().withMessage("Description must be a string")];var l=class{constructor(e){this.client=e;}async createRole(e,s){try{await i(M,{name:e,description:s});let r={name:e,description:s};return (await this.client.post("/roles",r)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async getAllRole(){try{return (await this.client.get("/roles")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}async getRoleById(e){try{return (await this.client.get(`/roles/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async updateRoleById(e,s,r){try{await i(A,{name:s,description:r});let o={name:s,description:r};return (await this.client.patch(`/roles/${e}`,o)).data}catch(o){return Array.isArray(o)?{error:o.join(", "),status:400}:{error:o.response?.data||o.message,status:o.response?.status||500}}}async deleteRoleById(e){try{return (await this.client.delete(`/roles/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async getPermissionsByRoleId(e){try{return (await this.client.get(`/roles/permissions/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}};var R=[expressValidator.body("module").notEmpty().withMessage("Module is required"),expressValidator.body("module").isString().withMessage("Module must be a string"),expressValidator.body("module").trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),expressValidator.body("module").isLength({min:3,max:16}).withMessage("Module must be between 3 and 16 characters"),expressValidator.body("access").notEmpty().withMessage("Access is required"),expressValidator.body("access").isString().withMessage("Access must be a string"),expressValidator.body("access").trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),expressValidator.body("access").isIn(["create","read","update","delete"]).withMessage("Access is must be create, read, update, delete"),expressValidator.body("description").optional().isString().withMessage("Description must be a string")],x=[expressValidator.body("module").optional().isString().trim().isLength({min:3,max:16}).withMessage("Module must be between 3 and 16 characters").customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),expressValidator.body("access").optional().isString().trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")).isIn(["create","read","update","delete"]),expressValidator.body("description").optional().isString().withMessage("Description must be a string")],q=[expressValidator.body("permissionId").notEmpty().withMessage("Permission ID is required"),expressValidator.body("permissionId").isArray({min:1}).withMessage("Atleast one permission ID is required"),expressValidator.body("permissionId").custom(t=>Array.isArray(t)?t.every(e=>typeof e=="number"&&!isNaN(e)):false).withMessage("Each permission ID must be a number")];var g=class{constructor(e){this.client=e;}async createPermission(e,s,r){try{return await i(R,{module:e,access:s,description:r}),(await this.client.post("/permissions",{module:e,access:s,description:r})).data}catch(o){return Array.isArray(o)?{error:o.join(", "),status:400}:{error:o.response?.data||o.message,status:o.response?.status||500}}}async getAllPermissions(){try{return (await this.client.get("/permissions")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}async getPermissionById(e){try{return (await this.client.get(`/permissions/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async updatePermissionById(e,s,r,o){try{return await i(x,{module:s,access:r,description:o}),(await this.client.patch(`/permissions/${e}`,{module:s,access:r,description:o})).data}catch(c){return Array.isArray(c)?{error:c.join(", "),status:400}:{error:c.response?.data||c.message,status:c.response?.status||500}}}async deletePermissionById(e){try{return (await this.client.delete(`/permissions/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async setPermissionByRoleId(e,s){try{return await i(q,{roleId:e,permissionId:s}),(await this.client.patch(`/permissions/set-permission/${e}`,{permissionId:s})).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async setAllPermissions(e){try{return (await this.client.patch(`/permissions/set-all-permission/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}};exports.PermissionsService=g;exports.RoleService=l;exports.UserService=m;exports.createConnection=U;
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import _ from'axios';import {body,validationResult}from'express-validator';var w=t=>_.create({baseURL:t});var d=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey,this.apiSecretKey=e.apiSecretKey,this.client=w(this.baseURL);}getHeaders(){return {apikey:this.apiKey,apisecretkey:this.apiSecretKey}}async get(e){return this.client.get(e,{headers:this.getHeaders()})}async post(e,s){return this.client.post(e,s,{headers:this.getHeaders()})}async patch(e,s){return this.client.patch(e,s,{headers:this.getHeaders()})}async delete(e){return this.client.delete(e,{headers:this.getHeaders()})}};function U(t){return new d(t)}function i(t,e){return new Promise((s,r)=>{let o={body:e};(async()=>{for(let p of t.flat())await p(o,{},()=>{});let h=validationResult(o);if(h.isEmpty())s(true);else {let p=h.array().map(C=>C.msg);r(p);}})();})}var y=[body("email").optional().isEmail().withMessage("Must be valid email address."),body("contactNumber").optional().isLength({min:6}).withMessage("Contact number must be at least 6 characters long"),body("password").notEmpty().isString().withMessage("Password is required"),body("password").isLength({min:8}).withMessage("Password must be at least 8 characters long"),body("password").matches(/[A-Z]/).withMessage("Password must contain at least one uppercase letter"),body("password").matches(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/).withMessage("Password must contain at least one symbol"),body("roleId").notEmpty().withMessage("Role ID is required"),body("roleId").isArray({min:1}).withMessage("Atleast one role ID is required"),body("roleId").custom(t=>Array.isArray(t)?t.every(e=>typeof e=="number"&&!isNaN(e)):false).withMessage("Each role ID must be a number"),body().custom(t=>{if(!t.email&&!t.contactNumber)throw new Error("Either email or contact number is required");return true})],b=[body("password").notEmpty().withMessage("Password is required"),body("password").isLength({min:8}).withMessage("Password must be at least 8 characters long"),body("password").matches(/[A-Z]/).withMessage("Password must contain at least one uppercase letter"),body("password").matches(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/).withMessage("Password must contain at least one symbol"),body("confirmPassword").notEmpty().withMessage("Confirm Password is required"),body("confirmPassword").custom((t,{req:e})=>t===e.body.password).withMessage("Confirm Password must match Password")],P=[body("currentPassword").notEmpty().withMessage("Current Password is required"),body("currentPassword").isString().withMessage("Current Password must be a string"),body("newPassword").notEmpty().withMessage("New Password is required"),body("newPassword").isLength({min:8}).withMessage("New Password must be at least 8 characters long"),body("newPassword").matches(/[A-Z]/).withMessage("New Password must contain at least one uppercase letter"),body("newPassword").matches(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/).withMessage("New Password must contain at least one symbol"),body("confirmPassword").notEmpty().withMessage("Confirm Password is required"),body("confirmPassword").custom((t,{req:e})=>t===e.body.newPassword).withMessage("Confirm Password must match New Password")],f=[body("email").optional().isEmail().withMessage("Must be a valid email address"),body("contactNumber").optional().isLength({min:6}).withMessage("Contact number must be at least 6 characters long"),body().custom(t=>{if(!t.email&&!t.contactNumber)throw new Error("Either email or contact number is required");return true})],I=[body("email").optional().isEmail().withMessage("Must be a valid email address"),body("contactNumber").optional().isLength({min:6}).withMessage("Contact number must be at least 6 characters long"),body("roleId").notEmpty().withMessage("Role ID is required"),body("roleId").isArray({min:1}).withMessage("Atleast one role ID is required"),body("roleId").custom(t=>Array.isArray(t)?t.every(e=>typeof e=="number"&&!isNaN(e)):false).withMessage("Each role ID must be a number")];var m=class{constructor(e){this.client=e;}async createUser(e){try{return await i(y,e),(await this.client.post("/users",e)).data}catch(s){return Array.isArray(s)?{error:s.join(", "),status:400}:{error:s.response?.data||s.message,status:s.response?.status||500}}}async login(e){try{return (await this.client.post("/users/login",e)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async forgotPassword(e){try{return await i(f,e),(await this.client.post("/users/forgot-password",e)).data}catch(s){return Array.isArray(s)?{error:s.join(", "),status:400}:{error:s.response?.data||s.message,status:s.response?.status||500}}}async resetPassword(e,s){try{return await i(b,s),(await this.client.patch(`/users/reset-password/${e}`,s)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async changePassword(e,s){try{return await i(P,s),(await this.client.patch(`/users/change-password/${e}`,s)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async getUserById(e){try{return (await this.client.get(`/users/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async deleteUserById(e){try{return (await this.client.delete(`/users/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async logout(e){try{return (await this.client.get(`/users/logout/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async verifyEmail(e){try{return (await this.client.get(`/users/verify-email/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async updateUserRole(e,s){try{return await i(I,s),(await this.client.patch(`/users/update-role/${e}`,s)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async getAccessToken(){try{return (await this.client.get("/users/jwt-secert")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}async getRefreshToken(){try{return (await this.client.get("/users/refresh-secert")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}};var M=[body("name").notEmpty().withMessage("Name is required"),body("name").isString().withMessage("Name must be a string"),body("name").trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),body("name").isLength({min:3,max:16}).withMessage("Name must be between 3 and 16 characters"),body("description").optional().isString().withMessage("Description must be a string")],A=[body("name").optional().isString().trim().isLength({min:3,max:16}).withMessage("Name must be between 3 and 16 characters").customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),body("description").optional().isString().withMessage("Description must be a string")];var l=class{constructor(e){this.client=e;}async createRole(e,s){try{await i(M,{name:e,description:s});let r={name:e,description:s};return (await this.client.post("/roles",r)).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async getAllRole(){try{return (await this.client.get("/roles")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}async getRoleById(e){try{return (await this.client.get(`/roles/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async updateRoleById(e,s,r){try{await i(A,{name:s,description:r});let o={name:s,description:r};return (await this.client.patch(`/roles/${e}`,o)).data}catch(o){return Array.isArray(o)?{error:o.join(", "),status:400}:{error:o.response?.data||o.message,status:o.response?.status||500}}}async deleteRoleById(e){try{return (await this.client.delete(`/roles/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async getPermissionsByRoleId(e){try{return (await this.client.get(`/roles/permissions/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}};var R=[body("module").notEmpty().withMessage("Module is required"),body("module").isString().withMessage("Module must be a string"),body("module").trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),body("module").isLength({min:3,max:16}).withMessage("Module must be between 3 and 16 characters"),body("access").notEmpty().withMessage("Access is required"),body("access").isString().withMessage("Access must be a string"),body("access").trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),body("access").isIn(["create","read","update","delete"]).withMessage("Access is must be create, read, update, delete"),body("description").optional().isString().withMessage("Description must be a string")],x=[body("module").optional().isString().trim().isLength({min:3,max:16}).withMessage("Module must be between 3 and 16 characters").customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")),body("access").optional().isString().trim().customSanitizer(t=>t.toLowerCase().replace(/\s+/g,"-")).isIn(["create","read","update","delete"]),body("description").optional().isString().withMessage("Description must be a string")],q=[body("permissionId").notEmpty().withMessage("Permission ID is required"),body("permissionId").isArray({min:1}).withMessage("Atleast one permission ID is required"),body("permissionId").custom(t=>Array.isArray(t)?t.every(e=>typeof e=="number"&&!isNaN(e)):false).withMessage("Each permission ID must be a number")];var g=class{constructor(e){this.client=e;}async createPermission(e,s,r){try{return await i(R,{module:e,access:s,description:r}),(await this.client.post("/permissions",{module:e,access:s,description:r})).data}catch(o){return Array.isArray(o)?{error:o.join(", "),status:400}:{error:o.response?.data||o.message,status:o.response?.status||500}}}async getAllPermissions(){try{return (await this.client.get("/permissions")).data}catch(e){return {error:e.response?.data||e.message,status:e.response?.status||500}}}async getPermissionById(e){try{return (await this.client.get(`/permissions/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async updatePermissionById(e,s,r,o){try{return await i(x,{module:s,access:r,description:o}),(await this.client.patch(`/permissions/${e}`,{module:s,access:r,description:o})).data}catch(c){return Array.isArray(c)?{error:c.join(", "),status:400}:{error:c.response?.data||c.message,status:c.response?.status||500}}}async deletePermissionById(e){try{return (await this.client.delete(`/permissions/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}async setPermissionByRoleId(e,s){try{return await i(q,{roleId:e,permissionId:s}),(await this.client.patch(`/permissions/set-permission/${e}`,{permissionId:s})).data}catch(r){return Array.isArray(r)?{error:r.join(", "),status:400}:{error:r.response?.data||r.message,status:r.response?.status||500}}}async setAllPermissions(e){try{return (await this.client.patch(`/permissions/set-all-permission/${e}`)).data}catch(s){return {error:s.response?.data||s.message,status:s.response?.status||500}}}};export{g as PermissionsService,l as RoleService,m as UserService,U as createConnection};
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@zlspace/z-auth",
3
+ "version": "1.0.0",
4
+ "description": "ZAuth is a authentication service for ZLS.NP",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist/",
10
+ "README.md"
11
+ ],
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.mjs",
17
+ "require": "./dist/index.js",
18
+ "default": "./dist/index.mjs"
19
+ },
20
+ "./package.json": "./package.json"
21
+ },
22
+ "typesVersions": {
23
+ "*": {
24
+ "*": [
25
+ "dist/index.d.ts"
26
+ ]
27
+ }
28
+ },
29
+ "scripts": {
30
+ "test": "echo \"Error: no test specified\" && exit 1",
31
+ "build": "tsup index.ts --dts --format cjs,esm --out-dir dist",
32
+ "prepublishOnly": "npm run build"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/zerologicspace/z-auth-client.git"
37
+ },
38
+ "homepage": "https://github.com/zerologicspace/z-auth-client",
39
+ "keywords": [
40
+ "zls",
41
+ "zls.np",
42
+ "zauth",
43
+ "authentication",
44
+ "authorization"
45
+ ],
46
+ "author": "Zero Logic Space",
47
+ "license": "ISC",
48
+ "devDependencies": {
49
+ "@types/express": "^5.0.0",
50
+ "@types/node": "^22.18.1",
51
+ "concurrently": "^8.2.2",
52
+ "nodemon": "^3.1.7",
53
+ "prettier": "^3.3.3",
54
+ "ts-node": "^10.9.2",
55
+ "tsc-alias": "^1.8.10",
56
+ "tsup": "^8.5.0",
57
+ "typescript": "^5.9.2",
58
+ "winston": "^3.3.3"
59
+ },
60
+ "dependencies": {
61
+ "@types/axios": "^0.14.4",
62
+ "axios": "^1.11.0",
63
+ "express": "^4.21.1",
64
+ "express-validator": "^7.2.1"
65
+ }
66
+ }