Exemplo n.º 1
0
 def send_password_reset_email(cls, email):
     user_doc = DM.db[User.COLLECTION_NAME].find_one({User.EMAIL: email})
     if user_doc is None:
         # do nothing and return if the user doc is not available
         return
     # generate reset password token
     reset_password_token = secrets.token_urlsafe()
     # token valid for 30 mins from now
     valid_till = datetime.utcnow() + timedelta(minutes=30)
     # save to reset token collection
     user_id = str(user_doc["_id"])
     DM.db[PasswordResetTokens.COLLECTION_NAME].insert_one({
         PasswordResetTokens.USERID:
         user_id,
         PasswordResetTokens.TOKEN:
         reset_password_token,
         PasswordResetTokens.IS_CONSUMED:
         False,
         PasswordResetTokens.VALID_TILL:
         valid_till
     })
     # TODO: change mail subject line & body
     send_email(
         to=email,
         subject=f"MB: Password reset email",
         body=
         f"UserId: {user_id}, Reset password token: {reset_password_token}, valid till: {valid_till}"
     )
Exemplo n.º 2
0
def remove_account(request):
    if request.user.is_authenticated():
        # TODO: fix the way to send user notification of account deletion
        subject = u'[УДАЛЕНИЕ АККАУНТА] id=%s - %s %s' % (request.user.id,
                request.profile.first_name, request.profile.last_name)
        send_email(None, subject, 'letters/remove_account.html', {'profile': request.profile},
                'remove_account', 'noreply')
        return HttpResponse('ok')
    return HttpResponse(u'Чтобы удалить аккаунт, необходимо войти в систему')
Exemplo n.º 3
0
 def save(self, **kwargs):
     for user in self.users_cache:
         ctx = {
             'uid': int_to_base36(user.id),
             'user': user,
             'token': kwargs['token_generator'].make_token(user),
             'URL_PREFIX': settings.URL_PREFIX,
         }
         send_email(user.get_profile(), u'Смена пароля на grakon.org', 'letters/password_reset_email.html',
                 ctx, 'password_reset', 'noreply')
Exemplo n.º 4
0
async def create_comment(comment: Comment, request: Request):
    comment.ip = request.client.host
    comment.timestamp = datetime.now()
    await post_comment(comment)

    send_email(receiver=settings.MY_EMAIL,
               subject="dotmethod | new message on the blog",
               text=f"From: {comment.name}\nMessage: {comment.body}")

    return comment
Exemplo n.º 5
0
    def handle(self, *args, **options):
        from services.email import send_email

        with open('/home/serg/gn1.txt') as f:
            emails = [line.strip() for line in f]

        for email in emails:
            print email
            send_email(None, u'Приглашение к участнию в новой площадке Гракон',
                    'letters/gn_invitation.html', {}, 'gn_invitation', 'noreply', to_email=email)
            sleep(0.2)
Exemplo n.º 6
0
    def handle(self, *args, **options):
        from services.email import send_email

        with open('/home/serg/emails.txt') as f:
            emails = [line.strip() for line in f][:9000]

        for email in emails:
            print email
            send_email(None, u'Гракон готовится к выборам 14 октября',
                    'letters/invitation.html', {}, '14_10_invitation', 'noreply', to_email=email)
            sleep(0.2)
Exemplo n.º 7
0
    def send(self):
        ctx = {
            'message': escape_html(self.cleaned_data['body']),
            'profile': self.request.profile,
            'hide_signature': True,
        }

        if not self.request.profile:
            ctx['name'] = self.cleaned_data['name']
            ctx['email'] = self.cleaned_data['email']

        send_email(None, u'[ОБРАТНАЯ СВЯЗЬ]', 'letters/feedback.html', ctx, 'feedback', 'noreply')
Exemplo n.º 8
0
 def save(self, **kwargs):
     for user in self.users_cache:
         ctx = {
             "uid": int_to_base36(user.id),
             "user": user,
             "token": kwargs["token_generator"].make_token(user),
             "URL_PREFIX": settings.URL_PREFIX,
         }
         send_email(
             user.get_profile(),
             u"Смена пароля на grakon.org",
             "letters/password_reset_email.html",
             ctx,
             "password_reset",
             "noreply",
         )
Exemplo n.º 9
0
async def issuer_badge(
    request: Request,
    issuer_id: str,
    badge_id: str,
    recipients: List[RecipientIn], 
    current_user: UserInDB = Depends(get_current_user)
):
    issuer = await IssuersDB().get_issuer_by_id(issuer_id)
    badge = await BadgesDB().get_badge_by_id(badge_id, issuer_id)
    if issuer is None or badge is None:
        raise HTTPException(status_code=HTTP_404_NOT_FOUND)

    for recipient in recipients:
        # Add recipients to DB if they don't already exist.
        recipient_in_db = await RecipientsDB().get_recipient_by_email(recipient.email)
        if recipient_in_db is None: 
            recipient_in_db = await RecipientsDB().create_recipient(recipient)
        
        # If recipient already has public key associated with the issuer,
        # Then just issue them a certificate. Otherwise, send the recipient
        # an invite email.
        if issuer_id in recipient_in_db.addresses:
            await issue_cert(issuer, recipient_in_db, badge)
        else:
            invite = await InvitesDB().get_by_issuer_and_recipient_ids(issuer_id, recipient_in_db.id)
            if invite is None:
                invite = await InvitesDB().create(InviteInCreate(issuer_id=issuer_id, recipient_id=recipient_in_db.id, badge_id=badge_id))
            
            if badge_id not in invite.badges:
                InvitesDB().add_badge(invite.id, badge_id)

            invite_html = templates.TemplateResponse(
                "invite.html",
                {
                    "request": request,
                    "issuer_url": f'{API_URL}/issuers/{issuer_id}/profile',
                    "nonce": invite.nonce
                }
            ).body.decode('utf-8')

            send_email(
                from_address="*****@*****.**",
                to_addresses=[recipient_in_db.email],
                subject="[DX - uBadge]",
                body=invite_html,
                is_html=True
            )
Exemplo n.º 10
0
def notify_user(profile_id):
    nrs = NotificationRecipient.objects.select_related('notification') \
            .filter(recipient=profile_id, email_sent=False, is_read=False) \
            .order_by('notification__time')

    notifications = []
    for nr in nrs:
        notification_type = NOTIFICATIONS[nr.notification.type]
        data = json.loads(nr.notification.data)
        ctx = notification_type.context(data)
        ctx.update({'URL_PREFIX': settings.URL_PREFIX, 'STATIC_URL': settings.STATIC_URL})
        notifications.append(render_to_string(notification_type.template, ctx))

    if len(notifications) > 0:
        profile = Profile.objects.select_related('user').get(id=profile_id)
        send_email(profile, u'Активность на площадке Гракон', 'letters/notifications.html',
                {'notifications': notifications}, 'notification', 'noreply')

        nrs = NotificationRecipient.objects.filter(id__in=[nr.id for nr in nrs]) \
                .update(email_sent=True)
Exemplo n.º 11
0
 def __send_email_address_verification_mail__(cls, email,
                                              verification_token):
     # TODO: change body and subject
     send_email(to=email,
                subject="Verify MB user",
                body=f"Verification Token: {verification_token}")
Exemplo n.º 12
0
        recipient = Profile.objects.select_related('user').get(id=recipient_id)
    except ValueError, Profile.DoesNotExist:
        return HttpResponse(u'Получатель указан неверно')

    title = escape_html(form.cleaned_data['title'])
    body = escape_html(form.cleaned_data['body'])
    show_email = form.cleaned_data['show_email']

    subject = u'Пользователь %s написал вам сообщение' % unicode(request.profile)
    ctx = {
        'title': title,
        'body': body,
        'show_email': show_email,
        'sender': request.profile,
    }
    send_email(recipient, subject, 'letters/message.html', ctx, 'message', 'noreply',
            reply_to=request.profile.user.email if show_email else None)

    Message.objects.create(sender=request.profile, receiver=recipient, title=title,
            body=body, show_email=show_email)

    return HttpResponse('ok')

@authenticated_ajax_post
def add_role(request):
    try:
        loc_id = int(request.POST.get('loc_id', ''))
        location = Location.objects.select_related().get(id=loc_id)
    except (ValueError, Location.DoesNotExist):
        return HttpResponse(u'Неверно указан loc_id')

    if not location.is_tik() and not location.is_uik():
Exemplo n.º 13
0
 def send_activation_email(self):
     send_email(self.user.get_profile(), u'Активация учетной записи на grakon.org', 'letters/activation_email.html',
             {'activation_key': self.activation_key}, 'activation', 'noreply')