@bagelink/auth 1.1.39 → 1.1.43

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/dist/index.mjs CHANGED
@@ -1,160 +1,140 @@
1
- import 'axios';
1
+ import axios from 'axios';
2
2
 
3
- let api$1 = null;
4
- function getApi() {
5
- if (!api$1) {
6
- throw new Error("API not initialized. Call initApi first.");
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => {
6
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ return value;
8
+ };
9
+ class AuthApi {
10
+ constructor(baseURL) {
11
+ __publicField(this, "api");
12
+ this.api = axios.create({
13
+ baseURL,
14
+ headers: {
15
+ "Content-Type": "application/json"
16
+ }
17
+ });
18
+ this.setupInterceptors();
7
19
  }
8
- return api$1;
9
- }
10
-
11
- const ax = getApi();
12
- ax.interceptors.request.use((config) => {
13
- const token = localStorage.getItem("access_token");
14
- if (token !== null && config.headers) {
15
- config.headers.Authorization = `Bearer ${token}`;
20
+ setupInterceptors() {
21
+ this.api.interceptors.request.use((config) => {
22
+ const token = localStorage.getItem("access_token");
23
+ if (token !== null && config.headers) {
24
+ config.headers.Authorization = `Bearer ${token}`;
25
+ }
26
+ const urlParams = new URLSearchParams(window.location.search);
27
+ const resetToken = urlParams.get("token");
28
+ if (resetToken !== null && config.headers) {
29
+ config.headers.Authorization = `Bearer ${resetToken}`;
30
+ }
31
+ return config;
32
+ });
16
33
  }
17
- const urlParams = new URLSearchParams(window.location.search);
18
- const resetToken = urlParams.get("token");
19
- if (resetToken !== null && config.headers) {
20
- config.headers.Authorization = `Bearer ${resetToken}`;
34
+ async login(username, password) {
35
+ const { data } = await this.api.post("/auth/login", {
36
+ username: username.toLowerCase(),
37
+ password
38
+ });
39
+ localStorage.setItem("access_token", data.access_token);
40
+ return { data };
41
+ }
42
+ logout() {
43
+ localStorage.removeItem("access_token");
44
+ window.location.reload();
45
+ }
46
+ async passwordRecovery(email) {
47
+ return this.api.post("/auth/password-recovery", { email });
48
+ }
49
+ async resetPassword(newPassword) {
50
+ return this.api.post("/auth/reset-password", { new_password: newPassword });
51
+ }
52
+ async getCurrentUser() {
53
+ return this.api.get("/users/me");
54
+ }
55
+ async signup(user) {
56
+ return this.api.post("/users/signup", {
57
+ email: user.email.toLowerCase(),
58
+ password: user.password,
59
+ first_name: user.first_name,
60
+ last_name: user.last_name
61
+ });
62
+ }
63
+ async updatePassword(form) {
64
+ return this.api.patch("/users/me/password", {
65
+ current_password: form.current_password,
66
+ new_password: form.new_password
67
+ });
68
+ }
69
+ async updateUserProfile(user) {
70
+ return this.api.patch("/users/me", user);
71
+ }
72
+ async setUserStatus(userId, isActive) {
73
+ return this.api.patch(`/users/${userId}`, { is_active: isActive });
74
+ }
75
+ async deleteUser(userId) {
76
+ return this.api.delete(`/users/${userId}`);
77
+ }
78
+ async getUsers(limit = 100, skip) {
79
+ return this.api.get("/users/", { params: { skip, limit } });
80
+ }
81
+ async createUser(user) {
82
+ return this.api.post("/users/", user);
83
+ }
84
+ async getUser(userId) {
85
+ return this.api.get(`/users/${userId}`);
21
86
  }
22
- return config;
23
- });
24
- async function login(username, password) {
25
- const { data } = await ax.post("/auth/login", {
26
- username: username.toLowerCase(),
27
- password
28
- });
29
- localStorage.setItem("access_token", data.access_token);
30
- }
31
- function logout() {
32
- localStorage.removeItem("access_token");
33
- window.location.reload();
34
- }
35
- async function passwordRecovery(email) {
36
- return ax.post(`/auth/password-recovery`, { email });
37
- }
38
- async function resetPassword(newPassword) {
39
- return ax.post("/auth/reset-password", { new_password: newPassword });
40
- }
41
- async function getCurrentUser() {
42
- return ax.get("/auth/me");
43
- }
44
- async function signup(user) {
45
- return ax.post("/auth/signup", {
46
- email: user.email.toLowerCase(),
47
- password: user.password,
48
- first_name: user.first_name,
49
- last_name: user.last_name
50
- });
51
- }
52
- async function updatePassword(form) {
53
- return ax.put("/auth/password", {
54
- current_password: form.current_password,
55
- new_password: form.new_password
56
- });
57
- }
58
- async function updateUserProfile(user) {
59
- return ax.put("/auth/profile", user);
60
- }
61
- async function setUserStatus(userId, isActive) {
62
- return ax.patch(`/auth/users/${userId}/status`, { is_active: isActive });
63
- }
64
- async function deleteUser(userId) {
65
- return ax.delete(`/auth/users/${userId}`);
66
87
  }
67
88
 
68
- let api = null;
69
- let onError = null;
70
- let createRef = null;
71
- const defaultReactiveFactory = (initial) => {
72
- let value = initial;
73
- return {
74
- get value() {
75
- return value;
76
- },
77
- set: (newValue) => {
78
- value = newValue;
79
- }
80
- };
89
+ let authApi = null;
90
+ const currentUser = {
91
+ value: {
92
+ id: "",
93
+ email: "",
94
+ first_name: "",
95
+ last_name: "",
96
+ is_superuser: false,
97
+ is_active: false
98
+ },
99
+ set: (newValue) => {
100
+ currentUser.value = newValue;
101
+ }
81
102
  };
82
- function createVueReactiveFactory(app) {
83
- return (initial) => {
84
- const refValue = app.ref(initial);
85
- return {
86
- get value() {
87
- return refValue.value;
88
- },
89
- set: (v) => {
90
- refValue.value = v;
91
- }
92
- };
93
- };
94
- }
95
- function initAuth({
96
- axios,
97
- errorHandler,
98
- reactive = defaultReactiveFactory
99
- } = {}) {
100
- api = axios || null;
101
- onError = errorHandler || null;
102
- createRef = reactive;
103
+ function initAuth(baseURL) {
104
+ if (!authApi) {
105
+ authApi = new AuthApi(baseURL);
106
+ }
103
107
  return {
104
108
  install(app) {
105
- if (app.ref) {
106
- createRef = createVueReactiveFactory(app);
107
- }
108
- },
109
- useAuth
109
+ app.config.globalProperties.$auth = useAuth();
110
+ }
110
111
  };
111
112
  }
112
113
  function useAuth() {
113
- if (!api || !createRef) {
114
- throw new Error("Auth composable not initialized. Call initAuth first.");
114
+ if (!authApi) {
115
+ throw new Error("Auth not initialized. Call initAuth first.");
115
116
  }
116
- const currentUser = createRef({
117
- id: "",
118
- email: "",
119
- first_name: "",
120
- last_name: "",
121
- is_superuser: false,
122
- is_active: false
123
- });
124
- const passwordForm = createRef({
125
- current_password: "",
126
- new_password: "",
127
- confirmNewPassword: ""
128
- });
129
117
  const getFullName = () => `${currentUser.value.first_name} ${currentUser.value.last_name}`;
130
118
  const getIsLoggedIn = () => currentUser.value.id.length > 0;
131
- function handleError(error) {
132
- if (onError) {
133
- onError(error);
134
- }
135
- throw error;
136
- }
137
- async function logout$1() {
119
+ async function logout() {
138
120
  try {
139
- await logout();
121
+ await authApi.logout();
140
122
  } catch (error) {
141
- handleError(error);
123
+ throw error;
142
124
  }
143
125
  }
144
- async function login$1(credentials) {
145
- const email = credentials.email.toLowerCase();
146
- const { password } = credentials;
126
+ async function login(credentials) {
147
127
  try {
148
- await login(email, password);
128
+ await authApi.login(credentials.email.toLowerCase(), credentials.password);
149
129
  await checkAuth();
150
130
  } catch (error) {
151
- handleError(error);
131
+ throw error;
152
132
  }
153
133
  }
154
134
  async function checkAuth() {
155
135
  try {
156
136
  if (!getIsLoggedIn()) {
157
- const { data } = await getCurrentUser();
137
+ const { data } = await authApi.getCurrentUser();
158
138
  currentUser.set(data);
159
139
  }
160
140
  } catch (error) {
@@ -162,95 +142,81 @@ function useAuth() {
162
142
  }
163
143
  return getIsLoggedIn();
164
144
  }
165
- async function signup$1(user) {
145
+ async function signup(user) {
166
146
  try {
167
147
  if (user.password !== user.confirmPassword) {
168
148
  throw new Error("Passwords do not match");
169
149
  }
170
- const { data } = await signup(user);
150
+ const { data } = await authApi.signup(user);
171
151
  currentUser.set(data);
172
152
  } catch (error) {
173
- handleError(error);
153
+ throw error;
174
154
  }
175
155
  }
176
156
  async function recoverPassword(email) {
177
157
  try {
178
- await passwordRecovery(email);
158
+ await authApi.passwordRecovery(email);
179
159
  } catch (error) {
180
- handleError(error);
160
+ throw error;
181
161
  }
182
162
  }
183
- async function resetPassword$1(form) {
163
+ async function resetPassword(newPassword) {
184
164
  try {
185
- if (form.new_password !== form.confirmNewPassword) {
186
- throw new Error("Passwords do not match");
187
- }
188
- await resetPassword(form.new_password);
189
- form = {
190
- current_password: "",
191
- new_password: "",
192
- confirmNewPassword: ""
193
- };
165
+ await authApi.resetPassword(newPassword);
194
166
  } catch (error) {
195
- handleError(error);
167
+ throw error;
196
168
  }
197
169
  }
198
- async function updatePassword$1() {
170
+ async function updatePassword(form) {
199
171
  try {
200
- if (passwordForm.value.new_password !== passwordForm.value.confirmNewPassword) {
172
+ if (form.new_password !== form.confirmNewPassword) {
201
173
  throw new Error("Passwords do not match");
202
174
  }
203
- await updatePassword(passwordForm.value);
204
- passwordForm.set({
205
- current_password: "",
206
- new_password: "",
207
- confirmNewPassword: ""
208
- });
175
+ await authApi.updatePassword(form);
209
176
  } catch (error) {
210
- handleError(error);
177
+ throw error;
211
178
  }
212
179
  }
213
180
  async function updateProfile(user) {
214
181
  try {
215
- const { data } = await updateUserProfile(user);
182
+ const { data } = await authApi.updateUserProfile(user);
216
183
  currentUser.set({ ...currentUser.value, ...data });
217
184
  } catch (error) {
218
- handleError(error);
185
+ throw error;
219
186
  }
220
187
  }
221
188
  async function toggleUserStatus(userId, isActive) {
222
189
  try {
223
- await setUserStatus(userId, isActive);
190
+ await authApi.setUserStatus(userId, isActive);
224
191
  } catch (error) {
225
- handleError(error);
192
+ throw error;
226
193
  }
227
194
  }
228
- async function deleteUser$1(userId) {
195
+ async function deleteUser(userId) {
229
196
  try {
230
- await deleteUser(userId);
197
+ await authApi.deleteUser(userId);
231
198
  } catch (error) {
232
- handleError(error);
199
+ throw error;
233
200
  }
234
201
  }
235
202
  return {
236
203
  // State
237
204
  currentUser,
238
- passwordForm,
239
205
  // Getters
240
206
  getFullName,
241
207
  getIsLoggedIn,
242
208
  // Actions
243
- logout: logout$1,
244
- login: login$1,
209
+ logout,
210
+ login,
245
211
  checkAuth,
246
- signup: signup$1,
212
+ signup,
247
213
  recoverPassword,
248
- resetPassword: resetPassword$1,
249
- updatePassword: updatePassword$1,
214
+ resetPassword,
215
+ updatePassword,
250
216
  updateProfile,
251
217
  toggleUserStatus,
252
- deleteUser: deleteUser$1
218
+ deleteUser
253
219
  };
254
220
  }
255
221
 
256
- export { deleteUser, getCurrentUser, initAuth, login, logout, passwordRecovery, resetPassword, setUserStatus, signup, updatePassword, updateUserProfile, useAuth };
222
+ export { AuthApi, initAuth, useAuth };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@bagelink/auth",
3
3
  "type": "module",
4
- "version": "1.1.39",
4
+ "version": "1.1.43",
5
5
  "description": "Bagelink auth package",
6
6
  "author": {
7
7
  "name": "Bagel Studio",
@@ -41,12 +41,22 @@
41
41
  "devDependencies": {
42
42
  "@types/node": "^20.0.0",
43
43
  "typescript": "^5.0.0",
44
- "unbuild": "^2.0.0"
44
+ "unbuild": "^2.0.0",
45
+ "@typescript-eslint/eslint-plugin": "^7.0.1",
46
+ "@typescript-eslint/parser": "^7.0.1",
47
+ "eslint": "^8.56.0",
48
+ "rimraf": "^5.0.5",
49
+ "tsup": "^8.0.2"
50
+ },
51
+ "peerDependencies": {
52
+ "vue": "^3.0.0"
45
53
  },
46
54
  "scripts": {
47
55
  "dev": "unbuild --stub",
48
56
  "build": "unbuild",
49
57
  "start": "tsx src/index.ts",
50
- "watch": "tsx watch src/index.ts"
58
+ "watch": "tsx watch src/index.ts",
59
+ "lint": "eslint . --ext .ts",
60
+ "clean": "rimraf dist"
51
61
  }
52
62
  }
package/src/api/auth.ts CHANGED
@@ -1,81 +1,121 @@
1
- import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
2
- import type { User, NewUser, UpdatePasswordForm } from '../types'
3
- import { getApi } from './api'
1
+ import type { InternalAxiosRequestConfig } from 'axios'
2
+ import type {
3
+ User,
4
+ NewUser,
5
+ UpdatePasswordForm,
6
+ Token,
7
+ NewPassword,
8
+ UserCreate,
9
+ SanitizedUserOut,
10
+ SanitizedUserList,
11
+ LoginResponse,
12
+ PasswordRecoveryResponse,
13
+ ResetPasswordResponse,
14
+ GetUserResponse,
15
+ UpdateUserResponse,
16
+ DeleteUserResponse,
17
+ GetUsersResponse,
18
+ CreateUserResponse,
19
+ GetMeResponse,
20
+ UpdateMeResponse,
21
+ UpdatePasswordResponse,
22
+ SignupResponse
23
+ } from '../types'
24
+ import axios from 'axios'
4
25
 
5
- export interface NewPasswordPayload {
6
- token: string
7
- new_password: string
8
- }
26
+ export class AuthApi {
27
+ private api: ReturnType<typeof axios.create>
28
+
29
+ constructor(baseURL?: string) {
30
+ this.api = axios.create({
31
+ baseURL,
32
+ headers: {
33
+ 'Content-Type': 'application/json',
34
+ },
35
+ })
36
+ this.setupInterceptors()
37
+ }
38
+
39
+ private setupInterceptors() {
40
+ this.api.interceptors.request.use((config: InternalAxiosRequestConfig) => {
41
+ const token = localStorage.getItem('access_token')
42
+ if (token !== null && config.headers) {
43
+ config.headers.Authorization = `Bearer ${token}`
44
+ }
9
45
 
10
- const ax = getApi()
46
+ const urlParams = new URLSearchParams(window.location.search)
47
+ const resetToken = urlParams.get('token')
11
48
 
12
- ax.interceptors.request.use((config: InternalAxiosRequestConfig) => {
13
- const token = localStorage.getItem('access_token')
14
- if (token !== null && config.headers) {
15
- config.headers.Authorization = `Bearer ${token}`
49
+ if (resetToken !== null && config.headers) {
50
+ config.headers.Authorization = `Bearer ${resetToken}`
51
+ }
52
+ return config
53
+ })
16
54
  }
17
55
 
18
- const urlParams = new URLSearchParams(window.location.search)
19
- const resetToken = urlParams.get('token')
56
+ async login(username: string, password: string): Promise<LoginResponse> {
57
+ const { data } = await this.api.post<Token>('/auth/login', {
58
+ username: username.toLowerCase(),
59
+ password,
60
+ })
61
+ localStorage.setItem('access_token', data.access_token)
62
+ return { data } as LoginResponse
63
+ }
20
64
 
21
- if (resetToken !== null && config.headers) {
22
- config.headers.Authorization = `Bearer ${resetToken}`
65
+ logout() {
66
+ localStorage.removeItem('access_token')
67
+ window.location.reload()
23
68
  }
24
- return config
25
- })
26
-
27
- export async function login(username: string, password: string) {
28
- const { data } = await ax.post('/auth/login', {
29
- username: username.toLowerCase(),
30
- password,
31
- })
32
- localStorage.setItem('access_token', data.access_token)
33
- }
34
69
 
35
- export function logout() {
36
- localStorage.removeItem('access_token')
37
- window.location.reload()
38
- }
70
+ async passwordRecovery(email?: string): Promise<PasswordRecoveryResponse> {
71
+ return this.api.post('/auth/password-recovery', { email })
72
+ }
39
73
 
40
- export async function passwordRecovery(email?: string): Promise<AxiosResponse> {
41
- return ax.post(`/auth/password-recovery`, { email })
42
- }
74
+ async resetPassword(newPassword: NewPassword['new_password']): Promise<ResetPasswordResponse> {
75
+ return this.api.post('/auth/reset-password', { new_password: newPassword })
76
+ }
43
77
 
44
- export async function resetPassword(
45
- newPassword: NewPasswordPayload['new_password'],
46
- ): Promise<AxiosResponse> {
47
- return ax.post('/auth/reset-password', { new_password: newPassword })
48
- }
78
+ async getCurrentUser(): Promise<GetMeResponse> {
79
+ return this.api.get<SanitizedUserOut>('/users/me')
80
+ }
49
81
 
50
- // User Management APIs
51
- export async function getCurrentUser(): Promise<AxiosResponse<User>> {
52
- return ax.get('/auth/me')
53
- }
82
+ async signup(user: NewUser): Promise<SignupResponse> {
83
+ return this.api.post<SanitizedUserOut>('/users/signup', {
84
+ email: user.email.toLowerCase(),
85
+ password: user.password,
86
+ first_name: user.first_name,
87
+ last_name: user.last_name,
88
+ })
89
+ }
54
90
 
55
- export async function signup(user: NewUser): Promise<AxiosResponse<User>> {
56
- return ax.post('/auth/signup', {
57
- email: user.email.toLowerCase(),
58
- password: user.password,
59
- first_name: user.first_name,
60
- last_name: user.last_name,
61
- })
62
- }
91
+ async updatePassword(form: UpdatePasswordForm): Promise<UpdatePasswordResponse> {
92
+ return this.api.patch('/users/me/password', {
93
+ current_password: form.current_password,
94
+ new_password: form.new_password,
95
+ })
96
+ }
63
97
 
64
- export async function updatePassword(form: UpdatePasswordForm): Promise<AxiosResponse> {
65
- return ax.put('/auth/password', {
66
- current_password: form.current_password,
67
- new_password: form.new_password,
68
- })
69
- }
98
+ async updateUserProfile(user: Partial<User>): Promise<UpdateMeResponse> {
99
+ return this.api.patch<SanitizedUserOut>('/users/me', user)
100
+ }
70
101
 
71
- export async function updateUserProfile(user: Partial<User>): Promise<AxiosResponse<User>> {
72
- return ax.put('/auth/profile', user)
73
- }
102
+ async setUserStatus(userId: string, isActive: boolean): Promise<UpdateUserResponse> {
103
+ return this.api.patch<SanitizedUserOut>(`/users/${userId}`, { is_active: isActive })
104
+ }
74
105
 
75
- export async function setUserStatus(userId: string, isActive: boolean): Promise<AxiosResponse> {
76
- return ax.patch(`/auth/users/${userId}/status`, { is_active: isActive })
77
- }
106
+ async deleteUser(userId: string): Promise<DeleteUserResponse> {
107
+ return this.api.delete(`/users/${userId}`)
108
+ }
109
+
110
+ async getUsers(limit: number = 100, skip?: number): Promise<GetUsersResponse> {
111
+ return this.api.get<SanitizedUserList>('/users/', { params: { skip, limit } })
112
+ }
78
113
 
79
- export async function deleteUser(userId: string): Promise<AxiosResponse> {
80
- return ax.delete(`/auth/users/${userId}`)
114
+ async createUser(user: UserCreate): Promise<CreateUserResponse> {
115
+ return this.api.post<SanitizedUserOut>('/users/', user)
116
+ }
117
+
118
+ async getUser(userId: string): Promise<GetUserResponse> {
119
+ return this.api.get<SanitizedUserOut>(`/users/${userId}`)
120
+ }
81
121
  }