示例#1
0
    def send_mail_again(self, request, *args, **kwargs):
        """
        @apiVersion 1.0.0
        @api {POST} /user/send_mail_again send mail again
        @apiName SendVerifyMail
        @apiGroup Kitchenrock_API Account
        @apiPermission none

        @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: Mobile web, tablet web, 8: Desktop web)
        @apiHeader {string} Device Required, Device id, If from browser, please use md5 of useragent.
        @apiHeader {string} Appid Required
        @apiHeader {string} Agent Optional
        @apiHeader {string} Authorization Optional. format: token <token_string>
        @apiHeaderExample {json} Request Header Non Authenticate Example:
        {
            "Type": 1,
            "Device": "postman-TEST",
            "Appid": 1,
            "Agent": "Samsung A5 2016, Android app, build_number other_info"
        }

        @apiParam {string} id_user
        @apiParam {string} type If send mail again for activation, type = activation. If send mail again for reset pass, type = reset.

        @apiSuccess {string} message
        """
        id_user = request.data.get('id_user', None)
        type = request.data.get('type', 'activation')
        user = User.objects.get(id=id_user)
        if 'activation' == type:
            pinObj = PinCode.objects.filter(
                user=id_user, is_active=1).order_by('-id').first()
            if pinObj:
                UserService.send_verify(pin=pinObj.pin, email=user.email)
            else:
                p = PinCode()
                p.pin = Utils.id_generator(4)
                p.user_id = id_user
                p.is_active = True
                p.save()
                UserService.send_verify(pin=p.pin, email=user.email)
        elif 'reset' == type:
            pinObj = PinCode.objects.filter(
                user=id_user, is_active=0).order_by('-id').first()
            if pinObj:
                EmailService.reset_pin(pin=pinObj.pin, email=user.email)
            else:
                p = PinCode()
                p.pin = Utils.id_generator(4)
                p.user_id = id_user
                p.save()
                EmailService.reset_pin(pin=p.pin, email=user.email)
        else:
            return Response({"message": "Paramater TYPE is invalid"},
                            status=status.HTTP_400_BAD_REQUEST)
        return Response({
            "message":
            "A mail with pin code has been sent to your email, please check your email."
        })
示例#2
0
 def get_list(self, request, filter={}, **kwargs):
     kwargs['limit'] = int(request.query_params.get('limit', '20'))
     kwargs['offset'] = int(request.query_params.get('offset', '0'))
     kwargs['search'] = request.query_params.get('search', None)
     users = UserService.get_users(filter=filter, **kwargs)
     serializer = UserSerializer(instance=users['result'], many=True)
     return Response({'result': serializer.data, 'count': users['count']})
示例#3
0
 def get_user(self, *args, **kwargs):
     """Get user base on uidb64
     :return: User
     """
     uidb64 = kwargs.get('uidb64')
     uid = urlsafe_base64_decode(uidb64)
     return UserService.get_user(uid)
示例#4
0
 def update(self, instance, validated_data):
     data = self.data
     for key in validated_data:
         data[key] = validated_data[key]
     # Not save password in this step
     if 'password' in data:
         del data['password']
     return UserService.save(data)
示例#5
0
 def create(self, validated_data):
     try:
         for key in ['groups', 'user_permission']:
             if key in validated_data:
                 del validated_data[key]
         user = UserService.save(validated_data)
         return user
     except Exception:
         raise exceptions.APIException()
示例#6
0
 def edit(self, current, id, data):
     user = UserService.get_user(id)
     if not user:
         raise exceptions.NotFound()
     if permissions.allow_access_user(current, user=user):
         serializer = UserSerializer(instance=user, data=data)
         serializer.is_valid(raise_exception=True)
         serializer.save()
         return Response(serializer.data)
示例#7
0
 def validate(self, attrs):
     email = attrs.get('email')
     confirm_password = attrs.get('confirm_password')
     new_password = attrs.get('new_password')
     user_id = attrs.get('user_id')
     if (email or user_id) and confirm_password and new_password:
         if email:
             user = UserService.get_by_email(email)
         elif user_id:
             user = UserService.get_user(user_id)
         if user:
             user.set_password(new_password)
             user.save()
             attrs['user'] = user
             return attrs
         else:
             raise exceptions.ValidationError(_('User not found.'))
     else:
         raise exceptions.ValidationError(_('Must include password.'))
示例#8
0
 def send_reset_pass_code(self, request):
     data = request.data.copy()
     email = data.get('email', None)
     if not email:
         raise exceptions.ParseError(_('Please provide email.'))
     user = UserService.get_by_email(email)
     token = default_token_generator.make_token(user)
     uid = urlsafe_base64_encode(force_bytes(user.pk))
     return Response({
         'uid': uid.decode('utf-8'),
         'token': token,
         'username': user.email
     })
示例#9
0
 def send_reset_password_link(self, request):
     email = request.data.get('email', None)
     if not email:
         raise exceptions.ParseError(_('Please provide email.'))
     user = UserService.get_by_email(email)
     if not user:
         raise exceptions.NotFound(_('User not found.'))
     token = default_token_generator.make_token(user)
     uid = urlsafe_base64_encode(force_bytes(user.pk))
     EmailService.reset_link(token=token, uid=uid, user=user)
     return Response({
         "message":
         "A link with instruction has been sent to your email, please check your email to reset password."
     })
示例#10
0
 def reset_by_code(self, request):
     email = request.data.get('email', None)
     if not email:
         raise exceptions.ParseError(_('Please provide email.'))
     user = UserService.get_by_email(email)
     if not user:
         raise exceptions.NotFound(_('Email not found.'))
     token = default_token_generator.make_token(user)
     pin = Utils.id_generator(4)
     p = PinCode(pin=pin, user=user)
     p.save()
     EmailService.reset_pin(pin=pin, email=email)
     return Response({
         "message":
         "A link with instruction has been sent to your email, please check your email to reset password.",
         "uid": user.id
     })
示例#11
0
    def verify(self, request, *args, **kwargs):
        """
        @apiVersion 1.0.0
        @api {POST} /user/verify verify account signup token
        @apiName Verify
        @apiGroup Kitchenrock_API Account
        @apiPermission none
	
	    @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: Mobile web, tablet web, 8: Desktop web)
        @apiHeader {string} Device Required, Device id, If from browser, please use md5 of useragent.
        @apiHeader {string} Appid Required
        @apiHeader {string} Agent Optional
        @apiHeader {string} Authorization Optional. format: token <token_string>
        @apiHeaderExample {json} Request Header Non Authenticate Example:
        {
            "Type": 1,
            "Device": "postman-TEST",
            "Appid": 1,
            "Agent": "Samsung A5 2016, Android app, build_number other_info"
        }

        @apiParam {string} pin
        @apiParam {string} id_user

        @apiSuccess {object} user
        @apiSuccess {string} token
        @apiSuccess {string} appkey
        """
        pin = request.data.get('pin', None)
        client = request.client
        remember_me = bool(request.data.get('remember_me', False))
        id_user = request.data.get('id_user', None)
        type = request.data.get('type', 'activation')
        if not pin:
            raise exceptions.ParseError(('Please provide pin code.'))

        if 'activation' == type:
            user_mail = UserService.verify_by_pin(pin=pin, id_user=id_user)
            if user_mail is False:
                raise exceptions.ParseError(_('Invalid pin.'))
            # return Response({"message": "Your account has been activated"})
            return self.response_login(id=user_mail.user_id,
                                       client=client,
                                       remember_me=remember_me)
示例#12
0
 def get_user(self, id, **kwargs):
     user = UserService.get_user(id, **kwargs)
     if user is None:
         exceptions.NotFound()
     return user
示例#13
0
    def handle(self, *args, **options):
        database = options.get('database', DEFAULT_DB_ALIAS)
        username = options.get(User.USERNAME_FIELD)
        user_type = options.get('type', None)
        password = None
        user_data = {}
        fake_user_data = {}
        default_username = get_default_username()
        try:
            # Get a username
            verbose_field_name = self.username_field.verbose_name
            while username is None:
                input_msg = capfirst(verbose_field_name)
                if default_username:
                    input_msg += " (leave blank to use '%s')" % default_username
                username_rel = self.username_field.rel
                input_msg = force_str('%s%s: ' % (
                    input_msg,
                    ' (%s.%s)' % (
                        username_rel.to._meta.object_name,
                        username_rel.field_name
                    ) if username_rel else '')
                )
                username = self.get_input_data(self.username_field, input_msg, default_username)
                if not username:
                    continue
                try:
                    User._default_manager.db_manager(database).get_by_natural_key(username)
                except User.DoesNotExist:
                    pass
                else:
                    self.stderr.write("Error: That %s is already taken." %
                            verbose_field_name)
                    username = None
            user_type_choises = copy.deepcopy(USER_TYPE_CHOICES)
            user_type_choises.sort(key=lambda tup: tup[0])
            types = [('%s:%s' % tp) for tp in user_type_choises]
            msg = 'Type (%s):' % (' '.join(types))
            while not user_type or not UserType.is_valid_type(user_type):
                user_type = self.get_input_data('user_type', msg)
                if not user_type:
                    continue
                user_type = int(user_type)
                if not UserType.is_valid_type(user_type):
                    self.stderr.write("Error: Invalid user type")
                    user_type = False
                
            manager_id = 0
            if user_type in [UserType.VISITOR, UserType.MANAGER]:
                while not manager_id:
                    raw_value = input('Manager id: ')
                    try:
                        manager_id = int(raw_value)
                        manager = User.objects.get(id=manager_id)
                        if not manager.user_type in [UserType.STAFF]:
                            raise Exception('Only staff can doing this, type = '+str(manager.user_type))
                    except Exception as pe:
                        if user_type == UserType.MANAGER:
                            print ("No manager set: "+str(pe))
                            #not required
                            break
                        else:
                            self.stderr.write("Error: Invalid manager id: "+str(pe))
                            manager_id = 0

            for field_name in User.REQUIRED_FIELDS:
                field = User._meta.get_field(field_name)
                user_data[field_name] = options.get(field_name)
                while user_data[field_name] is None:
                    message = force_str('%s%s: ' % (
                        capfirst(field.verbose_name),
                        ' (%s.%s)' % (
                            field.remote_field.model._meta.object_name,
                            field.remote_field.field_name,
                        ) if field.remote_field else '',
                    ))
                    input_value = self.get_input_data(field, message)
                    user_data[field_name] = input_value
                    fake_user_data[field_name] = input_value
                    if field.remote_field:
                        fake_user_data[field_name] = field.remote_field.model(input_value)

            profile = {}
            if user_type in [UserType.SUPERUSER, UserType.STAFF]:
                profile = {
                    'gender': 1,
                    'dob': '1988-12-12'
                }
            for field_name in ['gender', 'dob']:
                field = UserProfile._meta.get_field(field_name)
                while profile.get(field_name, None) is None:
                    message = force_str('%s%s: ' % (
                        capfirst(field.verbose_name),
                        ' (%s.%s)' % (
                            field.remote_field.model._meta.object_name,
                            field.remote_field.field_name,
                        ) if field.remote_field else '',
                    ))
                    input_value = self.get_input_data(field, message)
                    profile[field_name] = input_value

            while password is None:
                password = getpass.getpass()
                password2 = getpass.getpass(force_str('Password (again): '))
                if password != password2:
                    self.stderr.write("Error: Your passwords didn't match.")
                    password = None
                    continue

        except KeyboardInterrupt:
            self.stderr.write("\nOperation cancelled.")
            sys.exit(1)

        if username:
            if user_type == UserType.SUPERUSER:
                user_data['is_superuser'] = True
                user_data['is_staff'] = True
                user_data['is_active'] = True
            if user_type == UserType.STAFF:
                user_data['is_staff'] = True
                user_data['is_active'] = True

            user_data['manager_id'] = manager_id
            user_data[User.USERNAME_FIELD] = username
            user_data['password'] = password
            user_data['manager_id'] = int(manager_id)
            user_data['user_type'] = user_type
            user_data['profile'] = profile
            UserService.save(user_data)
            if options['verbosity'] >= 1:
                self.stdout.write("User created successfully.")