예제 #1
0
파일: admin.py 프로젝트: viraatdas/cardshop
def toggle_account(request, username):

    profile = Profile.get_or_none(username)
    if profile is None:
        raise Http404("Profile not found")

    profile.user.is_active = not profile.user.is_active
    status = "enabled" if profile.user.is_active else "disabled"
    try:
        profile.user.save()
    except Exception as exp:
        logger.error(exp)
        messages.error(
            request,
            "User Account for {user} could not be {status}. (ref: {exp})".
            format(user=profile, status=status, exp=exp),
        )
    else:
        messages.success(
            request,
            "User Account for {user} has been successfuly {status}.".format(
                user=profile, status=status),
        )

    return redirect("admin")
예제 #2
0
파일: admin.py 프로젝트: kiwix/cardshop
def delete_account(request, username):

    profile = Profile.get_or_none(username)
    if profile is None:
        raise Http404(_("Profile not found"))

    user_repr = str(profile)

    try:
        do_delete_account(profile)
    except Exception as exp:
        logger.error(exp)
        messages.error(
            request,
            _("Error while deleting %(user)s. Please contact support (ref: %(err)s)"
              ) % {
                  "user": user_repr,
                  "err": exp
              },
        )
    else:
        messages.success(
            request,
            _("User Account for %(user)s has been successfuly deleted.") %
            {"user": user_repr},
        )

    return redirect("admin")
예제 #3
0
파일: admin.py 프로젝트: kiwix/cardshop
def toggle_account(request, username):

    profile = Profile.get_or_none(username)
    if profile is None:
        raise Http404(_("Profile not found"))

    profile.user.is_active = not profile.user.is_active
    status = "enabled" if profile.user.is_active else "disabled"
    try:
        profile.user.save()
    except Exception as exp:
        logger.error(exp)
        messages.error(
            request,
            _("User Account for %(user)s could not be %(status)s. (ref: %(err)s)"
              ) % {
                  "user": profile,
                  "status": status,
                  "err": exp
              },
        )
    else:
        messages.success(
            request,
            _("User Account for %(user)s has been successfuly %(status)s.") % {
                "user": profile,
                "status": status
            },
        )

    return redirect("admin")
예제 #4
0
파일: admin.py 프로젝트: viraatdas/cardshop
    def save(self):
        if not self.is_valid():
            raise ValueError("{cls} is not valid".format(type(self)))

        organization = Organization.get_or_none(
            self.cleaned_data.get("organization"))
        return Profile.create(
            organization=organization,
            first_name=self.cleaned_data.get("name").strip(),
            email=self.cleaned_data.get("email"),
            username=self.cleaned_data.get("username"),
            password=self.cleaned_data.get("password"),
            is_admin=self.cleaned_data.get("is_admin"),
        )
예제 #5
0
파일: admin.py 프로젝트: kiwix/cardshop
    def save(self):
        if not self.is_valid():
            raise ValueError(
                _("%(class)s is not valid") % {"class": type(self)})

        organization = Organization.get_or_none(
            self.cleaned_data.get("organization"))
        return Profile.create(
            organization=organization,
            first_name=self.cleaned_data.get("name").strip(),
            email=self.cleaned_data.get("email"),
            username=self.cleaned_data.get("username"),
            password=self.cleaned_data.get("password"),
            is_admin=self.cleaned_data.get("is_admin"),
            can_order_physical=self.cleaned_data.get("can_sd"),
            expiry=None,
        )
예제 #6
0
파일: admin.py 프로젝트: palash-cj/cardshop
def delete_account(request, username):

    profile = Profile.get_or_none(username)
    if profile is None:
        raise Http404("Profile not found")

    user_repr = str(profile)

    try:
        do_delete_account(profile)
    except Exception as exp:
        logger.error(exp)
        messages.error(
            request,
            f"Error while deleting {user_repr}. Please contact support (ref: {exp})",
        )
    else:
        messages.success(
            request,
            f"User Account for {user_repr} has been successfuly deleted.",
        )

    return redirect("admin")
예제 #7
0
 def clean_email(self):
     try:
         return Profile.get_using(self.cleaned_data.get("email"))
     except Exception:
         raise forms.ValidationError(_("No account for e-mail"),
                                     code="invalid")
예제 #8
0
def create_user_account(request):
    """create a user account automatically from an email address

    - must be authenticated via a `Token: {ACCOUNTS_API_TOKEN}` header
    - JSON payload must include an `email` field
    - optionnal payload fields:
      - username: used instead of email if provided
      - name: used instead of email if provided
      - password: used instead of auto-generated one is provided
    - returns a {"username": str, password: str} payload"""
    if request.headers.get("Token") != settings.ACCOUNTS_API_TOKEN:
        return JsonResponse({"error": "PermissionDenied"}, status=403)

    try:
        payload = request.body
        if not payload:
            raise ValueError("Missing payload")
        if type(payload) is bytes:
            payload = payload.decode("UTF-8")
        data = json.loads(payload)
    except Exception as exc:
        return JsonResponse({"error": str(exc)}, status=400)

    # email is mandatory
    email = str(data.get("email", "")) or None
    if not email:
        return JsonResponse({"error": "missing required email"}, status=400)

    # parse expiry if provided
    expiry = data.get("expiry")
    if expiry:
        try:
            expiry = datetime.datetime.fromisoformat(expiry)
        except Exception:
            return JsonResponse({"error": "Unable to parse expiry date"},
                                status=400)

    limited = bool(data.get("limited", True))

    name = str(data.get("name", email.split("@")[0]))
    username = str(data.get("username", email))
    password = str(data.get("password", "")) or None
    if not password:
        password = User.objects.make_random_password(length=8)

    if (User.objects.filter(username=username).count()
            or Organization.objects.filter(slug=username).count()):
        return JsonResponse(
            {"error": f"Username `{username}` is already taken"}, status=409)

    if Profile.taken(email):
        account = Profile.objects.filter(user__email=email).first()
        if expiry and account.expire_on is not None:
            account.expire_on = expiry
            account.save()
        return JsonResponse(
            {
                "error":
                f"Email `{email}` already has an account ({account.username})"
            },
            status=409,
        )

    # good to go, create an Organization, User and Profile
    try:
        org = None
        org = Organization.objects.create(
            slug=username,
            name="Single" if username == name else name,
            email=email,
            units=102400 if limited else None,
        )
        profile = Profile.create(
            organization=org,
            first_name=name,
            email=email,
            username=username,
            password=password,
            is_admin=False,
            expiry=expiry,
            can_order_physical=False,
        )
    except Exception as exc:
        if org:
            try:
                org.delete()
            except Exception:
                pass
        return JsonResponse({"error": f"Failed to create account: {exc}"},
                            status=500)

    return JsonResponse(
        {
            "username": profile.username,
            "password": password,
            "name": profile.name,
        },
        status=201,
    )
예제 #9
0
파일: admin.py 프로젝트: viraatdas/cardshop
 def clean_email(self):
     if Profile.taken(email=self.cleaned_data.get("email")):
         raise forms.ValidationError("Email is already in use.",
                                     code="invalid")
     return self.cleaned_data.get("email")
예제 #10
0
파일: admin.py 프로젝트: viraatdas/cardshop
 def clean_username(self):
     if Profile.exists(username=self.cleaned_data.get("username")):
         raise forms.ValidationError("Username is already taken.",
                                     code="invalid")
     return self.cleaned_data.get("username")