Download src/modules/auth/auth.service.js from moustafa7/gymco: direct link, hf CLI and curl.
- Browser
- Download file 6.83 kB
-
https://huggingface.co/spaces/moustafa7/gymco/resolve/main/src/modules/auth/auth.service.js
- Command line
-
hf download hf://spaces/moustafa7/gymco/src/modules/auth/auth.service.js
-
curl -L -o auth.service.js https://huggingface.co/spaces/moustafa7/gymco/resolve/main/src/modules/auth/auth.service.js
6.83 kB
| import { ApiError } from '../../common/errors/ApiError.js'; | |
| import { comparePassword, hashPassword } from '../../common/utils/password.js'; | |
| import { signAccessToken, signRefreshToken, verifyRefreshToken } from '../../common/utils/jwt.js'; | |
| import { sendPasswordResetOtp } from '../../config/mailer.js'; | |
| import { authRepository } from './auth.repository.js'; | |
| const sanitizeUser = (user) => ({ | |
| id: user.id, | |
| gymId: user.gymId, | |
| memberId: user.memberId, | |
| name: user.name, | |
| email: user.email, | |
| phone: user.phone, | |
| nationalId: user.nationalId, | |
| role: user.role, | |
| gym: user.gym ? { id: user.gym.id, name: user.gym.name } : undefined, | |
| }); | |
| const REFRESH_TOKEN_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000; | |
| const createRefreshTokenRecord = async (userId, refreshToken) => { | |
| await authRepository.saveRefreshToken({ | |
| userId, | |
| token: refreshToken, | |
| expiresAt: new Date(Date.now() + REFRESH_TOKEN_EXPIRY_MS), | |
| }); | |
| }; | |
| export const authService = { | |
| async register(payload) { | |
| const normalized = payload.owner | |
| ? payload | |
| : { | |
| gym: { | |
| name: payload.gymName, | |
| phone: payload.gymPhone, | |
| address: payload.gymAddress, | |
| }, | |
| owner: { | |
| name: payload.ownerName, | |
| email: payload.email, | |
| password: payload.password, | |
| phone: payload.ownerPhone || payload.gymPhone, | |
| nationalId: payload.ownerNationalId, | |
| }, | |
| }; | |
| const existing = await authRepository.findUserByEmail(normalized.owner.email); | |
| if (existing) throw ApiError.conflict('Email is already registered'); | |
| const password = await hashPassword(normalized.owner.password); | |
| const result = await authRepository.createGymWithOwnerTrial({ | |
| gym: normalized.gym, | |
| owner: { | |
| name: normalized.owner.name, | |
| email: normalized.owner.email, | |
| password, | |
| role: 'owner', | |
| }, | |
| ownerPhone: normalized.owner.phone, | |
| ownerNationalId: normalized.owner.nationalId, | |
| }); | |
| const refreshToken = signRefreshToken(result.owner); | |
| await createRefreshTokenRecord(result.owner.id, refreshToken); | |
| return { | |
| user: sanitizeUser({ ...result.owner, gym: result.gym }), | |
| gym: result.gym, | |
| gymSubscription: result.gymSubscription, | |
| tokens: { accessToken: signAccessToken(result.owner), refreshToken }, | |
| }; | |
| }, | |
| async checkEmail(email) { | |
| const user = await authRepository.findUserByEmail(email); | |
| return { available: !user }; | |
| }, | |
| async login({ email, password }) { | |
| const user = await authRepository.findUserByEmail(email); | |
| if (!user || user.deletedAt || !user.isActive) throw ApiError.unauthorized('Invalid credentials'); | |
| const matches = await comparePassword(password, user.password); | |
| if (!matches) throw ApiError.unauthorized('Invalid credentials'); | |
| const refreshToken = signRefreshToken(user); | |
| await createRefreshTokenRecord(user.id, refreshToken); | |
| return { | |
| user: sanitizeUser(user), | |
| tokens: { accessToken: signAccessToken(user), refreshToken }, | |
| }; | |
| }, | |
| async refresh(refreshToken) { | |
| let payload; | |
| try { | |
| payload = verifyRefreshToken(refreshToken); | |
| } catch { | |
| throw ApiError.unauthorized('Invalid refresh token'); | |
| } | |
| const stored = await authRepository.findRefreshToken(refreshToken); | |
| if (!stored || stored.revokedAt || stored.expiresAt < new Date()) { | |
| throw ApiError.unauthorized('Refresh token expired or revoked'); | |
| } | |
| const user = await authRepository.findUserById(payload.sub); | |
| if (!user || !user.isActive) throw ApiError.unauthorized('Invalid refresh token'); | |
| await authRepository.revokeRefreshToken(stored.id); | |
| const newRefreshToken = signRefreshToken(user); | |
| await createRefreshTokenRecord(user.id, newRefreshToken); | |
| return { | |
| user: sanitizeUser(user), | |
| tokens: { accessToken: signAccessToken(user), refreshToken: newRefreshToken }, | |
| }; | |
| }, | |
| async me(userId) { | |
| const user = await authRepository.findUserById(userId); | |
| if (!user) throw ApiError.notFound('User not found'); | |
| return sanitizeUser(user); | |
| }, | |
| async loginAccounts() { | |
| const users = await authRepository.listLoginAccounts(); | |
| return users.map((user) => ({ | |
| id: user.id, | |
| name: user.name, | |
| email: user.email, | |
| role: user.role, | |
| gymName: user.gym?.name || 'بدون جيم', | |
| password: user.isDemoAccount ? 'Admin@12345' : null, | |
| passwordLabel: user.isDemoAccount ? 'Admin@12345' : 'متغيرة ومش قابلة للاسترجاع', | |
| })); | |
| }, | |
| async forgotPassword(email) { | |
| const user = await authRepository.findUserByEmail(email); | |
| const message = 'If the email exists, a verification code has been sent.'; | |
| if (!user || user.deletedAt || !user.isActive) return { message }; | |
| await authRepository.deleteUnusedPasswordResets(user.id); | |
| const otp = Math.floor(100000 + Math.random() * 900000).toString(); | |
| const expiresAt = new Date(Date.now() + 15 * 60 * 1000); | |
| await authRepository.createPasswordReset({ userId: user.id, token: otp, expiresAt }); | |
| await sendPasswordResetOtp({ to: user.email, name: user.name, otp }); | |
| return { message }; | |
| }, | |
| async verifyOtp({ email, otp }) { | |
| const user = await authRepository.findUserByEmail(email); | |
| if (!user) throw ApiError.badRequest('Invalid or expired verification code'); | |
| const reset = await authRepository.findValidPasswordReset({ userId: user.id, token: otp }); | |
| if (!reset) throw ApiError.badRequest('Invalid or expired verification code'); | |
| return { valid: true, resetToken: otp }; | |
| }, | |
| async resetPassword({ email, otp, newPassword }) { | |
| const user = await authRepository.findUserByEmail(email); | |
| if (!user) throw ApiError.badRequest('Invalid or expired verification code'); | |
| const reset = await authRepository.findValidPasswordReset({ userId: user.id, token: otp }); | |
| if (!reset) throw ApiError.badRequest('Invalid or expired verification code'); | |
| await authRepository.updatePassword(user.id, await hashPassword(newPassword)); | |
| await authRepository.markPasswordResetUsed(reset.id); | |
| await authRepository.revokeAllUserTokens(user.id); | |
| return { message: 'Password has been changed successfully' }; | |
| }, | |
| async changePassword(userId, { currentPassword, newPassword }) { | |
| const user = await authRepository.findUserById(userId); | |
| if (!user) throw ApiError.notFound('User not found'); | |
| const matches = await comparePassword(currentPassword, user.password); | |
| if (!matches) throw ApiError.unauthorized('Current password is incorrect'); | |
| await authRepository.updatePassword(user.id, await hashPassword(newPassword)); | |
| await authRepository.revokeAllUserTokens(userId); | |
| return { message: 'Password has been changed successfully' }; | |
| }, | |
| }; | |