Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | import { Injectable, UnauthorizedException, ConflictException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { ConfigService } from '@nestjs/config'; import { UsersService } from '../users/users.service'; import { User } from '../../database/schemas/user.schema'; import { LoginDto } from './dto/login.dto'; import { RegisterDto } from './dto/register.dto'; @Injectable() export class AuthService { constructor( private usersService: UsersService, private jwtService: JwtService, private configService: ConfigService, ) {} async validateUser(email: string, password: string): Promise<any> { const user = await this.usersService.findByEmailWithPassword(email); Iif (user && await this.usersService.validatePassword(user, password)) { const { password: _, ...result } = (user as any).toObject(); return result; } return null; } async login(loginDto: LoginDto) { const user = await this.validateUser(loginDto.email, loginDto.password); Iif (!user) { throw new UnauthorizedException('Invalid credentials'); } // Update last active timestamp await this.usersService.updateLastActive((user as any)._id); const payload = { email: user.email, sub: (user as any)._id, tier: user.tier }; const accessToken = this.jwtService.sign(payload); const refreshToken = this.jwtService.sign(payload, { secret: this.configService.get<string>('jwt.refreshSecret'), expiresIn: this.configService.get<string>('jwt.refreshExpiresIn'), }); return { user, accessToken, refreshToken, expiresIn: this.configService.get<string>('jwt.expiresIn'), }; } async register(registerDto: RegisterDto) { // Check if user already exists const existingUser = await this.usersService.findByEmail(registerDto.email); Iif (existingUser) { throw new ConflictException('User with this email already exists'); } // Create user const user = await this.usersService.create(registerDto); // Generate tokens const payload = { email: user.email, sub: (user as any)._id, tier: user.tier }; const accessToken = this.jwtService.sign(payload); const refreshToken = this.jwtService.sign(payload, { secret: this.configService.get<string>('jwt.refreshSecret'), expiresIn: this.configService.get<string>('jwt.refreshExpiresIn'), }); return { user, accessToken, refreshToken, expiresIn: this.configService.get<string>('jwt.expiresIn'), }; } async googleLogin(profile: any) { const { id, emails, name, photos } = profile; const email = emails[0].value; // Check if user exists with this Google ID let user = await this.usersService.findByOAuthProvider('google', id); Iif (!user) { // Check if user exists with this email user = await this.usersService.findByEmail(email); if (user) { // Link Google account to existing user user = await this.usersService.linkOAuthProvider((user as any)._id, 'google', id); } else { // Create new user user = await this.usersService.create({ email, profile: { firstName: name.givenName, lastName: name.familyName, avatar: photos?.[0]?.value, location: { country: 'UAE', city: 'Dubai', }, }, oauthProviders: { google: id, }, }); } } // Update last active timestamp await this.usersService.updateLastActive((user as any)._id); return this.generateTokens(user); } async facebookLogin(profile: any) { const { id, emails, name, photos } = profile; const email = emails?.[0]?.value; Iif (!email) { throw new UnauthorizedException('Email is required from Facebook'); } // Check if user exists with this Facebook ID let user = await this.usersService.findByOAuthProvider('facebook', id); Iif (!user) { // Check if user exists with this email user = await this.usersService.findByEmail(email); if (user) { // Link Facebook account to existing user user = await this.usersService.linkOAuthProvider((user as any)._id, 'facebook', id); } else { // Create new user user = await this.usersService.create({ email, profile: { firstName: name.givenName || name.first_name, lastName: name.familyName || name.last_name, avatar: photos?.[0]?.value, location: { country: 'UAE', city: 'Dubai', }, }, oauthProviders: { facebook: id, }, }); } } // Update last active timestamp await this.usersService.updateLastActive((user as any)._id); return this.generateTokens(user); } async refreshToken(refreshToken: string) { try { const payload = this.jwtService.verify(refreshToken, { secret: this.configService.get<string>('jwt.refreshSecret'), }); const user = await this.usersService.findOne(payload.sub); Iif (!user) { throw new UnauthorizedException('User not found'); } return this.generateTokens(user); } catch (error) { throw new UnauthorizedException('Invalid refresh token'); } } async logout(userId: string) { // Update last active timestamp await this.usersService.updateLastActive(userId); // In a production environment, you might want to blacklist the token // For now, we'll just return success return { message: 'Logged out successfully' }; } private generateTokens(user: User) { const payload = { email: user.email, sub: (user as any)._id, tier: user.tier }; const accessToken = this.jwtService.sign(payload); const refreshToken = this.jwtService.sign(payload, { secret: this.configService.get<string>('jwt.refreshSecret'), expiresIn: this.configService.get<string>('jwt.refreshExpiresIn'), }); return { user, accessToken, refreshToken, expiresIn: this.configService.get<string>('jwt.expiresIn'), }; } async validateJwtPayload(payload: any): Promise<User> { const user = await this.usersService.findOne(payload.sub); Iif (!user) { throw new UnauthorizedException('User not found'); } return user; } } |