Esempio n. 1
0
        public static async Task SendPasswordRecoveryEmail(MongoWrapper mongoWrapper,
                                                           SmtpConfiguration smtpConfig,
                                                           User user)
        {
            var confirmationCollection = mongoWrapper.Database.GetCollection <ReferenceToken>(typeof(ReferenceToken).Name);

            var tokenTask = GeneralUtils.GenerateRandomString(6, "1234567890".ToCharArray());

            string token = await tokenTask;

            ReferenceToken confirmation = new ReferenceToken()
            {
                UserId    = user._id,
                TokenType = TokenType.PasswordRecovery,
                _id       = token,
            };

            var insertConfirmationTask = confirmationCollection.InsertOneAsync(confirmation);

            await insertConfirmationTask;

            var sendEmailTask = SendEmail
                                (
                smtpConfig: smtpConfig,
                body: $"Você está recebendo este e-mail pois uma mudança de senha foi requisitada. Caso não tenha requisitado uma mudança de senha, ignore este e-mail.<br>Seu código de nova senha FindFM: <b>{token}</b>",
                subject: "[FindFM] Recuperação de senha - Código",
                encoding: Encoding.UTF8,
                from: new MailAddress(smtpConfig.Email, smtpConfig.DisplayName, Encoding.UTF8),
                to: new[] { new MailAddress(user.Email, user.FullName, Encoding.UTF8) }
                                );

            var sendEmailContinuation = sendEmailTask.ContinueWith(t =>
            {
                LOGGER.Error(t.Exception, "Sending password recovery e-mail has failed!");
            },
                                                                   TaskContinuationOptions.OnlyOnFaulted);

            await sendEmailTask;
        }
Esempio n. 2
0
        public static async Task SendConfirmationEmail(MongoWrapper mongoWrapper,
                                                       SmtpConfiguration smtpConfig,
                                                       User user)
        {
            var confirmationCollection = mongoWrapper.Database.GetCollection <ReferenceToken>(typeof(ReferenceToken).Name);

            var tokenTask = GeneralUtils.GenerateRandomString(6, "1234567890".ToCharArray());

            string token = await tokenTask;

            ReferenceToken confirmation = new ReferenceToken()
            {
                UserId    = user._id,
                TokenType = TokenType.Confirmation,
                _id       = token,
            };

            var insertConfirmationTask = confirmationCollection.InsertOneAsync(confirmation);

            await insertConfirmationTask;

            var sendEmailTask = SendEmail
                                (
                smtpConfig: smtpConfig,
                body: $"Seu código de confirmação FindFM: <b>{token}</b>",
                subject: "[FindFM] Confirmação de E-mail",
                encoding: Encoding.UTF8,
                from: new MailAddress(smtpConfig.Email, smtpConfig.DisplayName, Encoding.UTF8),
                to: new[] { new MailAddress(user.Email, user.FullName, Encoding.UTF8) }
                                );

            var sendEmailContiuation = sendEmailTask.ContinueWith(t =>
            {
                LOGGER.Error(t.Exception, "Sending confirmation e-mail has failed!");
            },
                                                                  TaskContinuationOptions.OnlyOnFaulted);

            await sendEmailTask;
        }
Esempio n. 3
0
        /// <summary>
        /// Resolves a token to a FileReference, if the token exists for this user.
        /// The action should be called once the calling code can ensure the file is handled ok.
        /// </summary>
        /// <param name="mongoWrapper">For accessing the database</param>
        /// <param name="tokenId">The token ID to search for</param>
        /// <param name="userId">The user ID to correlate with the token</param>
        /// <returns>A Tuple of the FileReference and an async action to expire the token</returns>
        public static async Task <(FileReference, Func <Task>)> GetFileForReferenceToken(MongoWrapper mongoWrapper, string tokenId, ObjectId userId)
        {
            var tokenCollection = mongoWrapper.Database.GetCollection <DataReferenceToken <ConsumableData <ObjectId> > >(nameof(ReferenceToken));

            var tokenFilterBuilder = new FilterDefinitionBuilder <DataReferenceToken <ConsumableData <ObjectId> > >();
            var tokenFilter        = tokenFilterBuilder.And
                                     (
                GeneralUtils.NotDeactivated(tokenFilterBuilder),
                tokenFilterBuilder.Eq(t => t._id, tokenId),
                tokenFilterBuilder.Eq(t => t.UserId, userId)
                                     );

            var tokenUpdateBuilder = new UpdateDefinitionBuilder <DataReferenceToken <ConsumableData <ObjectId> > >();
            var tokenUpdate        = tokenUpdateBuilder
                                     .Set(t => t.DeactivationDate, DateTime.UtcNow)
                                     .Set(t => t.AdditionalData.IsConsumed, true);

            DataReferenceToken <ConsumableData <ObjectId> > token = (await tokenCollection.FindAsync(tokenFilter, new FindOptions <DataReferenceToken <ConsumableData <ObjectId> >, DataReferenceToken <ConsumableData <ObjectId> > >
            {
                Limit = 1,
                AllowPartialResults = false,
            })).SingleOrDefault();

            if (token == null)
            {
                throw new ValidationException("Token de Arquivo não encontrado!");
            }

            var gridFsBucket = new GridFSBucket <ObjectId>(mongoWrapper.Database);

            var fileFilterBuilder = new FilterDefinitionBuilder <GridFSFileInfo <ObjectId> >();
            var fileFilter        = fileFilterBuilder.Eq(finfo => finfo.Id, token.AdditionalData.Data);

            var fileInfo = (await gridFsBucket.FindAsync(fileFilter, new GridFSFindOptions <ObjectId>
            {
                Limit = 1,
            })).SingleOrDefault();

            if (fileInfo == null)
            {
                throw new ApplicationException("Arquivo não encontrado, mas havia um token ativado referenciando-o!");
            }

            var fileReference = new FileReference
            {
                FileInfo = new Models.FileInfo
                {
                    FileMetadata = BsonSerializer.Deserialize <FileMetadata>(fileInfo.Metadata),
                    Size         = fileInfo.Length
                },
                _id = token.AdditionalData.Data
            };

            return
                (
                fileReference,
                async() =>
            {
                var tokenUpdateTask = tokenCollection.UpdateOneAsync
                                      (
                    tokenFilter,
                    tokenUpdate
                                      );

                var userCollection = mongoWrapper.Database.GetCollection <User>(nameof(User));

                var userFilterBuilder = new FilterDefinitionBuilder <User>();
                var userFilter = userFilterBuilder.And
                                 (
                    GeneralUtils.NotDeactivated(userFilterBuilder),
                    userFilterBuilder.Eq(u => u._id, userId)
                                 );

                var userUpdateBuilder = new UpdateDefinitionBuilder <User>();
                var userUpdate = userUpdateBuilder.Inc(u => u.FileBytesOccupied, fileReference.FileInfo.Size);

                var userUpdateTask = userCollection.UpdateOneAsync
                                     (
                    userFilter,
                    userUpdate
                                     );

                await tokenUpdateTask;
                await userUpdateTask;
            }
                );
        }