public async Task <IHttpActionResult> Login(LoginModel model)
        {
            if (model == null || !model.IsValid())
            {
                return(Content(HttpStatusCode.BadRequest, new Error("Missing or empty 'user' and 'password' properties in message body")));
            }

            var userKey      = CreateUserKey(model.Username);
            var userDocument = await _bucket.GetDocumentAsync <User>(userKey);

            if (!userDocument.Success)
            {
                if (userDocument.Status == ResponseStatus.KeyNotFound)
                {
                    return(Content(HttpStatusCode.Unauthorized, new Error("Invalid username and/or password")));
                }
                return(Content(HttpStatusCode.InternalServerError, new Error(userDocument.Message)));
            }

            var user = userDocument.Content;

            if (user.Password != CalcuateMd5Hash(model.Password))
            {
                return(Content(HttpStatusCode.Unauthorized, new Error("Invalid username and/or password")));
            }

            var data = new
            {
                token = BuildToken(user.Username)
            };
            var context = $"User {model.Username} logged in successfully";

            return(Content(HttpStatusCode.OK, new Result(data, context)));
        }
Esempio n. 2
0
        public async Task <ResponseModel <Todo> > CreateOrUpdateTodoAsync(Todo entity)
        {
            try
            {
                if (entity == null)
                {
                    CheckEntity(entity);
                }

                ResponseModel <Todo> response = new ResponseModel <Todo>();
                if (entity.Id == null)
                {
                    entity.Id             = Guid.NewGuid().ToString();
                    entity.CreateDateTime = DateTime.Now;
                    entity.PinnedDateTime = (entity.IsPinned ? DateTime.Now : (DateTime?)null);
                    await todosBucket.InsertAsync(entity.Id, entity);

                    var todoDocument = await todosBucket.GetDocumentAsync <Todo>(entity.Id);

                    response.Entity = todoDocument.Content;
                }
                else
                {
                    var context  = new BucketContext(todosBucket);
                    var category = context.Query <Todo>().FirstOrDefault(u => u.Id == entity.Id);
                    if (category == null)
                    {
                        response.Code    = 0x0005;
                        response.Error   = true;
                        response.Message = "Yapılacak bilgileri eşleşmedi, lütfen tekrar deneyiniz.";
                    }
                    else
                    {
                        var todoDocument = await todosBucket.GetDocumentAsync <Todo>(entity.Id);

                        todoDocument.Content.Title          = entity.Title;
                        todoDocument.Content.Content        = entity.Content;
                        todoDocument.Content.IsPinned       = entity.IsPinned;
                        todoDocument.Content.PinnedDateTime = (entity.IsPinned ? DateTime.Now : (DateTime?)null);
                        todoDocument.Content.Alert          = entity.Alert;
                        todoDocument.Content.IsItDone       = entity.IsItDone;
                        await todosBucket.UpsertAsync(todoDocument.Document);

                        context.SubmitChanges();
                        response.Entity = todoDocument.Content;
                    }
                }
                return(response);
            }
            catch (Exception e)
            {
                return(ThrowingCatch(entity, e));
            }
        }
        public async Task <Lesson> Create(Lesson lesson)
        {
            lesson.Id      = Guid.NewGuid().ToString();
            lesson.Created = DateTime.Now;
            lesson.Updated = DateTime.Now;
            await this.bucket.InsertAsync <Lesson>($"lesson::{lesson.Id}", lesson);

            var result = (await bucket.GetDocumentAsync <Lesson>($"lesson::{lesson.Id}")).Content;

            return(result);
        }
Esempio n. 4
0
        public async Task <ResponseModel <User> > CreateOrUpdateUserAsync(User entity)
        {
            ResponseModel <User> response = new ResponseModel <User>();

            try
            {
                if (entity == null)
                {
                    CheckEntity(entity);
                }

                if (entity.Id == null)
                {
                    entity.Id             = Guid.NewGuid().ToString();
                    entity.CreateDateTime = DateTime.Now;
                    entity.Password       = Hasher.Hash(entity.Password);
                    await usersBucket.InsertAsync(entity.Id, entity);

                    var userDocument = await usersBucket.GetDocumentAsync <User>(entity.Id);

                    response.Entity = userDocument.Content;
                }
                else
                {
                    var context = new BucketContext(usersBucket);
                    var user    = context.Query <User>().FirstOrDefault(u => u.Id == entity.Id);
                    if (user == null)
                    {
                        response.Code    = 0x0003;
                        response.Error   = true;
                        response.Message = "Kullanıcı bilgileri eşleşmedi, lütfen tekrar deneyiniz.";
                    }
                    else
                    {
                        var userDocument = await usersBucket.GetDocumentAsync <User>(entity.Id);

                        userDocument.Content.NameSurname = entity.NameSurname;
                        userDocument.Content.Username    = entity.Username;
                        userDocument.Content.Password    = Hasher.Hash(entity.Password);
                        await usersBucket.UpsertAsync(userDocument.Document);

                        context.SubmitChanges();
                        response.Entity = userDocument.Content;
                    }
                }

                return(response);
            }
            catch (Exception e)
            {
                return(ThrowingCatch(entity, e));
            }
        }
Esempio n. 5
0
        public async Task <ResponseModel <Category> > CreateOrUpdateCategoryAsync(Category entity)
        {
            try
            {
                if (entity == null)
                {
                    CheckEntity(entity);
                }

                ResponseModel <Category> response = new ResponseModel <Category>();
                if (entity.Id == null)
                {
                    entity.Id             = Guid.NewGuid().ToString();
                    entity.CreateDateTime = DateTime.Now;
                    entity.PinnedDateTime = (entity.IsPinned ? DateTime.Now : (DateTime?)null);
                    await categoriesBucket.InsertAsync(entity.Id, entity);

                    var categoryDocument = await categoriesBucket.GetDocumentAsync <Category>(entity.Id);

                    response.Entity = categoryDocument.Content;
                }
                else
                {
                    var context  = new BucketContext(categoriesBucket);
                    var category = context.Query <Category>().FirstOrDefault(u => u.Id == entity.Id);
                    if (category == null)
                    {
                        response.Code    = 0x0004;
                        response.Error   = true;
                        response.Message = "Kategori bilgileri eşleşmedi, lütfen tekrar deneyiniz.";
                    }
                    else
                    {
                        var categoryDocument = await categoriesBucket.GetDocumentAsync <Category>(entity.Id);

                        categoryDocument.Content.Name           = entity.Name;
                        categoryDocument.Content.IsPinned       = entity.IsPinned;
                        categoryDocument.Content.PinnedDateTime = (entity.IsPinned ? DateTime.Now : (DateTime?)null);
                        await categoriesBucket.UpsertAsync(categoryDocument.Document);

                        context.SubmitChanges();
                        response.Entity = categoryDocument.Content;
                    }
                }
                return(response);
            }
            catch (Exception e)
            {
                return(ThrowingCatch(entity, e));
            }
        }
Esempio n. 6
0
        public async Task MutateIn_ExecuteAsync_ModifiesDocument(bool useMutation)
        {
            Setup(useMutation);

            var key = "MutateIn_ExecuteAsync_ModifiesDocument";
            await _bucket.UpsertAsync(key, new { foo = "bar", bar = "foo" });

            var builder = _bucket.MutateIn <dynamic>(key).Replace("foo", "baz");

            var result = await builder.ExecuteAsync();

            Assert.IsTrue(result.Success);

            var document = await _bucket.GetDocumentAsync <dynamic>(key);

            Assert.AreEqual("baz", document.Content.foo.ToString());
        }
Esempio n. 7
0
        public async Task <List <Post> > GetAll(List <string> ids)
        {
            var getDocumentTasks = new List <Task <IDocumentResult <Post> > >();

            ids.ForEach(x => getDocumentTasks.Add(_postsBucket.GetDocumentAsync <Post>(x)));
            var results = await Task.WhenAll(getDocumentTasks);

            return(results.Select(r => r.Document.Content).ToList());
        }
Esempio n. 8
0
        public async Task GetDocumentAsync_IdIsInOperationResult()
        {
            var key   = "GetDocumentAsync_IdIsInOperationResult";
            var value = "thevalue";

            _bucket.Remove(key);
            _bucket.Insert(key, value);
            var result = await _bucket.GetDocumentAsync <string>(key).ConfigureAwait(false);

            Assert.AreEqual(key, result.Id);
        }
Esempio n. 9
0
        public static IObservable <IDocument <T> > GetDocumentObservable <T>(this IBucket bucket, string id)
        {
            return(Observable.FromAsync(() => bucket.GetDocumentAsync <T>(id))
                   .Where(p => p.Status != ResponseStatus.KeyNotFound)
                   .Select(p =>
            {
                CheckResultForError(p);

                return p.Document;
            }));
        }
Esempio n. 10
0
        public static async Task <string> GetValueAsync(long key)
        {
            var docResult = await _bucket.GetDocumentAsync <dynamic>(key.ToString());

            if (docResult.Status == ResponseStatus.KeyNotFound)
            {
                throw new CouchbaseNotFoundException("Key not found");
            }

            return(docResult.Document.Content.url);
        }
        public async Task <Job> GetJobAsync(long id)
        {
            var result = await _bucket.GetDocumentAsync <Job>(Job.GetKey(id));

            if (result.Status == ResponseStatus.KeyNotFound)
            {
                return(null);
            }

            // Throw an exception on a low-level error
            result.EnsureSuccess();

            return(result.Content);
        }
Esempio n. 12
0
        public static async Task <string> GetLongUrl(string shortUrl)
        {
            // Get ID
            long id  = new ShortUrl(shortUrl);
            var  res = await _bucket.GetDocumentAsync <dynamic>(id.ToString());

            if (res.Success)
            {
                return(res.Document.Content.url);
            }

            if (res.Status == ResponseStatus.KeyNotFound)
            {
                throw new CouchbaseNotFoundException(res.Message);
            }

            throw new Exception(res.Message);
        }
        public async Task <bool> ExistsGroup(Guid groupId, string organizerId)
        {
            var documentResult = await _relationsBucket.GetDocumentAsync <GroupDocument>($"groups|{groupId.ToString()}");

            return(documentResult.Content != null && documentResult.Content.OrganizerId == organizerId);
        }
        public async Task <T> FindAsync(string key)
        {
            var result = await _bucket.GetDocumentAsync <T>(key);

            return(result.Document.ConvertEntity());
        }
Esempio n. 15
0
        public async Task <TaskDocument> Get(Guid taskId)
        {
            var documentResult = await _bucket.GetDocumentAsync <TaskDocument>(taskId.ToString());

            return(documentResult.Document.Content);
        }
        /// <inheritdoc/>
        public async Task Renew(TimeSpan expiration)
        {
            if (expiration <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(expiration), "Value must be positive.");
            }

            var key      = LockDocument.GetKey(Name);
            var document = new LockDocument
            {
                Holder            = Holder,
                RequestedDateTime = DateTime.UtcNow
            };

            IOperationResult <LockDocument> result;

            if (_cas == 0)
            {
                // We're creating a new lock
                _log.Debug("Requesting lock '{0}' for holder '{1}' for {2}", Name, Holder, expiration);
                result = await _bucket.InsertAsync(key, document, expiration).ConfigureAwait(false);
            }
            else
            {
                _log.Debug("Renewing lock '{0}' for holder '{1}' for {2}", Name, Holder, expiration);
                result = await _bucket.UpsertAsync(key, document, _cas, expiration).ConfigureAwait(false);
            }

            if (result.Status == ResponseStatus.DocumentMutationDetected || result.Status == ResponseStatus.KeyExists)
            {
                _log.Debug("Lock '{0}' unavailable, getting lock info", Name);

                var getResult = await _bucket.GetDocumentAsync <LockDocument>(key).ConfigureAwait(false);

                if (getResult.Status == ResponseStatus.KeyNotFound)
                {
                    // Couldn't find the lock, must have expired between Insert and Get, try one more time
                    result = await _bucket.InsertAsync(key, document, expiration).ConfigureAwait(false);

                    if (result.Status == ResponseStatus.KeyExists)
                    {
                        throw new CouchbaseLockUnavailableException(Name);
                    }

                    _log.Debug("Lock '{0}' issued to holder '{1}'", Name, Holder);
                    result.EnsureSuccess();

                    _expirationInterval = expiration;
                    _cas = result.Cas;
                    return;
                }

                getResult.EnsureSuccess();

                _log.Debug("Unable to acquire lock '{0}' for holder '{1}'", Name, Holder);

                throw new CouchbaseLockUnavailableException(Name)
                      {
                          Holder = getResult.Content.Holder
                      };
            }

            _log.Debug("Lock '{0}' issued to holder '{1}'", Name, Holder);
            result.EnsureSuccess();

            _expirationInterval = expiration;
            _cas = result.Cas;
        }