| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198 |
- import {
- Injectable,
- NotFoundException,
- HttpException,
- HttpStatus,
- BadRequestException,
- InternalServerErrorException,
- UnauthorizedException
- } from '@nestjs/common'
- import { In, Repository, UpdateResult } from 'typeorm'
- import { InjectRepository } from '@nestjs/typeorm'
- import { Users } from './entities/users.entity'
- import { IUsers } from './interfaces/users.interface'
- import { UserCreateDto } from './dto/user-create.dto'
- import { UserProfileDto } from './dto/user-profile.dto'
- import { UserUpdateDto } from './dto/user-update.dto'
- import { HashingService } from '../shared/hashing/hashing.service'
- import { SmsService } from '../sms/sms.service'
- import * as randomstring from 'randomstring'
- import { MembershipService } from '../membership/membership.service'
- import { paginate, Pagination } from 'nestjs-typeorm-paginate'
- import { Role } from '../model/role.enum'
- import { PageRequest } from '../common/dto/page-request'
- @Injectable()
- export class UsersService {
- constructor(
- @InjectRepository(Users)
- private readonly userRepository: Repository<Users>,
- private readonly hashingService: HashingService,
- private readonly smsService: SmsService,
- private readonly membershipService: MembershipService
- ) { }
- async findAll(req: PageRequest<Users>): Promise<Pagination<Users>> {
- return await paginate<Users>(this.userRepository, req.page, req.search)
- }
- public async findByEmail(email: string): Promise<Users> {
- const user = await this.userRepository.findOneBy({
- email: email
- })
- if (!user) {
- throw new NotFoundException(`User not found`)
- }
- return user
- }
- public async findById(userId: number): Promise<Users> {
- const user = await this.userRepository.findOneBy({
- id: +userId
- })
- if (!user) {
- throw new NotFoundException(`User #${userId} not found`)
- }
- return user
- }
- async findInfoByIds(userIds: number[]): Promise<Users[]> {
- const userList = await this.userRepository.createQueryBuilder('users')
- .select(['users.id', 'users.name'])
- .where({
- id: In(userIds),
- }).getMany()
-
- return userList
- }
- public async loginByPhone(phone: string, code: string, invitor: number | null): Promise<Users> {
- const verified = await this.smsService.verify(phone, code)
- if (!verified) {
- throw new InternalServerErrorException('手机号或验证码错误')
- }
- let newRegister = false
- let user = await this.userRepository.findOneBy({ phone: phone })
- if (!user) {
- newRegister = true
- user = new Users()
- user.phone = phone
- user.name = '0x' + randomstring.generate({ length: 8, charset: 'alphanumeric' })
- user.username = phone
- user.invitor = invitor || 48
- }
- user = await this.userRepository.save(user)
- if (newRegister) {
- await this.membershipService.trial(user.id)
- }
- return user
- }
- public async loginAdmin(username: string, password: string): Promise<Users> {
- let user = await this.userRepository.findOneBy({ username })
- if (!user) {
- throw new UnauthorizedException('用户名或密码错误')
- }
- const isMatch = await this.hashingService.compare(password, user.password)
- if (!isMatch) {
- throw new UnauthorizedException('用户名或密码错误')
- }
- if (!user.roles.includes(Role.Admin)) {
- throw new UnauthorizedException('用户名或密码错误')
- }
- return user
- }
- public async create(userDto: UserCreateDto): Promise<IUsers> {
- try {
- if (userDto.password) {
- userDto.password = await this.hashingService.hash(userDto.password)
- }
- return await this.userRepository.save(userDto)
- } catch (err) {
- throw new InternalServerErrorException(err.message)
- }
- }
- public async updateByEmail(email: string): Promise<Users> {
- try {
- const user = await this.userRepository.findOneBy({ email: email })
- user.password = await this.hashingService.hash(Math.random().toString(36).slice(-8))
- return await this.userRepository.save(user)
- } catch (err) {
- throw new HttpException(err, HttpStatus.BAD_REQUEST)
- }
- }
- public async updateByPassword(email: string, password: string): Promise<Users> {
- try {
- const user = await this.userRepository.findOneBy({ email: email })
- user.password = await this.hashingService.hash(password)
- return await this.userRepository.save(user)
- } catch (err) {
- throw new HttpException(err, HttpStatus.BAD_REQUEST)
- }
- }
- public async updatePassword(id: number, password: string): Promise<Users> {
- try {
- const user = await this.userRepository.findOneBy({ id })
- user.password = await this.hashingService.hash(password)
- return await this.userRepository.save(user)
- } catch (err) {
- throw new HttpException(err, HttpStatus.BAD_REQUEST)
- }
- }
- public async updateProfileUser(id: number, userProfileDto: UserProfileDto): Promise<Users> {
- try {
- const user = await this.userRepository.findOneBy({ id: +id })
- if (userProfileDto.name) user.name = userProfileDto.name
- if (userProfileDto.avatar) user.avatar = userProfileDto.avatar
- return await this.userRepository.save(user)
- } catch (err) {
- throw new HttpException(err, HttpStatus.BAD_REQUEST)
- }
- }
- public async updateUser(id: number, userUpdateDto: UserUpdateDto): Promise<UpdateResult> {
- try {
- const user = await this.userRepository.update(
- {
- id: +id
- },
- { ...userUpdateDto }
- )
- return user
- } catch (err) {
- throw new BadRequestException('User not updated')
- }
- }
- public async deleteUser(id: number): Promise<void> {
- const user = await this.findById(id)
- await this.userRepository.remove(user)
- }
- public async getInvites(userId: number) {
- return await this.userRepository.find({
- where: {
- invitor: userId
- }
- })
- }
- public async updateIat(user: Users, iat?: number) {
- user.iat = iat || Math.floor(new Date().getTime() / 1000) - 1
- return await this.userRepository.save(user)
- }
- }
|