Esempio n. 1
0
        public DateTime GetLastAssignmentSubmitDate(int assignmentId, string authToken)
        {
            DateTime       lastSubmit = DateTime.MinValue;
            Authentication auth       = new Authentication();

            if (auth.IsValidKey(authToken) == true)
            {
                OsbideUser authUser = GetActiveUser(authToken);

                //log the last activity date
                LogUserTransaction(authUser);

                //find the time of the last submit
                var query = (from log in Db.SubmitEvents
                             where log.AssignmentId == assignmentId &&
                             log.EventLog.SenderId == authUser.Id
                             orderby log.EventLog.DateReceived descending
                             select log).FirstOrDefault();
                if (query != null)
                {
                    lastSubmit = query.EventLog.DateReceived;
                }
            }
            return(lastSubmit);
        }
Esempio n. 2
0
        /// <summary>
        /// Logs the user into the system
        /// </summary>
        /// <param name="profile"></param>
        public string LogIn(OsbideUser profile)
        {
            profile = new OsbideUser(profile);
            HttpCookie cookie = new HttpCookie(ProfileCookieKey);

            //compute hash for this login attempt
            string hash = ComputeHash(profile.Email);

            //store profile in the authentication hash
            _cache[hash] = profile.Id;

            //store the key to the hash inside a cookie for the user
            cookie.Values[userNameKey] = hash;

            //Set a really long expiration date for the cookie.  Note that the server's copy of the
            //hash key will expire much sooner than this.
            cookie.Expires = DateTime.UtcNow.AddDays(360);

            //and then store it in the next response
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Response.Cookies.Set(cookie);
            }

            return(hash);
        }
Esempio n. 3
0
        public List <Course> GetCoursesForUser(string authToken)
        {
            List <Course> courses = new List <Course>();

            Authentication auth = new Authentication();

            if (auth.IsValidKey(authToken) == true)
            {
                OsbideUser authUser = GetActiveUser(authToken);

                //log the last activity date
                LogUserTransaction(authUser);

                //AC: I'm getting an exception when I try sorting by name USING EF/LINQ, so I guess I'll do it the hard way
                SortedDictionary <string, Course> sorted = new SortedDictionary <string, Course>();
                var query = (from cur in Db.CourseUserRelationships
                             where cur.UserId == authUser.Id &&
                             cur.Course.IsDeleted == false
                             select cur.Course)
                            .ToList();
                foreach (Course c in query)
                {
                    if (sorted.ContainsKey(c.Name) == false)
                    {
                        sorted.Add(c.Name, c);
                    }
                }
                foreach (KeyValuePair <string, Course> kvp in sorted)
                {
                    courses.Add(new Course(kvp.Value));
                }
            }
            return(courses);
        }
Esempio n. 4
0
 /// <summary>
 /// add user subscriptions
 /// </summary>
 /// <param name="user"></param>
 public void AddSubscriptionSubject(OsbideUser user)
 {
     if (user != null)
     {
         SubscriptionSubjects.Add(user);
     }
 }
Esempio n. 5
0
        public ActionResult Login(LoginViewModel vm)
        {
            if (ModelState.IsValid)
            {
                if (UserPassword.ValidateUser(vm.UserName, vm.Password, Db))
                {
                    Authentication auth = new Authentication();
                    OsbideUser     user = Db.Users.Where(u => u.Email.CompareTo(vm.UserName) == 0).FirstOrDefault();
                    if (user != null)
                    {
                        auth.LogIn(user);

                        //did the user come from somewhere?
                        if (string.IsNullOrEmpty(vm.ReturnUrl) == false)
                        {
                            Response.Redirect(vm.ReturnUrl);
                        }

                        return(RedirectToAction("Index", "Profile"));
                    }
                }
            }

            //if we got this far, must've had a bad user name or password
            ModelState.AddModelError("", "Invalid email or password.");
            return(View());
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Authentication auth = new Authentication();
            string         key  = auth.GetAuthenticationKey();
            OsbideUser     user = auth.GetActiveUser(key);

            //check web.config to see if we are requiring VS plugin install
            if (ConfigurationManager.AppSettings["RequireVsPlugin"].Equals("true"))
            {
                //is the user a student?
                if (user.Email != null && user.Role == SystemRole.Student)
                {
                    DateTime lastActivity = DateTime.UtcNow;
                    using (OsbideContext db = OsbideContext.DefaultWebConnection)
                    {
                        lastActivity = db.Users.Where(u => u.Id == user.Id).Select(u => u.LastVsActivity).FirstOrDefault();
                    }

                    //only allow access if they've been active in Visual Studio in the last 7 days
                    if (lastActivity < DateTime.UtcNow.Subtract(new TimeSpan(7, 0, 0, 0, 0)))
                    {
                        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "RequiresActiveVsConnection" }));
                    }
                }
            }
        }
Esempio n. 7
0
        public int SubmitLocalErrorLog(LocalErrorLog errorLog)
        {
            //check to see if the user exists in the database.  If not, reset sender and try again
            //(next IF statement)
            if (errorLog.SenderId != 0)
            {
                OsbideUser userCheck = Db.Users.Find(errorLog.SenderId);
                if (userCheck == null)
                {
                    errorLog.SenderId = 0;
                }
            }

            //reset the sender if necessary
            if (errorLog.SenderId == 0)
            {
                errorLog.Sender   = SaveUser(errorLog.Sender);
                errorLog.SenderId = errorLog.Sender.Id;
            }
            errorLog.Sender = null;
            Db.LocalErrorLogs.Add(errorLog);
            try
            {
                Db.SaveChanges();
            }
            catch (Exception)
            {
                return((int)Enums.ServiceCode.Error);
            }
            return(errorLog.Id);
        }
Esempio n. 8
0
        public int SubmitLocalErrorLog(LocalErrorLog errorLog, string authToken)
        {
            Authentication auth = new Authentication();

            if (auth.IsValidKey(authToken) == true)
            {
                OsbideUser authUser = GetActiveUser(authToken);
                LogUserTransaction(authUser);

                //replace the error log's sender information with what we obtained from the auth key
                errorLog.Sender   = null;
                errorLog.SenderId = authUser.Id;

                //add to the db and give it a try
                Db.LocalErrorLogs.Add(errorLog);
                try
                {
                    Db.SaveChanges();
                }
                catch (Exception)
                {
                    return((int)Enums.ServiceCode.DatabaseError);
                }
                return(errorLog.Id);
            }
            else
            {
                return((int)Enums.ServiceCode.AuthenticationError);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Will return a list of recent compile errors for the given user
        /// </summary>
        /// <param name="user"></param>
        /// <param name="timeframe">How far back the system should look</param>
        /// <returns></returns>
        protected string[] GetRecentCompileErrors(OsbideUser user, DateTime timeframe)
        {
            var errors = new List <string>();

            var errorItems = RecentErrorProc.Get(user.Id, timeframe);

            return(errorItems.Where(e => e.CriticalErrorName.Length > 0).Select(e => e.CriticalErrorName).ToArray());
        }
Esempio n. 10
0
 public CommentTimelineViewModel()
 {
     Timeline          = new CommentTimeline();
     CodeBeforeComment = new Dictionary <string, TimelineCodeDocument>();
     CodeAfterComment  = new Dictionary <string, TimelineCodeDocument>();
     Log    = new EventLog();
     Author = new OsbideUser();
 }
Esempio n. 11
0
 //
 // GET: /Setup/
 public ActionResult Index()
 {
     //check for default schools and chat rooms.  If they exist, redirect to the home page
     if (Db.ChatRooms.Count() != 0 && Db.Schools.Count() != 0)
     {
         return(RedirectToAction("Index", "Home"));
     }
     return(View(OsbideUser.GenericUser()));
 }
Esempio n. 12
0
        /// <summary>
        /// Logs a VS transaction for the given auth key
        /// </summary>
        /// <param name="authKey"></param>
        private void LogUserTransaction(string authToken)
        {
            OsbideUser user = GetActiveUser(authToken);

            if (user != null)
            {
                LogUserTransaction(user);
            }
        }
Esempio n. 13
0
        public int SubmitAssignment(int assignmentId, EventLog assignmentLog, OsbideUser currentUser)
        {
            EventLog submittedLog = SubmitLog(assignmentLog, currentUser);

            if (submittedLog != null)
            {
                return(submittedLog.Id);
            }
            return(-1);
        }
Esempio n. 14
0
        private void LogUserTransaction(OsbideUser user)
        {
            OsbideUser dbUser = Db.Users.Where(u => u.Id == user.Id).FirstOrDefault();

            if (dbUser != null)
            {
                dbUser.LastVsActivity = DateTime.UtcNow;
                Db.SaveChanges();
            }
        }
Esempio n. 15
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Authentication auth = new Authentication();
            string         key  = auth.GetAuthenticationKey();
            OsbideUser     user = auth.GetActiveUser(key);

            if (user == null || user.RoleValue <= (int)SystemRole.Student)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Feed", action = "Index" }));
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Returns a <see cref="FileCache"/> with the default region tailored to the
        /// specified user
        /// </summary>
        /// <param name="client">The user who is accessing the file cache (typically the
        /// person making the web request)</param>
        /// <returns></returns>
        public static FileCache GetCacheInstance(OsbideUser client)
        {
            FileCache fc = new FileCache(FileCacheHelper.CachePath, new ObjectBinder());

            fc.DefaultRegion = client.Id.ToString();
            fc.DefaultPolicy = new CacheItemPolicy()
            {
                SlidingExpiration = new TimeSpan(7, 0, 0, 0)
            };
            return(fc);
        }
Esempio n. 17
0
        public ControllerBase()
        {
            //set up DB
            Db = OsbideContext.DefaultWebConnection;

            //set up current user
            Authentication auth    = new Authentication();
            string         authKey = auth.GetAuthenticationKey();
            int            id      = auth.GetActiveUserId(authKey);

            //make sure that we got back a good key
            if (id > 0)
            {
                CurrentUser = Db.Users.Find(id);
                if (CurrentUser != null)
                {
                    CurrentUser.PropertyChanged += CurrentUser_PropertyChanged;
                }
                else
                {
                    CurrentUser = new OsbideUser();
                }
            }
            else
            {
                CurrentUser = new OsbideUser();
            }

            //set up caches
            GlobalCache = FileCacheHelper.GetGlobalCacheInstance();
            UserCache   = FileCacheHelper.GetCacheInstance(CurrentUser);

            //update all users scores if necessary
            object lastScoreUpdate  = GlobalCache["lastScoreUpdate"];
            bool   needsScoreUpdate = true;

            if (lastScoreUpdate != null)
            {
                DateTime lastUpdate = (DateTime)lastScoreUpdate;
                if (lastUpdate.AddDays(1) > DateTime.UtcNow)
                {
                    needsScoreUpdate = false;
                }
            }
            if (needsScoreUpdate == true)
            {
                //UpdateUserScores();
                GlobalCache["lastScoreUpdate"] = DateTime.UtcNow;
            }

            //make current user available to all views
            ViewBag.CurrentUser = CurrentUser;
        }
Esempio n. 18
0
        public StudentCommentTimeline()
        {
            CrowdCodings      = new PostCoding();
            CodeBeforeComment = new Dictionary <string, CodeDocument>();
            CodeAfterComment  = new Dictionary <string, CodeDocument>();

            ProgrammingState       = new TimelineState();
            ProgrammingState.State = "not available";

            ExpertCoding = new ContentCoding();
            Log          = new EventLog();
            Author       = new OsbideUser();
        }
Esempio n. 19
0
        public string Login(string email, string hashedPassword)
        {
            string hash = "";

            if (UserPassword.ValidateUserHashedPassword(email, hashedPassword, Db))
            {
                Authentication auth = new Authentication();
                OsbideUser     user = Db.Users.Where(u => u.Email.CompareTo(email) == 0).FirstOrDefault();
                if (user != null)
                {
                    hash = auth.LogIn(user);
                    LogUserTransaction(user);
                }
            }
            return(hash);
        }
Esempio n. 20
0
        public int SubmitLog(EventLog log, string authToken)
        {
            //verify request before continuing
            Authentication auth = new Authentication();

            if (auth.IsValidKey(authToken) == false)
            {
                return((int)Enums.ServiceCode.AuthenticationError);
            }

            //AC: kind of hackish, but event logs that we receive should already have an ID
            //attached to them from being stored in the machine's local DB.  We can use
            //that ID to track the success/failure of asynchronous calls.
            int localId = log.Id;

            //we don't want the local id, so be sure to clear
            log.Id = 0;

            //replace sender information with what is contained in the auth key
            OsbideUser authUser = GetActiveUser(authToken);

            //log the last activity date
            LogUserTransaction(authUser);

            //students: send all events.
            //other: send only "ask for help" events
            if (authUser.Role != SystemRole.Student)
            {
                if (log.LogType != AskForHelpEvent.Name)
                {
                    return(localId);
                }
            }

            EventLog submittedLog = SubmitLog(log, authUser);

            if (submittedLog == null)
            {
                return((int)Enums.ServiceCode.DatabaseError);
            }
            else
            {
                //Return the ID number of the local object so that the caller knows that it's been successfully
                //saved into the main system.
                return(localId);
            }
        }
Esempio n. 21
0
        public int SubmitAssignment(int assignmentId, EventLog assignmentLog, string authToken)
        {
            int            result = -1;
            Authentication auth   = new Authentication();

            if (auth.IsValidKey(authToken) == true)
            {
                //replace sender information with what is contained in the auth key
                OsbideUser authUser = GetActiveUser(authToken);

                //log the last activity date
                LogUserTransaction(authUser);

                result = SubmitAssignment(assignmentId, assignmentLog, authUser);
            }
            return(result);
        }
Esempio n. 22
0
        private void UpdateSubscriptions(EditProfileViewModel vm)
        {
            //remove all current subscriptions that are not required
            List <UserSubscription> nonEssentialSubscriptions = Db.UserSubscriptions
                                                                .Where(s => s.ObserverInstitutionId == CurrentUser.InstitutionId)
                                                                .Where(s => s.ObserverSchoolId == CurrentUser.SchoolId)
                                                                .Where(s => s.IsRequiredSubscription == false)
                                                                .ToList();

            foreach (UserSubscription subscription in nonEssentialSubscriptions)
            {
                Db.UserSubscriptions.Remove(subscription);
            }
            Db.SaveChanges();

            //add in requested subscriptions
            foreach (string key in Request.Form.Keys)
            {
                if (key.StartsWith("subscription_") == true)
                {
                    int      userId = -1;
                    string[] pieces = key.Split('_');
                    if (pieces.Length == 2)
                    {
                        if (Int32.TryParse(pieces[1], out userId) == true)
                        {
                            OsbideUser user = Db.Users.Where(u => u.Id == userId).FirstOrDefault();
                            if (user != null)
                            {
                                UserSubscription sub = new UserSubscription()
                                {
                                    IsRequiredSubscription = false,
                                    ObserverSchoolId       = CurrentUser.SchoolId,
                                    ObserverInstitutionId  = CurrentUser.InstitutionId,
                                    SubjectSchoolId        = user.SchoolId,
                                    SubjectInstitutionId   = user.InstitutionId
                                };
                                Db.UserSubscriptions.Add(sub);
                            }
                        }
                    }
                }
            }
            Db.SaveChanges();
        }
Esempio n. 23
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel vm)
        {
            if (ModelState.IsValid)
            {
                OsbideUser user = Db.Users.Where(e => e.Email.ToLower() == vm.EmailAddress.ToLower()).FirstOrDefault();
                if (user != null)
                {
                    if (user.SchoolId == vm.SchoolId && user.InstitutionId == vm.InstitutionId)
                    {
                        Authentication auth        = new Authentication();
                        string         newPassword = auth.GenerateRandomString(7);
                        UserPassword   password    = Db.UserPasswords.Where(up => up.UserId == user.Id).FirstOrDefault();
                        if (password != null)
                        {
                            //update password
                            password.Password = UserPassword.EncryptPassword(newPassword, user);
                            Db.SaveChanges();

                            //send email
                            string             body = "Your OSBIDE password has been reset.\n Your new password is: \"" + newPassword + "\".\n\nPlease change this password as soon as possible.";
                            List <MailAddress> to   = new List <MailAddress>();
                            to.Add(new MailAddress(user.Email));
                            Email.Send("[OSBIDE] Password Reset Request", body, to);
                            vm.PasswordResetRequestComplete = true;
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Account not found.  Please check the supplied email address and institution information.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Account not found.  Please check the supplied email address and institution information.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Account not found.  Please check the supplied email address and institution information.");
            }

            vm.Schools = Db.Schools.ToList();
            return(View(vm));
        }
Esempio n. 24
0
        public OsbideUser SaveUser(OsbideUser userToSave)
        {
            //reset sender id
            userToSave.Id = 0;

            //make sure that the user is valid
            if (
                userToSave.FirstName == null
                ||
                userToSave.LastName == null
                ||
                userToSave.InstitutionId == null
                ||
                userToSave.FirstName.Length == 0
                ||
                userToSave.LastName.Length == 0
                ||
                userToSave.InstitutionId.Length == 0
                )
            {
                return(userToSave);
            }

            //try to find the user in the DB before creating a new record
            OsbideUser dbUser = (from user in Db.Users
                                 where
                                 user.FirstName.CompareTo(userToSave.FirstName) == 0
                                 &&
                                 user.LastName.CompareTo(userToSave.LastName) == 0
                                 &&
                                 user.InstitutionId.CompareTo(userToSave.InstitutionId) == 0
                                 select user).FirstOrDefault();

            if (dbUser != null)
            {
                userToSave.Id = dbUser.Id;
            }
            else
            {
                Db.Users.Add(userToSave);
                Db.SaveChanges();
            }
            return(userToSave);
        }
Esempio n. 25
0
        /// <summary>
        /// Returns the active user
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public OsbideUser GetActiveUser(string authToken)
        {
            int        id      = -1;
            OsbideUser profile = null;

            try
            {
                id      = (int)_cache[authToken];
                profile = _db.Users.Find(id);
            }
            catch (Exception)
            {
            }
            if (profile == null)
            {
                return(new OsbideUser());
            }
            return(new OsbideUser(profile));
        }
Esempio n. 26
0
        public int SubmitLog(EventLog log)
        {
            //AC: kind of hackish, but event logs that we receive should already have an ID
            //attached to them from being stored in the machine's local DB.  We can use
            //that ID to track the success/failure of asynchronous calls.
            int localId = log.Id;

            //we don't want the local id, so be sure to clear
            log.Id = 0;

            //check to see if the user exists in the database.  If not, reset sender and try again
            //(next IF statement)
            if (log.SenderId != 0)
            {
                OsbideUser userCheck = Db.Users.Find(log.SenderId);
                if (userCheck == null)
                {
                    log.SenderId = 0;
                }
            }

            //reset the sender if necessary
            if (log.SenderId == 0)
            {
                log.Sender   = SaveUser(log.Sender);
                log.SenderId = log.Sender.Id;
            }
            log.Sender = null;
            Db.EventLogs.Add(log);
            try
            {
                Db.SaveChanges();
            }
            catch (Exception)
            {
                return((int)Enums.ServiceCode.Error);
            }

            //Return the ID number of the local object so that the caller knows that it's been successfully
            //saved into the main system.
            return(localId);
        }
Esempio n. 27
0
 public ActionResult ForgotEmail(ForgotEmailViewModel vm)
 {
     if (ModelState.IsValid)
     {
         OsbideUser user = (from u in Db.Users
                            where u.SchoolId.CompareTo(vm.SchoolId) == 0 &&
                            u.InstitutionId.CompareTo(vm.InstitutionId) == 0
                            select u).FirstOrDefault();
         if (user != null)
         {
             vm.EmailAddress = user.Email;
         }
         else
         {
             ModelState.AddModelError("", "No account matches the supplied institution and ID number provided.");
         }
     }
     vm.Schools = Db.Schools.ToList();
     return(View(vm));
 }
Esempio n. 28
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Authentication auth         = new Authentication();
            string         key          = auth.GetAuthenticationKey();
            OsbideUser     user         = auth.GetActiveUser(key);
            bool           hasValidRole = true;

            if (user != null)
            {
                foreach (SystemRole role in _roles)
                {
                    if (user.Role == role)
                    {
                        hasValidRole = false;
                    }
                }
            }
            if (hasValidRole == false)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Profile", action = "Index" }));
            }
        }
Esempio n. 29
0
        private void UpdateBasicSettings(EditProfileViewModel vm)
        {
            //make sure that the specified school ID / institution ID isn't already daken
            OsbideUser dbUser = Db.Users
                                .Where(u => u.SchoolId == vm.User.SchoolId)
                                .Where(u => u.InstitutionId == vm.User.InstitutionId)
                                .FirstOrDefault();

            if (dbUser != null)
            {
                if (dbUser.Id != CurrentUser.Id)
                {
                    vm.UpdateBasicSettingsMessage = "The specified school / institution ID is already taken";
                    return;
                }
            }
            CurrentUser.FirstName         = vm.User.FirstName;
            CurrentUser.LastName          = vm.User.LastName;
            CurrentUser.SchoolId          = vm.User.SchoolId;
            CurrentUser.InstitutionId     = vm.User.InstitutionId;
            CurrentUser.Gender            = vm.User.Gender;
            vm.UpdateBasicSettingsMessage = "Your settings have been updated.";
        }
Esempio n. 30
0
        private void UpdateEmail(EditProfileViewModel vm)
        {
            //Attempt to update email address.
            //Check to make sure email address isn't in use
            OsbideUser user = Db.Users.Where(u => u.Email.CompareTo(vm.NewEmail) == 0).FirstOrDefault();

            if (user == null && string.IsNullOrEmpty(vm.NewEmail) == false)
            {
                //update email address
                CurrentUser.Email = vm.NewEmail;

                //the email address acts as the hash for the user's password so we've got to change that as well
                UserPassword up = Db.UserPasswords.Where(p => p.UserId == CurrentUser.Id).FirstOrDefault();
                up.Password = UserPassword.EncryptPassword(vm.OldPassword, CurrentUser);
                Db.SaveChanges();

                vm.UpdateEmailSuccessMessage = string.Format("Your email has been successfully updated to \"{0}.\"", CurrentUser.Email);
            }
            else
            {
                ModelState.AddModelError("", "The requested email is already in use.");
            }
        }