public static void LoadOwnedRooms(this IMessangerRepository repository, MessangerUser user)
        {
            if (!user.IsAdmin)
                return;

            user.OwnedGroups.AsQueryable().Select(g => g.CreatorKey == user.Key);
        }
        public static void SetUserInGroup(this ICache cache, MessangerUser user, MessangerGroup room, bool value)
        {
            string key = CacheKeys.GetUserInGroup(user, room);

            // Cache this forever since people don't leave rooms often
            cache.Set(key, value, TimeSpan.FromDays(365));
        }
        public MessangerUser AddUser(string userName, string email, string password)
        {
            if (!IsValidUserName(userName))
                throw new InvalidOperationException(string.Format("'{0}' is not a valid user name.", userName));

            if (string.IsNullOrEmpty(password))
                ThrowPasswordIsRequired();

            EnsureUserNameIsAvailable(userName);

            var user = new MessangerUser
            {
                Name = userName,
                Email = email,
                Status = (int)UserStatus.Active,
                Id = Guid.NewGuid().ToString("d"),
                Salt = _crypto.CreateSalt(),
                LastActivity = DateTime.UtcNow,
            };

            ValidatePassword(password);
            user.HashedPassword = password.ToSha256(user.Salt);

            _repository.Add(user);

            return user;
        }
        public static bool IsUserInGroup(this IMessangerRepository repository, ICache cache, MessangerUser user, MessangerGroup group)
        {
            bool? cached = cache.IsUserInGroup(user, group);

            if (cached == null)
            {
                //TODO: resolve issue here
                cached = repository.IsUserInGroup(user, group);
                cache.SetUserInGroup(user, group, cached.Value);
            }

            return cached.Value;
        }
 public UserViewModel(MessangerUser user)
 {
     Name = user.Name;
     Hash = user.Hash;
     Active = user.Status == (int)UserStatus.Active;
     Status = ((UserStatus)user.Status).ToString();
     Note = user.Note;
     AfkNote = user.AfkNote;
     IsAfk = user.IsAfk;
     Flag = user.Flag;
     Country = Services.MessangerService.GetCountry(user.Flag);
     LastActivity = user.LastActivity;
     IsAdmin = user.IsAdmin;
     Id = user.Id;
 }
        public static dynamic GetAllNewMessgesForUser(this IMessangerRepository repository, MessangerUser usr)
        {
            return (from item in repository.Groups.Include(g => g.Messages).ToList()
                    let grp = item

                    //from user in item.Users
                    //where user.Key == usr.Key && item.CreatorKey == usr.Key
                    from msg in item.Messages
                    where msg.IsNew
                    let msgs = msg
                    select new { Group = grp, Messages = msg } into tuple
                    group tuple by tuple.Group into g
                    select new
                    {
                        Group = g.Key,
                        Messages = g.Select(m => m.Messages).AsEnumerable()
                    }).ToList();
        }
        private HttpResponseMessage CreateResponseMessage(MessangerUser user)
        {
            HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Created);
            message.Content = new StringContent(user.Key.ToString());
            message.Headers.Location = new Uri(Url.Link("DefaultApiActionParam", new { action = "get", userId = user.Id }));

            return message;
        }
 public static string GetUserInGroup(MessangerUser user, MessangerGroup room)
 {
     return "UserInRoom" + user.Key + "_" + room.Key;
 }
        public Common.Models.MessangerUser AddUser(string userName, string identity, string email)
        {
            if (!IsValidUserName(userName))
                throw new InvalidOperationException(String.Format("'{0}' is not a valid user name.", userName));

            // This method is used in the auth workflow. If the username is taken it will add a number to the user name.
            if (UserExists(userName))
            {
                var usersWithNameLikeMine = _repository.Users.Count(u => u.Name.StartsWith(userName));
                userName += usersWithNameLikeMine;
            }

            var user = new MessangerUser
            {
                Name = userName,
                Status = (int)UserStatus.Active,
                Email = email,
                Hash = email.ToMD5(),
                Identity = identity,
                Id = Guid.NewGuid().ToString("d"),
                LastActivity = DateTime.UtcNow
            };

            _repository.Add(user);
            _repository.CommitChanges();

            return user;
        }
 private static void EnsureCreatorOrAdmin(MessangerUser user, MessangerGroup group)
 {
     if (user != group.Creator && !user.IsAdmin)
     {
         throw new InvalidOperationException("You are not the creator of room '" + group.Name + "'");
     }
 }
 private void UpdateActivity(MessangerUser user)
 {
     _service.UpdateActivity(user, Context.ConnectionId, UserAgent);
     _repository.CommitChanges();
 }
        private void OnUserInitialize(ClientState clientState, MessangerUser user)
        {
            // Update the active room on the client (only if it's still a valid room)
            if (user.Groups.Any(room => room.Name.Equals(clientState.ActiveGroup, StringComparison.OrdinalIgnoreCase)))
                // Update the active room on the client (only if it's still a valid room)
                Clients.Caller.activeRoom = clientState.ActiveGroup;

            (this as INotificationService).LogOn(user, Context.ConnectionId);
        }
        void INotificationService.OnUserJoinedGroup(MessangerUser user, MessangerGroup group)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            if (group == null)
                throw new ArgumentNullException("group");

            Clients.Group(group.Name).userJoinedGroup(user);
        }
 private void AddAuthCookie(bool remember, MessangerUser mesUser)
 {
     IAuthenticationTokenService tokenService = Bootstrapper.Kernel.Get<IAuthenticationTokenService>();
     if (tokenService == null)
         throw new InvalidOperationException("Fail to resolve IAuthenticationTokenService.");
     string token = tokenService.GetAuthenticationToken(mesUser);
     HttpCookie cookieTokn = new HttpCookie(Constants.UserTokenCookie, token);
     cookieTokn.HttpOnly = true;
     cookieTokn.Expires = remember ? (DateTime.Now + TimeSpan.FromDays(30)) : DateTime.UtcNow.AddMinutes(40);
     Response.Cookies.Add(cookieTokn);
 }
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid &&
                WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                string tokenIssuerId = string.Empty;

                if (Request.Cookies[_aspSesId] != null)
                {
                    var cookie = Request.Cookies[_aspSesId];
                    SessionTokenIssuer.Instance.AddOrUpdate(new SessionInfo()
                    {
                        Session = Session.SessionID,
                        Expire = DateTime.UtcNow.AddMinutes(40)
                    }, (tokenIssuerId = Guid.NewGuid().ToString()));

                    SessionTokenIssuer.Instance.AddOrUpdateUserName(tokenIssuerId, model.UserName);
                }

                var authClient = WebHelper.GetClientIndetification();

                int userId = -1;
                string authToken = Authorization.AuthTokenManagerEx.Instance.Generate(authClient);
                if (Authorization.AuthTokenManagerEx.Instance[authClient] != null)
                {
                    userId = WebSecurity.GetUserId(model.UserName);
                    Authorization.AuthTokenManagerEx.Instance[authClient].UserId = userId;
                    Authorization.AuthTokenManagerEx.Instance[authClient].UserName = model.UserName;

                    var cInfo = new ClientInfo() { Id = userId, UserName = model.UserName };
                    Authorization.AuthTokenManagerEx.Instance.AddClientInfo(cInfo, authToken);
                }
                InitializeSessionValiable(model);

                using (var mesRepo = Bootstrapper.Kernel.Get<Repositories.IMessangerRepository>())
                {
                    var mesUser = mesRepo.GetUserByIdentity(string.Format("{0}_{1}", model.UserName, userId));

                    //Add data of logged user to corresponding MessangerUsers table
                    if (mesUser == null)
                    {
                        string email = string.Empty;
                        using (var aspRepo = Bootstrapper.Kernel.Get<Repositories.IAspUserRepository>())
                        {
                            //get user email from asp db login
                            if (aspRepo != null)
                                email = aspRepo.GetByName(model.UserName).Email;
                        }
                        mesUser = new MessangerUser()
                        {
                            Id = Guid.NewGuid().ToString("d"),
                            Identity = string.Format("{0}_{1}", model.UserName, userId),
                            IsBanned = false,
                            LastActivity = DateTime.UtcNow,
                            Name = model.UserName,
                            Status = (int)Common.Models.UserStatus.Active,
                            Note = "created from LogOn workflow",
                            Email = email,
                            Hash = email.ToMD5()
                        };
                        mesRepo.Add(mesUser);
                    }
                    else if (mesUser != null && string.IsNullOrEmpty(mesUser.Salt))
                    {
                        mesUser.Salt = Bootstrapper.Kernel.Get<ICryptoService>().CreateSalt();
                        mesUser.HashedPassword = model.Password.ToSha256(mesUser.Salt);
                        mesRepo.CommitChanges();
                    }

                    AddAuthCookie(model.RememberMe, mesUser);
                    // save messanger state to cookies object
                    if (mesUser != null && Request.Cookies.Get(_msConst) != null)
                    {
                        var state = JsonConvert.SerializeObject(new
                        {
                            userId = mesUser.Id,
                            aspUserId = userId,
                            userName = model.UserName,
                            hash = mesUser.Hash,
                            tokenId = tokenIssuerId
                        });

                        var cookie = new HttpCookie(_msConst, HttpUtility.UrlEncode(state));
                        cookie.HttpOnly = true;
                        if (model.RememberMe)
                            cookie.Expires = DateTime.UtcNow.AddDays(30);
                        else
                            cookie.Expires = DateTime.UtcNow.AddMinutes(40);
                        HttpContext.Response.Cookies.Add(cookie);
                    }
                    else if (mesUser != null)
                    {
                        var state = JsonConvert.SerializeObject(new
                        {
                            userId = mesUser.Id,
                            aspUserId = userId,
                            userName = model.UserName,
                            hash = mesUser.Hash,
                            tokenId = tokenIssuerId
                        });

                        var cookie = new HttpCookie(_msConst, HttpUtility.UrlEncode(state));
                        cookie.HttpOnly = true;
                        if (model.RememberMe)
                            cookie.Expires = DateTime.UtcNow.AddDays(30);
                        else
                            cookie.Expires = DateTime.UtcNow.AddMinutes(40);

                        HttpContext.Response.Cookies.Add(cookie);
                    }
                }//end of using mesRepo
                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
            return View(model);
        }
 public string GetAuthenticationToken(MessangerUser user)
 {
     byte[] buffer = _encoding.GetBytes(user.Id);
     buffer = _cryptoService.Protect(buffer);
     return TokenEncode(buffer);
 }
 private bool IsUserAllowed(MessangerGroup group, MessangerUser user)
 {
     return group.AllowedUsers.Contains(user) || user.IsAdmin;
 }
        private void GenericOpenOrCloseGroup(MessangerUser user, MessangerGroup targetGroup, bool close)
        {
            EnsureOwnerOrAdmin(user, targetGroup);

            if (!close && !targetGroup.Closed)
                throw new InvalidOperationException(string.Format("{0} is already open.", targetGroup.Name));

            else if (close && targetGroup.Closed)
                throw new InvalidOperationException(String.Format("{0} is already closed.", targetGroup.Name));

            targetGroup.Closed = close;
            _repository.CommitChanges();
        }
 private static void EnsureOwnerOrAdmin(MessangerUser user, MessangerGroup room)
 {
     if (!room.Owners.Contains(user) && !user.IsAdmin)
     {
         throw new InvalidOperationException("You are not an owner of room '" + room.Name + "'");
     }
 }
        void INotificationService.LogOn(MessangerUser user, string clientId)
        {
            if (user.OwnedGroups.Count == 0)
                user.OwnedGroups = (from item in _repository.Groups
                                    where item.CreatorKey == user.Key
                                    select item).ToList();

            //var groups = new List<ViewModels.GroupViemModel>();
            // Update the client state
            Clients.Caller.uid = user.Id;
            Clients.Caller.name = user.Name;
            Clients.Caller.hash = user.Hash;
            Clients.Caller.aspUserId = string.IsNullOrEmpty(user.Identity) ? -1 : int.Parse(user.Identity.Split('_')[1]);

            foreach (var group in user.OwnedGroups)
            {
                // Tell the people in this group that you've joined
                //Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner).Wait();

                // Add the caller to the group so they receive messages
                //TODO: check here When user navigates to differ link it adds the same client ID to existing groups....
                try
                {
                    Groups.Add(clientId, group.Name).Wait();
                }
                catch (Exception ex)
                {
                    if ((ex is AggregateException) &&
                        !((ex as AggregateException).InnerException is System.Threading.Tasks.TaskCanceledException))
                    {
                        MvcApplication.Logger.Error("INotificationService.LogOn", ex.InnerException);
                    }
                }

                //groups.Add(new RoomViewModel
                //{
                //	Name = room.Name,
                //	Private = room.Private,
                //	Closed = room.Closed
                //});
            }
            _service.UpdateActivity(user, clientId, UserAgent);

            // Initialize the chat with the groups the user is in
            //Clients.Caller.logOn(groups);
        }
        void INotificationService.LogOut(MessangerUser user, string clientId)
        {
            DisconnectClient(clientId);

            var groups = user.Groups.Select(g => g.Name);
            Clients.Caller.logOut(groups);
        }
 private void EnsureSaltedPassword(MessangerUser user, string password)
 {
     if (string.IsNullOrEmpty(user.Salt))
     {
         user.Salt = _crypto.CreateSalt();
     }
     user.HashedPassword = password.ToSha256(user.Salt);
 }
 private void OnUpdateActivity(MessangerUser user, MessangerGroup group)
 {
     var userViewModel = new UserViewModel(user);
     Clients.Group(group.Name).updateActivity(userViewModel, group.Name);
 }
        public static bool? IsUserInGroup(this ICache cache, MessangerUser user, MessangerGroup room)
        {
            string key = CacheKeys.GetUserInGroup(user, room);

            return (bool?)cache.Get(key);
        }
 private void UpdateActivity(MessangerUser user, MessangerGroup group)
 {
     UpdateActivity(user);
     OnUpdateActivity(user, group);
 }
 public static void RemoveUserInGroup(this ICache cache, MessangerUser user, MessangerGroup room)
 {
     cache.Remove(CacheKeys.GetUserInGroup(user, room));
 }
        public static MessangerGroup VerifyUserGroup(this IMessangerRepository repository, ICache cache, MessangerUser user, string groupName)
        {
            if (String.IsNullOrEmpty(groupName))
            {
                throw new InvalidOperationException("Use '/join room' to join a room.");
            }

            groupName = MessangerService.NormalizeGroupName(groupName);

            MessangerGroup room = repository.GetGroupByName(groupName);

            if (room == null)
            {
                throw new InvalidOperationException(String.Format("You're in '{0}' but it doesn't exist.", groupName));
            }

            if (!repository.IsUserInGroup(cache, user, room))
            {
                throw new InvalidOperationException(String.Format("You're not in '{0}'. Use '/join {0}' to join it.", groupName));
            }

            return room;
        }
 private static void EnsureAdmin(MessangerUser user)
 {
     if (!user.IsAdmin)
     {
         throw new InvalidOperationException("You are not an admin");
     }
 }