コード例 #1
0
class Register(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __user = None
    __logger = None
    __correlation_id = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__user = UserModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())

    @stop_request_if_authenticated
    def post(self, request):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""

        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "register_request_token": "",
            "first_name": "",
            "last_name": "",
            "username": "",
            "email": "",
            "password": ""
        })

        self.__form.add_inputs({
            'first_name': {
                'value': request_data["first_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_names': {
                        'error': _('Error! First name contains invalid characters.')
                    },
                    'length_between': {
                        'param': [0, 20],
                        'error': _('Error! First name must be 1 to 20 characters long.')
                    }
                }
            },
            'last_name': {
                'value': request_data["last_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_names': {
                        'error': _('Error! Last name contains invalid characters.')
                    },
                    'length_between': {
                        'param': [0, 20],
                        'error': _('Error! Last name must be 1 to 20 characters long.')
                    }
                }
            },
            'username': {
                'value': request_data["username"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'alpha_numeric': {
                        'error': _('Error! Username must be alpha numeric.')
                    },
                    'length_between': {
                        'param': [4, 10],
                        'error': _('Error! Username must be 5 to 10 characters long.')
                    }
                }
            },
            'email': {
                'value': request_data["email"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'sv_email': {
                        'error': _('Error! Admin email is invalid.')
                    }
                }
            },
            'password': {
                'value': request_data["password"],
                'validate': {
                    'sv_password': {
                        'error': _('Error! Password must contain at least uppercase letter, lowercase letter, numbers and special character.')
                    },
                    'length_between': {
                        'param': [7, 20],
                        'error': _('Error! Password length must be from 8 to 20 characters.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id))

        register_request = self.__user.get_register_request_by_token(request_data["register_request_token"])

        if not register_request:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Register token is invalid or expired.")
            }], {}, self.__correlation_id))

        payload = json.loads(register_request.payload)

        if self.__user.username_used(self.__form.get_sinput("username")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Username is already used.")
            }], {}, self.__correlation_id))

        if self.__user.email_used(self.__form.get_sinput("email")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Email is already used for other account.")
            }], {}, self.__correlation_id))

        result = self.__user.insert_one({
            "username": self.__form.get_sinput("username"),
            "email": self.__form.get_sinput("email"),
            "first_name": self.__form.get_sinput("first_name"),
            "last_name": self.__form.get_sinput("last_name"),
            "password": self.__form.get_sinput("password"),
            "is_staff": False,
            "is_active": True,
            "is_superuser": True if payload["role"] == "admin" else False
        })

        if result:
            self.__user.delete_register_request_by_token(request_data["register_request_token"])
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Account created successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating your account.")
            }], {}, self.__correlation_id))
コード例 #2
0
class Users(View):
    """Create and List Users Private Endpoint Controller"""
    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__user = UserModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__user_id = None
        self.__correlation_id = ""
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated_and_has_permission("manage_settings")
    def post(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data(
            "post", {
                "invitation": "",
                "first_name": "",
                "last_name": "",
                "username": "",
                "role": "",
                "email": "",
                "password": ""
            })

        if request_data["invitation"] != "":

            self.__form.add_inputs({
                'first_name': {
                    'value': request_data["first_name"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_names': {
                            'error':
                            _('Error! First name contains invalid characters.')
                        },
                        'length_between': {
                            'param': [0, 20],
                            'error':
                            _('Error! First name must be 1 to 20 characters long.'
                              )
                        }
                    }
                },
                'last_name': {
                    'value': request_data["last_name"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_names': {
                            'error':
                            _('Error! Last name contains invalid characters.')
                        },
                        'length_between': {
                            'param': [0, 20],
                            'error':
                            _('Error! Last name must be 1 to 20 characters long.'
                              )
                        }
                    }
                },
                'username': {
                    'value': request_data["username"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'alpha_numeric': {
                            'error':
                            _('Error! Username must be alpha numeric.')
                        },
                        'length_between': {
                            'param': [4, 10],
                            'error':
                            _('Error! Username must be 5 to 10 characters long.'
                              )
                        }
                    }
                },
                'email': {
                    'value': request_data["email"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_email': {
                            'error': _('Error! User email is invalid.')
                        }
                    }
                },
                'password': {
                    'value': request_data["password"],
                    'validate': {
                        'sv_password': {
                            'error':
                            _('Error! Password must contain at least uppercase letter, lowercase letter, numbers and special character.'
                              )
                        },
                        'length_between': {
                            'param': [7, 20],
                            'error':
                            _('Error! Password length must be from 8 to 20 characters.'
                              )
                        }
                    }
                },
                'role': {
                    'value': request_data["role"],
                    'validate': {
                        'any_of': {
                            'param': [["admin", "user"]],
                            'error': _('Error! Role is invalid.')
                        }
                    }
                }
            })

        else:

            self.__form.add_inputs({
                'email': {
                    'value': request_data["email"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_email': {
                            'error': _('Error! User email is invalid.')
                        }
                    }
                },
                'role': {
                    'value': request_data["role"],
                    'validate': {
                        'any_of': {
                            'param': [["admin", "user"]],
                            'error': _('Error! Role is invalid.')
                        }
                    }
                }
            })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

        if self.__user.email_used(self.__form.get_sinput("email")):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Email is already used for other account.")
                }], {}, self.__correlation_id))

        if request_data["invitation"] != "" and self.__user.username_used(
                self.__form.get_sinput("username")):
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Username is already used.")
                    }], {}, self.__correlation_id))

        if request_data["invitation"] != "":

            result = self.__user.insert_one({
                "username":
                self.__form.get_sinput("username"),
                "email":
                self.__form.get_sinput("email"),
                "first_name":
                self.__form.get_sinput("first_name"),
                "last_name":
                self.__form.get_sinput("last_name"),
                "password":
                self.__form.get_sinput("password"),
                "is_staff":
                False,
                "is_active":
                True,
                "is_superuser":
                True if self.__form.get_sinput("role") == "admin" else False
            })

            if result:
                return JsonResponse(
                    self.__response.send_private_success(
                        [{
                            "type": "success",
                            "message": _("Account created successfully.")
                        }], {}, self.__correlation_id))
            else:
                return JsonResponse(
                    self.__response.send_private_failure([{
                        "type":
                        "error",
                        "message":
                        _("Error! Something goes wrong while creating your account."
                          )
                    }], {}, self.__correlation_id))
        else:

            self.__user.delete_register_request_by_email(
                self.__form.get_sinput("email"))

            token = self.__user.create_register_request(
                self.__form.get_sinput("email"),
                self.__form.get_sinput("role"))

            if not token:
                return JsonResponse(
                    self.__response.send_private_failure([{
                        "type":
                        "error",
                        "message":
                        _("Error! Something goes wrong while creating reset request."
                          )
                    }], {}, self.__correlation_id))

            message = self.__user.send_register_request_message(
                self.__form.get_sinput("email"), token)

            if not message:
                return JsonResponse(
                    self.__response.send_private_failure([{
                        "type":
                        "error",
                        "message":
                        _("Error! Something goes wrong while sending register request."
                          )
                    }], {}, self.__correlation_id))
            else:
                return JsonResponse(
                    self.__response.send_private_success([{
                        "type":
                        "success",
                        "message":
                        _("Register Request instructions sent successfully.")
                    }], {}, self.__correlation_id))

    @allow_if_authenticated_and_has_permission("manage_settings")
    def get(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("get", {
            "offset": 0,
            "limit": 20
        })

        try:
            offset = int(request_data["offset"])
            limit = int(request_data["limit"])
        except Exception:
            offset = 0
            limit = 20

        return JsonResponse(
            self.__response.send_private_success(
                [], {
                    'users':
                    self.__format_users(self.__user.get_all(offset, limit)),
                    'metadata': {
                        'offset': offset,
                        'limit': limit,
                        'count': self.__user.count_all()
                    }
                }, self.__correlation_id))

    def __format_users(self, users):
        users_list = []

        for user in users:
            users_list.append({
                "id":
                user.id,
                "username":
                user.username,
                "first_name":
                user.first_name,
                "last_name":
                user.last_name,
                "email":
                user.email,
                "role":
                "Admin" if user.is_superuser == 1 else "User",
                "created_at":
                user.date_joined.strftime("%b %d %Y %H:%M:%S"),
                "edit_url":
                reverse("app.web.admin.user.edit", kwargs={'user_id':
                                                           user.id}),
                "delete_url":
                reverse("app.api.private.v1.admin.user.endpoint",
                        kwargs={'user_id': user.id})
            })

        return users_list
コード例 #3
0
class Register(View, Controller):
    """Register Private Endpoint Controller"""
    def __init__(self):
        self.__user = UserModule()

    @stop_request_if_authenticated
    def post(self, request):

        request_data = self.get_request_data(
            request, "post", {
                "register_request_token": "",
                "first_name": "",
                "last_name": "",
                "username": "",
                "email": "",
                "password": ""
            })

        self.form().add_inputs({
            'first_name': {
                'value': request_data["first_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_names': {
                        'error':
                        _('Error! First name contains invalid characters.')
                    },
                    'length_between': {
                        'param': [0, 20],
                        'error':
                        _('Error! First name must be 1 to 20 characters long.')
                    }
                }
            },
            'last_name': {
                'value': request_data["last_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_names': {
                        'error':
                        _('Error! Last name contains invalid characters.')
                    },
                    'length_between': {
                        'param': [0, 20],
                        'error':
                        _('Error! Last name must be 1 to 20 characters long.')
                    }
                }
            },
            'username': {
                'value': request_data["username"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'alpha_numeric': {
                        'error': _('Error! Username must be alpha numeric.')
                    },
                    'length_between': {
                        'param': [4, 10],
                        'error':
                        _('Error! Username must be 5 to 10 characters long.')
                    }
                }
            },
            'email': {
                'value': request_data["email"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_email': {
                        'error': _('Error! Admin email is invalid.')
                    }
                }
            },
            'password': {
                'value': request_data["password"],
                'validate': {
                    'sv_password': {
                        'error':
                        _('Error! Password must contain at least uppercase letter, lowercase letter, numbers and special character.'
                          )
                    },
                    'length_between': {
                        'param': [7, 20],
                        'error':
                        _('Error! Password length must be from 8 to 20 characters.'
                          )
                    }
                }
            }
        })

        self.form().process()

        if not self.form().is_passed():
            return self.json(self.form().get_errors())

        register_request = self.__user.get_register_request_by_token(
            request_data["register_request_token"])

        if not register_request:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Register token is invalid or expired.")
            }])

        payload = json.loads(register_request.payload)

        if self.__user.username_used(self.form().get_sinput("username")):
            return self.json([{
                "type": "error",
                "message": _("Error! Username is already used.")
            }])

        if self.__user.email_used(self.form().get_sinput("email")):
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Email is already used for other account.")
            }])

        result = self.__user.insert_one({
            "username":
            self.form().get_sinput("username"),
            "email":
            self.form().get_sinput("email"),
            "first_name":
            self.form().get_sinput("first_name"),
            "last_name":
            self.form().get_sinput("last_name"),
            "password":
            self.form().get_sinput("password"),
            "is_staff":
            False,
            "is_active":
            True,
            "is_superuser":
            True if payload["role"] == "admin" else False
        })

        if result:
            self.__user.delete_register_request_by_token(
                request_data["register_request_token"])
            return self.json([{
                "type": "success",
                "message": _("Account created successfully.")
            }])
        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while creating your account.")
            }])