users.service.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import {
  2. Injectable,
  3. NotFoundException,
  4. HttpException,
  5. HttpStatus,
  6. BadRequestException,
  7. InternalServerErrorException,
  8. UnauthorizedException
  9. } from '@nestjs/common'
  10. import { In, Repository, UpdateResult } from 'typeorm'
  11. import { InjectRepository } from '@nestjs/typeorm'
  12. import { Users } from './entities/users.entity'
  13. import { IUsers } from './interfaces/users.interface'
  14. import { UserCreateDto } from './dto/user-create.dto'
  15. import { UserProfileDto } from './dto/user-profile.dto'
  16. import { UserUpdateDto } from './dto/user-update.dto'
  17. import { HashingService } from '../shared/hashing/hashing.service'
  18. import { SmsService } from '../sms/sms.service'
  19. import * as randomstring from 'randomstring'
  20. import { MembershipService } from '../membership/membership.service'
  21. import { paginate, Pagination } from 'nestjs-typeorm-paginate'
  22. import { Role } from '../model/role.enum'
  23. import { PageRequest } from '../common/dto/page-request'
  24. @Injectable()
  25. export class UsersService {
  26. constructor(
  27. @InjectRepository(Users)
  28. private readonly userRepository: Repository<Users>,
  29. private readonly hashingService: HashingService,
  30. private readonly smsService: SmsService,
  31. private readonly membershipService: MembershipService
  32. ) { }
  33. async findAll(req: PageRequest<Users>): Promise<Pagination<Users>> {
  34. return await paginate<Users>(this.userRepository, req.page, req.search)
  35. }
  36. public async findByEmail(email: string): Promise<Users> {
  37. const user = await this.userRepository.findOneBy({
  38. email: email
  39. })
  40. if (!user) {
  41. throw new NotFoundException(`User not found`)
  42. }
  43. return user
  44. }
  45. public async findById(userId: number): Promise<Users> {
  46. const user = await this.userRepository.findOneBy({
  47. id: +userId
  48. })
  49. if (!user) {
  50. throw new NotFoundException(`User #${userId} not found`)
  51. }
  52. return user
  53. }
  54. async findInfoByIds(userIds: number[]): Promise<Users[]> {
  55. const userList = await this.userRepository.createQueryBuilder('users')
  56. .select(['users.id', 'users.name'])
  57. .where({
  58. id: In(userIds),
  59. }).getMany()
  60. return userList
  61. }
  62. public async loginByPhone(phone: string, code: string, invitor: number | null): Promise<Users> {
  63. const verified = await this.smsService.verify(phone, code)
  64. if (!verified) {
  65. throw new InternalServerErrorException('手机号或验证码错误')
  66. }
  67. let newRegister = false
  68. let user = await this.userRepository.findOneBy({ phone: phone })
  69. if (!user) {
  70. newRegister = true
  71. user = new Users()
  72. user.phone = phone
  73. user.name = '0x' + randomstring.generate({ length: 8, charset: 'alphanumeric' })
  74. user.username = phone
  75. user.invitor = invitor || 48
  76. }
  77. user = await this.userRepository.save(user)
  78. if (newRegister) {
  79. await this.membershipService.trial(user.id)
  80. }
  81. return user
  82. }
  83. public async loginAdmin(username: string, password: string): Promise<Users> {
  84. let user = await this.userRepository.findOneBy({ username })
  85. if (!user) {
  86. throw new UnauthorizedException('用户名或密码错误')
  87. }
  88. const isMatch = await this.hashingService.compare(password, user.password)
  89. if (!isMatch) {
  90. throw new UnauthorizedException('用户名或密码错误')
  91. }
  92. if (!user.roles.includes(Role.Admin)) {
  93. throw new UnauthorizedException('用户名或密码错误')
  94. }
  95. return user
  96. }
  97. public async create(userDto: UserCreateDto): Promise<IUsers> {
  98. try {
  99. if (userDto.password) {
  100. userDto.password = await this.hashingService.hash(userDto.password)
  101. }
  102. return await this.userRepository.save(userDto)
  103. } catch (err) {
  104. throw new InternalServerErrorException(err.message)
  105. }
  106. }
  107. public async updateByEmail(email: string): Promise<Users> {
  108. try {
  109. const user = await this.userRepository.findOneBy({ email: email })
  110. user.password = await this.hashingService.hash(Math.random().toString(36).slice(-8))
  111. return await this.userRepository.save(user)
  112. } catch (err) {
  113. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  114. }
  115. }
  116. public async updateByPassword(email: string, password: string): Promise<Users> {
  117. try {
  118. const user = await this.userRepository.findOneBy({ email: email })
  119. user.password = await this.hashingService.hash(password)
  120. return await this.userRepository.save(user)
  121. } catch (err) {
  122. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  123. }
  124. }
  125. public async updatePassword(id: number, password: string): Promise<Users> {
  126. try {
  127. const user = await this.userRepository.findOneBy({ id })
  128. user.password = await this.hashingService.hash(password)
  129. return await this.userRepository.save(user)
  130. } catch (err) {
  131. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  132. }
  133. }
  134. public async updateProfileUser(id: number, userProfileDto: UserProfileDto): Promise<Users> {
  135. try {
  136. const user = await this.userRepository.findOneBy({ id: +id })
  137. if (userProfileDto.name) user.name = userProfileDto.name
  138. if (userProfileDto.avatar) user.avatar = userProfileDto.avatar
  139. return await this.userRepository.save(user)
  140. } catch (err) {
  141. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  142. }
  143. }
  144. public async updateUser(id: number, userUpdateDto: UserUpdateDto): Promise<UpdateResult> {
  145. try {
  146. const user = await this.userRepository.update(
  147. {
  148. id: +id
  149. },
  150. { ...userUpdateDto }
  151. )
  152. return user
  153. } catch (err) {
  154. throw new BadRequestException('User not updated')
  155. }
  156. }
  157. public async deleteUser(id: number): Promise<void> {
  158. const user = await this.findById(id)
  159. await this.userRepository.remove(user)
  160. }
  161. public async getInvites(userId: number) {
  162. return await this.userRepository.find({
  163. where: {
  164. invitor: userId
  165. }
  166. })
  167. }
  168. public async updateIat(user: Users, iat?: number) {
  169. user.iat = iat || Math.floor(new Date().getTime() / 1000) - 1
  170. return await this.userRepository.save(user)
  171. }
  172. }