Example #1
0
        private void CreateBoxToken(string email)
        {
            UserToken token = null;

            using (var context = new Data.CoreContext()) {
                token           = context.UserTokens.Add(new UserToken());
                token.Email     = email;
                token.Token     = Guid.NewGuid().ToString();
                token.IssueDate = DateTime.Now;
                context.SaveChanges();
            }

            CleanOldTokens();

            // create encryption cookie
            //System.Web.Security.FormsAuthenticationTicket authTicket = new System.Web.Security.FormsAuthenticationTicket(
            //        1,
            //        token.Token,
            //        DateTime.Now,
            //        DateTime.Now.AddDays(1),
            //        true,
            //        "");

            //// add cookie to response stream
            //string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);

            //System.Web.HttpCookie authCookie = new System.Web.HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket);
            //System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);


            System.Web.Security.FormsAuthentication.SetAuthCookie(token.Token, true);
        }
Example #2
0
 /// <summary>
 /// Removes/Cancel the task.
 /// </summary>
 /// <param name="asyncTaskUId">The task UId to be updated</param>
 public void RemoveTask(string asyncTaskUId)
 {
     using (Data.CoreContext context = new Data.CoreContext()) {
         AsyncTask asyncTask = context.AsyncTasks.SingleOrDefault(a => a.AsyncTaskUId == asyncTaskUId);
         context.AsyncTasks.Remove(asyncTask);
         context.SaveChanges();
     }
 }
Example #3
0
 private void CleanOldTokens()
 {
     using (var context = new Data.CoreContext()) {
         DateTime    oneWeekAgo = DateTime.Today.AddDays(-7);
         UserToken[] oldTokens  = context.UserTokens.Where(t => t.IssueDate < oneWeekAgo).ToArray();
         foreach (UserToken token in oldTokens)
         {
             context.UserTokens.Remove(token);
         }
         context.SaveChanges();
     }
 }
Example #4
0
 private void ResetLoginErrorsCount(string email)
 {
     using (var context = new Data.CoreContext()) {
         User user = context.Users.SingleOrDefault(u => u.Email == email);
         if (user == null)
         {
             return;
         }
         user.LoginErrorsCount = 0;
         user.Blocked          = false;
         context.SaveChanges();
     }
 }
Example #5
0
 public void RemoveUser(string email)
 {
     using (var context = new Data.CoreContext()) {
         User user = GetUser(email);
         if (user == null)
         {
             return;
         }
         context.Users.Attach(user);
         context.Users.Remove(user);
         context.SaveChanges();
     }
 }
Example #6
0
        public void RemoveGroupCollection(string groupCollectionUId)
        {
            using (var context = new Data.CoreContext()) {
                GroupCollection groupCollection = GetGroupCollection(groupCollectionUId);
                if (groupCollection == null)
                {
                    return;
                }

                context.GroupCollections.Attach(groupCollection);
                context.GroupCollections.Remove(groupCollection);
                context.SaveChanges();
            }
        }
Example #7
0
        private void UpdateLoginErrorsCount(string email)
        {
            using (var context = new Data.CoreContext()) {
                User user = context.Users.SingleOrDefault(u => u.Email == email);
                if (user == null)
                {
                    return;
                }
                user.LoginErrorsCount++;
                if (user.LoginErrorsCount > MaxErrorCount && MaxErrorCount > 0 && MaxErrorCount != null)
                {
                    user.Blocked = true;
                }

                context.SaveChanges();
            }
        }
Example #8
0
        /// <summary>
        /// Creates tasks percentage.
        /// </summary>
        /// <param name="asyncTaskUId">The task UId to be updated</param>
        /// <param name="currentActivity">The current activity</param>
        /// <param name="pct">The current percentage</param>
        public void CreateTask(string asyncTaskUId, string type, string requiredRole, string currentActivity, string description, string fileName, string contentType, string mimeType)
        {
            AsyncTask asyncTask = new AsyncTask();
            asyncTask.AsyncTaskUId = asyncTaskUId;
            asyncTask.Type = type;
            asyncTask.CurrentAtivity = currentActivity;
            asyncTask.RequiredRole = requiredRole;
            asyncTask.Description = description;
            asyncTask.CurrentPercentage = 0;
            asyncTask.StartDate = DateTime.Now.ToUniversalTime();
            asyncTask.FileName = fileName;
            asyncTask.ResultContentType = contentType;
            asyncTask.ResultMimeType = mimeType;

            using (Data.CoreContext context = new Data.CoreContext()) {
                context.AsyncTasks.Add(asyncTask);
                context.SaveChanges();
            }
        }
Example #9
0
        public void SignOutUser()
        {
            string token = System.Threading.Thread.CurrentPrincipal.Identity.Name;

            if (String.IsNullOrEmpty(token))
            {
                return;
            }

            using (var context = new Data.CoreContext()) {
                UserToken oldToken = context.UserTokens.SingleOrDefault(t => t.Token == token);
                if (oldToken != null)
                {
                    context.UserTokens.Remove(oldToken);
                    context.SaveChanges();
                }
            }

            System.Web.Security.FormsAuthentication.SignOut();
        }
Example #10
0
        private PasswordReset CreatePasswordReset(string email, string pass)
        {
            PasswordReset reset = null;

            using (var context = new Data.CoreContext()) {
                PasswordReset oldReset = context.PasswordResets.SingleOrDefault(p => p.Email.ToLower() == email.ToLower());
                if (oldReset != null)
                {
                    context.PasswordResets.Remove(oldReset);
                }
                reset = new PasswordReset()
                {
                    Email = email, IssueDate = DateTime.Now, Key = Guid.NewGuid().ToString(), NewPassword = Crypt(pass)
                };
                context.PasswordResets.Add(reset);
                context.SaveChanges();
            }

            return(reset);
        }
Example #11
0
        /// <summary>
        /// Creates tasks percentage.
        /// </summary>
        /// <param name="asyncTaskUId">The task UId to be updated</param>
        /// <param name="currentActivity">The current activity</param>
        /// <param name="pct">The current percentage</param>
        public void CreateTask(string asyncTaskUId, string type, string requiredRole, string currentActivity, string description, string fileName, string contentType, string mimeType)
        {
            AsyncTask asyncTask = new AsyncTask();

            asyncTask.AsyncTaskUId      = asyncTaskUId;
            asyncTask.Type              = type;
            asyncTask.CurrentAtivity    = currentActivity;
            asyncTask.RequiredRole      = requiredRole;
            asyncTask.Description       = description;
            asyncTask.CurrentPercentage = 0;
            asyncTask.StartDate         = DateTime.Now.ToUniversalTime();
            asyncTask.FileName          = fileName;
            asyncTask.ResultContentType = contentType;
            asyncTask.ResultMimeType    = mimeType;

            using (Data.CoreContext context = new Data.CoreContext()) {
                context.AsyncTasks.Add(asyncTask);
                context.SaveChanges();
            }
        }
Example #12
0
        public bool ApplyResetPassword(string key)
        {
            PasswordReset reset = null;

            using (var context = new Data.CoreContext()) {
                DateTime limitDate = DateTime.Now.AddHours(-2);
                reset = context.PasswordResets.SingleOrDefault(p => p.Key == key && p.IssueDate > limitDate);
                if (reset == null)
                {
                    return(false);
                }

                User user = GetUser(reset.Email);
                if (user == null)
                {
                    return(false);
                }

                context.Users.Attach(user);

                if (user.Password != null)
                {
                    user.Password.Password = reset.NewPassword;
                    user.Blocked           = false;
                    user.LoginErrorsCount  = 0;
                }
                else
                {
                    user.Password = new UserPassword()
                    {
                        Email = user.Email, Password = reset.NewPassword
                    }
                };

                context.PasswordResets.Remove(reset);

                context.SaveChanges();
            }

            return(true);
        }
Example #13
0
        /// <summary>
        /// Finishes the task.
        /// </summary>
        /// <param name="asyncTaskUId">The task UId to be updated</param>
        /// <param name="result">The byte array result</param>
        public void FinishTask(string asyncTaskUId)
        {
            using (Data.CoreContext context = new Data.CoreContext()) {
                AsyncTask asyncTask = context.AsyncTasks.SingleOrDefault(a => a.AsyncTaskUId == asyncTaskUId);
                if (asyncTask == null)
                    return;

                compress.Close();
                compress.Dispose();

                asyncTask.Result = memoryStream.ToArray();
                asyncTask.FileSize = asyncTask.Result.Length;
                asyncTask.EndDate = DateTime.Now.ToUniversalTime();
                context.SaveChanges();

                memoryStream.Close();
                memoryStream.Dispose();

                GC.Collect();

            }
        }
Example #14
0
        /// <summary>
        /// Updates tasks percentage.
        /// </summary>
        /// <param name="asyncTaskUId">The task UId to be updated</param>
        /// <param name="currentActivity">The current activity</param>
        /// <param name="pct">The current percentage</param>
        public AsyncTask UpdateTask(string asyncTaskUId, string currentActivity, short pct)
        {
            AsyncTask asyncTask = null;

            using (Data.CoreContext context = new Data.CoreContext()) {
                try {
                    asyncTask = context.AsyncTasks.SingleOrDefault(a => a.AsyncTaskUId == asyncTaskUId);
                    if (asyncTask == null)
                    {
                        return(null);
                    }
                    asyncTask.CurrentAtivity    = currentActivity;
                    asyncTask.CurrentPercentage = pct;
                    context.SaveChanges();
                }
                catch {
                    asyncTask = null;
                }

                return(asyncTask);
            }
        }
Example #15
0
        /// <summary>
        /// Finishes the task.
        /// </summary>
        /// <param name="asyncTaskUId">The task UId to be updated</param>
        /// <param name="result">The byte array result</param>
        public void FinishTask(string asyncTaskUId)
        {
            using (Data.CoreContext context = new Data.CoreContext()) {
                AsyncTask asyncTask = context.AsyncTasks.SingleOrDefault(a => a.AsyncTaskUId == asyncTaskUId);
                if (asyncTask == null)
                {
                    return;
                }

                compress.Close();
                compress.Dispose();

                asyncTask.Result   = memoryStream.ToArray();
                asyncTask.FileSize = asyncTask.Result.Length;
                asyncTask.EndDate  = DateTime.Now.ToUniversalTime();
                context.SaveChanges();

                memoryStream.Close();
                memoryStream.Dispose();

                GC.Collect();
            }
        }
Example #16
0
        public GroupCollection SaveGroupCollection(GroupCollection groupCollection)
        {
            using (var context = new Data.CoreContext()) {
                GroupCollection oldGroupCollection = GetGroupCollection(groupCollection.GroupCollectionUId);

                List <GroupCollection_Group> removedGroups = new List <GroupCollection_Group>();
                List <GroupCollection_Group> addedGroups   = groupCollection.CollectionGroups.ToList();

                if (oldGroupCollection == null)
                {
                    context.GroupCollections.Add(groupCollection);
                }
                else
                {
                    removedGroups = oldGroupCollection.CollectionGroups.Where(o => !groupCollection.CollectionGroups.Any(u => u.UserGroupUId == o.UserGroupUId)).ToList();
                    addedGroups   = groupCollection.CollectionGroups.Where(u => !oldGroupCollection.CollectionGroups.Any(o => o.UserGroupUId == u.UserGroupUId)).ToList();

                    context.GroupCollections.Attach(oldGroupCollection);
                    context.Entry <GroupCollection>(oldGroupCollection).CurrentValues.SetValues(groupCollection);
                }

                foreach (GroupCollection_Group m in removedGroups)
                {
                    context.GroupCollection_Groups.Remove(m);
                }

                foreach (GroupCollection_Group m in addedGroups)
                {
                    m.GroupCollectionUId = groupCollection.GroupCollectionUId;
                    context.GroupCollection_Groups.Add(m);
                }

                context.SaveChanges();

                return(groupCollection);
            }
        }
Example #17
0
        public void Log(string actionDescription, string errorDescription = null, bool saveParameters = true)
        {
            string url = "unknow";
            string login = "******";
            string ip = "unknow";
            DateTime when = DateTime.Now.ToUniversalTime();
            Dictionary<string, object> dicParameters = null;

            var httpContext = System.Web.HttpContext.Current;
            if (httpContext != null) {
                url = httpContext.Request.Url.OriginalString;
                ip = httpContext.Request.UserHostAddress;

                // if was not via IMPORT
                if (security == null)
                    security = new SecurityService();

                User user = security.GetSignedUser();

                if (user != null)
                    login = user.Email;

                if (user != null && user.LoginNT != null)
                    login = login + " (" + user.LoginNT + ")";

                if (saveParameters) {

                    dicParameters = new Dictionary<string, object>();

                    //Salvar dados que são enviados no corpo da requisição
                    if (httpContext.Request.InputStream.Length > 0) {
                        httpContext.Request.InputStream.Position = 0;
                        using (StreamReader reader = new StreamReader(httpContext.Request.InputStream)) {
                            if (httpContext.Request.ContentType.ToLower().Contains("application/json;"))
                                dicParameters["body"] = Newtonsoft.Json.JsonConvert.DeserializeObject(reader.ReadToEnd());
                            else
                                dicParameters["body"] = reader.ReadToEnd();
                        }
                    }
                    //Salvar dados que são enviados via GET
                    if (httpContext.Request.QueryString.HasKeys()) {
                        Dictionary<string, string> dicGet = new Dictionary<string, string>();
                        dicParameters["get"] = NameValueCollectionToDictionary(httpContext.Request.QueryString);
                    }
                    //Salvar dados que são enviados via POST
                    if (httpContext.Request.Form.HasKeys()) {
                        dicParameters["post"] = NameValueCollectionToDictionary(httpContext.Request.Form);
                    }
                }
            }

            string parameters = null;

            if (dicParameters != null && dicParameters.Count > 0)
                parameters = Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters);

            short logType = 0;
            if (!string.IsNullOrEmpty(errorDescription)) {
                logType = (short)LogTypes.ERROR;
            }

            Log log = new Log() { LogUId = Guid.NewGuid().ToString(), ActionDescription = actionDescription, ErrorDescription = errorDescription, LogType = logType, SignedUser = login, Url = url, UserIp = ip, When = when, Parameters = parameters };

            try {
                using (var context = new Data.CoreContext()) {
                    context.Logs.Add(log);
                    context.SaveChanges();

                    // delete old records
                    DateTime yearAgo = when.AddYears(-1);
                    context.Database.ExecuteSqlCommand("DELETE FROM Logs WHERE Logs.When < '" + yearAgo.Year + "-" + yearAgo.Month + "-" + yearAgo.Day + " 00:00:00'");
                }
            }
            catch (Exception) { }
        }
Example #18
0
        /// <summary>
        /// Updates tasks percentage.
        /// </summary>
        /// <param name="asyncTaskUId">The task UId to be updated</param>
        /// <param name="currentActivity">The current activity</param>
        /// <param name="pct">The current percentage</param>
        public AsyncTask UpdateTask(string asyncTaskUId, string currentActivity, short pct)
        {
            AsyncTask asyncTask = null;
            using (Data.CoreContext context = new Data.CoreContext()) {
                try {
                    asyncTask = context.AsyncTasks.SingleOrDefault(a => a.AsyncTaskUId == asyncTaskUId);
                    if (asyncTask == null)
                        return null;
                    asyncTask.CurrentAtivity = currentActivity;
                    asyncTask.CurrentPercentage = pct;
                    context.SaveChanges();
                }
                catch {
                    asyncTask = null;
                }

                return asyncTask;
            }
        }
Example #19
0
 /// <summary>
 /// Removes/Cancel the task.
 /// </summary>
 /// <param name="asyncTaskUId">The task UId to be updated</param>
 public void RemoveTask(string asyncTaskUId)
 {
     using (Data.CoreContext context = new Data.CoreContext()) {
         AsyncTask asyncTask = context.AsyncTasks.SingleOrDefault(a => a.AsyncTaskUId == asyncTaskUId);
         context.AsyncTasks.Remove(asyncTask);
         context.SaveChanges();
     }
 }
Example #20
0
        public void Log(string actionDescription, string errorDescription = null, bool saveParameters = true)
        {
            string   url   = "unknow";
            string   login = "******";
            string   ip    = "unknow";
            DateTime when  = DateTime.Now.ToUniversalTime();
            Dictionary <string, object> dicParameters = null;

            var httpContext = System.Web.HttpContext.Current;

            if (httpContext != null)
            {
                url = httpContext.Request.Url.OriginalString;
                ip  = httpContext.Request.UserHostAddress;

                // if was not via IMPORT
                if (security == null)
                {
                    security = new SecurityService();
                }

                User user = security.GetSignedUser();

                if (user != null)
                {
                    login = user.Email;
                }

                if (user != null && user.LoginNT != null)
                {
                    login = login + " (" + user.LoginNT + ")";
                }

                if (saveParameters)
                {
                    dicParameters = new Dictionary <string, object>();

                    //Salvar dados que são enviados no corpo da requisição
                    if (httpContext.Request.InputStream.Length > 0)
                    {
                        httpContext.Request.InputStream.Position = 0;
                        using (StreamReader reader = new StreamReader(httpContext.Request.InputStream)) {
                            if (httpContext.Request.ContentType.ToLower().Contains("application/json;"))
                            {
                                dicParameters["body"] = Newtonsoft.Json.JsonConvert.DeserializeObject(reader.ReadToEnd());
                            }
                            else
                            {
                                dicParameters["body"] = reader.ReadToEnd();
                            }
                        }
                    }
                    //Salvar dados que são enviados via GET
                    if (httpContext.Request.QueryString.HasKeys())
                    {
                        Dictionary <string, string> dicGet = new Dictionary <string, string>();
                        dicParameters["get"] = NameValueCollectionToDictionary(httpContext.Request.QueryString);
                    }
                    //Salvar dados que são enviados via POST
                    if (httpContext.Request.Form.HasKeys())
                    {
                        dicParameters["post"] = NameValueCollectionToDictionary(httpContext.Request.Form);
                    }
                }
            }

            string parameters = null;

            if (dicParameters != null && dicParameters.Count > 0)
            {
                parameters = Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters);
            }

            short logType = 0;

            if (!string.IsNullOrEmpty(errorDescription))
            {
                logType = (short)LogTypes.ERROR;
            }

            Log log = new Log()
            {
                LogUId = Guid.NewGuid().ToString(), ActionDescription = actionDescription, ErrorDescription = errorDescription, LogType = logType, SignedUser = login, Url = url, UserIp = ip, When = when, Parameters = parameters
            };

            try {
                using (var context = new Data.CoreContext()) {
                    context.Logs.Add(log);
                    context.SaveChanges();

                    // delete old records
                    DateTime yearAgo = when.AddYears(-1);
                    context.Database.ExecuteSqlCommand("DELETE FROM Logs WHERE Logs.When < '" + yearAgo.Year + "-" + yearAgo.Month + "-" + yearAgo.Day + " 00:00:00'");
                }
            }
            catch (Exception) { }
        }
Example #21
0
        public User SaveUser(User user)
        {
            using (var context = new Data.CoreContext()) {
                CheckUniqueLoginNT(user);

                // gets the old version of user
                User oldUser = GetUser(user.Email);

                List <GroupMembership> removedGroups = new List <GroupMembership>();
                List <GroupMembership> addedGroups   = user.Memberships.ToList();

                List <GroupCollectionMembership> removedGroupCollection = new List <GroupCollectionMembership>();
                List <GroupCollectionMembership> addedGroupCollection   = user.GroupCollectionMemberships.ToList();

                if (user.Password != null)
                {
                    user.Password.Password = Crypt(user.Password.Password);
                    user.Password.Email    = user.Email;
                }

                if (String.IsNullOrWhiteSpace(user.LoginNT))
                {
                    user.LoginNT = null;
                }

                user.LoginErrorsCount = 0;

                if (oldUser != null)
                {
                    //Groups
                    removedGroups = oldUser.Memberships.Where(o => !user.Memberships.Any(u => u.UserGroupUId == o.UserGroupUId)).ToList();
                    addedGroups   = user.Memberships.Where(u => !oldUser.Memberships.Any(o => o.UserGroupUId == u.UserGroupUId)).ToList();

                    //GroupsCollection
                    removedGroupCollection = oldUser.GroupCollectionMemberships.Where(o => !user.GroupCollectionMemberships.Any(u => u.GroupCollectionUId == o.GroupCollectionUId)).ToList();
                    addedGroupCollection   = user.GroupCollectionMemberships.Where(u => !oldUser.GroupCollectionMemberships.Any(o => o.GroupCollectionUId == u.GroupCollectionUId)).ToList();

                    context.Users.Attach(oldUser);
                    context.Entry <User>(oldUser).CurrentValues.SetValues(user);

                    // if the password was changed
                    if (oldUser.Password != null && user.Password != null)
                    {
                        oldUser.Password.Password = user.Password.Password;
                    }

                    // ig it has no password before, and now it was added
                    if (oldUser.Password == null && user.Password != null)
                    {
                        context.UserPasswords.Add(user.Password);
                    }
                }
                else
                {
                    context.Users.Add(user);
                }

                foreach (GroupMembership m in removedGroups)
                {
                    context.GroupMemberships.Remove(m);
                }

                foreach (GroupMembership m in addedGroups)
                {
                    m.Email = user.Email;
                    context.GroupMemberships.Add(m);
                }

                foreach (GroupCollectionMembership m in removedGroupCollection)
                {
                    context.GroupCollectionMemberships.Remove(m);
                }

                foreach (GroupCollectionMembership m in addedGroupCollection)
                {
                    m.Email = user.Email;
                    context.GroupCollectionMemberships.Add(m);
                }


                context.SaveChanges();
            }
            return(user);
        }