users.service.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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, MoreThanOrEqual, LessThanOrEqual, And } 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 { ApiUserService } from '../api-users/api-user.service'
  22. import { paginate, Pagination } from 'nestjs-typeorm-paginate'
  23. import { Role } from '../model/role.enum'
  24. import { PageRequest } from '../common/dto/page-request'
  25. import { th } from 'date-fns/locale'
  26. import { startOfDay, endOfDay, addDays, format } from 'date-fns'
  27. import { where } from 'sequelize'
  28. @Injectable()
  29. export class UsersService {
  30. constructor(
  31. @InjectRepository(Users)
  32. private readonly userRepository: Repository<Users>,
  33. private readonly hashingService: HashingService,
  34. private readonly smsService: SmsService,
  35. private readonly membershipService: MembershipService,
  36. private readonly apiUserService: ApiUserService
  37. ) {}
  38. async findAll(req: PageRequest<Users>): Promise<Pagination<Users>> {
  39. return await paginate<Users>(this.userRepository, req.page, req.search)
  40. }
  41. public async findByEmail(email: string): Promise<Users> {
  42. const user = await this.userRepository.findOneBy({
  43. email: email
  44. })
  45. if (!user) {
  46. throw new NotFoundException(`User not found`)
  47. }
  48. return user
  49. }
  50. public async findById(userId: number): Promise<Users> {
  51. const user = await this.userRepository.findOneBy({
  52. id: +userId
  53. })
  54. if (!user) {
  55. throw new NotFoundException(`User #${userId} not found`)
  56. }
  57. return user
  58. }
  59. async findInfoByIds(userIds: number[]): Promise<Users[]> {
  60. const userList = await this.userRepository
  61. .createQueryBuilder('users')
  62. .select(['users.id', 'users.name'])
  63. .where({
  64. id: In(userIds)
  65. })
  66. .getMany()
  67. return userList
  68. }
  69. public async loginByPhone(phone: string, code: string, invitor: number | null): Promise<Users> {
  70. const verified = await this.smsService.verify(phone, code)
  71. if (!verified) {
  72. throw new InternalServerErrorException('手机号或验证码错误')
  73. }
  74. let newRegister = false
  75. let user = await this.userRepository.findOneBy({ phone: phone })
  76. if (!user) {
  77. newRegister = true
  78. user = new Users()
  79. user.phone = phone
  80. user.name = '0x' + randomstring.generate({ length: 8, charset: 'alphanumeric' })
  81. user.username = phone
  82. user.invitor = invitor || 48
  83. try {
  84. const invitorUser = await this.findById(invitor)
  85. if (!!invitorUser.apiUserId) {
  86. user.apiUserId = invitorUser.apiUserId
  87. }
  88. } catch (error) {}
  89. }
  90. user = await this.userRepository.save(user)
  91. if (newRegister) {
  92. await this.membershipService.trial(user.id)
  93. }
  94. return user
  95. }
  96. public async loginAdmin(username: string, password: string): Promise<Users> {
  97. let user = await this.userRepository
  98. .createQueryBuilder('users')
  99. .where({ username })
  100. .addSelect('users.password')
  101. .getOne()
  102. if (!user) {
  103. throw new UnauthorizedException('用户名或密码错误')
  104. }
  105. const isMatch = await this.hashingService.compare(password, user.password)
  106. if (!isMatch) {
  107. throw new UnauthorizedException('用户名或密码错误')
  108. }
  109. if (!user.roles.includes(Role.Admin) && !user.roles.includes(Role.Api) && !user.roles.includes(Role.Org)) {
  110. throw new UnauthorizedException('用户名或密码错误')
  111. }
  112. return user
  113. }
  114. public async create(userDto: UserCreateDto) {
  115. try {
  116. if (userDto.password) {
  117. userDto.password = await this.hashingService.hash(userDto.password)
  118. }
  119. let user = await this.userRepository.save(userDto)
  120. if (userDto.roles.includes(Role.Api)) {
  121. let apiUser = await this.apiUserService.create(user.id)
  122. user.apiUserId = apiUser.id
  123. user = await this.userRepository.save(user)
  124. }
  125. return user
  126. } catch (err) {
  127. throw new InternalServerErrorException(err.message)
  128. }
  129. }
  130. public async createSubUser(userDto: UserCreateDto, apiUserId: number): Promise<IUsers> {
  131. try {
  132. const apiUser = await this.findById(apiUserId)
  133. if (userDto.password) {
  134. userDto.password = await this.hashingService.hash(userDto.password)
  135. }
  136. userDto.apiUserId = apiUser.apiUserId
  137. let user = await this.userRepository.save(userDto)
  138. return user
  139. } catch (err) {
  140. throw new InternalServerErrorException(err.message)
  141. }
  142. }
  143. public async updateByEmail(email: string): Promise<Users> {
  144. try {
  145. const user = await this.userRepository.findOneBy({ email: email })
  146. user.password = await this.hashingService.hash(Math.random().toString(36).slice(-8))
  147. return await this.userRepository.save(user)
  148. } catch (err) {
  149. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  150. }
  151. }
  152. public async updateByPassword(email: string, password: string): Promise<Users> {
  153. try {
  154. const user = await this.userRepository.findOneBy({ email: email })
  155. user.password = await this.hashingService.hash(password)
  156. return await this.userRepository.save(user)
  157. } catch (err) {
  158. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  159. }
  160. }
  161. public async updatePassword(id: number, password: string): Promise<Users> {
  162. try {
  163. const user = await this.userRepository.findOneBy({ id })
  164. user.password = await this.hashingService.hash(password)
  165. return await this.userRepository.save(user)
  166. } catch (err) {
  167. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  168. }
  169. }
  170. public async updateProfileUser(id: number, userProfileDto: UserProfileDto): Promise<Users> {
  171. try {
  172. const user = await this.userRepository.findOneBy({ id: +id })
  173. if (userProfileDto.name) user.name = userProfileDto.name
  174. if (userProfileDto.avatar) user.avatar = userProfileDto.avatar
  175. return await this.userRepository.save(user)
  176. } catch (err) {
  177. throw new HttpException(err, HttpStatus.BAD_REQUEST)
  178. }
  179. }
  180. public async updateUser(id: number, userUpdateDto: UserUpdateDto): Promise<UpdateResult> {
  181. try {
  182. const user = await this.userRepository.update(
  183. {
  184. id: +id
  185. },
  186. { ...userUpdateDto }
  187. )
  188. return user
  189. } catch (err) {
  190. throw new BadRequestException('User not updated')
  191. }
  192. }
  193. public async deleteUser(id: number): Promise<void> {
  194. const user = await this.findById(id)
  195. await this.userRepository.remove(user)
  196. }
  197. public async getInvites(userId: number) {
  198. return await this.userRepository.find({
  199. where: {
  200. invitor: userId
  201. }
  202. })
  203. }
  204. public async updateIat(user: Users, iat?: number) {
  205. user.iat = iat || Math.floor(new Date().getTime() / 1000) - 1
  206. return await this.userRepository.save(user)
  207. }
  208. public async getCount(apiUserId: number, roles?: Role, date?: string) {
  209. return await this.userRepository.count({
  210. where: {
  211. orgId: apiUserId,
  212. roles: roles,
  213. createdAt: date
  214. ? And(MoreThanOrEqual(startOfDay(new Date(date))), LessThanOrEqual(endOfDay(new Date(date))))
  215. : undefined
  216. }
  217. })
  218. }
  219. public async getWeekCount(apiUserId: number) {
  220. const date1 = new Date()
  221. let dayInfo = {}
  222. for (let i = 0; i < 7; i++) {
  223. let date2 = format(addDays(date1, 0 - i), 'yyyy-MM-dd')
  224. let api = await this.getCount(apiUserId, Role.Api, date2)
  225. let user = await this.getCount(apiUserId, Role.User, date2)
  226. dayInfo[format(addDays(date1, 0 - i), 'MM-dd')] = {
  227. api: api,
  228. user: user
  229. }
  230. }
  231. return dayInfo
  232. }
  233. public async getUsers(apiUserId: number, roles?: Role) {
  234. let users = await this.userRepository.findBy({
  235. orgId: apiUserId,
  236. roles: roles
  237. })
  238. return users.map((item) => {
  239. return item.id
  240. })
  241. }
  242. public async findByPhone(phone: string[]) {
  243. return await this.userRepository.findBy({
  244. phone: In(phone)
  245. })
  246. }
  247. }