Пример #1
0
        // POST api/log
        public Response Post(User user)
        {
            var response = new Response()
            {
                valid = false
            };

            var oldUser = db.User.Where(u => u.username == user.username).First();

            if (oldUser != null && oldUser.active != 0)
            {
                var triedPass = Util.saltPassword(user.password, oldUser.salt);
                if (triedPass == oldUser.password)
                {
                    db.Token.Where(t => t.userId == oldUser.id || t.expires < DateTime.Now).ToList().ForEach(t => db.Token.Remove(t));
                    Token token = new Token()
                    {
                        expires = DateTime.Now.AddMinutes(15),
                        token1  = Guid.NewGuid().ToString(),
                        userId  = oldUser.id
                    };
                    db.Token.Add(token);
                    db.SaveChanges();

                    response.valid    = true;
                    response.token    = token.token1;
                    response.expires  = token.expires;
                    response.idUser   = token.userId;
                    response.userName = oldUser.username;
                    response.avatar   = oldUser.avatar;
                    return(response);
                }
            }
            return(response);
        }
Пример #2
0
        // PUT api/Post/5
        public HttpResponseMessage PutPost(string token, int id, Post post)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            Token oldToken = db.Token.Where(t => t.token1 == token && t.expires > DateTime.Now).FirstOrDefault();

            if (oldToken != null)
            {
                if (id != post.id)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                Post oldPost = db.Post.Find(id);
                if (oldPost.idUser != oldToken.userId)
                {
                    ModelState.AddModelError("Forbiden", "operation not allowed");
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                oldPost.idCategory  = post.Category.id;
                oldPost.postContent = post.postContent;
                oldPost.synopsis    = post.synopsis;
                oldPost.title       = post.title;

                oldToken.expires = DateTime.Now.AddMinutes(15);
                Util.RemoveTokens(db);

                db.Entry(oldToken).State      = EntityState.Modified;
                db.Entry(post.Category).State = EntityState.Unchanged;
                db.Entry(oldPost).State       = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                ModelState.AddModelError("token", "token expired");
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
        // PUT api/Password/5
        public HttpResponseMessage PutPassword(string id, NewPassword pass)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }           

             Token token = db.Token.Where(t => t.token1 == id && t.expires > DateTime.Now).FirstOrDefault();
             if (token != null)
             {          

                 var user = db.User.Find(token.userId);
                 var salted = Util.saltPassword(pass.oldPassword, user.salt);

                 if (salted != user.password)
                 {
                     db.Token.Remove(token);
                     db.SaveChanges();
                     ModelState.AddModelError("token", "token expired");
                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                 }

                 RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
                 byte[] random = new byte[10];
                 rngCsp.GetBytes(random);
                 var strSalt = BitConverter.ToString(random).Replace("-", "");

                 user.password = Util.saltPassword(pass.password, strSalt);
                 user.salt = strSalt;
                 
                 Util.RemoveTokens(db);
                 db.Token.Remove(token);
                 db.Entry(user).State = EntityState.Modified;

                 try
                 {
                     db.SaveChanges();
                 }
                 catch (DbUpdateConcurrencyException ex)
                 {
                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
                 }
                 return Request.CreateResponse(HttpStatusCode.OK);
             }
             else
             {
                 ModelState.AddModelError("token", "token expired");
                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
             }            
        }
Пример #4
0
        // PUT api/Comment/5
        public HttpResponseMessage PutComment(string token, int id, Comment comment)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != comment.id)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            Token oldToken = db.Token.Where(t => t.token1 == token && t.expires > DateTime.Now).FirstOrDefault();

            if (oldToken != null)
            {
                Comment oldComment = db.Comment.Find(id);
                if (oldComment.idUser != oldToken.userId)
                {
                    ModelState.AddModelError("Forbiden", "operation not allowed");
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                oldComment.comment1 = comment.comment1;

                oldToken.expires         = DateTime.Now.AddMinutes(15);
                db.Entry(oldToken).State = EntityState.Modified;
                Utils.Util.RemoveTokens(db);


                db.Entry(oldComment).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                ModelState.AddModelError("token", "token expired");
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Пример #5
0
        public void Send(string token, string message)
        {
            try
            {
                using (BlogAngularEntities db = new BlogAngularEntities())
                {
                    var oldToken = db.Token.Find(token);
                    if (oldToken != null)
                    {
                        var user = db.User.Find(oldToken.userId);
                        oldToken.expires = DateTime.Now.AddMinutes(35);
                        Util.RemoveTokens(db);

                        storeMessage(db, user, message);

                        // Call the broadcastMessage method to update clients.
                        Clients.All.broadcastMessage(new ChatMessage()
                        {
                            Username = user.username,
                            Message  = message,
                            Hour     = DateTime.Now.ToString("h:mm:ss"),
                            Avatar   = user.avatar,
                        });

                        db.SaveChanges();
                    }
                    else
                    {
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
Пример #6
0
        //// GET api/User
        //public IEnumerable<User> GetUsers()
        //{
        //    return db.User.AsEnumerable();
        //}

        //// GET api/User/5
        //public User GetUser(int id)
        //{
        //    User user = db.User.Find(id);
        //    if (user == null)
        //    {
        //        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        //    }

        //    return user;
        //}

        // PUT api/User/5
        //public HttpResponseMessage PutUser(int id, User user)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        //    }

        //    if (id != user.id)
        //    {
        //        return Request.CreateResponse(HttpStatusCode.BadRequest);
        //    }

        //    db.Entry(user).State = EntityState.Modified;

        //    try
        //    {
        //        db.SaveChanges();
        //    }
        //    catch (DbUpdateConcurrencyException ex)
        //    {
        //        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        //    }

        //    return Request.CreateResponse(HttpStatusCode.OK);
        //}

        // POST api/User
        public HttpResponseMessage PostUser(User user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
                    byte[] random = new byte[10];
                    rngCsp.GetBytes(random);
                    var strSalt = BitConverter.ToString(random).Replace("-", "");

                    user.password = Util.saltPassword(user.password, strSalt);
                    user.salt     = strSalt;
                    user.created  = DateTime.Now;
                    user.avatar   = "default.png";
                    user.active   = 0;

                    db.User.Add(user);
                    db.SaveChanges();

                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                    response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.id }));
                    return(response);
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Пример #7
0
        // PUT api/Category/5
        public HttpResponseMessage PutCategory(string token, int id, Category category)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            Token oldToken = db.Token.Where(t => t.token1 == token && t.expires > DateTime.Now).FirstOrDefault();

            if (oldToken != null)
            {
                if (id != category.id)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                oldToken.expires = DateTime.Now.AddMinutes(15);
                Util.RemoveTokens(db);
                db.Entry(oldToken).State = EntityState.Modified;
                db.Entry(category).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                ModelState.AddModelError("token", "token expired");
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
        // GET api/ChatMessage
        public IEnumerable <ChatMessage> GetChatMessages(string id)
        {
            Token token = db.Token.Where(t => t.token1 == id && t.expires > DateTime.Now).FirstOrDefault();

            if (token != null)
            {
                ChatHub.storeOldChat(db, DateTime.Now);
                token.expires = DateTime.Now.AddMinutes(15);
                Util.RemoveTokens(db);
                db.Entry(token).State = EntityState.Modified;
                db.SaveChanges();
                var chatmessages = db.ChatMessage.Include(c => c.User).OrderBy(c => c.Created).ToList();
                return(chatmessages.Select(c => new ChatMessage()
                {
                    Avatar = c.User.avatar,
                    Message = c.Message,
                    Username = c.User.username,
                    Hour = c.Created.ToString("h:mm:ss")
                }));
            }
            return(new List <ChatMessage>());
        }
Пример #9
0
        public async Task <HttpResponseMessage> PostUpload(string id)
        {
            Token token = db.Token.Where(t => t.token1 == id && t.expires > DateTime.Now).FirstOrDefault();

            if (token != null)
            {
                // Check if the request contains multipart/form-data.
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                token.expires = DateTime.Now.AddMinutes(15);
                Util.RemoveTokens(db);
                db.Entry(token).State = EntityState.Modified;

                User user = db.User.Find(token.userId);

                string root     = HttpContext.Current.Server.MapPath("~/cliente/app/images/avatars");
                var    provider = new MultipartFormDataStreamProvider(root);

                try
                {
                    // Read the form data.
                    await Request.Content.ReadAsMultipartAsync(provider);


                    // This illustrates how to get the file names.
                    foreach (MultipartFileData fileData in provider.FileData)
                    {
                        if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                        {
                            return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
                        }
                        string fileName = fileData.Headers.ContentDisposition.FileName;
                        if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                        {
                            fileName = fileName.Trim('"');
                        }
                        if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                        {
                            fileName = Path.GetFileName(fileName);
                        }
                        string path = Path.Combine(root, user.username + fileName.Substring(fileName.LastIndexOf('.')));
                        File.Delete(path);
                        File.Move(fileData.LocalFileName, path);

                        user.avatar = user.username + fileName.Substring(fileName.LastIndexOf('.'));
                        db.SaveChanges();
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                catch (System.Exception e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
                }
            }
            else
            {
                ModelState.AddModelError("token", "token expired");
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }